/* global React, C, Screen, Header, Tabs, Segmented, RosterRow, Toggle, Avatar, Pill, Chevron, GOLFERS, OPP_LINEUP */
// screens-5.jsx — PGA Matchup view

function PGAMatchupScreen() {
  const me = window.useStore((s) => s.me);
  const matchup = window.useStore((s) => s.matchup);
  const opponentHandle = matchup.opponentHandle;
  const dimCommon = matchup.dimCommon;
  const mode = matchup.mode;

  const [tournament, setTournament] = React.useState(null);
  const [standings, setStandings] = React.useState([]);
  const [myLineup, setMyLineup] = React.useState(null);
  const [oppLineup, setOppLineup] = React.useState(null);
  const [oppMember, setOppMember] = React.useState(null);
  const [loading, setLoading] = React.useState(true);

  // Load tournament + standings + my lineup on mount.
  React.useEffect(() => {
    const api = window.cambamApi;
    if (!api || !api.isConfigured?.()) { setLoading(false); return; }
    let cancelled = false;
    (async () => {
      try {
        const t = await api.currentTournament?.();
        if (cancelled) return;
        setTournament(t || null);
        if (!t) { setLoading(false); return; }
        const [st, mine] = await Promise.all([
          api.loadStandings(t.id),
          api.loadLineup(t.id),
        ]);
        if (cancelled) return;
        setStandings(st || []);
        setMyLineup(mine || null);
        setLoading(false);
      } catch (e) {
        console.warn('matchup load failed', e);
        if (!cancelled) setLoading(false);
      }
    })();
    return () => { cancelled = true; };
  }, []);

  // Resolve opponent member from selected handle (or default to top-ranked non-self).
  React.useEffect(() => {
    if (!standings.length) return;
    let opp = standings.find((r) => r.member?.handle === opponentHandle && r.member?.id !== me?.id)?.member;
    if (!opp) opp = standings.find((r) => r.member?.id !== me?.id)?.member;
    setOppMember(opp || null);
  }, [standings, opponentHandle, me?.id]);

  // Load opponent's lineup when both tournament + opponent are resolved.
  React.useEffect(() => {
    if (!tournament || !oppMember) { setOppLineup(null); return; }
    const api = window.cambamApi;
    if (!api) return;
    let cancelled = false;
    (async () => {
      try {
        const data = await api.loadMemberLineup(oppMember.id, tournament.id);
        if (!cancelled) setOppLineup(data || null);
      } catch (e) {
        console.warn('opp lineup load failed', e);
      }
    })();
    return () => { cancelled = true; };
  }, [tournament?.id, oppMember?.id]);

  const myList = (myLineup?.lineup_golfers || []).slice().sort((a, b) => a.slot - b.slot).map((lg) => ({
    name: lg.golfer_name, golferId: lg.golfer_id, price: lg.price, points: 0, tone: 1,
  }));
  const oppList = (oppLineup?.lineup_golfers || []).slice().sort((a, b) => a.slot - b.slot).map((lg) => ({
    name: lg.golfer_name, golferId: lg.golfer_id, price: lg.price, points: 0, tone: 1,
  }));
  const myNames = new Set(myList.map((g) => g.name));
  const oppNames = new Set(oppList.map((g) => g.name));
  const sharedCount = myList.filter((g) => oppNames.has(g.name)).length;
  const myStanding = standings.find((r) => r.member?.id === me?.id);
  const oppStanding = oppMember ? standings.find((r) => r.member?.id === oppMember.id) : null;

  const openOpponentPicker = () => {
    if (window.appNav) window.appNav.openSheet('member-picker', { purpose: 'matchup-opponent' });
  };

  const oppDisplay = oppMember
    ? { name: oppMember.display_name || oppMember.handle || '—', handle: oppMember.handle || '', tone: oppMember.avatar_tone, champion: !!oppMember.champion, id: oppMember.id }
    : { name: 'No opponent', handle: '', tone: 2 };

  return (
    <Screen label="05 PGA Matchup" bottomNav="pools">
      <Header
        title={tournament?.name || (loading ? 'Loading…' : 'Matchup')}
        subtitle="Head-to-head"
        onBack
      />
      <Tabs items={['Lineup', 'Standings', 'Matchup', 'Clubhouse']} active="Matchup" onChange={poolTab} />

      {!tournament && !loading && (
        <div style={{ padding: '32px 24px', color: C.text2, font: '400 14px/22px Inter', textAlign: 'center' }}>
          No tournament selected.
        </div>
      )}

      {tournament && standings.length < 2 && !loading && (
        <div style={{ padding: '32px 24px', color: C.text2, font: '400 14px/22px Inter', textAlign: 'center' }}>
          Add at least one other member to enable matchups.
        </div>
      )}

      {tournament && standings.length >= 2 && (
        <>
          <div style={{ padding: '14px 16px 8px' }}>
            <button onClick={openOpponentPicker} style={{
              width: '100%', height: 44, background: C.surface, border: 'none',
              borderRadius: 8, padding: '0 14px',
              display: 'flex', alignItems: 'center', justifyContent: 'space-between',
              color: C.text, cursor: 'pointer',
            }}>
              <span style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <span style={{
                  font: '500 11px/16px Inter', textTransform: 'uppercase', letterSpacing: 0.04 * 11, color: C.text3,
                }}>vs</span>
                <span style={{ font: '600 15px/20px Inter', color: C.text }}>{oppDisplay.name}</span>
                <span style={{ font: '400 13px/18px Inter', color: C.text2 }}>{oppDisplay.handle}</span>
              </span>
              <Chevron dir="down" size={14} />
            </button>
          </div>

          <ScoreBlock
            me={myList} opp={oppList} oppMember={oppDisplay} mode={mode}
            myPoints={myStanding ? Number(myStanding.fantasy_pts || 0) : 0}
            oppPoints={oppStanding ? Number(oppStanding.fantasy_pts || 0) : 0}
            myRank={myStanding?.rank} oppRank={oppStanding?.rank}
          />

          <div style={{ padding: '4px 16px 12px' }}>
            <Segmented
              items={['Live', 'Projected']}
              active={mode === 'projected' ? 'Projected' : 'Live'}
              onChange={(v) => window.STORE.patch('matchup', { mode: v.toLowerCase() })}
              size="sm"
            />
          </div>

          {oppMember && !oppLineup && tournament.status === 'upcoming' && (
            <div style={{ margin: '0 16px 12px', padding: '12px 14px', background: C.surface, borderRadius: 8, color: C.text2, font: '400 13px/18px Inter' }}>
              {oppDisplay.name}'s lineup is hidden until lineups lock.
            </div>
          )}

          <div style={{ padding: '0 0 4px' }}>
            {Array.from({ length: Math.max(6, Math.max(myList.length, oppList.length)) }).map((_, i) => {
              const m = myList[i], o = oppList[i];
              const mCommon = m && oppNames.has(m.name);
              const oCommon = o && myNames.has(o.name);
              return (
                <div key={i} style={{
                  display: 'grid', gridTemplateColumns: '1fr 1px 1fr',
                  alignItems: 'stretch',
                  padding: '8px 0',
                  borderTop: i > 0 ? `1px solid ${C.hairline}` : 'none',
                }}>
                  <MiniGolfer g={m} side="me"  dim={dimCommon && mCommon} />
                  <div style={{ width: 1, background: C.hairline, margin: '6px 0' }} />
                  <MiniGolfer g={o} side="opp" dim={dimCommon && oCommon} />
                </div>
              );
            })}
          </div>

          <div style={{
            margin: '16px 16px 0',
            padding: '12px 14px', background: C.surface, borderRadius: 12,
            display: 'flex', alignItems: 'center', gap: 12,
          }}>
            <div style={{ flex: 1 }}>
              <div style={{ font: '500 16px/22px Inter', color: C.text }}>Dim common players</div>
              <div style={{ font: '400 12px/16px Inter', color: C.text2, marginTop: 2 }}>
                {sharedCount} of your {myList.length} also picked by {oppDisplay.name.split(' ')[0]}
              </div>
            </div>
            <Toggle on={dimCommon} onChange={(v) => window.STORE.patch('matchup', { dimCommon: v })} />
          </div>
        </>
      )}

      <div style={{ height: 16 }} />
    </Screen>
  );
}

