/* global React */
/* ──────────────────────────────────────────────────────────────
   screens.jsx — individual screen components
   ────────────────────────────────────────────────────────────── */

const { useState, useEffect, useMemo, useRef } = React;

// ──────────────────────────────────────────────────────────────
// Masthead — appears across all screens
// ──────────────────────────────────────────────────────────────

function Masthead({ issueNum, dateStr, weather }) {
  return (
    <header className="masthead">
      <div className="top-line">
        <span>Issue No. {issueNum}</span>
        <span>Springbrook · ELT</span>
      </div>
      <h1 className="title">The Morning <em>Brief</em></h1>
      <div className="tagline">A challenge accepted.</div>
      <div className="rule-pair">
        <span>{dateStr}</span>
        <span>{weather}</span>
      </div>
    </header>
  );
}

// ──────────────────────────────────────────────────────────────
// Intro screen
// ──────────────────────────────────────────────────────────────

function IntroScreen({ me, onBegin }) {
  const firstName = me.name.split(' ')[0];
  return (
    <div className="fade-in">
      <div className="section" style={{ marginTop: 32 }}>
        <div className="eyebrow ember">For your eyes only</div>
        <h2 className="serif" style={{ fontSize: 32, marginTop: 8, letterSpacing: '-0.01em', lineHeight: 1.15 }}>
          Good morning, {firstName}.
        </h2>
      </div>

      <p className="lead" style={{ marginTop: 22 }}>
        <span className="drop">L</span>ast night at Sixty Vines, Chris joked I&apos;d
        build something with AI during dinner. I didn&apos;t — the conversations were
        too good. So here it is for breakfast instead.
      </p>

      <div className="section">
        <div className="section-head">
          <h2 className="serif">What this is</h2>
          <span className="num">0:04 read</span>
        </div>

        <div className="body" style={{ display: 'grid', gap: 14 }}>
          <Step n="01" body={<>Four questions about the week. Then one slider about where you sit on the AI curve. Answers stay between us.</>} />
          <Step n="02" body={<>Once everyone files (or 11:40 hits), one entry from each of you goes into a quick anonymous vote. One pick — the coolest AI thing a peer did this week. Takes a minute.</>} />
          <Step n="03" body={<>Claude reads the room and writes a one-page synthesis. You see it in this same window.</>} />
        </div>

        <div className="tip">
          Be specific. Be a little uncareful. The point is not to look good — it&apos;s to find out where we actually are.
        </div>
      </div>

      <div className="sticky-action">
        <button className="btn ember block" onClick={onBegin}>
          Begin the briefing <span className="arrow">→</span>
        </button>
      </div>

      <div className="colophon">
        Filed by B. Bruschke
      </div>
    </div>
  );
}

function Step({ n, body }) {
  return (
    <div style={{ display: 'flex', gap: 14, alignItems: 'flex-start' }}>
      <div className="serif" style={{ fontSize: 26, color: 'var(--ember)', lineHeight: 1, marginTop: 2, width: 32, flexShrink: 0 }}>
        {n}
      </div>
      <div style={{ flex: 1, fontFamily: "'Fraunces', serif", fontSize: 16, lineHeight: 1.5 }}>
        {body}
      </div>
    </div>
  );
}

// ──────────────────────────────────────────────────────────────
// Submit screen — 4 questions + maturity
// ──────────────────────────────────────────────────────────────

