/* global React, C, Screen, Header, Tabs, Avatar, Pill, Chevron, Close, Sparkline, GAME_LOG */
// screens-6.jsx — Golfer detail sheet (Game Log tab)

function GolferDetailScreen() {
  // Render a bottom-sheet over the underlying screen. The golfer being shown
  // comes from sheetPayload set by openSheet({...}).
  const payload = window.useStore((s) => s.sheetPayload) || {};
  const [tab, setTab] = React.useState('Overview');
  const [live, setLive] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const close = () => { const n = window.appNav; if (n) n.closeSheet(); };

  // Resolve the golfer's live row from `field` + `golfer_scores` at the
  // current tournament; falls back to whatever was passed in via sheetPayload.
  React.useEffect(() => {
    const api = window.cambamApi;
    if (!api || !api.isConfigured?.()) { setLoading(false); return; }
    const golferId = payload.golferId || payload.golfer_id || payload.name;
    if (!golferId) { setLoading(false); return; }
    let cancelled = false;
    (async () => {
      try {
        const t = await api.currentTournament?.();
        if (!t || cancelled) { setLoading(false); return; }
        const data = await api.loadGolferDetail(golferId, t.id);
        if (!cancelled) { setLive(data); setLoading(false); }
      } catch (e) {
        console.warn('golfer load failed', e);
        if (!cancelled) setLoading(false);
      }
    })();
    return () => { cancelled = true; };
  }, [payload.golferId, payload.name]);

  // Merge live row over payload — payload has tone/displayName etc.
  const golfer = {
    name: live?.name || payload.name || '—',
    country: live?.country || payload.country || '',
    tone: payload.tone || 1,
    worldRank: live?.world_rank ?? payload.worldRank ?? null,
    price: live?.salary ?? payload.price ?? null,
    points: live?.fantasy_pts ?? payload.points ?? 0,
    status: live?.status || payload.status || null,
    score_to_par: live?.score_to_par ?? null,
    thru: live?.thru ?? null,
    round: live?.round ?? null,
    r1: live?.r1, r2: live?.r2, r3: live?.r3, r4: live?.r4,
    live: live?.status === 'playing' || payload.live || false,
  };

  return (
    <Screen label="06 Golfer Detail" bottomNav={null} scroll={false}>
      <div onClick={close} style={{ position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.55)' }} />

      <div style={{
        position: 'absolute', left: 0, right: 0, bottom: 0,
        height: 'calc(100% - 56px)',
        background: C.surface,
        borderTopLeftRadius: 16, borderTopRightRadius: 16,
        display: 'flex', flexDirection: 'column', overflow: 'hidden',
      }}>
        <div style={{
          display: 'flex', alignItems: 'center', padding: '8px 12px 0', flexShrink: 0,
          position: 'relative',
        }}>
          <div style={{ flex: 1, display: 'flex', justifyContent: 'center' }}>
            <div style={{ width: 36, height: 4, borderRadius: 999, background: C.hairline, marginTop: 4 }} />
          </div>
          <button aria-label="Close golfer detail" onClick={close} style={{
            position: 'absolute', right: 12, top: 6,
            width: 32, height: 32, borderRadius: 999, background: C.surface2,
            border: 'none', cursor: 'pointer', color: C.text2,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}><Close size={16} /></button>
        </div>

        <div style={{ flex: 1, overflow: 'auto', paddingBottom: 40 }}>
          <div style={{ padding: '12px 16px 16px', textAlign: 'center' }}>
            <Avatar name={golfer.name} size={80} tone={golfer.tone || 2} />
            <div style={{ font: '700 22px/28px Inter', color: C.text, marginTop: 12 }}>{golfer.name}</div>
            <div style={{ font: '400 13px/18px Inter', color: C.text2, marginTop: 2 }}>
              {golfer.country || '—'} · {golfer.worldRank ? `World Rank #${golfer.worldRank}` : 'PGA Tour'}
            </div>
            <div style={{ marginTop: 10 }}>
              {golfer.live ? (
                <Pill kind="live" leadingDot>{`Playing${golfer.thru ? ` · Thru ${golfer.thru}` : ''}${golfer.round ? ` · R${golfer.round}` : ''}`}</Pill>
              ) : golfer.status === 'mc' || golfer.status === 'MC' ? (
                <Pill kind="mc">MC</Pill>
              ) : golfer.status === 'wd' ? (
                <Pill kind="mc">WD</Pill>
              ) : golfer.status === 'finished' ? (
                <Pill kind="finished">Finished</Pill>
              ) : loading ? (
                <Pill kind="neutral">Loading…</Pill>
              ) : (
                <Pill kind="neutral">{golfer.price != null ? `$${golfer.price}` : '—'}</Pill>
              )}
            </div>
          </div>

          <div style={{ margin: '0 16px 16px', padding: '14px 16px', background: C.surface2, borderRadius: 12 }}>
            <div style={{
              font: '500 11px/16px Inter', textTransform: 'uppercase', letterSpacing: 0.04 * 11,
              color: C.text3,
            }}>Current event</div>
            <div style={{
              display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginTop: 6,
            }}>
              <div style={{ font: '600 16px/22px Inter', color: C.text }}>
                {golfer.status === 'mc' || golfer.status === 'MC' ? 'Missed cut'
                : golfer.status === 'finished' ? 'Finished'
                : golfer.live ? 'On the course'
                : loading ? 'Loading…'
                : 'Pre-tournament'}
              </div>
              <div className="tnum" style={{ font: '700 28px/32px Inter', color: C.emerald }}>
                {Number(golfer.points || 0).toFixed(1)}
              </div>
            </div>
            <div style={{ font: '400 13px/20px Inter', color: C.text2, marginTop: 6 }}>
              {[
                golfer.r1 != null && `R1 ${golfer.r1}`,
                golfer.r2 != null && `R2 ${golfer.r2}`,
                golfer.r3 != null && `R3 ${golfer.r3}`,
                golfer.r4 != null && `R4 ${golfer.r4}`,
                golfer.score_to_par != null && `${golfer.score_to_par > 0 ? '+' : ''}${golfer.score_to_par}`,
              ].filter(Boolean).join(' · ') || 'Per-round scores appear after Round 1 begins.'}
            </div>
          </div>

          <div style={{ borderBottom: `1px solid ${C.hairline}` }}>
            <Tabs items={['Overview', 'Game Log', 'Stats']} active={tab} onChange={setTab} />
          </div>

          {tab === 'Game Log' && <GameLogTab />}
          {tab === 'Overview' && <OverviewTab golfer={golfer} />}
          {tab === 'Stats'    && <StatsTab golfer={golfer} />}
        </div>
      </div>
    </Screen>
  );
}

function GameLogTab() {
  // Per-golfer career game log isn't in the schema yet (no game_log table);
  // we'd need to add Tour-API-sourced history. Show an honest empty state.
  return (
    <div style={{ padding: '32px 24px', color: C.text2, font: '400 13px/20px Inter', textAlign: 'center' }}>
      Career game log isn't tracked yet.<br/>
      Past-event stats appear in the database after the season's first major wraps.
    </div>
  );
}

function OverviewTab({ golfer }) {
  return (
    <div style={{ padding: '16px' }}>
      <div style={{
        display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12,
      }}>
        <Stat label="World rank" value={golfer.worldRank ? `#${golfer.worldRank}` : '—'} />
        <Stat label="Salary" value={golfer.price != null ? `$${golfer.price}` : '—'} />
        <Stat label="This event" value={Number(golfer.points || 0).toFixed(1)} />
        <Stat label="Status" value={golfer.live ? 'Playing' : golfer.status === 'mc' || golfer.status === 'MC' ? 'MC' : golfer.status === 'finished' ? 'Finished' : '—'} />
      </div>
      <div style={{ marginTop: 14, color: C.text3, font: '400 12px/18px Inter' }}>
        Career stats (cuts made, top 10s, earnings) require a Tour-API integration that isn't wired yet.
      </div>
    </div>
  );
}

function StatsTab({ golfer }) {
  // Per-round stats would need to be parsed from the live feed (SG: OTT etc).
  // For now show the per-round scores we already have, and an honest note.
  const rounds = [
    { label: 'R1', val: golfer.r1 },
    { label: 'R2', val: golfer.r2 },
    { label: 'R3', val: golfer.r3 },
    { label: 'R4', val: golfer.r4 },
  ];
  const hasAny = rounds.some((r) => r.val != null);
  return (
    <div style={{ padding: '16px' }}>
      {hasAny ? (
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr 1fr', gap: 8 }}>
          {rounds.map((r, i) => (
            <div key={i} style={{ padding: '12px 14px', background: C.surface2, borderRadius: 12 }}>
              <div style={{ font: '500 11px/16px Inter', color: C.text3, textTransform: 'uppercase', letterSpacing: 0.04 * 11 }}>{r.label}</div>
              <div className="tnum" style={{ font: '700 22px/28px Inter', color: C.text, marginTop: 4 }}>{r.val != null ? r.val : '—'}</div>
            </div>
          ))}
        </div>
      ) : (
        <div style={{ padding: '24px 4px', color: C.text2, font: '400 13px/20px Inter', textAlign: 'center' }}>
          Round scores appear after the first tee time.
        </div>
      )}
    </div>
  );
}

function Stat({ label, value }) {
  return (
    <div style={{ padding: '10px 12px', background: C.surface2, borderRadius: 10 }}>
      <div style={{ font: '500 11px/16px Inter', color: C.text3, textTransform: 'uppercase', letterSpacing: 0.04 * 11 }}>{label}</div>
      <div className="tnum" style={{ font: '700 18px/22px Inter', color: C.text, marginTop: 2 }}>{value}</div>
    </div>
  );
}

Object.assign(window, { GolferDetailScreen });
