// Stryke screens — settlement, mark paid, recap, standings, run it back
window.SCREENS = window.SCREENS || {};
const { useState: useS4, useEffect: useE4 } = React;

// ───────────────────────── Settlement ledger
function SettlementLedger() {
  const S = window.STU; const { nav, back, eng, round } = window.useStryke();
  const [showMath, setShowMath] = useS4(false);
  return (
    <Page footer={<Button variant="primary" full onClick={() => nav('markPaid')}>Confirm · mark who's paid</Button>}>
      <TopBar title="Settle up" onBack={back} sub="Minimized — fewest transfers" />
      <div style={{ padding: '4px 20px 16px' }}>
        {eng.transfers.length === 0
          ? <div style={{ padding: 24, textAlign: 'center', color: S.inkSoft, fontSize: 14 }}>All square — nobody owes anyone.</div>
          : eng.transfers.map((t, i) => (
            <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '16px 0', borderBottom: `1px solid ${S.line}` }}>
              <Avatar name={eng.nameOf(t.from)} size={42} />
              <svg width="26" height="16" viewBox="0 0 26 16" fill="none" style={{ flexShrink: 0 }}><path d="M2 8h20m0 0l-5-5m5 5l-5 5" stroke={S.inkFaint} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>
              <Avatar name={eng.nameOf(t.to)} size={42} dark />
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 14.5, fontWeight: 600 }}>{eng.nameOf(t.from)} → {eng.nameOf(t.to)}</div>
                <div style={{ fontSize: 11.5, color: S.inkSoft }}>Skins + dots, netted</div>
              </div>
              <div className="stu-num" style={{ fontSize: 22, fontWeight: 700 }}>${t.amount}</div>
            </div>
          ))}

        <div className="stu-tap" onClick={() => setShowMath(m => !m)} style={{ marginTop: 14, display: 'flex', alignItems: 'center', gap: 8, color: S.inkSoft, fontSize: 13, fontWeight: 600 }}>
          <span>{showMath ? 'Hide' : 'See'} the math</span>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" style={{ transform: showMath ? 'rotate(180deg)' : 'none', transition: 'transform .2s' }}><path d="M6 9l6 6 6-6" stroke={S.inkSoft} strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/></svg>
        </div>
        {showMath && (
          <div className="stu-in" style={{ marginTop: 10, padding: 16, background: S.surface, borderRadius: 16, display: 'flex', flexDirection: 'column', gap: 8 }}>
            {eng.leaderboard.map(p => (
              <div key={p.id} style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 13 }}>
                <span style={{ flex: 1, fontWeight: 600 }}>{p.name.split(' ')[0]}</span>
                <span className="stu-num" style={{ color: S.inkSoft }}>{p.skins}×${round.skinValue} + {p.dots}×${round.dotValue}</span>
                <span className="stu-num" style={{ width: 50, textAlign: 'right', fontWeight: 700, color: eng.netCash[p.id] >= 0 ? S.good : S.warn }}>{eng.netCash[p.id] >= 0 ? '+' : '−'}${Math.abs(eng.netCash[p.id])}</span>
              </div>
            ))}
            <div style={{ fontSize: 11, color: S.inkFaint, marginTop: 4 }}>Pot funded equally, rounded to $1. Three-way debts netted to the fewest transfers.</div>
          </div>
        )}
        <div style={{ marginTop: 16 }}><LegalNote /></div>
      </div>
    </Page>
  );
}