function SubmitScreen({ me, onSubmit }) {
  const [answers, setAnswers] = useState({ q1: '', q2: '', q3: '', q4: '' });
  const [maturity, setMaturity] = useState(null);

  const missing = [];
  if (!answers.q1.trim()) missing.push(1);
  if (!answers.q2.trim()) missing.push(2);
  if (!answers.q3.trim()) missing.push(3);
  if (!answers.q4.trim()) missing.push(4);
  if (maturity == null) missing.push(5);
  const allAnswered = missing.length === 0;

  const set = (k) => (e) => setAnswers((a) => ({ ...a, [k]: e.target.value }));

  return (
    <div className="fade-in">
      <div className="section" style={{ marginTop: 28 }}>
        <div className="eyebrow ember">The questionnaire</div>
        <h2 className="serif" style={{ fontSize: 28, marginTop: 6, letterSpacing: '-0.01em', lineHeight: 1.15 }}>
          Four questions and a number.
        </h2>
        <p className="body muted" style={{ marginTop: 10 }}>
          Aim for honest over impressive. You can&apos;t edit after you file.
        </p>
      </div>

      <div className="section">
        {window.QUESTIONS.map((q) => (
          <div className="q" key={q.n}>
            <div className="q-num">QUESTION 0{q.n}</div>
            <div className="q-prompt">{q.prompt}</div>
            <div className="q-hint">{q.hint}</div>
            <textarea
              value={answers[`q${q.n}`]}
              onChange={set(`q${q.n}`)}
              placeholder={q.placeholder}
              rows={q.n === 3 ? 3 : 4}
            />
            <div className="charcount">
              {answers[`q${q.n}`].trim().length} chars
            </div>
          </div>
        ))}

        {/* Maturity */}
        <div className="q">
          <div className="q-num">QUESTION 05 · MATURITY</div>
          <div className="q-prompt">Where are you with AI?</div>
          <div className="q-hint">Honest. No one sees the individual number, only the shape of the room.</div>

          <div className="maturity">
            {window.MATURITY_LABELS.map((label, i) => (
              <button
                key={i}
                className={maturity === i + 1 ? 'active' : ''}
                onClick={() => setMaturity(i + 1)}
                type="button"
              >
                <span className="n">{i + 1}</span>
                <span className="lbl">{label}</span>
              </button>
            ))}
          </div>
          <div className="maturity-descriptor">
            {maturity ? `“${window.MATURITY_DESCRIPTORS[maturity - 1]}”` : ''}
          </div>
        </div>
      </div>

      <div className="sticky-action">
        <button
          className="btn ember block"
          disabled={!allAnswered}
          onClick={() => onSubmit({ ...answers, maturity, ts: Date.now() })}
        >
          {allAnswered ? <>File the brief <span className="arrow">→</span></> : `Missing: ${missing.map((n) => 'Q' + n).join(', ')}`}
        </button>
      </div>
    </div>
  );
}

// ──────────────────────────────────────────────────────────────
// Waiting screen — submitted, waiting for voting to open
// ──────────────────────────────────────────────────────────────

function WaitingScreen({ me, participants, submissions, deadlineISO }) {
  const filed = participants.filter((p) => submissions[p.id]);
  const remaining = participants.filter((p) => !submissions[p.id]);
  const [tick, setTick] = useState(0);
  useEffect(() => {
    const t = setInterval(() => setTick((x) => x + 1), 1000);
    return () => clearInterval(t);
  }, []);

  const msLeft = deadlineISO ? new Date(deadlineISO).getTime() - Date.now() : 0;
  const mins = Math.max(0, Math.floor(msLeft / 60000));
  const secs = Math.max(0, Math.floor((msLeft % 60000) / 1000));

  return (
    <div className="fade-in">
      <div className="section" style={{ marginTop: 28 }}>
        <div className="eyebrow ember">Brief filed</div>
        <h2 className="serif" style={{ fontSize: 30, marginTop: 6, letterSpacing: '-0.01em', lineHeight: 1.15 }}>
          Thanks. Holding for the rest.
        </h2>
        <p className="body muted" style={{ marginTop: 10 }}>
          Voting opens when everyone files — or at 11:40, whichever comes first.
        </p>
      </div>

      <div className="section">
        <div style={{ display: 'flex', gap: 18, alignItems: 'flex-end', justifyContent: 'space-between' }}>
          <div>
            <div className="eyebrow">Filed</div>
            <div className="counter">
              {filed.length}<span className="of">/{participants.length}</span>
            </div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <div className="eyebrow">Voting opens in</div>
            <div className="countdown" style={{ marginTop: 8 }}>
              <span className="num">{String(mins).padStart(2, '0')}:{String(secs).padStart(2, '0')}</span>
              <span>· or sooner</span>
            </div>
          </div>
        </div>

        {/* Progress bar */}
        <div style={{ height: 4, background: 'var(--card-2)', borderRadius: 2, marginTop: 14, overflow: 'hidden' }}>
          <div
            style={{
              width: `${(filed.length / participants.length) * 100}%`,
              background: 'var(--ember)', height: '100%',
              transition: 'width 600ms ease-out',
            }}
          />
        </div>
      </div>

      <div className="section">
        <div className="section-head">
          <h2 className="serif">Around the table</h2>
          <span className="num">{remaining.length} pending</span>
        </div>

        <ul className="status-list">
          {participants.map((p) => {
            const done = !!submissions[p.id];
            const isMe = p.id === me.id;
            return (
              <li key={p.id}>
                <span className={`dot ${done ? 'done' : ''} ${isMe ? 'you' : ''}`}></span>
                <span className="name">
                  {p.name}
                  {isMe ? <span className="me">— you</span> : null}
                </span>
                <span className="role">{p.role.replace('Chief ', 'C-').replace(' Officer', '')}</span>
              </li>
            );
          })}
        </ul>
      </div>

      <div className="tip">
        Refill your coffee. I&apos;ll push you to the vote the moment we&apos;re ready.
      </div>
    </div>
  );
}

