// Stryke screens — round play
window.SCREENS = window.SCREENS || {};
const { useState: useS3, useEffect: useE3, useRef: useR3 } = React;

// ───────────────────────── Round dashboard / hub (scoring-path fork)
function RoundDashboard() {
  const S = window.STU; const { nav, back, group, round, players, eng } = window.useStryke();
  const inProgress = eng.holesPlayed > 0;
  return (
    <Page footer={
      <div style={{ display: 'flex', gap: 10 }}>
        <Button variant="soft" full onClick={() => nav('leaderboard')}>Leaderboard</Button>
        <Button variant="primary" full onClick={() => nav('settlement')}>Settle up</Button>
      </div>
    }>
      <TopBar title={`${group.name} · Wk ${round.week}`} onBack={back} sub={`${round.course} · ${players.length} players`} right={inProgress ? <Chip style={{ background: S.ink, color: '#fff' }}><span className="stu-live-dot" style={{ width: 6, height: 6, borderRadius: '50%', background: S.lime }}></span> THRU {eng.holesPlayed}</Chip> : null} />
      <div style={{ padding: '6px 20px 16px' }}>
        {/* scoring path fork */}
        <Label>HOW ARE YOU SCORING?</Label>
        <div style={{ display: 'flex', gap: 12, marginTop: 10 }}>
          <div className="stu-tap stu-press" onClick={() => nav('liveScore')} style={{ flex: 1, background: S.ink, color: '#fff', borderRadius: 20, padding: 18 }}>
            <div style={{ width: 42, height: 42, borderRadius: 13, background: 'rgba(255,255,255,0.1)', display: 'grid', placeItems: 'center', marginBottom: 14 }}>
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none"><path d="M5 12h14M12 5v14" stroke={S.lime} strokeWidth="2.4" strokeLinecap="round"/></svg>
            </div>
            <div style={{ fontSize: 16, fontWeight: 700 }}>Score live</div>
            <div style={{ fontSize: 12.5, color: 'rgba(255,255,255,0.6)', marginTop: 4, lineHeight: 1.35 }}>Tap in each hole. Leaderboard updates instantly.</div>
          </div>
          <div className="stu-tap stu-press" onClick={() => nav('kitScan')} style={{ flex: 1, background: S.surface, borderRadius: 20, padding: 18 }}>
            <div style={{ width: 42, height: 42, borderRadius: 13, background: S.lime, display: 'grid', placeItems: 'center', marginBottom: 14 }}>
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none"><path d="M4 8V5a1 1 0 011-1h3M16 4h3a1 1 0 011 1v3M20 16v3a1 1 0 01-1 1h-3M8 20H5a1 1 0 01-1-1v-3" stroke={S.ink} strokeWidth="2.2" strokeLinecap="round"/></svg>
            </div>
            <div style={{ fontSize: 16, fontWeight: 700 }}>Captain Kit</div>
            <div style={{ fontSize: 12.5, color: S.inkSoft, marginTop: 4, lineHeight: 1.35 }}>Play on paper. Snap the card — Stryke reads it.</div>
          </div>
        </div>

        {/* games + stakes */}
        <Label style={{ marginTop: 24 }}>GAMES</Label>
        <div style={{ marginTop: 10, display: 'flex', flexWrap: 'wrap', gap: 8 }}>
          {round.formats.skins && <Chip active>Skins · ${round.skinValue}</Chip>}
          {round.formats.dots && <Chip active>Dots · ${round.dotValue}</Chip>}
          {round.formats.nassau && <Chip active>Nassau</Chip>}
          {round.formats.teams && <Chip active>Best Ball</Chip>}
          <Chip onClick={() => nav('chooseFormat')}>+ Edit</Chip>
        </div>

        {/* roster */}
        <Label style={{ marginTop: 24 }}>PLAYERS</Label>
        <div style={{ marginTop: 10, display: 'flex', flexDirection: 'column', gap: 8 }}>
          {eng.leaderboard.map((p, i) => (
            <div key={p.id} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 14px', background: S.surface, borderRadius: 14 }}>
              <Avatar name={p.name} size={36} dark={p.captain} />
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 14, fontWeight: 600 }}>{p.name}{p.captain && <span style={{ color: S.inkSoft, fontWeight: 500, fontSize: 11.5 }}> · You</span>}</div>
                <div style={{ fontSize: 11.5, color: S.inkSoft }}>HCP {p.hcp} · {p.joined ? 'In the game' : 'Not joined'}</div>
              </div>
              <div className="stu-num" style={{ fontSize: 13, color: S.inkSoft }}>{p.skins} skins</div>
            </div>
          ))}
        </div>
        <div style={{ marginTop: 16 }}><LegalNote /></div>
      </div>
    </Page>
  );
}