// ───────────────────────── Mark paid (external)
function MarkPaid() {
  const S = window.STU; const { nav, back, eng, paid, markPaid, flash } = window.useStryke();
  const allPaid = eng.transfers.every((t, i) => paid[`${t.from}-${t.to}`]);
  return (
    <Page footer={<Button variant={allPaid ? 'lime' : 'primary'} full onClick={() => nav('recap')}>{allPaid ? 'All settled · See the recap' : 'See the recap →'}</Button>}>
      <TopBar title="Mark paid" onBack={back} sub="Money moves outside Stryke" />
      <div style={{ padding: '4px 20px 16px', display: 'flex', flexDirection: 'column', gap: 10 }}>
        {eng.transfers.map((t, i) => {
          const key = `${t.from}-${t.to}`; const isPaid = paid[key];
          return (
            <div key={i} style={{ padding: 16, background: isPaid ? S.goodSoft : S.surface, borderRadius: 18, transition: 'background .2s' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                <Avatar name={eng.nameOf(t.from)} size={36} />
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 14.5, fontWeight: 600 }}>{eng.nameOf(t.from)} → {eng.nameOf(t.to)}</div>
                  <div className="stu-num" style={{ fontSize: 12.5, color: S.inkSoft }}>${t.amount}</div>
                </div>
                <button className="stu-btn stu-tap" onClick={() => { markPaid(key); if (!isPaid) flash('Marked paid'); }} style={{ background: isPaid ? S.good : S.ink, color: '#fff', borderRadius: 100, padding: '9px 16px', fontSize: 13 }}>{isPaid ? '✓ Paid' : 'Mark paid'}</button>
              </div>
              {!isPaid && (
                <div style={{ display: 'flex', gap: 8, marginTop: 12 }}>
                  <button className="stu-btn stu-tap" onClick={() => flash('Venmo handle copied')} style={{ flex: 1, background: S.white, color: S.ink, borderRadius: 100, padding: '9px', fontSize: 12.5 }}>Copy Venmo</button>
                  <button className="stu-btn stu-tap" onClick={() => flash('Reminder sent')} style={{ flex: 1, background: S.white, color: S.ink, borderRadius: 100, padding: '9px', fontSize: 12.5 }}>Remind</button>
                </div>
              )}
            </div>
          );
        })}
        <LegalNote style={{ marginTop: 4 }} />
      </div>
    </Page>
  );
}

// ───────────────────────── Confetti (celebratory)
function Confetti() {
  const S = window.STU;
  const bits = Array.from({ length: 22 }).map((_, i) => ({
    left: (i * 4.7 + (i % 3) * 7) % 100, delay: (i % 6) * 0.12, dur: 1.4 + (i % 4) * 0.25,
    c: i % 3 === 0 ? S.lime : i % 3 === 1 ? S.ink : S.limeDeep, w: 6 + (i % 3) * 2,
  }));
  return (
    <div style={{ position: 'absolute', inset: 0, overflow: 'hidden', pointerEvents: 'none', zIndex: 5 }}>
      {bits.map((b, i) => (
        <div key={i} style={{ position: 'absolute', top: -12, left: b.left + '%', width: b.w, height: b.w * 1.6, background: b.c, borderRadius: 2, animation: `stuConfetti ${b.dur}s ${b.delay}s ease-in forwards` }}></div>
      ))}
    </div>
  );
}

