// Stryke screens — Captain Kit scan, scan review, settings/house rules
window.SCREENS = window.SCREENS || {};
const { useState: useS5, useEffect: useE5 } = React;

// ───────────────────────── Captain Kit scan (capture)
function CaptainKitScan() {
  const S = window.STU; const { nav, back } = window.useStryke();
  const [scanning, setScanning] = useS5(false);
  useE5(() => { if (scanning) { const t = setTimeout(() => nav('scanReview'), 1900); return () => clearTimeout(t); } }, [scanning]);
  const Corner = ({ pos }) => {
    const base = { position: 'absolute', width: 34, height: 34, borderColor: S.lime, borderStyle: 'solid', borderWidth: 0 };
    const m = { tl: { top: 0, left: 0, borderTopWidth: 3, borderLeftWidth: 3, borderTopLeftRadius: 8 }, tr: { top: 0, right: 0, borderTopWidth: 3, borderRightWidth: 3, borderTopRightRadius: 8 }, bl: { bottom: 0, left: 0, borderBottomWidth: 3, borderLeftWidth: 3, borderBottomLeftRadius: 8 }, br: { bottom: 0, right: 0, borderBottomWidth: 3, borderRightWidth: 3, borderBottomRightRadius: 8 } };
    return <div style={{ ...base, ...m[pos] }}></div>;
  };
  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: S.ink, color: '#fff' }}>
      <TopBar title="Captain Kit" onBack={back} right={<span style={{ fontSize: 12.5, color: 'rgba(255,255,255,0.6)' }}>Hole 18</span>} />
      <style>{`.stu-tb-dark .stu-tap svg path{stroke:#fff}`}</style>
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '0 24px' }}>
        <div style={{ position: 'relative', width: '100%', maxWidth: 320, aspectRatio: '0.78', display: 'grid', placeItems: 'center' }}>
          {/* mock scorecard inside frame */}
          <div style={{ width: '86%', height: '86%', background: '#FBFAF4', borderRadius: 6, transform: 'rotate(-2deg)', boxShadow: '0 14px 40px rgba(0,0,0,0.5)', padding: '12px 10px', overflow: 'hidden' }}>
            <div style={{ textAlign: 'center', color: '#333', fontFamily: window.STU.num, fontSize: 11, fontWeight: 700, letterSpacing: 1 }}>PINE HOLLOW · SCORECARD</div>
            <div style={{ height: 1, background: '#ddd', margin: '6px 0' }}></div>
            {['TR','MI','DE','GA'].map((p, r) => (
              <div key={p} style={{ display: 'flex', gap: 2, marginBottom: 4 }}>
                <div style={{ width: 22, fontSize: 9, color: '#333', fontWeight: 700, fontFamily: window.STU.num }}>{p}</div>
                {Array.from({ length: 9 }).map((_, c) => (
                  <div key={c} style={{ flex: 1, height: 12, borderBottom: '1px solid #ccc', textAlign: 'center', fontSize: 9, color: '#222', fontFamily: window.STU.num }}>{[4,5,5,3,4,4,3,6,4][(c+r)%9]}</div>
                ))}
              </div>
            ))}
          </div>
          <Corner pos="tl" /><Corner pos="tr" /><Corner pos="bl" /><Corner pos="br" />
          {scanning && <div style={{ position: 'absolute', left: 0, right: 0, height: 3, background: S.lime, boxShadow: `0 0 14px ${S.lime}`, animation: 'stuScanLine 1.6s ease-in-out infinite', top: 0 }}></div>}
          <style>{`@keyframes stuScanLine{0%{top:4%}50%{top:94%}100%{top:4%}}`}</style>
        </div>
        <div style={{ textAlign: 'center', marginTop: 26, height: 42 }}>
          {scanning
            ? <div style={{ display: 'flex', alignItems: 'center', gap: 8, justifyContent: 'center', color: S.lime }}><Spark size={15} color={S.lime} /><span style={{ fontSize: 15, fontWeight: 600 }}>Reading your card…</span></div>
            : <div style={{ fontSize: 14, color: 'rgba(255,255,255,0.7)', lineHeight: 1.4 }}>Line up the card inside the guides.<br/>One clear shot is enough.</div>}
        </div>
      </div>
      <div style={{ padding: '0 24px calc(28px + env(safe-area-inset-bottom))', display: 'flex', justifyContent: 'center' }}>
        <button className="stu-btn" disabled={scanning} onClick={() => setScanning(true)} style={{ width: 72, height: 72, borderRadius: '50%', background: scanning ? 'rgba(255,255,255,0.2)' : '#fff', boxShadow: `0 0 0 4px ${S.ink}, 0 0 0 6px rgba(255,255,255,0.4)` }}>
          {scanning ? <span style={{ display: 'inline-block', width: 22, height: 22, border: `3px solid ${S.ink}`, borderTopColor: 'transparent', borderRadius: '50%', animation: 'stuSpin .7s linear infinite' }}></span> : <span style={{ width: 56, height: 56, borderRadius: '50%', background: S.lime, display: 'inline-block' }}></span>}
        </button>
        <style>{`@keyframes stuSpin{to{transform:rotate(360deg)}}`}</style>
      </div>
    </div>
  );
}