function ScoreBlock({ me = [], opp = [], oppMember, mode = 'live', myPoints = 0, oppPoints = 0, myRank, oppRank }) {
  const myMember = window.useStore((s) => s.me) || { displayName: 'CamBam', handle: '@cambam', tone: 6 };
  const myPts  = Number(myPoints) || 0;
  const oppPts = Number(oppPoints) || 0;
  const myFilled  = me.filter(Boolean).length;
  const oppFilled = opp.filter(Boolean).length;
  // Projected = naive 2x once half the tournament is past; otherwise just current pts.
  const myProj  = myPts * 2;
  const oppProj = oppPts * 2;
  const oppName = oppMember && oppMember.name || 'Opponent';
  const oppHandle = oppMember && oppMember.handle || '';

  return (
    <div style={{
      margin: '0 16px', background: C.surface, borderRadius: 12, padding: 16,
      position: 'relative', overflow: 'hidden',
    }}>
      <div style={{
        position: 'absolute', inset: 0, pointerEvents: 'none',
        background: 'radial-gradient(circle at 50% 0%, rgba(31, 138, 91,0.06) 0%, transparent 65%)',
      }} />

      <div style={{
        display: 'grid', gridTemplateColumns: '1fr 1fr', alignItems: 'center', gap: 24,
        position: 'relative',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <Avatar name={myMember.displayName} size={44} tone={myMember.tone || 6} ring />
          <div>
            <div style={{ font: '600 15px/20px Inter', color: C.text }}>{myMember.displayName}</div>
            <div style={{ font: '400 12px/16px Inter', color: C.text2 }}>{myMember.handle}</div>
          </div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, justifyContent: 'flex-end' }}>
          <div style={{ textAlign: 'right' }}>
            <div style={{ font: '600 15px/20px Inter', color: C.text }}>{oppName}</div>
            <div style={{ font: '400 12px/16px Inter', color: C.text2 }}>{oppHandle}</div>
          </div>
          <Avatar name={oppName} size={44} tone={(oppMember && oppMember.tone) || 2} champion={oppMember && oppMember.champion} />
        </div>
      </div>

      <div style={{
        display: 'grid', gridTemplateColumns: '1fr auto 1fr',
        alignItems: 'center', marginTop: 14, position: 'relative',
      }}>
        <div className="tnum" style={{ font: '700 36px/40px Inter', color: myPts >= oppPts ? C.emerald : C.text }}>
          {myPts.toFixed(1)}
        </div>
        <div style={{
          font: '500 11px/14px Inter', textTransform: 'uppercase', letterSpacing: 0.04 * 11,
          color: C.text3, padding: '0 16px', textAlign: 'center',
        }}>{mode === 'projected' ? 'Proj' : 'Pts'}</div>
        <div className="tnum" style={{ font: '700 36px/40px Inter', color: oppPts > myPts ? C.emerald : C.text, textAlign: 'right' }}>
          {oppPts.toFixed(1)}
        </div>
      </div>

      <div style={{ marginTop: 14, display: 'flex', flexDirection: 'column', gap: 10, position: 'relative' }}>
        <StatRow label={mode === 'projected' ? 'Live' : 'Proj'} left={myProj.toFixed(1)} right={oppProj.toFixed(1)} leftWin={myProj >= oppProj} rightWin={oppProj > myProj} />
        <StatRow label="Rank"  left={myRank != null ? `#${myRank}` : '—'}    right={oppRank != null ? `#${oppRank}` : '—'}    leftWin={myRank != null && oppRank != null && myRank < oppRank} rightWin={myRank != null && oppRank != null && oppRank < myRank} />
        <StatRow label="Picks" left={`${myFilled}/6`}    right={`${oppFilled}/6`} />
      </div>
    </div>
  );
}

