/* global React, C, Screen, Header, Avatar, Pill, Check, Chevron */
// screens-stats.jsx — personal Stats tab.

function StatsScreen() {
  const me = window.useStore((s) => s.me) || {};
  const [stats, setStats] = React.useState(null);
  const [tournaments, setTournaments] = React.useState([]);
  const [membersCount, setMembersCount] = React.useState(0);

  React.useEffect(() => {
    const api = window.cambamApi;
    if (!api || !api.isConfigured?.() || !me.id) return;
    let cancelled = false;
    (async () => {
      try {
        const [s, ts, ms] = await Promise.all([
          api.loadMemberStats(me.id, 2026),
          api.loadAllTournaments(2026),
          api.loadAllMembers(),
        ]);
        if (cancelled) return;
        setStats(s);
        setTournaments(ts || []);
        setMembersCount((ms || []).length || 1);
      } catch (e) { console.warn('stats load failed', e); }
    })();
    return () => { cancelled = true; };
  }, [me.id]);

  const myRowFor = (tournamentId) => stats?.rows?.find((r) => r.tournament?.id === tournamentId);
  const seasonRankLabel = stats && stats.events_played > 0 ? `${stats.best_rank ?? '—'}/${membersCount}` : `—/${membersCount}`;
  const bestEvent = stats?.best_event ? stats.best_event.name : '—';
  const bestResult = stats?.best_rank != null ? `#${stats.best_rank}` : '—';

  return (
    <Screen label="08 Stats" bottomNav="stats">
      <Header
        title="Stats"
        subtitle={`${me.handle || ''} · 2026 season`}
      />

      {/* Identity card */}
      <div style={{
        margin: '4px 16px 16px', padding: '20px',
        background: C.surface, borderRadius: 12,
        display: 'flex', alignItems: 'center', gap: 14,
      }}>
        <Avatar name={me.displayName || me.handle || 'You'} size={56} tone={me.tone || 6} champion={!!me.champion} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ font: '600 20px/26px Inter', color: C.text }}>{me.displayName || me.handle || 'You'}</div>
          <div style={{ font: '400 13px/18px Inter', color: C.text2, marginTop: 2 }}>
            {me.email || ''}
          </div>
          <div style={{
            font: '500 11px/16px Inter', color: C.text3, marginTop: 4,
            textTransform: 'uppercase', letterSpacing: 0.04 * 11,
          }}>{me.role === 'commissioner' ? 'Commissioner' : me.role === 'deputy' ? 'Deputy' : 'Member'} · {membersCount} member{membersCount === 1 ? '' : 's'}</div>
        </div>
      </div>

      {/* Season summary */}
      <div style={{
        margin: '0 16px 24px', padding: '16px 20px',
        background: C.surface, borderRadius: 12,
        display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12,
      }}>
        <StatCell label="Season" value={(stats?.total_pts ?? 0).toFixed(1)} tone="text" />
        <StatCell label="Rank"   value={seasonRankLabel} tone="text" />
        <StatCell label="Best"   value={bestResult}   sub={bestEvent} tone="emerald" />
      </div>

      {/* My majors */}
      <SectionLabel>My five</SectionLabel>
      <div style={{ margin: '0 16px 24px', background: C.surface, borderRadius: 12, overflow: 'hidden' }}>
        {tournaments.length === 0 ? (
          <div style={{ padding: '16px 20px', color: C.text2, font: '400 13px/18px Inter' }}>No tournaments yet.</div>
        ) : tournaments.map((t, i) => {
          const my = myRowFor(t.id);
          const startsAt = t.starts_at ? new Date(t.starts_at) : null;
          const endsAt = t.ends_at ? new Date(t.ends_at) : null;
          const range = startsAt && endsAt
            ? `${startsAt.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}–${endsAt.toLocaleDateString('en-US', { day: 'numeric' })}`
            : '';
          return (
            <MajorRow
              key={t.id}
              major={t.name}
              venue={t.venue}
              state={t.status === 'final' ? 'done' : t.status === 'live' ? 'live' : 'upcoming'}
              result={my ? `#${my.rank ?? '—'}` : (t.status === 'live' ? 'LIVE' : null)}
              pts={my ? Number(my.fantasy_pts || 0).toFixed(1) : null}
              when={!my && range ? range : null}
              last={i === tournaments.length - 1}
            />
          );
        })}
      </div>

      <SectionLabel>Career</SectionLabel>
      <div style={{ margin: '0 16px 24px', background: C.surface, borderRadius: 12 }}>
        <CareerRow label="Events played" value={String(stats?.events_played ?? 0)} />
        <CareerRow label="Total points" value={(stats?.total_pts ?? 0).toFixed(1)} />
        <CareerRow label="Best finish" value={stats?.best_rank ? `#${stats.best_rank}` : '—'} sub={bestEvent} last />
      </div>

      <div style={{
        margin: '0 16px 32px', padding: '14px 18px',
        background: C.surface, borderRadius: 12, color: C.text3,
        font: '400 12px/18px Inter',
      }}>
        Trophies, buy-in ledger, and head-to-head are coming as the season's data accumulates.
      </div>
    </Screen>
  );
}

// ─── Bits ───────────────────────────────────────────────────────────

