// iso-demo.jsx
// The live poll that the whole toy city is voting on. Two pieces:
//   • IsoMonitor  — a chunky retro CRT sitting in the scene, screen = LivePoll
//   • DemoLightbox — the full, interactive demo (vote from a phone, watch live)
// Colours come from CSS vars (--c-*) so the Tweaks palette flows through.

const OPTIONS = [
  { label: 'Single-origin', votes: 132, key: 'primary' },
  { label: 'House blend',   votes: 74,  key: 'blue' },
  { label: 'Decaf',         votes: 23,  key: 'amber' },
  { label: 'Tea, actually', votes: 14,  key: 'green' },
];

// Slowly trickle votes in so the screen feels alive (ambient, subtle).
function useLiveVotes(start, on = true) {
  const [votes, setVotes] = React.useState(start);
  React.useEffect(() => {
    if (!on) return;
    let timer;
    const tick = () => setVotes((v) => {
      const w = v.map((n) => n + 2), sum = w.reduce((a, b) => a + b, 0);
      let r = Math.random() * sum, idx = 0;
      for (let i = 0; i < w.length; i++) { r -= w[i]; if (r <= 0) { idx = i; break; } }
      const next = v.slice(); next[idx] += 1; return next;
    });
    const loop = () => { timer = setTimeout(() => { tick(); loop(); }, 900 + Math.random() * 1100); };
    loop();
    return () => clearTimeout(timer);
  }, [on]);
  return [votes, setVotes];
}

