// bdk-toys.jsx — the easter eggs: slot machine, runaway free-money button, Kev's face, fake popups.

const BDK_SYMBOLS = ['◆', '7', '$', 'K', '★'];

function SlotsApp() {
  const [reels, setReels] = React.useState(['$', '$', '$']);
  const [spinning, setSpinning] = React.useState(false);
  const [bal, setBal] = React.useState(100);
  const [msg, setMsg] = React.useState('PULL TO BEGIN YOUR JOURNEY.');
  const count = React.useRef(0);
  const stopped = React.useRef([true, true, true]);
  const timers = React.useRef([]);
  const boxRef = React.useRef(null);
  React.useEffect(() => () => { timers.current.forEach((t) => { clearTimeout(t); clearInterval(t); }); }, []);

  const settle = (f) => {
    if (f[0] === f[1] && f[1] === f[2]) {
      setBal((b) => Math.round((b + 485) * 100) / 100);
      setMsg('JACKPOT! +$485.00 (ALLEGEDLY)');
      window.BDKSOUND.play('jackpot');
      const r = boxRef.current && boxRef.current.getBoundingClientRect();
      if (r) window.bdkConfetti(r.left + r.width / 2, r.top + r.height / 2);
    } else if (f[0] === f[1] || f[1] === f[2] || f[0] === f[2]) {
      setBal((b) => Math.round((b + 2.42) * 100) / 100);
      setMsg('SO CLOSE. +$2.42. KEEP GOING (DON’T).');
    } else {
      setMsg(['HOUSE WINS. CLASSIC.', 'THAT ONE WAS RIGGED.', 'A LEARNING OPPORTUNITY.', 'VARIANCE. DEFINITELY VARIANCE.'][Math.floor(Math.random() * 4)]);
    }
  };

  const pull = () => {
    if (spinning) return;
    window.BDKSOUND.play('blip');
    count.current += 1;
    setSpinning(true);
    setBal((b) => Math.round((b - 4.85) * 100) / 100);
    setMsg('SPINNING. THIS IS THE ONE.');
    const rig = count.current % 6 === 4 || Math.random() < 0.05;
    const final = rig
      ? Array(3).fill(BDK_SYMBOLS[Math.floor(Math.random() * BDK_SYMBOLS.length)])
      : [0, 1, 2].map(() => BDK_SYMBOLS[Math.floor(Math.random() * BDK_SYMBOLS.length)]);
    stopped.current = [false, false, false];
    const iv = setInterval(() => {
      setReels((r) => r.map((s, i) => (stopped.current[i] ? s : BDK_SYMBOLS[Math.floor(Math.random() * BDK_SYMBOLS.length)])));
    }, 70);
    timers.current.push(iv);
    [620, 1080, 1540].forEach((t, i) => {
      timers.current.push(setTimeout(() => {
        stopped.current[i] = true;
        setReels((r) => r.map((s, j) => (j === i ? final[i] : s)));
        window.BDKSOUND.play('click');
        if (i === 2) {
          clearInterval(iv);
          setSpinning(false);
          settle(final);
        }
      }, t));
    });
  };

  return (
    <div ref={boxRef}>
      <div className="bdk-slot-bal">
        <span>BANKROLL</span>
        <span style={{ color: bal >= 100 ? 'var(--accent2)' : 'var(--bad)', fontWeight: 700 }}>
          ${bal.toFixed(2)}
        </span>
      </div>
      <div className="bdk-reels">
        {reels.map((s, i) => (
          <div key={i} className={'bdk-reel' + (spinning && !stopped.current[i] ? ' spin' : '')}>{s}</div>
        ))}
      </div>
      <p className="bdk-slot-msg">{msg}</p>
      <button className="bdk-cta" style={{ width: '100%', boxSizing: 'border-box' }} onClick={pull} disabled={spinning}>
        {spinning ? 'NO TOUCHING' : 'PULL ($4.85)'}
      </button>
      <p className="bdk-fine">RTP: vibes% · house edge: yes · winnings are emotional only</p>
    </div>
  );
}

