// league.jsx — Leaderboard / Health Behavior Score (League Points)
const { useState: useStateL } = React;

function League({ go, data }) {
  const [tab, setTab] = useStateL('league');
  const [explain, setExplain] = useStateL(false);

  return (
    <Screen bg={T.surface} nav="league">
      <TopBar title="League" right={
        <button onClick={() => setExplain(true)} style={{ width: 42, height: 42, borderRadius: 999, background: T.bg, border: 'none', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', boxShadow: `inset 0 0 0 1px ${T.line}` }}>
          <span style={{ fontSize: 18, fontWeight: 800, color: T.ink2 }}>?</span>
        </button>
      }/>

      {/* safety banner */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 9, padding: '12px 14px', borderRadius: 14, background: T.coralTint, marginBottom: 16 }}>
        <Icon name="leaf" size={18} color={T.coral} sw={2}/>
        <div style={{ fontSize: 12.5, color: T.ink2, fontWeight: 600, lineHeight: 1.4 }}><b style={{ color: T.ink }}>건강 행동</b>만 비교해요. 체중·칼로리·외모는 순위에 쓰지 않아요.</div>
      </div>

      {/* segmented */}
      <div style={{ display: 'flex', gap: 4, padding: 4, background: T.surface2, borderRadius: 14, marginBottom: 18 }}>
        {[['league', 'League'], ['friends', 'Friends'], ['squad', 'Squad']].map(s => (
          <button key={s[0]} onClick={() => setTab(s[0])} style={{
            flex: 1, height: 40, borderRadius: 11, border: 'none', cursor: 'pointer', fontFamily: 'inherit',
            fontSize: 14.5, fontWeight: 700, letterSpacing: -0.2,
            background: tab === s[0] ? T.bg : 'transparent', color: tab === s[0] ? T.ink : T.ink3,
            boxShadow: tab === s[0] ? '0 2px 6px rgba(28,27,25,0.08)' : 'none', transition: 'all .15s',
          }}>{s[1]}</button>
        ))}
      </div>

      {tab === 'league' && <LeagueView data={data} go={go} onExplain={() => setExplain(true)}/>}
      {tab === 'friends' && <FriendsView go={go} data={data}/>}
      {tab === 'squad' && <SquadView go={go} data={data}/>}

      <div style={{ height: 12 }}/>
      <ScoreSheet open={explain} onClose={() => setExplain(false)}/>
    </Screen>
  );
}

const STANDINGS = [
  { rank: 1, name: 'Minji', pts: 420, days: 5, me: false },
  { rank: 2, name: 'Joon', pts: 401, days: 5 },
  { rank: 3, name: 'Sora', pts: 390, days: 4 },
  { rank: 7, name: 'Hana', pts: 355, days: 4 },
  { rank: 8, name: 'You', pts: 342, days: 4, me: true },
  { rank: 9, name: 'Doyun', pts: 337, days: 3 },
  { rank: 27, name: 'Private User', pts: 120, days: 1, priv: true },
  { rank: 28, name: 'Alex', pts: 115, days: 1 },
];

function Row({ r }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 12, padding: '12px 14px', borderRadius: 16,
      background: r.me ? T.coralTint : T.bg,
      boxShadow: r.me ? `inset 0 0 0 2px ${T.coral}` : '0 1px 3px rgba(28,27,25,0.04)',
    }}>
      <div style={{ width: 26, textAlign: 'center', fontSize: 15, fontWeight: 800, color: r.rank <= 3 ? T.amberDark : T.ink3 }}>{r.rank}</div>
      <div style={{ width: 36, height: 36, borderRadius: 999, background: r.priv ? T.surface2 : ['#30B0C7','#FF9500','#34C759','#007AFF','#5856D6'][r.rank % 5], color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 800, fontSize: 14, flexShrink: 0 }}>
        {r.priv ? <Icon name="lock" size={15} color={T.ink3} sw={2}/> : (r.me ? '지' : r.name[0])}
      </div>
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 15.5, fontWeight: r.me ? 800 : 700, color: T.ink }}>{r.name}</div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 4, fontSize: 12.5, color: T.ink3, fontWeight: 600 }}><Icon name="flame" size={13} color={T.amber}/>{r.days} healthy days</div>
      </div>
      <div style={{ fontSize: 16, fontWeight: 800, color: r.me ? T.coralDark : T.ink, fontVariantNumeric: 'tabular-nums' }}>{r.pts}</div>
    </div>
  );
}

function ZoneLabel({ children, tone }) {
  return <div style={{ display: 'flex', alignItems: 'center', gap: 8, margin: '14px 4px 8px' }}>
    <span style={{ width: 6, height: 6, borderRadius: 999, background: tone }}/>
    <span style={{ fontSize: 12, fontWeight: 800, color: tone, letterSpacing: 0.5 }}>{children}</span>
  </div>;
}

