/* global React, C, Screen, Header, Avatar, Pill, Tabs, Toggle, RosterRow, Chevron, Close, Sparkline */
// screens-profile.jsx — Public member profile.
// Tapping any avatar (standings, matchup, clubhouse) opens this.

function ProfileScreen() {
  const payload = window.useStore((s) => s.sheetPayload) || {};
  const me = window.useStore((s) => s.me) || {};
  const close = () => { const n = window.appNav; if (n) n.closeSheet?.(); };

  const [member, setMember] = React.useState(payload.memberId ? null : payload);
  const [stats, setStats] = React.useState(null);
  const [lineup, setLineup] = React.useState(null);
  const [tournament, setTournament] = React.useState(null);

  React.useEffect(() => {
    const api = window.cambamApi;
    if (!api || !api.isConfigured?.()) return;
    let cancelled = false;
    (async () => {
      try {
        const t = await api.currentTournament?.();
        if (cancelled) return;
        setTournament(t || null);
        const memberId = payload.memberId || payload.id;
        if (memberId) {
          const [m, s, ln] = await Promise.all([
            api.loadMemberProfile(memberId),
            api.loadMemberStats(memberId, 2026),
            t ? api.loadMemberLineup(memberId, t.id) : Promise.resolve(null),
          ]);
          if (cancelled) return;
          if (m) setMember(m);
          setStats(s);
          setLineup(ln);
        }
      } catch (e) { console.warn('profile load failed', e); }
    })();
    return () => { cancelled = true; };
  }, [payload.memberId, payload.id]);

  const m = member || {};
  const displayName = m.display_name || m.displayName || m.name || payload.name || '—';
  const handle = m.handle || payload.handle || '';
  const tone = m.avatar_tone ?? m.tone ?? payload.tone ?? 1;
  const champion = !!(m.champion || payload.champion);
  const joinedAt = m.joined_at ? new Date(m.joined_at).toLocaleDateString('en-US', { month: 'short', year: 'numeric' }) : '';
  const roleLabel = m.role === 'commissioner' ? 'Commissioner' : m.role === 'deputy' ? 'Deputy' : 'Member';
  const isYou = (m.id && m.id === me.id) || handle === me.handle;

  return (
    <Screen label="11 Profile" bottomNav={null}>
      <Header
        title=""
        subtitle=""
        onBack
        right={<button onClick={close} style={{
          width: 40, height: 40, borderRadius: 999, background: 'transparent',
          border: 'none', cursor: 'pointer', color: C.text2,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}><Close size={18} /></button>}
      />

      <div style={{ padding: '0 24px 16px', textAlign: 'center' }}>
        <Avatar name={displayName} size={96} tone={tone} champion={champion} />
        <div style={{ font: '700 24px/30px Inter', color: C.text, marginTop: 14 }}>{displayName}</div>
        <div style={{ font: '400 14px/20px Inter', color: C.text2, marginTop: 2 }}>
          {[handle, roleLabel, joinedAt && `Joined ${joinedAt}`].filter(Boolean).join(' · ')}
        </div>
        {isYou && (
          <div style={{ marginTop: 14 }}>
            <Pill kind="paid">You</Pill>
          </div>
        )}
      </div>

      <SectionLabel>2026 season</SectionLabel>
      <div style={{
        margin: '0 16px 24px', padding: '16px 20px',
        background: C.surface, borderRadius: 12,
        display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12,
      }}>
        <Stat label="Season" value={(stats?.total_pts ?? 0).toFixed(1)} />
        <Stat label="Events" value={String(stats?.events_played ?? 0)} tone="emerald" />
        <Stat label="Best"   value={stats?.best_rank ? `#${stats.best_rank}` : '—'} sub={stats?.best_event?.name || ''} />
      </div>

      <SectionLabel right={tournament?.name || ''}>{handle ? `${handle}'s lineup` : 'Lineup'}</SectionLabel>
      <div style={{ margin: '0 0 24px' }}>
        {!lineup ? (
          <div style={{ padding: '20px 24px', color: C.text2, font: '400 13px/18px Inter', textAlign: 'center' }}>
            {tournament?.status === 'upcoming' ? 'Lineup hidden until lock.' : 'No lineup recorded.'}
          </div>
        ) : (lineup.lineup_golfers || []).slice().sort((a, b) => a.slot - b.slot).map((g) => (
          <RosterRow key={g.slot} name={g.golfer_name} country="" price={g.price} points={0} tone={1} status="" />
        ))}
      </div>
    </Screen>
  );
}

function ActionBtn({ label, primary }) {
  return (
    <button style={{
      height: 48, borderRadius: 8,
      background: primary ? C.emerald : C.surface,
      color: primary ? '#0a0a0a' : C.text,
      border: primary ? 'none' : `1px solid ${C.hairline}`,
      font: '600 14px/1 Inter', cursor: 'pointer',
    }}>{label}</button>
  );
}

function Stat({ label, value, sub, tone }) {
  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, right }) {
  return (
    <div style={{
      padding: '0 16px 12px',
      display: 'flex', alignItems: 'baseline', justifyContent: 'space-between',
    }}>
      <span style={{
        font: '500 11px/16px Inter', textTransform: 'uppercase', letterSpacing: 0.04 * 11,
        color: C.text3,
      }}>{children}</span>
      {right && <span style={{ font: '400 11px/16px Inter', color: C.text3 }}>{right}</span>}
    </div>
  );
}

function TrophyChip({ icon, label, sub, earned }) {
  return (
    <div style={{
      padding: '12px 8px', borderRadius: 12,
      background: earned ? 'rgba(31, 138, 91, 0.10)' : C.surface,
      border: `1px solid ${earned ? C.emerald : C.hairline}`,
      opacity: earned ? 1 : 0.55,
      display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
    }}>
      <span style={{
        width: 28, height: 28, borderRadius: 999,
        background: earned ? C.emerald : C.surface2,
        color: earned ? '#0a0a0a' : C.text3,
        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>
  );
}

Object.assign(window, { ProfileScreen });