// ──────────────────────────────────────────────────────────────
// Voting screen
// ──────────────────────────────────────────────────────────────

function VotingScreen({ me, entries, onSubmit }) {
  const [pickId, setPickId] = useState(null);
  const myEntryId = window.getEntryIdForParticipant(me.id);

  const choose = (entryId) => {
    if (entryId === myEntryId) return;
    setPickId((v) => (v === entryId ? null : entryId));
  };

  return (
    <div className="fade-in">
      <div className="section" style={{ marginTop: 28 }}>
        <div className="eyebrow ember">Voting open</div>
        <h2 className="serif" style={{ fontSize: 30, marginTop: 6, letterSpacing: '-0.01em', lineHeight: 1.15 }}>
          Pick the cool one.
        </h2>
        <p className="body muted" style={{ marginTop: 10 }}>
          Highlight a peer. Which one of these is the coolest AI thing someone
          did this week? Your own entry is grayed out — no self-votes.
        </p>
      </div>

      <div className="section vote-cat">
        <div>
          {entries.map((e) => {
            const isMine = e.id === myEntryId;
            const isSelected = pickId === e.id;
            return (
              <div
                key={e.id}
                className={`entry ${isSelected ? 'selected' : ''} ${isMine ? 'disabled' : ''}`}
                onClick={() => choose(e.id)}
              >
                <div className="entry-num">
                  {String(e.id.replace('entry-', '')).padStart(2, '0')}
                </div>
                <div className="entry-body">
                  {e.text}
                  {isMine && (
                    <div style={{ fontSize: 11, marginTop: 6, color: 'var(--ink-3)', fontStyle: 'italic' }}>
                      — this one&apos;s yours
                    </div>
                  )}
                </div>
                <span className="check">{isSelected ? '✓' : ''}</span>
              </div>
            );
          })}
        </div>
      </div>

      <div className="sticky-action">
        <button
          className="btn ember block"
          disabled={!pickId}
          onClick={() => onSubmit({ pick: pickId })}
        >
          {pickId ? <>Cast vote <span className="arrow">→</span></> : 'Pick one'}
        </button>
      </div>
    </div>
  );
}

// ──────────────────────────────────────────────────────────────
// Voted (waiting on synthesis) screen
// ──────────────────────────────────────────────────────────────

function VotedScreen({ me, voteCount, totalVoters }) {
  return (
    <div className="fade-in">
      <div className="section" style={{ marginTop: 28 }}>
        <div className="eyebrow ember">Votes cast</div>
        <h2 className="serif" style={{ fontSize: 30, marginTop: 6, letterSpacing: '-0.01em', lineHeight: 1.15 }}>
          Counted. Hold while Claude reads the room.
        </h2>
      </div>

      <div className="section">
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end' }}>
          <div>
            <div className="eyebrow">Ballots in</div>
            <div className="counter">{voteCount}<span className="of">/{totalVoters}</span></div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <span className="chip ember pulse">SYNTHESIZING</span>
          </div>
        </div>
        <div style={{ height: 4, background: 'var(--card-2)', borderRadius: 2, marginTop: 14, overflow: 'hidden' }}>
          <div
            style={{
              width: `${(voteCount / totalVoters) * 100}%`,
              background: 'var(--ember)', height: '100%',
              transition: 'width 600ms',
            }}
          />
        </div>
      </div>

      <div className="tip">
        Synthesis takes about 20 seconds. The page will refresh itself the moment it&apos;s ready.
      </div>
    </div>
  );
}

// ──────────────────────────────────────────────────────────────
// Results screen
// ──────────────────────────────────────────────────────────────