// ───────────────────────── Scan review / confirm
function ScanReview() {
  const S = window.STU; const { nav, back, players, flash } = window.useStryke();
  // front 9 from seed; flag two low-confidence cells
  const grid = {
    tr: [4,5,5,3,4,4,3,6,4], mi: [4,4,5,4,5,4,4,5,4], de: [5,4,6,4,4,5,3,5,5], ga: [5,5,6,4,5,6,4,6,5],
  };
  const flags = [['ga', 2], ['de', 5]]; // [pid, holeIdx] low-confidence
  const [vals, setVals] = useS5(grid);
  const [fixed, setFixed] = useS5({});
  const isFlag = (pid, i) => flags.some(f => f[0] === pid && f[1] === i) && !fixed[`${pid}-${i}`];
  const remaining = flags.filter(f => !fixed[`${f[0]}-${f[1]}`]).length;
  const bump = (pid, i) => {
    setVals(v => ({ ...v, [pid]: v[pid].map((x, j) => j === i ? (x % 8) + 1 : x) }));
    setFixed(f => ({ ...f, [`${pid}-${i}`]: true }));
  };
  return (
    <Page footer={<Button variant={remaining ? 'soft' : 'lime'} full disabled={false} onClick={() => { flash(remaining ? 'Confirm the flagged cells' : 'Scores posted'); if (!remaining) nav('leaderboard'); }}>{remaining ? `${remaining} field${remaining > 1 ? 's' : ''} to confirm` : 'Confirm & post scores'}</Button>}>
      <TopBar title="Review scan" onBack={back} sub="Front 9 · tap a flagged cell to fix" />
      <div style={{ padding: '4px 20px 16px' }}>
        <div style={{ background: S.ink, color: '#fff', borderRadius: 16, padding: '13px 15px', display: 'flex', alignItems: 'center', gap: 11 }}>
          <Spark size={15} color={S.lime} />
          <div style={{ fontSize: 13, lineHeight: 1.35 }}>Stryke read your card. <b>{remaining || 'No'}</b> field{remaining === 1 ? '' : 's'} {remaining ? 'need a quick check' : '— all clear'}.</div>
        </div>

        {/* grid */}
        <div style={{ marginTop: 16, overflowX: 'auto' }} className="stu-scroll">
          <div style={{ display: 'flex', gap: 4, paddingLeft: 52, marginBottom: 6 }}>
            {Array.from({ length: 9 }).map((_, i) => <div key={i} className="stu-num" style={{ width: 30, textAlign: 'center', fontSize: 10.5, color: S.inkFaint, flexShrink: 0 }}>{i + 1}</div>)}
          </div>
          {players.map(p => (
            <div key={p.id} style={{ display: 'flex', alignItems: 'center', gap: 4, marginBottom: 6 }}>
              <div style={{ width: 48, fontSize: 12.5, fontWeight: 700, flexShrink: 0 }}>{p.name.split(' ')[0].slice(0, 4)}</div>
              {vals[p.id].map((v, i) => {
                const flag = isFlag(p.id, i);
                return (
                  <div key={i} className={(flag ? 'stu-tap ' : '') + 'stu-num'} onClick={flag ? () => bump(p.id, i) : undefined} style={{
                    width: 30, height: 34, flexShrink: 0, borderRadius: 8, display: 'grid', placeItems: 'center', fontSize: 14, fontWeight: 600,
                    background: flag ? S.lime : S.surface, boxShadow: flag ? `0 0 0 2px ${S.ink}` : 'none',
                    animation: flag ? 'stuPulse 1.8s ease-in-out infinite' : 'none',
                  }}>{v}</div>
                );
              })}
            </div>
          ))}
        </div>
        <div style={{ marginTop: 14, fontSize: 12, color: S.inkFaint, lineHeight: 1.45 }}>Highlighted cells were low-confidence. Nothing posts until you confirm — tap to correct, then post.</div>
        <button className="stu-btn stu-tap" onClick={() => nav('kitScan')} style={{ marginTop: 12, background: S.surface, color: S.ink, width: '100%', padding: '12px', borderRadius: 14, fontSize: 13.5 }}>Re-scan the card</button>
      </div>
    </Page>
  );
}

