// Stryke screens — onboarding: welcome, captain home, create group
window.SCREENS = window.SCREENS || {};
const { useState: useS1, useEffect: useE1, useRef: useRf1 } = React;

// ───────────────────────── Welcome / create-or-join
function Welcome() {
  const S = window.STU; const { nav } = window.useStryke();
  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: S.ink, color: S.white, padding: '0 26px' }}>
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
          <Spark size={24} color={S.lime} />
          <span style={{ fontSize: 26, fontWeight: 700, letterSpacing: '-0.03em' }}>Stryke</span>
        </div>
        <div style={{ fontSize: 40, fontWeight: 700, letterSpacing: '-0.04em', lineHeight: 1.02, marginTop: 28 }}>
          The live<br/>scoreboard for<br/>your <span style={{ color: S.lime }}>golf crew.</span>
        </div>
        <div style={{ fontSize: 15.5, color: 'rgba(255,255,255,0.6)', marginTop: 16, lineHeight: 1.45, maxWidth: 300 }}>
          One captain sets the game. The group joins by link — no download. Stryke runs the skins, tracks who owes who, and writes the recap.
        </div>
      </div>
      <div style={{ paddingBottom: 'calc(28px + env(safe-area-inset-bottom))' }}>
        <Button variant="lime" full onClick={() => nav('home')} style={{ marginBottom: 12 }}>Create a game</Button>
        <button className="stu-btn" onClick={() => nav('guestJoin')} style={{ width: '100%', background: 'rgba(255,255,255,0.08)', color: S.white, padding: '15px', borderRadius: 100, fontSize: 15.5 }}>I have an invite link</button>
        <div style={{ textAlign: 'center', fontSize: 12.5, color: 'rgba(255,255,255,0.45)', marginTop: 18 }}>Stryke never holds or moves money.</div>
      </div>
    </div>
  );
}

// ───────────────────────── Captain home / dashboard
function CaptainHome() {
  const S = window.STU; const { nav, goTab, group, players, round, eng } = window.useStryke();
  const recent = [
    { wk: '07', course: 'Pine Hollow', who: 'Trevor', res: '+$14', tag: 'Skins · Dots', go: () => nav('recap') },
    { wk: '06', course: 'Cypress Bend', who: 'Mike', res: '+$22', tag: 'Nassau', go: () => nav('standings') },
    { wk: '05', course: 'Pine Hollow', who: 'Dev', res: '+$9', tag: 'Skins', go: () => nav('standings') },
  ];
  return (
    <Page tab={<TabBar active="home" onNav={goTab} />}>
      <div style={{ padding: '14px 20px 0' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
            <Spark size={16} />
            <span style={{ fontSize: 20, fontWeight: 700, letterSpacing: '-0.03em' }}>Stryke</span>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <button className="stu-btn stu-tap" onClick={() => nav('joinGame')} aria-label="Join a game" style={{ width: 38, height: 38, borderRadius: '50%', background: S.surface, display: 'grid', placeItems: 'center' }}>
              <svg width="19" height="19" viewBox="0 0 24 24" fill="none">
                <path d="M4 8V5.5A1.5 1.5 0 0 1 5.5 4H8M16 4h2.5A1.5 1.5 0 0 1 20 5.5V8M20 16v2.5a1.5 1.5 0 0 1-1.5 1.5H16M8 20H5.5A1.5 1.5 0 0 1 4 18.5V16" stroke={S.ink} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
                <path d="M4 12h16" stroke={S.ink} strokeWidth="2" strokeLinecap="round"/>
              </svg>
            </button>
            <div className="stu-tap" onClick={() => nav('settings')}><Avatar name="Trevor Okafor" size={36} /></div>
          </div>
        </div>

        <div style={{ marginTop: 24 }}>
          <div style={{ fontSize: 13.5, fontWeight: 600, color: S.inkSoft }}>Good morning, Trevor</div>
          <div style={{ fontSize: 33, fontWeight: 700, letterSpacing: '-0.035em', lineHeight: 1.02, marginTop: 3 }}>{group.name}</div>
          <div style={{ fontSize: 13.5, color: S.inkSoft, marginTop: 5 }}>{players.length} members · 7 rounds played</div>
        </div>

        {/* Suggested run it back */}
        <Card dark radius={22} pad={20} onClick={() => nav('runItBack')} style={{ marginTop: 18, position: 'relative', overflow: 'hidden' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 7, color: S.lime }}>
            <Spark size={13} color={S.lime} />
            <span style={{ fontSize: 11.5, fontWeight: 700, letterSpacing: '0.04em', whiteSpace: 'nowrap' }}>SUGGESTED FOR YOU</span>
          </div>
          <div style={{ fontSize: 23, fontWeight: 700, letterSpacing: '-0.03em', marginTop: 12, lineHeight: 1.12 }}>Run it back at<br/>Pine Hollow</div>
          <div style={{ fontSize: 13, color: 'rgba(255,255,255,0.6)', marginTop: 8 }}>Same {players.length} · Skins + Dots · $2/skin — your usual Saturday 8:10</div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginTop: 16 }}>
            <span style={{ background: S.lime, color: S.ink, fontWeight: 700, fontSize: 14, padding: '12px 20px', borderRadius: 100, whiteSpace: 'nowrap', flexShrink: 0 }}>Set it up</span>
            <span className="stu-num" style={{ fontSize: 12.5, color: 'rgba(255,255,255,0.5)' }}>~38s</span>
          </div>
        </Card>

        <div style={{ display: 'flex', gap: 10, marginTop: 12 }}>
          <Button variant="soft" full size="md" onClick={() => nav('createRound')} icon={<span style={{ fontSize: 17, marginTop: -2 }}>+</span>}>New round</Button>
          <Button variant="soft" full size="md" onClick={() => nav('createGroup')}>New group</Button>
        </div>

        <div style={{ marginTop: 24, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <span style={{ fontSize: 14, fontWeight: 700 }}>Recent rounds</span>
          <span className="stu-tap" onClick={() => goTab('rounds')} style={{ fontSize: 13, color: S.inkSoft, fontWeight: 600, whiteSpace: 'nowrap' }}>See all</span>
        </div>
      </div>
      <div style={{ padding: '4px 20px 24px' }}>
        {recent.map((r, i) => (
          <div key={i} className="stu-tap" onClick={r.go} 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 }}>{r.wk}</div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 14.5, fontWeight: 600 }}>Week {parseInt(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: 15, fontWeight: 600, color: S.good, whiteSpace: 'nowrap' }}>{r.res}</div>
              <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: '0.04em', color: S.inkFaint, marginTop: 2 }}>SETTLED</div>
            </div>
          </div>
        ))}
      </div>
    </Page>
  );
}