// ───────────────────────── Recap (the broadcast)
function Recap() {
  const S = window.STU; const { nav, back, eng, round, group, flash } = window.useStryke();
  const [tone, setTone] = useS4('funny');
  const [confetti, setConfetti] = useS4(true);
  useE4(() => { const t = setTimeout(() => setConfetti(false), 2600); return () => clearTimeout(t); }, []);
  const winner = eng.leaderboard[0];
  const headline = tone === 'funny'
    ? `${winner.name.split(' ')[0]} takes the skins; Gabe chokes the press on 17.`
    : `${winner.name.split(' ')[0]} wins Week ${round.week} at ${round.course}.`;
  const beats = [
    { k: 'Biggest mover', v: 'Dev', d: 'birdied 15–16 to steal 2nd' },
    { k: 'Choke of the day', v: 'Gabe', d: 'pressed the back, lost it on 17' },
    { k: 'Longest drive', v: 'Mike', d: '312 yds on the 9th' },
  ];
  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: S.white, position: 'relative' }}>
      {confetti && <Confetti />}
      <div className="stu-scroll" style={{ flex: 1 }}>
        {/* black broadcast header */}
        <div style={{ background: S.ink, color: '#fff', padding: '16px 22px 26px', borderRadius: '0 0 28px 28px', position: 'relative' }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <button className="stu-tap" onClick={back} style={{ border: 'none', background: 'rgba(255,255,255,0.12)', width: 34, height: 34, borderRadius: '50%', display: 'grid', placeItems: 'center', cursor: 'pointer' }}>
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none"><path d="M15 5l-7 7 7 7" stroke="#fff" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/></svg>
            </button>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, color: S.lime }}><Spark size={12} color={S.lime} /><span style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.05em', whiteSpace: 'nowrap' }}>THE RECAP · WK {round.week}</span></div>
          </div>
          <div className="stu-in" style={{ fontSize: 29, fontWeight: 700, letterSpacing: '-0.035em', lineHeight: 1.08, marginTop: 16 }}>{headline}</div>
          <div style={{ fontSize: 13, color: 'rgba(255,255,255,0.55)', marginTop: 10 }}>{round.course} · {eng.inRound.length} players · Skins + Dots</div>
        </div>

        <div style={{ padding: '18px 22px 0' }}>
          {/* winner band */}
          <div className="stu-in" style={{ display: 'flex', alignItems: 'center', gap: 14, background: S.lime, borderRadius: 20, padding: '16px 18px', animation: 'stuBump .5s ease' }}>
            <Avatar name={winner.name} size={52} dark />
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.04em', color: 'rgba(21,21,21,0.6)' }}>ROUND WINNER</div>
              <div style={{ fontSize: 21, fontWeight: 700, letterSpacing: '-0.03em', marginTop: 1 }}>{winner.name}</div>
            </div>
            <div style={{ textAlign: 'right' }}>
              <div className="stu-num" style={{ fontSize: 25, fontWeight: 700 }}>+${eng.netCash[winner.id]}</div>
              <div style={{ fontSize: 11, fontWeight: 600 }}>{winner.skins} skins · {winner.dots} dots</div>
            </div>
          </div>
        </div>

        {/* tone toggle */}
        <div style={{ padding: '16px 22px 0', display: 'flex', alignItems: 'center', gap: 10 }}>
          <Label>RECAP TONE</Label>
          <Segmented style={{ flex: 1, maxWidth: 200 }} options={[{ value: 'funny', label: 'Funny' }, { value: 'straight', label: 'Straight' }]} value={tone} onChange={setTone} />
        </div>

        <div style={{ padding: '12px 22px', display: 'grid', gap: 9 }}>
          {beats.map((b, i) => (
            <div key={i} style={{ padding: '13px 16px', background: S.surface, borderRadius: 16 }}>
              <div style={{ fontSize: 11, fontWeight: 700, color: S.inkSoft, letterSpacing: '0.03em' }}>{b.k.toUpperCase()}</div>
              <div style={{ fontSize: 14.5, marginTop: 3 }}><b style={{ fontWeight: 700 }}>{b.v}</b> <span style={{ color: S.inkSoft }}>— {b.d}</span></div>
            </div>
          ))}
        </div>
      </div>
      <div style={{ padding: '12px 22px calc(20px + env(safe-area-inset-bottom))', display: 'flex', gap: 10 }}>
        <Button variant="primary" full onClick={() => flash('Recap shared')}>Share recap</Button>
        <Button variant="outline" full onClick={() => nav('standings')}>Standings</Button>
      </div>
    </div>
  );
}