// ── The in-scene screen: a COMPACT Google Slides editor (teaser) ───────────
function MiniEditor({ ambient = true }) {
  const [votes] = useLiveVotes(OPTIONS.map((o) => o.votes), ambient);
  const total = votes.reduce((a, b) => a + b, 0);
  const pct = (n) => Math.round((n / total) * 100);
  return (
    <div className="mini-ed">
      <div className="mini-bar">
        <span className="mini-logo" aria-hidden="true"><i /><i /><i /></span>
        <span className="mini-title">Interactive Demo</span>
        <span className="mini-sp" />
        <span className="mini-present">▶ Present</span>
      </div>
      <div className="mini-body">
        <div className="mini-rail">
          <span className="mt active"><i /><i /></span>
          <span className="mt" />
          <span className="mt" />
        </div>
        <div className="mini-canvas">
          <div className="mini-slide">
            <div className="mini-kick"><i className="dot" /> LIVE · {total} votes</div>
            <div className="mini-q">How are you brewing the team?</div>
            {OPTIONS.map((o, i) => (
              <div className="mini-opt" key={o.label}>
                <span className="mini-lbl">{o.label}</span>
                <span className="mini-track"><span className={'mini-fill c-' + o.key} style={{ width: pct(votes[i]) + '%' }} /></span>
                <span className="mini-pct">{pct(votes[i])}%</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

// ── The monitor housing — a chunky 90s computer showing Slides ─────────────
function IsoMonitor({ onOpen, ambient }) {
  return (
    <div className="iso-monitor">
      <button className="crt" onClick={onOpen} aria-label="Open the live interactive demo">
        <span className="crt-screen"><MiniEditor ambient={ambient} /></span>
        <span className="crt-chin">
          <span className="crt-led" />
          <span className="crt-brand">doppio ◆</span>
          <span className="crt-knob" />
        </span>
      </button>
      <span className="crt-badge"><span className="crt-play">▶</span> try the live demo</span>
    </div>
  );
}

// ── Full interactive demo ───────────────────────────────────────────────────
function DemoLightbox({ onClose }) {
  const [votes, setVotes] = useLiveVotes(OPTIONS.map((o) => o.votes), true);
  const [userVote, setUserVote] = React.useState(null);
  const total = votes.reduce((a, b) => a + b, 0);
  const pct = (n) => (total ? Math.round((n / total) * 100) : 0);

  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', onKey);
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => { document.removeEventListener('keydown', onKey); document.body.style.overflow = prev; };
  }, [onClose]);

  const cast = (i) => {
    setVotes((v) => {
      const next = v.slice();
      if (userVote !== null) next[userVote] = Math.max(0, next[userVote] - 1);
      next[i] += 1; return next;
    });
    setUserVote(i);
  };

  // a little live "room" of voxel heads — count grows with the vote total
  const crowdKeys = ['primary', 'blue', 'amber', 'green', 'purple'];
  const crowd = Array.from({ length: 26 }, (_, i) => crowdKeys[(i * 3 + 1) % crowdKeys.length]);

  return (
    <div className="lb-back" onMouseDown={onClose}>
      <div className="ed" onMouseDown={(e) => e.stopPropagation()}>

        {/* title bar */}
        <div className="ed-bar">
          <span className="ed-logo" aria-hidden="true"><i /><i /><i /></span>
          <span className="ed-title">Interactive Demo</span>
          <span className="ed-file">doppio.slides</span>
          <span className="ed-spacer" />
          <span className="ed-livechip"><i /> LIVE</span>
          <button className="ed-present" type="button">▶ Present</button>
          <button className="ed-share" type="button">Share</button>
          <button className="ed-x" onClick={onClose} aria-label="Close demo">×</button>
        </div>

        {/* toolbar */}
        <div className="ed-tools">
          <button className="tbtn wide" type="button">+ <span>Slide</span></button>
          <span className="tsep" />
          <button className="tbtn" type="button" title="Text">T</button>
          <button className="tbtn" type="button" title="Box">▢</button>
          <button className="tbtn" type="button" title="Circle">◯</button>
          <button className="tbtn" type="button" title="Line">—</button>
          <span className="tsep" />
          <button className="tbtn" type="button" title="Upload"><svg width="13" height="13" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M7 9.2V2M4 5l3-3 3 3M2.5 11.5h9" /></svg></button>
          <span className="ed-tools-r">Slide 2 of 4 · doppio ◆</span>
        </div>

        {/* editor body */}
        <div className="ed-body">

          {/* slide rail */}
          <div className="ed-rail">
            <div className="ed-th active">
              <span className="ed-th-n">2</span>
              <div className="ed-th-poll">
                <i className="c-primary" style={{ width: '70%' }} />
                <i className="c-blue" style={{ width: '46%' }} />
                <i className="c-amber" style={{ width: '24%' }} />
              </div>
            </div>
            <div className="ed-th">
              <span className="ed-th-n">1</span>
              <div className="ed-th-cover"><b>Q4</b><span>kickoff</span></div>
            </div>
            <div className="ed-th">
              <span className="ed-th-n">3</span>
              <div className="ed-th-metrics"><i /><i /><i /></div>
            </div>
            <div className="ed-th">
              <span className="ed-th-n">4</span>
              <div className="ed-th-cloud"><b>focus</b><span>ship</span><em>trust</em></div>
            </div>
            <button className="ed-th add" type="button">+</button>
          </div>

          {/* canvas with the live slide */}
          <div className="ed-canvas">
            <div className="ed-slide">
              <div className="ed-kick"><span className="dot" /> LIVE · <b>{total} votes</b> · slide 2</div>
              <h3 className="ed-q">How are you brewing the team?</h3>
              <div className="ed-opts">
                {OPTIONS.map((o, i) => (
                  <div className="ed-opt" key={o.label}>
                    <div className="ed-opt-h">
                      <span className="ed-opt-lbl">{o.label}{userVote === i && <span className="you">your vote</span>}</span>
                      <span className="ed-opt-pct">{pct(votes[i])}<span className="v">%</span></span>
                    </div>
                    <div className="ed-track"><div className={'ed-fill c-' + o.key} style={{ width: pct(votes[i]) + '%' }} /></div>
                  </div>
                ))}
              </div>
              <div className="ed-crowd">
                <span className="ed-crowd-row">{crowd.map((c, i) => <i key={i} className={'c-' + c} />)}</span>
                <span className="ed-crowd-n">{total} in the room</span>
              </div>
            </div>
          </div>

          {/* audience / voting panel */}
          <div className="ed-side">
            <div className="ed-side-lbl">Audience · tap to vote</div>
            <div className="ed-phone">
              <div className="ed-phone-notch" />
              <div className="ed-phone-head"><span>◆ doppio</span><span className="code">DPP-42</span></div>
              <div className="ed-phone-q">How are you brewing the team?</div>
              {OPTIONS.map((o, i) => (
                <button key={o.label} className={'ed-vote' + (userVote === i ? ' cast' : '')} onClick={() => cast(i)}>
                  <span>{o.label}</span><span className="tick">✓</span>
                </button>
              ))}
              <div className="ed-phone-hint">{userVote === null ? 'tap an option to vote' : 'tap another to change'}</div>
            </div>
            <div className="ed-stats">
              <div className="ed-stat"><span>responses</span><span className="v big">{total}</span></div>
              <div className="ed-stat"><span>join code</span><span className="v acc">DPP-42</span></div>
              <div className="ed-stat"><span>link</span><span className="v">doppio.us</span></div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { MiniEditor, IsoMonitor, DemoLightbox });