function FreeMoneyApp() {
  const zone = React.useRef(null);
  const [pos, setPos] = React.useState({ x: 100, y: 72 });
  const [dodges, setDodges] = React.useState(0);
  const [claimed, setClaimed] = React.useState(false);
  const surrendered = dodges >= 12;

  const jump = () => {
    const z = zone.current;
    if (!z) return;
    const r = z.getBoundingClientRect();
    setPos({
      x: 8 + Math.random() * Math.max(10, r.width - 166),
      y: 8 + Math.random() * Math.max(10, r.height - 54),
    });
    setDodges((d) => d + 1);
    window.BDKSOUND.play('pop');
  };

  const onZoneMove = (e) => {
    if (claimed || surrendered) return;
    const z = zone.current;
    if (!z) return;
    const r = z.getBoundingClientRect();
    const cx = r.left + pos.x + 75;
    const cy = r.top + pos.y + 19;
    if (Math.hypot(e.clientX - cx, e.clientY - cy) < 85) jump();
  };

  const onBtnDown = (e) => {
    if (claimed) return;
    if (!surrendered) { e.preventDefault(); jump(); return; }
    setClaimed(true);
    window.BDKSOUND.play('jackpot');
    window.bdkConfetti(e.clientX, e.clientY);
  };

  return (
    <div>
      <p className="bdk-eyebrow">LIMITED TIME OFFER — NO CATCH WHATSOEVER</p>
      <p className="bdk-p">Claim your <b>FREE MONEY</b> below. Just click the button. Should be easy.</p>
      <div className="bdk-runzone" ref={zone} onPointerMove={onZoneMove}>
        {!claimed && (
          <button className="bdk-runbtn" style={{ left: pos.x, top: pos.y }} onPointerDown={onBtnDown}>
            {dodges === 0 ? 'CLAIM FREE MONEY' : surrendered ? 'FINE. CLICK ME.' : ['ALMOST HAD IT', 'TOO SLOW', 'NICE TRY', 'SO CLOSE'][dodges % 4]}
          </button>
        )}
        {claimed && (
          <div className="bdk-runwon">
            <b>YOU WON: CODE BDKev</b>
            <p className="bdk-p">Statistically worth more than free money.</p>
          </div>
        )}
      </div>
      <p className="bdk-runstats">CLAIM ATTEMPTS: {dodges} · SUCCESS RATE: {claimed ? '100%, EVENTUALLY' : '0%'}</p>
    </div>
  );
}

const BDK_QUOTES = [
  'Trust the process.',
  'This is a business expense.',
  'We’re so back.',
  'Per my last email: ALL IN.',
  'Circle back? I never left.',
  'Down bad is a temporary KPI.',
  'This IS the due diligence.',
  'Let’s take this offline. To the casino.',
];

function KevFace({ style, inline }) {
  const [bub, setBub] = React.useState(null);
  const [pulse, setPulse] = React.useState(0);
  const tm = React.useRef(null);
  const lastQ = React.useRef(-1);
  React.useEffect(() => () => clearTimeout(tm.current), []);

  const poke = () => {
    let i;
    do { i = Math.floor(Math.random() * BDK_QUOTES.length); } while (i === lastQ.current);
    lastQ.current = i;
    setBub(BDK_QUOTES[i]);
    setPulse((p) => p + 1);
    window.BDKSOUND.play('kev');
    clearTimeout(tm.current);
    tm.current = setTimeout(() => setBub(null), 2600);
  };

  return (
    <div className={'bdk-kev' + (inline ? ' inline' : '')} style={style} data-screen-label="Kev (clickable)">
      <button className="bdk-kev-face" key={pulse} style={pulse ? { animation: 'bdkShake .45s' } : null} onClick={poke} title="Click the CEO">
        <img src="bdk/assets/kev.jpg" alt="Biz Dev Kev" />
      </button>
      <span className="bdk-kev-badge">CEO ◆ BIZ DEV KEV</span>
      {bub ? <div className="bdk-bubble" key={'b' + pulse}>{bub}</div> : null}
    </div>
  );
}