// ───────────────────────── Standings / history
function Standings() {
  const S = window.STU; const { nav, goTab, group } = window.useStryke();
  const season = [
    { name: 'Trevor Okafor', pts: 86, wins: 3, net: '+$58' },
    { name: 'Mike Reyes', pts: 74, wins: 2, net: '+$41' },
    { name: 'Dev Anand', pts: 68, wins: 1, net: '−$12' },
    { name: 'Gabe Munoz', pts: 52, wins: 1, net: '−$87' },
  ];
  const history = [
    { wk: '07', course: 'Pine Hollow', who: 'Trevor', go: () => nav('recap') },
    { wk: '06', course: 'Cypress Bend', who: 'Mike' },
    { wk: '05', course: 'Pine Hollow', who: 'Dev' },
    { wk: '04', course: 'The Knoll', who: 'Trevor' },
  ];
  return (
    <Page tab={<TabBar active="standings" onNav={goTab} />} footer={<Button variant="lime" full onClick={() => nav('runItBack')} icon={<Spark size={14} />}>Run it back</Button>}>
      <TopBar title="Standings" sub={`${group.name} · Season 2026`} />
      <div style={{ padding: '4px 20px 8px' }}>
        <Label>SEASON LEADERBOARD</Label>
        <div style={{ marginTop: 10, display: 'flex', flexDirection: 'column', gap: 8 }}>
          {season.map((p, i) => (
            <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 13, padding: '12px 14px', background: i === 0 ? S.ink : S.surface, color: i === 0 ? '#fff' : S.ink, borderRadius: 16 }}>
              <div className="stu-num" style={{ width: 16, fontSize: 15, fontWeight: 600, color: i === 0 ? S.lime : S.inkFaint }}>{i + 1}</div>
              <Avatar name={p.name} size={36} lime={i === 0} dark={i !== 0 && false} />
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 14.5, fontWeight: 600 }}>{p.name}</div>
                <div style={{ fontSize: 11.5, color: i === 0 ? 'rgba(255,255,255,0.6)' : S.inkSoft }}>{p.wins} wins · {p.net} season</div>
              </div>
              <div className="stu-num" style={{ fontSize: 20, fontWeight: 700 }}>{p.pts}</div>
            </div>
          ))}
        </div>

        {/* rivalry */}
        <div style={{ marginTop: 18, padding: 16, background: S.surface, borderRadius: 18, display: 'flex', alignItems: 'center', gap: 12 }}>
          <Spark size={15} />
          <div style={{ flex: 1, fontSize: 13, lineHeight: 1.4 }}><b>Rivalry:</b> Trevor leads Mike <span className="stu-num">4–3</span> head-to-head this season.</div>
        </div>

        <Label style={{ marginTop: 22 }}>ROUND HISTORY</Label>
        <div style={{ marginTop: 10, display: 'flex', flexDirection: 'column' }}>
          {history.map((r, i) => (
            <div key={i} className={r.go ? 'stu-tap' : ''} onClick={r.go} style={{ display: 'flex', alignItems: 'center', gap: 13, padding: '13px 0', borderBottom: `1px solid ${S.line}` }}>
              <div className="stu-num" style={{ width: 42, height: 42, borderRadius: 13, background: S.surface, display: 'grid', placeItems: 'center', fontSize: 14, fontWeight: 600 }}>{r.wk}</div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 14, fontWeight: 600 }}>Week {parseInt(r.wk)} · {r.course}</div>
                <div style={{ fontSize: 12, color: S.inkSoft }}>Won by {r.who}</div>
              </div>
              {r.go && <span style={{ fontSize: 12, fontWeight: 700, color: S.inkSoft }}>Recap →</span>}
            </div>
          ))}
        </div>
      </div>
    </Page>
  );
}

// ───────────────────────── Run it back
function RunItBack() {
  const S = window.STU; const { nav, back, group, round, players } = window.useStryke();
  return (
    <Page footer={<Button variant="lime" full onClick={() => nav('invite')} icon={<Spark size={14} />}>Create round · invite the crew</Button>}>
      <TopBar title="Run it back" onBack={back} />
      <div style={{ padding: '4px 20px 16px' }}>
        <div style={{ fontSize: 28, fontWeight: 700, letterSpacing: '-0.035em', lineHeight: 1.05 }}>Same crew,<br/>next Saturday.</div>
        <div style={{ fontSize: 14, color: S.inkSoft, marginTop: 8 }}>Stryke cloned your last setup. Tweak anything, then invite.</div>

        <div style={{ marginTop: 20, background: S.surface, borderRadius: 20, padding: 18, display: 'flex', flexDirection: 'column', gap: 2 }}>
          {[
            { k: 'Group', v: group.name, go: 'createGroup' },
            { k: 'Course', v: round.course, go: 'createRound' },
            { k: 'Format', v: 'Skins + Dots', go: 'chooseFormat' },
            { k: 'Stakes', v: `$${round.skinValue}/skin · $${round.dotValue}/dot`, go: 'gameSetup' },
            { k: 'Players', v: `${players.length} · same roster`, go: 'invite' },
          ].map((r, i, arr) => (
            <div key={i} className="stu-tap" onClick={() => nav(r.go)} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '13px 0', borderBottom: i < arr.length - 1 ? `1px solid ${S.lineMid}` : 'none' }}>
              <div style={{ width: 76, fontSize: 12.5, fontWeight: 700, color: S.inkSoft }}>{r.k}</div>
              <div style={{ flex: 1, fontSize: 14.5, fontWeight: 600 }}>{r.v}</div>
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none"><path d="M9 6l6 6-6 6" stroke={S.inkFaint} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>
            </div>
          ))}
        </div>

        <div style={{ marginTop: 16, padding: 16, background: S.ink, color: '#fff', borderRadius: 18, display: 'flex', alignItems: 'center', gap: 11 }}>
          <Spark size={15} color={S.lime} />
          <div style={{ fontSize: 13, lineHeight: 1.4 }}>The whole crew gets a tap-to-join link the moment you create it. Setup done in <span className="stu-num">~38s</span>.</div>
        </div>
      </div>
    </Page>
  );
}