function StatRow({ label, left, right, leftWin, rightWin }) {
  return (
    <div style={{
      display: 'grid', gridTemplateColumns: '1fr auto 1fr', alignItems: 'center', gap: 12,
    }}>
      <div className="tnum" style={{
        font: '500 15px/20px Inter', color: leftWin ? C.emerald : C.text,
        textAlign: 'left',
      }}>{left}</div>
      <div style={{
        font: '500 11px/14px Inter', textTransform: 'uppercase', letterSpacing: 0.04 * 11,
        color: C.text3, padding: '0 6px', minWidth: 44, textAlign: 'center',
      }}>{label}</div>
      <div className="tnum" style={{
        font: '500 15px/20px Inter', color: rightWin ? C.emerald : C.text,
        textAlign: 'right',
      }}>{right}</div>
    </div>
  );
}

function MiniGolfer({ g, side, dim }) {
  if (!g) return <div />;
  const align = side === 'me' ? 'left' : 'right';
  const flexDir = side === 'me' ? 'row' : 'row-reverse';
  const mc = g.mc;
  const open = () => { const n = window.appNav; if (n) n.openSheet('golfer-detail', g); };
  return (
    <div
      role="button" tabIndex={0} onClick={open}
      onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') open(); }}
      style={{
        display: 'flex', alignItems: 'center', gap: 10,
        padding: '0 14px', flexDirection: flexDir,
        opacity: dim ? 0.3 : 1, transition: 'opacity 200ms ease-out',
        position: 'relative', cursor: 'pointer',
      }}>
      <Avatar name={g.name} size={36} tone={g.tone} />
      <div style={{ flex: 1, minWidth: 0, textAlign: align }}>
        <div style={{
          font: '600 14px/18px Inter', color: C.text,
          whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
        }}>{g.name}</div>
        <div className="tnum" style={{
          font: '600 16px/20px Inter', color: mc ? C.red : C.text,
          marginTop: 2,
        }}>{Number(g.points || 0).toFixed(1)}</div>
      </div>
      {g.live && !dim && (
        <div className="live-pulse" style={{
          position: 'absolute', [side === 'me' ? 'right' : 'left']: 0, top: 8, bottom: 8, width: 2,
          background: C.emerald, borderRadius: 1,
        }} />
      )}
    </div>
  );
}

// MarginBars used to back a head-to-head card with hardcoded sample weeks.
// Kept around for when we wire it to real member_event_scores history.
function MarginBars({ margins }) {
  const max = Math.max(...margins.map(Math.abs));
  return (
    <div style={{
      display: 'flex', gap: 4, alignItems: 'center',
      height: 36, justifyContent: 'center',
    }}>
      {margins.map((m, i) => {
        const h = Math.max(4, (Math.abs(m) / max) * 16);
        const up = m > 0;
        return (
          <div key={i} style={{
            width: 8, height: 36, display: 'flex', flexDirection: 'column',
            alignItems: 'center', justifyContent: 'center',
            position: 'relative',
          }}>
            <div style={{
              width: 4, height: up ? h : 0, background: C.emerald,
              borderRadius: 2, marginBottom: up ? 1 : 0,
            }} />
            <div style={{ width: 8, height: 1, background: C.hairline }} />
            <div style={{
              width: 4, height: up ? 0 : h, background: C.text2,
              borderRadius: 2, marginTop: up ? 0 : 1,
            }} />
          </div>
        );
      })}
    </div>
  );
}

Object.assign(window, { PGAMatchupScreen });