function LeagueView({ data, go, onExplain }) {
  const leaderboard = data.leaderboard;
  const league = (leaderboard && leaderboard.league) || {};
  const standings = (window.FitbodyBackend && window.FitbodyBackend.leaderboardRows(leaderboard)) || STANDINGS;
  const pointsToPromotion = league.points_to_promotion || league.pointsToPromotion || 38;
  const rank = league.rank || 8;
  const size = league.size || 28;
  const points = league.points || 342;
  return (
    <div>
      {/* tier card */}
      <Card pad={20} style={{ marginBottom: 14, background: `linear-gradient(150deg, ${T.amberSoft}, ${T.bg})` }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 14 }}>
          <div style={{ width: 48, height: 48, borderRadius: 14, background: `linear-gradient(135deg, #C98A3C, #8A5A22)`, display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="medal" size={26} color="#fff"/></div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 18, fontWeight: 800, color: T.ink }}>{league.name || 'Bronze League'}</div>
            <div style={{ fontSize: 13, color: T.ink3, fontWeight: 600 }}>{league.week_label || league.weekLabel || 'Week 23'} · {league.remaining_label || league.remainingLabel || '2일 14시간 남음'}</div>
          </div>
        </div>
        <div style={{ display: 'flex', gap: 10 }}>
          <div style={{ flex: 1, background: T.bg, borderRadius: 14, padding: '12px 14px' }}>
            <div style={{ fontSize: 12, color: T.ink3, fontWeight: 700 }}>내 순위</div>
            <div style={{ fontSize: 22, fontWeight: 800, color: T.ink }}>{rank} <span style={{ fontSize: 13, color: T.ink3 }}>/ {size}</span></div>
          </div>
          <div style={{ flex: 1, background: T.bg, borderRadius: 14, padding: '12px 14px' }}>
            <div style={{ fontSize: 12, color: T.ink3, fontWeight: 700 }}>League Points</div>
            <button onClick={onExplain} style={{ background: 'none', border: 'none', padding: 0, cursor: 'pointer', fontFamily: 'inherit', display: 'flex', alignItems: 'baseline', gap: 4 }}>
              <span style={{ fontSize: 22, fontWeight: 800, color: T.coral }}>{points}</span>
              <span style={{ fontSize: 11, fontWeight: 700, color: T.ink3, textDecoration: 'underline' }}>설명</span>
            </button>
          </div>
        </div>
      </Card>

      {/* Ava rec */}
      <Card pad={16} style={{ marginBottom: 6, display: 'flex', alignItems: 'flex-start', gap: 11 }}>
        <AvaOrb size={36} speaking/>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 14.5, color: T.ink, fontWeight: 500, lineHeight: 1.5, marginBottom: 10 }}>승급권까지 <b style={{ color: T.coralDark }}>{pointsToPromotion}점</b> 남았어요. 오늘은 무리하지 말고 5분 Mobility Quest면 충분해요.</div>
          <Btn size="sm" style={{ width: 'auto', padding: '0 16px' }} onClick={() => go('player', { quest: { title: 'Mobility 리셋', seconds: 60, steps: ['천천히 어깨를 돌려요', '옆구리를 늘려요', '깊게 호흡해요'], avaLine: '점수보다 흐름이 중요해요', xp: 18 } })}>추천 Quest 시작</Btn>
        </div>
      </Card>

      <ZoneLabel tone={T.good}>PROMOTION ZONE · 상위 6명 승급</ZoneLabel>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>{standings.slice(0, 3).map(r => <Row key={r.rank} r={r}/>)}</div>
      <ZoneLabel tone={T.coral}>YOUR ZONE</ZoneLabel>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>{standings.slice(3, 6).map(r => <Row key={r.rank} r={r}/>)}</div>
      <ZoneLabel tone={T.ink3}>MAINTAIN ZONE</ZoneLabel>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>{standings.slice(6).map(r => <Row key={r.rank} r={r}/>)}</div>
    </div>
  );
}

function FriendsView({ go, data }) {
  const friends = (window.FitbodyBackend && window.FitbodyBackend.friendRows(data.leaderboard)) || [
    { rank: 1, name: 'Jimin', pts: 310, days: 4, tag: '🔥 4 healthy days' },
    { rank: 2, name: 'You', pts: 295, days: 3, me: true, tag: '🌱 3 healthy days' },
    { rank: 3, name: 'Sora', pts: 240, days: 2, tag: '🧘 recovery done' },
  ];
  return (
    <div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 14 }}>{friends.map(r => <Row key={r.rank} r={r}/>)}</div>
      <Card pad={16} style={{ display: 'flex', alignItems: 'flex-start', gap: 11 }}>
        <AvaOrb size={34} speaking/>
        <div style={{ fontSize: 14, color: T.ink, fontWeight: 500, lineHeight: 1.5 }}>친구를 이기는 것보다 흐름을 이어가는 게 목표예요. 3분 Quest 하나로 충분해요.</div>
      </Card>
      <Btn variant="pink" size="md" style={{ marginTop: 12 }} icon={<Icon name="share" size={18} color="#fff"/>} onClick={() => go('invite')}>친구 초대하기</Btn>
    </div>
  );
}