// ───────────────────────── Rounds list (current + history)
function Rounds() {
  const S = window.STU; const { nav, goTab, group, eng } = window.useStryke();
  const leader = eng.leaderboard[0];
  const past = [
    { wk: 6, course: 'Cypress Bend', who: 'Mike', tag: 'Nassau', net: '+$22' },
    { wk: 5, course: 'Pine Hollow', who: 'Dev', tag: 'Skins', net: '+$9' },
    { wk: 4, course: 'The Knoll', who: 'Trevor', tag: 'Skins · Dots', net: '+$17' },
    { wk: 3, course: 'Cypress Bend', who: 'Trevor', tag: 'Skins', net: '+$6' },
  ];
  return (
    <Page tab={<TabBar active="rounds" onNav={goTab} />} footer={<Button variant="primary" full onClick={() => nav('createRound')} icon={<span style={{ fontSize: 17, marginTop: -2 }}>+</span>}>New round</Button>}>
      <TopBar title="Rounds" sub={group.name} />
      <div style={{ padding: '4px 20px 8px' }}>
        <Label>IN PROGRESS</Label>
        <div style={{ marginTop: 10, background: S.ink, color: '#fff', borderRadius: 20, padding: 18 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <span className="stu-live-dot" style={{ width: 8, height: 8, borderRadius: '50%', background: S.lime, display: 'inline-block' }}></span>
            <span style={{ fontSize: 11.5, fontWeight: 700, letterSpacing: '0.04em', color: S.lime, whiteSpace: 'nowrap' }}>LIVE · THRU {eng.holesPlayed}</span>
          </div>
          <div style={{ fontSize: 21, fontWeight: 700, letterSpacing: '-0.03em', marginTop: 10 }}>Week 7 · Pine Hollow</div>
          <div style={{ fontSize: 13, color: 'rgba(255,255,255,0.62)', marginTop: 4 }}>Skins + Dots · {eng.inRound.length} players · {leader.name.split(' ')[0]} leads with {leader.skins} skins</div>
          <div style={{ display: 'flex', gap: 8, marginTop: 16 }}>
            <button className="stu-btn stu-tap" onClick={() => nav('liveScore')} style={{ background: S.lime, color: S.ink, borderRadius: 100, padding: '11px 18px', fontSize: 13.5 }}>Resume scoring</button>
            <button className="stu-btn stu-tap" onClick={() => nav('leaderboard')} style={{ background: 'rgba(255,255,255,0.1)', color: '#fff', borderRadius: 100, padding: '11px 18px', fontSize: 13.5 }}>Leaderboard</button>
          </div>
        </div>

        <Label style={{ marginTop: 24 }}>PAST ROUNDS</Label>
        <div style={{ marginTop: 10, display: 'flex', flexDirection: 'column' }}>
          {past.map((r, i) => (
            <div key={i} className="stu-tap" onClick={() => nav('recap')} style={{ display: 'flex', alignItems: 'center', gap: 13, padding: '14px 0', borderBottom: `1px solid ${S.line}` }}>
              <div className="stu-num" style={{ width: 44, height: 44, borderRadius: 14, background: S.surface, display: 'grid', placeItems: 'center', fontSize: 15, fontWeight: 600, flexShrink: 0 }}>{String(r.wk).padStart(2, '0')}</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 14.5, fontWeight: 600 }}>Week {r.wk} · {r.course}</div>
                <div style={{ fontSize: 12.5, color: S.inkSoft, marginTop: 1 }}>{r.tag} · Won by {r.who}</div>
              </div>
              <div style={{ textAlign: 'right', flexShrink: 0 }}>
                <div className="stu-num" style={{ fontSize: 14, fontWeight: 700, color: S.good, whiteSpace: 'nowrap' }}>{r.net}</div>
                <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: '0.04em', color: S.inkFaint, marginTop: 2 }}>SETTLED</div>
              </div>
            </div>
          ))}
        </div>

        <button className="stu-btn stu-tap" onClick={() => goTab('standings')} style={{ marginTop: 16, background: S.surface, color: S.ink, width: '100%', padding: '13px', borderRadius: 14, fontSize: 13.5 }}>View season standings →</button>
      </div>
    </Page>
  );
}

Object.assign(window.SCREENS, { settlement: SettlementLedger, markPaid: MarkPaid, recap: Recap, standings: Standings, runItBack: RunItBack, rounds: Rounds });