// ───────────────────────── Settings / house rules
function Settings() {
  const S = window.STU; const { nav, goTab, group } = window.useStryke();
  const [rules, setRules] = useS5(['Carryover skins on ties', 'Auto-press when 2 down', 'Greenies only on par 3s']);
  const [notif, setNotif] = useS5(true);
  const [tone, setTone] = useS5('funny');
  return (
    <Page tab={<TabBar active="settings" onNav={goTab} />}>
      <TopBar title="Settings" sub={group.name} />
      <div style={{ padding: '4px 20px 16px', display: 'flex', flexDirection: 'column', gap: 18 }}>
        <div>
          <Label>HOUSE RULES</Label>
          <div style={{ marginTop: 10, display: 'flex', flexDirection: 'column', gap: 8 }}>
            {rules.map((r, i) => (
              <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '12px 14px', background: S.surface, borderRadius: 14 }}>
                <span style={{ width: 7, height: 7, borderRadius: '50%', background: S.lime }}></span>
                <div style={{ flex: 1, fontSize: 14, fontWeight: 500 }}>{r}</div>
                <span className="stu-tap" onClick={() => setRules(rs => rs.filter((_, j) => j !== i))} style={{ color: S.inkFaint, fontSize: 18 }}>×</span>
              </div>
            ))}
            <button className="stu-btn stu-tap" onClick={() => setRules(rs => [...rs, 'New house rule'])} style={{ background: 'transparent', color: S.inkSoft, padding: '11px', borderRadius: 14, fontSize: 13.5, boxShadow: `inset 0 0 0 1.5px ${S.line}` }}>+ Add a house rule</button>
          </div>
        </div>

        <div>
          <Label>DEFAULTS</Label>
          <div style={{ marginTop: 10, background: S.surface, borderRadius: 16, padding: '4px 16px' }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '13px 0', borderBottom: `1px solid ${S.lineMid}` }}>
              <div style={{ fontSize: 14, fontWeight: 500 }}>Round notifications</div><Toggle on={notif} onChange={setNotif} />
            </div>
            <div style={{ padding: '13px 0' }}>
              <div style={{ fontSize: 14, fontWeight: 500, marginBottom: 10 }}>Default recap tone</div>
              <Segmented options={[{ value: 'funny', label: 'Funny' }, { value: 'straight', label: 'Straight' }]} value={tone} onChange={setTone} />
            </div>
          </div>
        </div>

        <div>
          <Label>TRUST</Label>
          <div style={{ marginTop: 10, display: 'flex', flexDirection: 'column', gap: 8 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '13px 14px', background: S.surface, borderRadius: 14 }}>
              <svg width="17" height="17" viewBox="0 0 24 24" fill="none"><path d="M3 6l3-1 6 2 6-2 3 1v12l-3 1-6-2-6 2-3-1z" stroke={S.inkSoft} strokeWidth="1.7" strokeLinejoin="round"/></svg>
              <div style={{ flex: 1, fontSize: 14, fontWeight: 500 }}>Edit & dispute trail</div>
              <span style={{ fontSize: 12.5, color: S.inkSoft }}>On</span>
            </div>
          </div>
        </div>

        <LegalNote />
        <div style={{ textAlign: 'center', fontSize: 11.5, color: S.inkFaint, paddingTop: 4 }}>Stryke · the live competition layer for golf groups</div>
      </div>
    </Page>
  );
}

Object.assign(window.SCREENS, { kitScan: CaptainKitScan, scanReview: ScanReview, settings: Settings });