// ───────────────────────── Create group
function CreateGroup() {
  const S = window.STU; const { nav, back, flash } = window.useStryke();
  const [name, setName] = useS1('Saturday Crew');
  const [rows, setRows] = useS1([
    { n: 'Trevor Okafor', h: '8' }, { n: 'Mike Reyes', h: '6' }, { n: 'Dev Anand', h: '12' }, { n: '', h: '' },
  ]);
  const update = (i, k, v) => setRows(rs => rs.map((r, j) => j === i ? { ...r, [k]: v } : r));
  const addRow = () => setRows(rs => [...rs, { n: '', h: '' }]);
  const filled = rows.filter(r => r.n.trim()).length;
  return (
    <Page footer={<Button variant="primary" full disabled={!name.trim() || filled < 1} onClick={() => { flash('Group saved'); nav('home', 'back'); }}>Save group · {filled} {filled === 1 ? 'member' : 'members'}</Button>}>
      <TopBar title="New group" onBack={back} />
      <div style={{ padding: '6px 20px 16px' }}>
        <Label>GROUP NAME</Label>
        <input className="stu-input" style={{ marginTop: 8, fontSize: 22, fontWeight: 700, borderRadius: 16, letterSpacing: '-0.02em' }} value={name} onChange={e => setName(e.target.value)} placeholder="e.g. Saturday Crew" />

        <div style={{ marginTop: 22, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <Label>MEMBERS</Label>
          <span style={{ fontSize: 11.5, color: S.inkFaint }}>Handicap optional</span>
        </div>
        <div style={{ marginTop: 10, display: 'flex', flexDirection: 'column', gap: 10 }}>
          {rows.map((r, i) => (
            <div key={i} style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
              <Avatar name={r.n || '?'} size={40} dark={!!r.n.trim()} />
              <input className="stu-input" value={r.n} onChange={e => update(i, 'n', e.target.value)} placeholder={`Player ${i + 1}`} style={{ flex: 1 }} />
              <input className="stu-input stu-num" value={r.h} onChange={e => update(i, 'h', e.target.value.replace(/[^0-9]/g, ''))} placeholder="HCP" style={{ width: 74, textAlign: 'center', padding: '14px 8px' }} />
            </div>
          ))}
        </div>
        <button className="stu-btn stu-tap" onClick={addRow} style={{ marginTop: 12, background: S.surface, color: S.ink, width: '100%', padding: '13px', borderRadius: 14, fontSize: 14, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8 }}>
          <span style={{ fontSize: 17 }}>+</span> Add another player
        </button>
        <div style={{ marginTop: 16, fontSize: 12.5, color: S.inkSoft, lineHeight: 1.45, display: 'flex', gap: 8, alignItems: 'flex-start' }}>
          <Spark size={13} color={S.inkFaint} style={{ marginTop: 2 }} />
          You can also skip this — a group is created automatically from your first round's roster.
        </div>
      </div>
    </Page>
  );
}

// ───────────────────────── Join a game (in-app, logged-in)
// Profile + handicap already on file, so this is identify-the-round + confirm — no name entry.
function JoinGame() {
  const S = window.STU; const { nav, back, flash } = window.useStryke();
  const [code, setCode] = useS1('');
  const [phase, setPhase] = useS1('enter'); // enter | finding | found
  const inputRef = useRf1(null);
  const clean = code.toUpperCase().replace(/[^A-Z0-9]/g, '').slice(0, 6);
  const full = clean.length === 6;

  useE1(() => {
    if (full) { setPhase('finding'); const t = setTimeout(() => setPhase('found'), 1050); return () => clearTimeout(t); }
    setPhase('enter');
  }, [full]);

  // mock round being joined (someone else's game — captained by Mike)
  const joining = { group: "Mike's Money Game", week: 8, course: 'Cypress Bend', fmt: 'Skins + Nassau', captain: 'Mike Reyes', date: 'Sat · 7:40 AM' };
  const inAlready = [{ n: 'Mike Reyes' }, { n: 'Dev Anand' }, { n: 'Gabe Munoz' }];

  const footer = phase === 'found'
    ? <Button variant="lime" full onClick={() => { flash("You're in — good luck"); nav('roundDash'); }}>Join the game</Button>
    : <Button variant="primary" full disabled icon={phase === 'finding' ? <span style={{ display: 'inline-block', width: 15, height: 15, border: `2.5px solid rgba(255,255,255,.4)`, borderTopColor: '#fff', borderRadius: '50%', animation: 'stuSpin .7s linear infinite' }}></span> : null}>{phase === 'finding' ? 'Finding game…' : 'Enter your 6-character code'}</Button>;

  return (
    <Page footer={footer}>
      <style>{`@keyframes stuSpin{to{transform:rotate(360deg)}}`}</style>
      <TopBar title="Join a game" onBack={back} sub="Got a code or QR from a captain?" />
      <div style={{ padding: '6px 20px 16px' }}>
        <div style={{ fontSize: 22, fontWeight: 700, letterSpacing: '-0.03em', lineHeight: 1.1 }}>Enter the round code</div>
        <div style={{ fontSize: 13.5, color: S.inkSoft, marginTop: 5 }}>It's on the captain's invite — 6 characters, like <span className="stu-num" style={{ fontWeight: 700, color: S.ink }}>CYP8GX</span>.</div>

        {/* segmented code entry */}
        <div style={{ position: 'relative', marginTop: 20 }}>
          <input ref={inputRef} value={clean} onChange={e => setCode(e.target.value)} autoFocus inputMode="text" autoCapitalize="characters" autoComplete="off" spellCheck={false} maxLength={6} aria-label="Round code" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', opacity: 0, zIndex: 2, border: 'none', background: 'transparent', caretColor: 'transparent', fontSize: 16, cursor: 'text' }} />
          <div style={{ display: 'flex', gap: 8 }}>
            {Array.from({ length: 6 }).map((_, i) => {
              const ch = clean[i];
              const activeBox = i === clean.length && phase === 'enter';
              return (
                <div key={i} className="stu-num" style={{ flex: 1, height: 60, borderRadius: 14, display: 'grid', placeItems: 'center', fontSize: 25, fontWeight: 700, background: S.surface, color: S.ink, boxShadow: activeBox ? `inset 0 0 0 2px ${S.ink}` : ch ? `inset 0 0 0 1.5px ${S.lineMid}` : 'none', transition: 'box-shadow .15s' }}>
                  {ch || (activeBox ? <span className="stu-live-dot" style={{ width: 2, height: 26, background: S.ink, borderRadius: 2 }}></span> : '')}
                </div>
              );
            })}
          </div>
        </div>

        {/* scan / paste affordances */}
        <div style={{ display: 'flex', gap: 10, marginTop: 14 }}>
          <button className="stu-btn stu-tap" onClick={() => { setCode('CYP8GX'); flash('QR scanned'); }} style={{ flex: 1, background: S.surface, color: S.ink, padding: '13px', borderRadius: 14, fontSize: 13.5, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8 }}>
            <svg width="17" height="17" viewBox="0 0 24 24" fill="none"><path d="M4 8V5.5A1.5 1.5 0 0 1 5.5 4H8M16 4h2.5A1.5 1.5 0 0 1 20 5.5V8M20 16v2.5a1.5 1.5 0 0 1-1.5 1.5H16M8 20H5.5A1.5 1.5 0 0 1 4 18.5V16M4 12h16" stroke={S.ink} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>
            Scan QR
          </button>
          <button className="stu-btn stu-tap" onClick={() => { setCode('CYP8GX'); }} style={{ flex: 1, background: S.surface, color: S.ink, padding: '13px', borderRadius: 14, fontSize: 13.5, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8 }}>
            <svg width="17" height="17" viewBox="0 0 24 24" fill="none"><path d="M9 5h6M9 5a2 2 0 0 0-2 2v0M9 5a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2M7 7H6a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-1" stroke={S.ink} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/></svg>
            Paste link
          </button>
        </div>

        {/* round preview once found */}
        {phase === 'found' && (
          <div style={{ marginTop: 24, animation: 'stuRise .4s cubic-bezier(.2,.7,.2,1) both' }}>
            <Label>YOU'RE JOINING</Label>
            <Card dark radius={20} pad={20} style={{ marginTop: 10 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 7, color: S.lime }}>
                <Spark size={13} color={S.lime} /><span style={{ fontSize: 11.5, fontWeight: 700, letterSpacing: '0.04em' }}>WEEK {joining.week}</span>
              </div>
              <div style={{ fontSize: 24, fontWeight: 700, letterSpacing: '-0.03em', marginTop: 10, lineHeight: 1.08 }}>{joining.group}</div>
              <div style={{ fontSize: 13.5, color: 'rgba(255,255,255,0.62)', marginTop: 6 }}>{joining.course} · {joining.fmt}</div>
              <div style={{ fontSize: 13.5, color: 'rgba(255,255,255,0.62)', marginTop: 2 }}>{joining.date} · {joining.captain} is captain</div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 16 }}>
                <div style={{ display: 'flex' }}>
                  {inAlready.map((p, i) => <div key={i} style={{ marginLeft: i ? -9 : 0, borderRadius: '50%', boxShadow: `0 0 0 2px ${S.ink}` }}><Avatar name={p.n} size={28} lime={i === 0} /></div>)}
                </div>
                <span style={{ fontSize: 12.5, color: 'rgba(255,255,255,0.55)' }}>{inAlready.length} already in</span>
              </div>
            </Card>

            {/* joining as — profile already on file */}
            <div style={{ marginTop: 12, display: 'flex', alignItems: 'center', gap: 12, padding: '13px 15px', background: S.surface, borderRadius: 16 }}>
              <Avatar name="Trevor Okafor" size={40} dark />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 14.5, fontWeight: 700 }}>Joining as Trevor Okafor</div>
                <div style={{ fontSize: 12.5, color: S.inkSoft, marginTop: 1 }}>HCP 8 · from your profile</div>
              </div>
              <Chip lime>You</Chip>
            </div>
            <div style={{ marginTop: 12, fontSize: 12.5, color: S.inkSoft, lineHeight: 1.45, display: 'flex', gap: 8, alignItems: 'flex-start' }}>
              <Spark size={13} color={S.inkFaint} style={{ marginTop: 2 }} />
              Your name and handicap are already set — nothing to re-enter. Tap join and you're on the card.
            </div>
          </div>
        )}
      </div>
    </Page>
  );
}

window.SCREENS.welcome = Welcome;
window.SCREENS.home = CaptainHome;
window.SCREENS.createGroup = CreateGroup;
window.SCREENS.joinGame = JoinGame;
