/* ============================================================
   LAUNCHPAD.FAIL — overlays (countdown, bet pick, win, lose)
   window.BetPick, window.Countdown, window.WinOverlay, window.LoseOverlay
   ============================================================ */
(function () {
  const { useState, useEffect, useRef } = React;
  const E = window.Engine;
  const useCountUp = window.useCountUp;
  const BETS = [0.01, 0.02, 0.05, 0.1];

  window.BetPick = function BetPick({ wagerSol, onPick }) {
    return (
      <div className="bet-pick">
        <div className="t">Choose your wager</div>
        <div className="bet-chips">
          {BETS.map(b => (
            <button key={b} className={'bet-chip' + (Math.abs(b - wagerSol) < 1e-6 ? ' on' : '')} onClick={() => onPick(b)}>{b} SOL</button>
          ))}
        </div>
      </div>
    );
  };

  window.Countdown = function Countdown({ n, onSkip }) {
    const igniting = n <= E.TIMING.igniteAt;
    return (
      <div className="countdown countdown--tap" onPointerDown={onSkip}>
        <div className={'num cd-anim' + (igniting ? ' cd-hot' : '')} key={n}>{n}</div>
        <div className="lab">{igniting ? 'ignition sequence…' : 'ignition in'}</div>
        <div className="cd-skip">tap to skip</div>
      </div>
    );
  };

  /* count-up provided by window.useCountUp (ui.jsx) */

  window.WinOverlay = function WinOverlay({ result, step, balance, onAgain }) {
    const payCount = useCountUp(result.payout, step >= 2, E.TIMING.countUpMs);
    const balCount = useCountUp(result.payout, step >= 3, E.TIMING.countUpMs);
    const nm = result.nearMiss;
    return (
      <div className="result win">
        <div className={'tag' + (nm ? ' tag--near' : '')}>{nm ? '🔥 SO CLOSE — escaped just in time' : (result.endMult >= 1 ? 'SAFE EJECT' : 'EJECTED EARLY')}</div>
        <div className="big-x" style={{ color: E.multColor(result.endMult) }}>{E.fmtMult(result.endMult)}x</div>
        {nm && <div className="near-sub">would’ve blown at {E.fmtMult(result.crash)}x</div>}
        {step >= 2 && (
          <div className="payout"><span className="moon-coin" />{E.fmtMoonFull(Math.round(payCount))} <span style={{ fontSize: 16, opacity: .8 }}>MOON</span></div>
        )}
        {step >= 3 && <div className="bal">balance +{E.fmtMoonFull(Math.round(balCount))}</div>}
        {step >= 3 && <FlyingCoins />}
        {step >= 3 && <button className="cta" style={{ marginTop: 22, pointerEvents: 'auto' }} onClick={onAgain}>Launch again</button>}
      </div>
    );
  };

  function FlyingCoins() {
    const coins = useRef(Array.from({ length: 9 }, (_, i) => ({
      id: i, dx: (Math.random() - 0.5) * 60, delay: i * 80, dur: 700 + Math.random() * 400,
    }))).current;
    return (
      <React.Fragment>
        {coins.map(c => (
          <span key={c.id} className="coin-fly" style={{
            left: `calc(50% + ${c.dx}px)`, top: '42%',
            animation: `coinfly ${c.dur}ms cubic-bezier(.4,.1,.5,1) ${c.delay}ms forwards`,
          }} />
        ))}
        <style>{`@keyframes coinfly{
          0%{opacity:0;transform:translate(0,0) scale(.6);}
          15%{opacity:1;transform:translate(0,-50px) scale(1.2);}
          100%{opacity:1;transform:translate(calc(150px - 50%), 420px) scale(.5);}
        }`}</style>
      </React.Fragment>
    );
  }

  window.LoseOverlay = function LoseOverlay({ result, onAgain }) {
    const [showBtn, setShowBtn] = useState(false);
    useEffect(() => { const t = setTimeout(() => setShowBtn(true), E.TIMING.loseBtnMs); return () => clearTimeout(t); }, []);
    return (
      <div className="result lose">
        <Boom />
        <div className="boom">BOOM</div>
        <div className="tag" style={{ marginTop: 8 }}>exploded at {E.fmtMult(result.endMult)}x</div>
        {showBtn && <button className="cta cta--again" style={{ marginTop: 26, pointerEvents: 'auto' }} onClick={onAgain}>Try again</button>}
      </div>
    );
  };

  function Boom() {
    const bits = useRef(Array.from({ length: 16 }, (_, i) => ({
      id: i, a: (i / 16) * Math.PI * 2, d: 80 + Math.random() * 90, s: 6 + Math.random() * 12,
      c: ['#ffd23e', '#ff8a3d', '#ff5630', '#e7573f'][i % 4],
    }))).current;
    return (
      <React.Fragment>
        {bits.map(b => (
          <span key={b.id} style={{
            position: 'absolute', left: '50%', top: '44%', width: b.s, height: b.s, borderRadius: 2,
            background: b.c, transform: 'translate(-50%,-50%)',
            animation: `boombit 700ms cubic-bezier(.2,.7,.3,1) forwards`,
            ['--bx']: Math.cos(b.a) * b.d + 'px', ['--by']: Math.sin(b.a) * b.d + 'px',
          }} />
        ))}
        <style>{`@keyframes boombit{
          0%{opacity:1;transform:translate(-50%,-50%) scale(1);}
          100%{opacity:0;transform:translate(calc(-50% + var(--bx)),calc(-50% + var(--by))) scale(.3) rotate(180deg);}
        }`}</style>
      </React.Fragment>
    );
  }
})();