// ───────────────────────── Live hole scoring
function LiveHoleScoring() {
  const S = window.STU; const { nav, back, players, scores, setScore, round, dots, toggleDot, eng, flash } = window.useStryke();
  const [hole, setHole] = useS3(eng.holesPlayed >= 18 ? 18 : Math.min(eng.holesPlayed + 1, 18));
  const par = window.PARS[hole - 1]; const si = window.SI[hole - 1];
  const liveDotTypes = ['Closest to pin', 'Longest drive', 'Birdie'];
  const get = (pid) => (scores[pid] || {})[hole] ?? par;
  const dotFor = (type) => dots.find(d => d.type === type && d.hole === hole)?.player;

  return (
    <Page footer={
      <Button variant={hole >= 18 ? 'lime' : 'primary'} full onClick={() => {
        players.forEach(p => { if ((scores[p.id] || {})[hole] == null) setScore(p.id, hole, par); });
        if (hole >= 18) { flash('Round complete'); nav('settlement'); }
        else { setHole(h => h + 1); flash('Hole ' + hole + ' saved'); document.querySelector('.stu-scroll')?.scrollTo(0, 0); }
      }}>{hole >= 18 ? 'Finish round · Settle up' : 'Save & next hole →'}</Button>
    }>
      <TopBar title={`Hole ${hole}`} onBack={back} sub={`Par ${par} · Stroke index ${si}`} right={<span className="stu-tap" onClick={() => nav('leaderboard')} style={{ fontSize: 13, fontWeight: 700, color: S.ink }}>Standings</span>} />
      {/* hole strip */}
      <div className="stu-scroll" style={{ display: 'flex', gap: 6, padding: '2px 20px 12px', overflowX: 'auto' }}>
        {Array.from({ length: 18 }).map((_, i) => {
          const h = i + 1; const done = players.every(p => (scores[p.id] || {})[h] != null);
          return (
            <button key={h} className="stu-btn stu-num" onClick={() => setHole(h)} style={{
              flexShrink: 0, width: 36, height: 36, borderRadius: 11, fontSize: 13, fontWeight: 700,
              background: h === hole ? S.ink : done ? S.surface : S.white, color: h === hole ? '#fff' : done ? S.ink : S.inkFaint,
              boxShadow: h === hole ? 'none' : `inset 0 0 0 1.5px ${S.line}`,
            }}>{h}</button>
          );
        })}
      </div>

      <div style={{ padding: '0 20px 8px', display: 'flex', flexDirection: 'column', gap: 10 }}>
        {players.map(p => {
          const strokes = window.strokesOn(p.hcp, hole);
          const g = get(p.id); const net = g - strokes; const rel = g - par;
          return (
            <div key={p.id} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 14px', background: S.surface, borderRadius: 18 }}>
              <Avatar name={p.name} size={40} dark={p.captain} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 14.5, fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{p.name.split(' ')[0]}</div>
                <div style={{ fontSize: 11.5, color: S.inkSoft, display: 'flex', gap: 6, alignItems: 'center', marginTop: 2 }}>
                  {strokes > 0 && <span style={{ display: 'inline-flex', alignItems: 'center', gap: 3 }}><span style={{ width: 6, height: 6, borderRadius: '50%', background: S.lime, display: 'inline-block' }}></span>{strokes} stroke</span>}
                  {round.netGross === 'net' && <span className="stu-num">net {net}</span>}
                </div>
              </div>
              <div className="stu-num" style={{ width: 30, textAlign: 'center', fontSize: 12, fontWeight: 700, color: rel < 0 ? S.good : rel > 0 ? S.inkFaint : S.inkSoft }}>{rel === 0 ? 'E' : rel > 0 ? '+' + rel : rel}</div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <button className="stu-btn" onClick={() => setScore(p.id, hole, Math.max(1, g - 1))} style={{ width: 42, height: 42, borderRadius: '50%', background: S.white, fontSize: 22 }}>−</button>
                <div key={g} className="stu-num" style={{ width: 34, textAlign: 'center', fontSize: 27, fontWeight: 600, animation: 'stuBump .26s ease' }}>{g}</div>
                <button className="stu-btn" onClick={() => setScore(p.id, hole, g + 1)} style={{ width: 42, height: 42, borderRadius: '50%', background: S.ink, color: '#fff', fontSize: 22 }}>+</button>
              </div>
            </div>
          );
        })}

        {/* dots this hole */}
        {round.formats.dots && (
          <div style={{ padding: 16, background: S.surface, borderRadius: 18 }}>
            <Label>DOTS ON THIS HOLE</Label>
            <div style={{ marginTop: 12, display: 'flex', flexDirection: 'column', gap: 12 }}>
              {liveDotTypes.map(type => (
                <div key={type} style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                  <div style={{ flex: 1, fontSize: 13, fontWeight: 600 }}>{type}</div>
                  <div style={{ display: 'flex', gap: 6 }}>
                    {players.map(p => {
                      const on = dotFor(type) === p.id;
                      return <div key={p.id} className="stu-tap" onClick={() => toggleDot(type, hole, on ? null : p.id, round.dotValue)} style={{ borderRadius: '50%', boxShadow: on ? `0 0 0 2px ${S.ink}` : 'none' }}><Avatar name={p.name} size={32} lime={on} /></div>;
                    })}
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
    </Page>
  );
}

// ───────────────────────── Live leaderboard (animated reorder)
function LiveLeaderboard() {
  const S = window.STU; const { nav, back, eng, round } = window.useStryke();
  const rowH = 70;
  const board = eng.leaderboard;
  const leader = board[0];
  return (
    <Page footer={<div style={{ display: 'flex', gap: 10 }}>
      <Button variant="soft" full onClick={() => nav('sideGames')}>Side games</Button>
      <Button variant="primary" full onClick={() => nav('liveScore')}>Score a hole</Button>
    </div>}>
      <TopBar title="Leaderboard" onBack={back} right={<Chip style={{ background: S.ink, color: '#fff' }}><span className="stu-live-dot" style={{ width: 6, height: 6, borderRadius: '50%', background: S.lime }}></span> THRU {eng.holesPlayed}</Chip>} />
      <div style={{ padding: '4px 20px 8px' }}>
        {/* skins pot */}
        <div style={{ background: S.surface, borderRadius: 18, padding: '15px 18px', display: 'flex', alignItems: 'center' }}>
          <div style={{ flex: 1 }}>
            <Label>SKINS POT · CARRYOVER</Label>
            <div style={{ fontSize: 15, fontWeight: 600, marginTop: 3 }}>{eng.carryNow ? `${eng.carryNow} skin${eng.carryNow > 1 ? 's' : ''} riding into hole ${eng.holesPlayed + 1}` : 'No carryover'}</div>
          </div>
          <div className="stu-num" style={{ fontSize: 28, fontWeight: 600 }}>${eng.carryNow ? eng.carryPot : round.skinValue}</div>
        </div>

        {/* animated board */}
        <div style={{ position: 'relative', height: board.length * rowH, marginTop: 14 }}>
          {board.map((p, i) => (
            <div key={p.id} style={{
              position: 'absolute', left: 0, right: 0, top: i * rowH, height: rowH - 8,
              transition: 'top .5s cubic-bezier(.3,1.2,.4,1)',
              display: 'flex', alignItems: 'center', gap: 13, padding: '0 14px', borderRadius: 16,
              background: i === 0 ? S.surface : 'transparent',
            }}>
              {i === 0 && <div style={{ position: 'absolute', left: 0, top: 12, bottom: 12, width: 4, background: S.lime, borderRadius: '0 3px 3px 0' }}></div>}
              <div className="stu-num" style={{ width: 16, fontSize: 16, fontWeight: 600, color: i === 0 ? S.ink : S.inkFaint }}>{i + 1}</div>
              <Avatar name={p.name} size={38} dark={i === 0} />
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 15.5, fontWeight: 600 }}>{p.name.split(' ')[0]}</div>
                <div style={{ display: 'flex', gap: 5, alignItems: 'center', marginTop: 3 }}>
                  {Array.from({ length: p.skins }).map((_, k) => <span key={k} style={{ width: 7, height: 7, borderRadius: '50%', background: S.ink, display: 'inline-block' }}></span>)}
                  <span style={{ fontSize: 11.5, color: S.inkSoft, marginLeft: p.skins ? 3 : 0 }}>{p.skins ? `${p.skins} skin${p.skins > 1 ? 's' : ''}` : 'no skins'}{p.dots ? ` · ${p.dots} dots` : ''}</span>
                </div>
              </div>
              <div style={{ textAlign: 'right' }}>
                <div className="stu-num" style={{ fontSize: 24, fontWeight: 600 }}>{p.net}</div>
                <div className="stu-num" style={{ fontSize: 12, color: S.inkSoft, whiteSpace: 'nowrap' }}>{p.toPar === 0 ? 'E' : p.toPar > 0 ? '+' + p.toPar : p.toPar} thru {eng.holesPlayed}</div>
              </div>
            </div>
          ))}
        </div>

        <div style={{ background: S.ink, color: '#fff', borderRadius: 16, padding: '14px 16px', display: 'flex', alignItems: 'center', gap: 11, marginTop: 4 }}>
          <Spark size={14} color={S.lime} />
          <span style={{ fontSize: 13, lineHeight: 1.35 }}>{leader.name.split(' ')[0]}'s up {leader.skins} skins. Gabe pressed the back — it's getting expensive.</span>
        </div>
      </div>
    </Page>
  );
}

// ───────────────────────── Side games
function SideGames() {
  const S = window.STU; const { nav, back, eng, dots, round } = window.useStryke();
  return (
    <Page footer={<Button variant="primary" full onClick={() => nav('settlement')}>Settle up →</Button>}>
      <TopBar title="Side games" onBack={back} />
      <div style={{ padding: '4px 20px 16px', display: 'flex', flexDirection: 'column', gap: 16 }}>
        {/* skins */}
        <div>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
            <Label>SKINS · HOLE BY HOLE</Label>
            <span className="stu-num" style={{ fontSize: 12, color: S.inkSoft }}>${round.skinValue}/skin</span>
          </div>
          <div className="stu-scroll" style={{ display: 'flex', gap: 6, marginTop: 10, overflowX: 'auto', paddingBottom: 4 }}>
            {eng.skinResults.map(r => (
              <div key={r.hole} style={{ flexShrink: 0, width: 52, textAlign: 'center', padding: '8px 0', borderRadius: 13, background: r.carried ? S.white : S.surface, boxShadow: r.carried ? `inset 0 0 0 1.5px ${S.lineMid}` : 'none' }}>
                <div className="stu-num" style={{ fontSize: 11, color: S.inkFaint }}>H{r.hole}</div>
                {r.carried
                  ? <div style={{ fontSize: 11, fontWeight: 700, color: S.inkSoft, marginTop: 4 }}>carry</div>
                  : <div style={{ marginTop: 4 }}><Avatar name={eng.nameOf(r.winner)} size={26} dark /></div>}
                <div className="stu-num" style={{ fontSize: 10.5, color: S.inkSoft, marginTop: 4 }}>${r.value}</div>
              </div>
            ))}
          </div>
          <div style={{ marginTop: 10, display: 'flex', flexDirection: 'column', gap: 6 }}>
            {eng.leaderboard.filter(p => p.skins > 0).sort((a, b) => b.skins - a.skins).map(p => (
              <div key={p.id} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 0' }}>
                <Avatar name={p.name} size={28} />
                <div style={{ flex: 1, fontSize: 13.5, fontWeight: 600 }}>{p.name.split(' ')[0]}</div>
                <div className="stu-num" style={{ fontSize: 13, color: S.inkSoft }}>{p.skins} skins</div>
                <div className="stu-num" style={{ fontSize: 13.5, fontWeight: 700, width: 44, textAlign: 'right' }}>${eng.skinsValueWon[p.id]}</div>
              </div>
            ))}
          </div>
        </div>

        {/* dots ledger */}
        <div>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
            <Label>DOT LEDGER</Label>
            <span className="stu-num" style={{ fontSize: 12, color: S.inkSoft }}>${round.dotValue}/dot</span>
          </div>
          <div style={{ marginTop: 10, display: 'flex', flexDirection: 'column', gap: 6 }}>
            {dots.map(d => (
              <div key={d.id} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 14px', background: S.surface, borderRadius: 13 }}>
                <Avatar name={eng.nameOf(d.player)} size={30} lime />
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13.5, fontWeight: 600 }}>{d.type}</div>
                  <div style={{ fontSize: 11.5, color: S.inkSoft }}>{eng.nameOf(d.player)} · hole {d.hole}</div>
                </div>
                <div className="stu-num" style={{ fontSize: 13.5, fontWeight: 700 }}>${d.value}</div>
              </div>
            ))}
          </div>
        </div>

        {/* nassau press tree (if on) */}
        {round.formats.nassau && (
          <div>
            <Label>NASSAU · PRESSES</Label>
            <div style={{ marginTop: 10, padding: 16, background: S.surface, borderRadius: 16, fontSize: 13, color: S.inkSoft }}>Front 9: Team A 1 up · Back 9: pressed on 13 · Overall: All square</div>
          </div>
        )}
      </div>
    </Page>
  );
}

Object.assign(window.SCREENS, { roundDash: RoundDashboard, liveScore: LiveHoleScoring, leaderboard: LiveLeaderboard, sideGames: SideGames });
