// screens/matchday-social.jsx — club identity and leaderboards
//
// Split out of matchday.jsx to keep that file manageable. Exposes:
//   window.ClubPicker        pick the club you support
//   window.ClubBadge         kit + name, used under a profile name
//   window.MatchdayLeaderboard  global / fanbase, windowed
//
// The club matters beyond decoration: md_scores snapshots club_id at play time,
// which is what makes the fanbase table possible.

(function () {
  const T = () => window.T;

  // ── Club picker ────────────────────────────────────────────────────────────
  function ClubPicker({ anonId, current, onPicked, onClose }) {
    const TT = T();
    const [clubs, setClubs] = React.useState(null);
    const [q, setQ] = React.useState('');
    const [saving, setSaving] = React.useState(null);

    React.useEffect(() => {
      window.fetchClubs().then(setClubs).catch(() => setClubs([]));
    }, []);

    const pick = async (c) => {
      setSaving(c.slug);
      try {
        await window.setMyClub(c.slug, anonId);
        onPicked && onPicked(c);
        onClose && onClose();
      } catch (e) {
        alert('Could not save: ' + e.message);
      } finally { setSaving(null); }
    };

    const norm = (s) => (s || '').normalize('NFKD')
      .replace(/[\u0300-\u036f]/g, '').toLowerCase();
    const filtered = !clubs ? [] :
      clubs.filter(c => !q || norm(c.name).includes(norm(q)));

    // group by country so the list is scannable at 100+ clubs
    const grouped = filtered.reduce((acc, c) => {
      (acc[c.country || 'Other'] = acc[c.country || 'Other'] || []).push(c);
      return acc;
    }, {});

    return (
      <div onClick={onClose} style={{
        position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.65)',
        display: 'flex', alignItems: 'flex-end', justifyContent: 'center', zIndex: 1000,
      }}>
        <div onClick={e => e.stopPropagation()} style={{
          background: TT.navy950, width: '100%', maxWidth: 480, height: '82vh',
          borderRadius: '18px 18px 0 0', display: 'flex', flexDirection: 'column',
          border: `1px solid ${TT.border}`,
        }}>
          <div style={{ padding: '16px 16px 12px', borderBottom: `1px solid ${TT.border}` }}>
            <div style={{ display: 'flex', justifyContent: 'space-between',
              alignItems: 'center', marginBottom: 4 }}>
              <div style={{ fontFamily: 'Bakbak One,sans-serif', fontSize: 16,
                color: TT.text, letterSpacing: '0.03em' }}>PICK YOUR CLUB</div>
              <button onClick={onClose} style={{ background: 'transparent',
                border: 'none', color: TT.textSec, fontSize: 22, cursor: 'pointer' }}>×</button>
            </div>
            <div style={{ fontSize: 11, color: TT.textMute, fontFamily: 'DM Sans',
              marginBottom: 12 }}>
              Your scores count toward your club's fanbase average.
            </div>
            <input
              value={q} onChange={e => setQ(e.target.value)}
              placeholder="Search clubs…" autoComplete="off"
              style={{
                width: '100%', padding: '11px 13px', borderRadius: 10,
                background: TT.navy900, border: `1px solid ${TT.border}`,
                color: TT.text, fontFamily: 'DM Sans', fontSize: 14, outline: 'none',
                boxSizing: 'border-box',
              }} />
          </div>

          <div className="no-scrollbar" style={{ flex: 1, overflowY: 'auto', padding: '8px 12px 24px' }}>
            {!clubs && <div style={{ padding: 24, textAlign: 'center',
              color: TT.textSec, fontSize: 12 }}>Loading…</div>}
            {Object.keys(grouped).sort().map(country => (
              <div key={country}>
                <div style={{ fontSize: 9, letterSpacing: '0.14em', fontWeight: 700,
                  color: TT.textMute, fontFamily: 'DM Sans', margin: '12px 4px 6px',
                  textTransform: 'uppercase' }}>{country}</div>
                {grouped[country].map(c => {
                  const isCurrent = current?.slug === c.slug;
                  return (
                    <div key={c.slug} onClick={() => pick(c)} style={{
                      display: 'flex', alignItems: 'center', gap: 11,
                      padding: '9px 10px', borderRadius: 10, cursor: 'pointer',
                      background: isCurrent ? 'rgba(245,200,66,0.12)' : 'transparent',
                      border: `1px solid ${isCurrent ? 'rgba(245,200,66,0.4)' : 'transparent'}`,
                      opacity: saving && saving !== c.slug ? 0.5 : 1,
                    }}>
                      <window.MatchdayKitSwatch club={c} size={30} />
                      <div style={{ flex: 1, fontFamily: 'DM Sans', fontSize: 13.5,
                        fontWeight: isCurrent ? 700 : 500,
                        color: isCurrent ? TT.gold400 : TT.text }}>{c.name}</div>
                      {isCurrent && <span style={{ color: TT.gold400, fontSize: 13 }}>✓</span>}
                    </div>
                  );
                })}
              </div>
            ))}
          </div>
        </div>
      </div>
    );
  }

  // ── Club badge — kit + name, for under a profile name ──────────────────────
  function ClubBadge({ club, onClick, size = 22 }) {
    const TT = T();
    if (!club) {
      return (
        <button onClick={onClick} style={{
          display: 'inline-flex', alignItems: 'center', gap: 7,
          padding: '5px 11px', borderRadius: 999, cursor: 'pointer',
          background: 'transparent', border: `1px dashed ${TT.border}`,
          color: TT.textSec, fontFamily: 'DM Sans', fontSize: 11.5, fontWeight: 600,
        }}>+ Pick your club</button>
      );
    }
    return (
      <button onClick={onClick} style={{
        display: 'inline-flex', alignItems: 'center', gap: 7,
        padding: '4px 11px 4px 5px', borderRadius: 999, cursor: 'pointer',
        background: 'rgba(255,255,255,0.05)', border: `1px solid ${TT.border}`,
        color: TT.text, fontFamily: 'DM Sans', fontSize: 11.5, fontWeight: 700,
      }}>
        <window.MatchdayKitSwatch club={club} size={size} />
        {club.name}
      </button>
    );
  }

  // ── Leaderboard ────────────────────────────────────────────────────────────
  // Windows exist so a mid-season joiner always has something winnable: you
  // can't retro-fit points for matchdays someone didn't play, so instead the
  // weekly board resets and is open to anyone from day one.
  function MatchdayLeaderboard({ anonId, compact, defaultBoard = 'global' }) {
    const TT = T();
    const [board, setBoard] = React.useState(defaultBoard);
    const [win, setWin] = React.useState('week');
    const [rows, setRows] = React.useState(null);
    const [err, setErr] = React.useState(null);

    React.useEffect(() => {
      let dead = false;
      setRows(null);
      (async () => {
        try {
          const data = board === 'global'
            ? await window.fetchLeaderboard(win, compact ? 5 : 100)
            : await window.fetchFanbaseLeaderboard(win, 1);
          if (!dead) setRows(data);
        } catch (e) { if (!dead) { setErr(e.message); setRows([]); } }
      })();
      return () => { dead = true; };
    }, [board, win, compact]);

    const Toggle = ({ opts, value, onChange }) => (
      <div style={{ display: 'flex', gap: 3, padding: 3, borderRadius: 9,
        background: TT.navy900, border: `1px solid ${TT.border}` }}>
        {opts.map(([k, label]) => (
          <button key={k} onClick={() => onChange(k)} style={{
            flex: 1, padding: '6px 10px', borderRadius: 7, border: 'none',
            cursor: 'pointer', whiteSpace: 'nowrap',
            background: value === k ? TT.gold500 : 'transparent',
            color: value === k ? '#1A1200' : TT.textSec,
            fontFamily: 'DM Sans', fontSize: 11, fontWeight: 700,
          }}>{label}</button>
        ))}
      </div>
    );

    const isMe = (r) => r.anon_id && anonId && r.anon_id === anonId;

    return (
      <div>
        <div style={{ display: 'flex', gap: 6, marginBottom: 10 }}>
          <div style={{ flex: 1 }}>
            <Toggle opts={[['global', 'Players'], ['fanbase', 'Fanbases']]}
              value={board} onChange={setBoard} />
          </div>
          <div style={{ flex: 1 }}>
            <Toggle opts={[['week', 'Week'], ['month', 'Month'], ['all', 'All']]}
              value={win} onChange={setWin} />
          </div>
        </div>

        {err && <div style={{ padding: 16, textAlign: 'center', fontSize: 12,
          fontFamily: 'DM Sans', color: TT.red }}>{err}</div>}

        {!rows && !err && <div style={{ padding: 20, textAlign: 'center',
          color: TT.textSec, fontSize: 12, fontFamily: 'DM Sans' }}>Loading…</div>}

        {rows && !rows.length && (
          <div style={{ padding: '22px 12px', textAlign: 'center' }}>
            <div style={{ fontSize: 12, color: TT.textSec, fontFamily: 'DM Sans' }}>
              {board === 'fanbase'
                ? 'No fanbase scores yet — pick a club and play a matchday.'
                : 'Nobody on the board yet. Play a matchday to be first.'}
            </div>
          </div>
        )}

        {rows && rows.map((r, i) => {
          const mine = board === 'global' && isMe(r);
          return (
            <div key={i} style={{
              display: 'flex', alignItems: 'center', gap: 10,
              padding: '9px 8px', borderBottom: `1px solid ${TT.border}`,
              background: mine ? 'rgba(245,200,66,0.07)' : 'transparent',
              borderRadius: mine ? 8 : 0,
            }}>
              <div style={{ width: 24, textAlign: 'center',
                fontFamily: 'Bakbak One,sans-serif', fontSize: 13,
                color: i < 3 ? TT.gold400 : TT.textMute }}>{r.rank ?? i + 1}</div>

              {(r.club_slug || r.primary_hex) && (
                <window.MatchdayKitSwatch
                  club={{ primary_hex: r.primary_hex, secondary_hex: r.secondary_hex,
                          pattern: r.pattern, name: r.club_name }}
                  size={24} />
              )}

              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontFamily: 'DM Sans', fontSize: 13, fontWeight: 700,
                  color: mine ? TT.gold400 : TT.text,
                  whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                  {board === 'global'
                    ? (r.display_name || 'Anonymous') + (mine ? ' (you)' : '')
                    : r.club_name}
                </div>
                <div style={{ fontSize: 10, color: TT.textMute, fontFamily: 'DM Sans',
                  whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                  {board === 'global'
                    // Club allegiance reads as identity in a way a play count
                    // doesn't, and it's the thing the fanbase table is built on.
                    // Falls back to the count when someone hasn't picked a club.
                    ? (r.club_name
                        ? `${r.club_name} · ${r.avg_points} avg`
                        : `${r.matchdays} matchday${r.matchdays === 1 ? '' : 's'} · ${r.avg_points} avg`)
                    : `${r.fans} fan${r.fans === 1 ? '' : 's'}`}
                </div>
              </div>

              <div style={{ textAlign: 'right' }}>
                <div style={{ fontFamily: 'Bakbak One,sans-serif', fontSize: 15,
                  color: TT.text }}>
                  {board === 'global' ? r.points : r.avg_points}
                </div>
                <div style={{ fontSize: 8.5, color: TT.textMute, fontFamily: 'DM Sans',
                  letterSpacing: '0.06em' }}>
                  {board === 'global' ? 'PTS' : 'AVG'}
                </div>
              </div>
            </div>
          );
        })}

        {board === 'fanbase' && rows && rows.length > 0 && (
          <div style={{ padding: '10px 4px 0', fontSize: 9.5, color: TT.textMute,
            fontFamily: 'DM Sans', lineHeight: 1.5 }}>
            Ranked by average score per supporter, so a small sharp fanbase can
            beat a big one.
          </div>
        )}
      </div>
    );
  }

  window.ClubPicker = ClubPicker;
  window.ClubBadge = ClubBadge;
  window.MatchdayLeaderboard = MatchdayLeaderboard;
})();