function ResultsScreen({ entries, votes, submissions, synthesis }) {
  // Tally single-pick votes
  const tally = useMemo(() => {
    const acc = {};
    Object.values(votes).forEach((v) => {
      if (!v || !v.pick) return;
      acc[v.pick] = (acc[v.pick] || 0) + 1;
    });
    return acc;
  }, [votes]);

  const podium = useMemo(() => {
    const ids = Object.keys(tally).sort((a, b) => tally[b] - tally[a]);
    return ids.map((id) => ({
      entry: entries.find((e) => e.id === id),
      author: window.getParticipantForEntryId(id),
      votes: tally[id],
    })).filter((p) => p.entry);
  }, [tally, entries]);

  // Maturity histogram
  const maturityCounts = [0, 0, 0, 0, 0];
  Object.values(submissions).forEach((s) => {
    if (s.maturity >= 1 && s.maturity <= 5) maturityCounts[s.maturity - 1] += 1;
  });
  const maxBar = Math.max(...maturityCounts, 1);

  return (
    <div className="fade-in">
      <div className="section" style={{ marginTop: 28 }}>
        <div className="eyebrow ember">Issue No. 001 · Round closed</div>
        <h2 className="serif" style={{ fontSize: 30, marginTop: 6, letterSpacing: '-0.01em', lineHeight: 1.15 }}>
          The read on the room.
        </h2>
      </div>

      {/* Synthesis — featured */}
      <div className="section">
        <div className="section-head">
          <h2 className="serif">Where we sit</h2>
          <span className="num">CLAUDE OPUS 4.7</span>
        </div>
        <div className="synthesis">
          <p>{synthesis.maturityRead}</p>
        </div>

        <div className="maturity-chart" style={{ marginTop: 18 }}>
          {maturityCounts.map((c, i) => (
            <div
              key={i}
              className={`bar ${c === 0 ? 'empty' : ''}`}
              style={{ height: `${(c / maxBar) * 100}%` }}
            >
              <span className="v">{c}</span>
            </div>
          ))}
        </div>
        <div className="maturity-labels">
          {window.MATURITY_LABELS.map((l) => <span key={l}>{l}</span>)}
        </div>
      </div>

      {/* Themes Q1 */}
      <div className="section">
        <div className="section-head">
          <h2 className="serif">What you wish AI would answer</h2>
          <span className="num">Q1 · 3 themes</span>
        </div>
        <div className="synthesis">
          {synthesis.themes_q1.map((t, i) => (
            <p key={i}>
              <span className="theme">{romanize(i + 1)}.</span> {t}
            </p>
          ))}
        </div>
      </div>

      {/* Themes Q2 */}
      <div className="section">
        <div className="section-head">
          <h2 className="serif">Where we&apos;d put the revenue energy</h2>
          <span className="num">Q2 · 3 themes</span>
        </div>
        <div className="synthesis">
          {synthesis.themes_q2.map((t, i) => (
            <p key={i}>
              <span className="theme">{romanize(i + 1)}.</span> {t}
            </p>
          ))}
        </div>
      </div>

      {/* Q3 paragraph */}
      <div className="section">
        <div className="section-head">
          <h2 className="serif">Who&apos;s ahead, and why</h2>
          <span className="num">Q3</span>
        </div>
        <div className="synthesis">
          <p>{synthesis.q3_paragraph}</p>
        </div>
      </div>

      {/* Winner */}
      <div className="section">
        <div className="section-head">
          <h2 className="serif">The cool one</h2>
          <span className="num">Q4 · winner</span>
        </div>

        {podium.slice(0, 1).map((w, i) => (
          <div className="winner" key={i}>
            <div className="award">
              The cool one
              <span className="votes">· {w.votes} {w.votes === 1 ? 'vote' : 'votes'}</span>
            </div>
            <div className="text">“{w.entry.text}”</div>
            <div className="byline">
              <span>—</span>
              <span className="name">{w.author?.name}</span>
              <span>·</span>
              <span>{w.author?.role}</span>
            </div>
          </div>
        ))}

        {podium.length > 1 && (
          <div style={{ marginTop: 18 }}>
            <div className="eyebrow" style={{ marginBottom: 8 }}>Runners up</div>
            {podium.slice(1, 4).map((w, i) => (
              <div className="winner" key={i} style={{ opacity: 0.85 }}>
                <div className="award">
                  {w.votes} {w.votes === 1 ? 'vote' : 'votes'}
                </div>
                <div className="text" style={{ fontSize: 15 }}>“{w.entry.text}”</div>
                <div className="byline">
                  <span>—</span>
                  <span className="name">{w.author?.name}</span>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      <div className="kicker">
        {synthesis.closing}
      </div>

      <div className="section">
        <div className="section-head">
          <h2 className="serif">A note from Brett</h2>
          <span className="num">2026-05-20</span>
        </div>
        <div className="synthesis">
          <p>
            It was genuinely great meeting all of you last night. I walked away
            with more energy than I have had in a long time — the conversations
            were sharper, warmer, and more honest than I had any right to expect
            from a first dinner. I am very excited to get to work with this
            team. Thank you for the welcome, and for indulging the little
            breakfast experiment. See you all very soon.
          </p>
          <p style={{ fontFamily: "'Fraunces', serif", fontStyle: 'italic', color: 'var(--ink-2)' }}>
            — Brett
          </p>
        </div>
      </div>

      <div className="colophon">
        Synthesis by Claude Opus 4.7 · {Object.keys(submissions).length} contributors · 1 cup of coffee
      </div>
    </div>
  );
}

function romanize(n) {
  return ['I', 'II', 'III', 'IV', 'V'][n - 1] || n;
}

// Expose
Object.assign(window, {
  Masthead,
  IntroScreen,
  SubmitScreen,
  WaitingScreen,
  VotingScreen,
  VotedScreen,
  ResultsScreen,
});