function BdkMascot() {
  const pupils = React.useRef([]);
  React.useEffect(() => {
    const move = (e) => {
      pupils.current.forEach((p) => {
        if (!p) return;
        const off = p._off || { x: 0, y: 0 };
        const r = p.getBoundingClientRect();
        // anchor = the eye's resting center (rect minus the offset we applied)
        const ax = r.left + r.width / 2 - off.x;
        const ay = r.top + r.height / 2 - off.y;
        const dx = e.clientX - ax, dy = e.clientY - ay;
        const ang = Math.atan2(dy, dx);
        const dist = Math.min(r.width, Math.hypot(dx, dy) / 8);
        const nx = Math.cos(ang) * dist, ny = Math.sin(ang) * dist;
        p._off = { x: nx, y: ny };
        p.style.transform = 'translate(-50%,-50%) translate(' + nx + 'px,' + ny + 'px)';
      });
    };
    window.addEventListener('pointermove', move);
    return () => window.removeEventListener('pointermove', move);
  }, []);
  return (
    <div className="bdk-mascot" data-screen-label="Chairman YEET">
      <img className="bdk-mascot-img" src="bdk/assets/yeet/chairman-blank.png" alt="Chairman YEET" draggable="false" />
      <span className="bdk-pupil" style={{ left: '35.4%', top: '42.5%' }} ref={(el) => (pupils.current[0] = el)}></span>
      <span className="bdk-pupil" style={{ left: '67.4%', top: '43.3%' }} ref={(el) => (pupils.current[1] = el)}></span>
    </div>
  );
}

const BDK_POPUPS = [
  { t: 'SYSTEM ERROR', b: 'ERROR 0x485: PROFITS NOT FOUND.', btns: ['RETRY', 'ACCEPT LOSSES'], char: 'chairman-dizzy' },
  { t: 'LICENSE MANAGER', b: 'Your free trial of Financial Responsibility has expired.', btns: ['RENEW ($9.99)', 'NEVER'], char: 'gamba-scream' },
  { t: 'CALENDAR', b: 'Meeting invite: “Quick sync re: your bankroll” — declined automatically on your behalf.', btns: ['THANKS'], char: 'diego' },
  { t: 'FUN FACT', b: '99.2% of gamblers quit right before losing even more.* (*source: Kev)', btns: ['OK', 'OK BUT LOUDER'], char: 'gamba-flex' },
  { t: 'UPDATE AVAILABLE', b: 'KevOS v0.486 — patch notes: removed money.', btns: ['INSTALL', 'LATER', 'NO (CORRECT)'], char: 'chairman-phone' },
  { t: 'HELP', b: 'No.', btns: ['FAIR'], char: 'diego' },
];

function BdkPopup({ p, onClose, onRetry }) {
  return (
    <div className="bdk-popup" style={{ left: p.x, top: p.y }} data-screen-label={'Popup: ' + p.spec.t}>
      <div className="bdk-popup-title">
        <span>⚠ {p.spec.t}</span>
        <button className="bdkwin-btn" onClick={() => { window.BDKSOUND.play('click'); onClose(p.id); }}>×</button>
      </div>
      <div className="bdk-popup-body">
        <div className="bdk-popup-row">
          {p.spec.char ? <img className="bdk-popup-char" src={'bdk/assets/yeet/' + p.spec.char + '.png'} alt="" /> : null}
          <p>{p.spec.b}</p>
        </div>
        <div className="bdk-popup-btns">
          {p.spec.btns.map((b) => (
            <button
              key={b}
              className="bdk-popup-btn"
              onClick={() => {
                window.BDKSOUND.play('blip');
                onClose(p.id);
                if (b === 'RETRY') onRetry(p);
              }}
            >{b}</button>
          ))}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { SlotsApp, FreeMoneyApp, KevFace, BdkMascot, BdkPopup, BDK_POPUPS, BDK_QUOTES });