function SquadView({ go, data }) {
  const squad = (window.FitbodyBackend && window.FitbodyBackend.squadData(data.leaderboard)) || {};
  const goals = squad.goals || [['Healthy days', 21, 28], ['Recovery quests', 5, 6], ['Motion practices', 8, 10]];
  const members = squad.members || [['Hana', 'High contribution', T.good], ['You', 'On track', T.coral], ['Min', 'Recovery hero', T.calm], ['Private', 'Participating', T.ink3]];
  return (
    <div>
      <Card pad={20} style={{ marginBottom: 14 }}>
        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 4 }}>
          <span style={{ fontSize: 17, fontWeight: 800, color: T.ink }}>{squad.name || 'Morning Reset'}</span>
          <span style={{ fontSize: 22, fontWeight: 800, color: T.coral }}>{squad.progress || 78}%</span>
        </div>
        <div style={{ fontSize: 13, color: T.ink3, fontWeight: 600, marginBottom: 14 }}>이번 주 팀 목표 달성률</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          {goals.map((g, i) => (
            <div key={i}>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13, fontWeight: 600, color: T.ink2, marginBottom: 6 }}><span>{g[0]}</span><span>{g[1]} / {g[2]}</span></div>
              <XPBar value={g[1]} max={g[2]} color={[T.coral, T.calm, T.amber][i]}/>
            </div>
          ))}
        </div>
      </Card>
      <div style={{ fontSize: 13, fontWeight: 800, color: T.ink3, letterSpacing: 0.5, margin: '4px 2px 10px' }}>Contribution</div>
      <Card pad={0} style={{ marginBottom: 14 }}>
        {members.map((m, i) => (
          <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '13px 16px', borderBottom: i < 3 ? `0.5px solid ${T.line}` : 'none' }}>
            <div style={{ width: 34, height: 34, borderRadius: 999, background: m[2], color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 800, fontSize: 13 }}>{m[0][0]}</div>
            <span style={{ flex: 1, fontSize: 15.5, fontWeight: 700, color: T.ink }}>{m[0]}</span>
            <span style={{ fontSize: 12.5, fontWeight: 700, color: m[2] }}>{m[1]}</span>
          </div>
        ))}
      </Card>
      <Card pad={16} style={{ display: 'flex', alignItems: 'flex-start', gap: 11 }}>
        <AvaOrb size={34} speaking/>
        <div style={{ fontSize: 14, color: T.ink, fontWeight: 500, lineHeight: 1.5 }}>팀 보상까지 2개 Quest 남았어요. 무리한 운동보다 짧은 회복 Quest도 좋아요.</div>
      </Card>
    </div>
  );
}

function ScoreSheet({ open, onClose }) {
  const rows = (window.FitbodyBackend && window.FitbodyBackend.scoreRows(window.FitbodyBackend.snapshot().leaderboard)) || [['Tiny Quest 완료', '+130', T.coral], ['꾸준함 보너스', '+62', T.amber], ['Motion Skill 연습', '+40', T.calm], ['Recovery Quest', '+35', T.good], ['검증 보너스', '+25', T.ink2], ['Daily cap 적용', '-18', T.ink3]];
  return (
    <Sheet open={open} onClose={onClose}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 6 }}>
        <AvaOrb size={36}/>
        <div style={{ fontSize: 19, fontWeight: 800, color: T.ink }}>League Points 설명</div>
      </div>
      <div style={{ fontSize: 14, color: T.ink2, marginBottom: 18 }}>점수는 운동량이 아니라 <b style={{ color: T.ink }}>건강 행동의 균형</b>으로 계산돼요.</div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 2, marginBottom: 16 }}>
        {rows.map((r, i) => (
          <div key={i} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '12px 0', borderBottom: `0.5px solid ${T.line}` }}>
            <span style={{ fontSize: 15, fontWeight: 600, color: T.ink }}>{r[0]}</span>
            <span style={{ fontSize: 16, fontWeight: 800, color: r[2], fontVariantNumeric: 'tabular-nums' }}>{r[1]}</span>
          </div>
        ))}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '14px 0 4px' }}>
          <span style={{ fontSize: 16, fontWeight: 800, color: T.ink }}>이번 주 합계</span>
          <span style={{ fontSize: 22, fontWeight: 800, color: T.coral }}>342</span>
        </div>
      </div>
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 8, padding: 14, borderRadius: 14, background: T.coralTint, marginBottom: 16 }}>
        <Icon name="leaf" size={18} color={T.coral} sw={2}/>
        <div style={{ fontSize: 13, color: T.ink2, fontWeight: 600, lineHeight: 1.45 }}>체중·감량·칼로리·운동량 총합은 순위에 절대 쓰지 않아요. Recovery Quest도 점수에 포함돼요.</div>
      </div>
      <Btn onClick={onClose}>이해했어요</Btn>
    </Sheet>
  );
}

Object.assign(window, { League });
