// Ranking — school / global / grade / weekly tabs
const Ranking = ({ profile }) => {
  const t = window.MP_I18N.t;
  const [scope, setScope] = React.useState('school');
  const [rows, setRows] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [demo, setDemo] = React.useState(false);

  React.useEffect(() => {
    setLoading(true);
    window.MP_API.ranking(scope, profile).then(r => {
      setRows(r.rows || []);
      setDemo(!!r.demo);
      setLoading(false);
    });
  }, [scope]);

  const tabs = [
    { id: 'school', label: t('my_school') },
    { id: 'global', label: t('global') },
    { id: 'grade',  label: t('grade_lvl') },
    { id: 'weekly', label: t('weekly') }
  ];

  return (
    <>
      <div className="topbar">
        <div className="brand">🏆 {t('ranking')}</div>
        <div className="spacer" />
        {profile.schoolCode && (
          <span className="chip">{t('school_code')}: <strong style={{ marginLeft: 4 }}>{profile.schoolCode}</strong></span>
        )}
      </div>

      <div className="tabs">
        {tabs.map(tb => (
          <button
            key={tb.id}
            className={'tab' + (scope === tb.id ? ' active' : '')}
            onClick={() => { window.MP_SOUND.tap(); setScope(tb.id); }}
          >
            {tb.label}
          </button>
        ))}
      </div>

      {loading ? (
        <div className="card text-center"><div className="caption">…</div></div>
      ) : rows.length === 0 ? (
        <div className="card text-center">
          <Mascot id="cometa" size={80} />
          <div className="h-3 mt-md">{t('no_ranking_yet')}</div>
        </div>
      ) : (
        <div className="col gap-sm">
          {rows.slice(0, 30).map((r, i) => {
            const isMe = r.me || (r.first_name === profile.firstName && r.last_initial === profile.lastInitial);
            const rankCls = i === 0 ? 'r1' : i === 1 ? 'r2' : i === 2 ? 'r3' : '';
            return (
              <div key={i} className={'rank-row' + (isMe ? ' me' : '')}>
                <div className={'rank-num ' + rankCls}>
                  {i < 3 ? ['🥇','🥈','🥉'][i] : i + 1}
                </div>
                <div className="rank-info">
                  <div className="rank-name">{r.first_name} {r.last_initial}.</div>
                  <div className="rank-school">{r.school_name || '—'}{r.grade ? ' · ' + r.grade + '°' : ''}</div>
                </div>
                <div className="rank-points">{r.total_points}</div>
              </div>
            );
          })}
          {demo && <div className="caption text-center mt-md">★ {window.MP_I18N.getLang()==='es' ? 'Datos de ejemplo (sin servidor)' : 'Demo data (no server)'}</div>}
        </div>
      )}
    </>
  );
};

window.Ranking = Ranking;