function StatCell({ label, value, sub, tone = 'text' }) {
  return (
    <div>
      <div style={{
        font: '500 11px/16px Inter', textTransform: 'uppercase', letterSpacing: 0.04 * 11,
        color: C.text3,
      }}>{label}</div>
      <div className="tnum" style={{
        font: '700 22px/28px Inter',
        color: tone === 'emerald' ? C.emerald : C.text,
        marginTop: 2,
      }}>{value}</div>
      {sub && <div style={{
        font: '400 11px/16px Inter', color: C.text3, marginTop: 1,
      }}>{sub}</div>}
    </div>
  );
}

function SectionLabel({ children }) {
  return (
    <div style={{
      padding: '0 16px 12px',
      font: '500 11px/16px Inter', textTransform: 'uppercase', letterSpacing: 0.04 * 11,
      color: C.text3,
    }}>{children}</div>
  );
}

function Trophy({ icon, label, sub, earned, locked, unclaimed }) {
  const ring = earned ? C.emerald : locked ? C.emeraldMute : C.hairline;
  const fill = earned ? 'rgba(31, 138, 91, 0.12)' : 'transparent';
  const iconColor = earned ? C.emerald : locked ? C.text2 : C.text3;
  return (
    <div style={{
      padding: '12px 8px', borderRadius: 12,
      background: C.surface, border: `1px solid ${ring}`,
      backgroundColor: fill || C.surface,
      display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
      opacity: unclaimed ? 0.55 : 1,
    }}>
      <span style={{
        width: 28, height: 28, borderRadius: 999,
        background: earned ? C.emerald : C.surface2,
        color: earned ? '#0a0a0a' : iconColor,
        font: '700 14px/1 Inter',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>{icon}</span>
      <span style={{
        font: '600 11px/14px Inter', color: C.text, textAlign: 'center',
      }}>{label}</span>
      <span style={{
        font: '400 10px/14px Inter', color: C.text3, textAlign: 'center',
      }}>{sub}</span>
    </div>
  );
}

function MajorRow({ major, venue, state, result, pts, when, winner, last }) {
  const live = state === 'live';
  const done = state === 'done';
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 12,
      padding: '14px 16px',
      borderBottom: last ? 'none' : `1px solid ${C.hairline}`,
    }}>
      <div style={{
        width: 32, height: 32, borderRadius: 999,
        background: done ? C.emeraldMute : live ? 'rgba(31, 138, 91, 0.18)' : C.surface2,
        color: done ? C.emerald : live ? C.emerald : C.text3,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        {done && <Check size={14} />}
        {live && <span className="live-pulse" style={{ width: 8, height: 8, borderRadius: 999, background: C.emerald }} />}
        {!done && !live && <span style={{ font: '600 11px/1 Inter' }}>{major.slice(0, 1)}</span>}
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ font: '600 15px/20px Inter', color: C.text }}>{major}</div>
        <div style={{ font: '400 12px/16px Inter', color: C.text2, marginTop: 1 }}>
          {venue}{winner && <> · won by <span style={{ color: C.text }}>{winner}</span></>}
        </div>
      </div>
      <div style={{ textAlign: 'right' }}>
        {result && (
          <div style={{
            font: '600 14px/18px Inter',
            color: live ? C.emerald : C.text,
          }}>{result}</div>
        )}
        {pts && (
          <div className="tnum" style={{
            font: '700 16px/22px Inter', color: C.text, marginTop: 1,
          }}>{pts}</div>
        )}
        {when && !pts && (
          <div style={{
            font: '500 13px/18px Inter', color: C.text2,
          }}>{when}</div>
        )}
      </div>
    </div>
  );
}

function CareerRow({ label, value, sub, last }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 12,
      padding: '14px 20px',
      borderBottom: last ? 'none' : `1px solid ${C.hairline}`,
    }}>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{
          font: '500 11px/16px Inter', textTransform: 'uppercase', letterSpacing: 0.04 * 11,
          color: C.text3,
        }}>{label}</div>
        {sub && <div style={{ font: '400 12px/16px Inter', color: C.text2, marginTop: 1 }}>{sub}</div>}
      </div>
      <div className="tnum" style={{ font: '600 15px/20px Inter', color: C.text, textAlign: 'right' }}>
        {value}
      </div>
    </div>
  );
}

// Gear icon (settings)
function Gear({ size = 20 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor"
      strokeWidth={1.7} strokeLinecap="round" strokeLinejoin="round">
      <circle cx="12" cy="12" r="3"/>
      <path d="M19.4 15a1.65 1.65 0 00.33 1.82l.06.06a2 2 0 11-2.83 2.83l-.06-.06a1.65 1.65 0 00-1.82-.33 1.65 1.65 0 00-1 1.51V21a2 2 0 11-4 0v-.09a1.65 1.65 0 00-1-1.51 1.65 1.65 0 00-1.82.33l-.06.06a2 2 0 11-2.83-2.83l.06-.06a1.65 1.65 0 00.33-1.82 1.65 1.65 0 00-1.51-1H3a2 2 0 110-4h.09a1.65 1.65 0 001.51-1 1.65 1.65 0 00-.33-1.82l-.06-.06a2 2 0 112.83-2.83l.06.06a1.65 1.65 0 001.82.33h0a1.65 1.65 0 001-1.51V3a2 2 0 014 0v.09a1.65 1.65 0 001 1.51 1.65 1.65 0 001.82-.33l.06-.06a2 2 0 112.83 2.83l-.06.06a1.65 1.65 0 00-.33 1.82v0a1.65 1.65 0 001.51 1H21a2 2 0 110 4h-.09a1.65 1.65 0 00-1.51 1z"/>
    </svg>
  );
}

Object.assign(window, { StatsScreen });
