// ViG Command Center — General Tier List Hub (S/A/B/C tiers from real roster data)
const { useState: useStateTL, useMemo: useMemoTL } = React;

const TL_TIERS = [
  ['S', '#FF6B00', 'Meta — build around these'],
  ['A', '#16a34a', 'Excellent — strong picks'],
  ['B', '#2563eb', 'Solid — situational value'],
  ['C', '#8b8b8b', 'Filler — early game only'],
];
const TL_TYPES = ['Ground', 'Mounted', 'Ranged', 'Siege'];
const TL_TYPE_COLOR = { Ground: '#2563eb', Mounted: '#dc2626', Ranged: '#16a34a', Siege: '#9333ea' };

function tlScore(g) {
  // composite: attack-weighted with covenant + spec bonus
  const cov = (g.cov && (g.cov.mc || g.cov.c1 || g.cov.c2 || g.cov.c3)) ? 1 : 0;
  return (g.totAtk || 0) + (g.totDef || 0) * 0.3 + cov * 120;
}
function tlTierOf(rankPct) {
  if (rankPct <= 0.12) return 'S';
  if (rankPct <= 0.38) return 'A';
  if (rankPct <= 0.72) return 'B';
  return 'C';
}

function TierListPage() {
  const V = window.VIG;
  const { isOwned } = (window.useOwn && useOwn()) || { isOwned: () => false };
  const [type, setType] = useStateTL('All');
  const [ownedOnly, setOwnedOnly] = useStateTL(false);

  const tiered = useMemoTL(() => {
    let pool = V.generals.filter(g => TL_TYPES.includes(g.type));
    if (type !== 'All') pool = pool.filter(g => g.type === type);
    // rank within the (type-)pool by composite score
    const scored = pool.map(g => ({ g, s: tlScore(g) })).sort((a, b) => b.s - a.s);
    const n = scored.length;
    const out = { S: [], A: [], B: [], C: [] };
    scored.forEach((x, i) => { out[tlTierOf(n > 1 ? i / (n - 1) : 0)].push(x.g); });
    return out;
  }, [type]);

  const ownedSet = (g) => isOwned(g);

  return (
    <div className="space-y-4">
      {/* controls */}
      <Card className="flex flex-wrap items-center gap-x-5 gap-y-3 p-3.5">
        <div>
          <div className="mb-1.5 text-[10px] font-bold uppercase tracking-wide text-zinc-400">Troop type</div>
          <div className="flex flex-wrap gap-1.5">
            {['All', ...TL_TYPES].map(t => (
              <button key={t} onClick={() => setType(t)} className={`rounded-lg border px-2.5 py-1.5 text-[12px] font-semibold transition-colors ${type === t ? 'border-brand text-white' : 'border-zinc-200 text-zinc-500 hover:bg-zinc-50 dark:border-zinc-700 dark:text-zinc-400 dark:hover:bg-zinc-800'}`} style={type === t ? { background: t === 'All' ? '#FF6B00' : TL_TYPE_COLOR[t], borderColor: t === 'All' ? '#FF6B00' : TL_TYPE_COLOR[t] } : null}>{t}</button>
            ))}
          </div>
        </div>
        <label className="flex cursor-pointer items-center gap-2 self-end pb-1.5 text-[12.5px] text-zinc-500 dark:text-zinc-300">
          <button onClick={() => setOwnedOnly(o => !o)} className="relative h-5 w-9 shrink-0 rounded-full transition-colors" style={{ background: ownedOnly ? '#FF6B00' : '#9ca3af' }}><span className="absolute top-0.5 h-4 w-4 rounded-full bg-white transition-all" style={{ left: ownedOnly ? 16 : 2 }}></span></button>
          Highlight only owned
        </label>
        <div className="ml-auto self-end pb-1 text-[11.5px] text-zinc-400">Tiers ranked by attack power, defense &amp; covenant value.</div>
      </Card>

      {/* tier rows */}
      {TL_TIERS.map(([tier, color, blurb]) => {
        const gens = tiered[tier] || [];
        return (
          <Card key={tier} className="overflow-hidden p-0">
            <div className="flex">
              <div className="flex w-16 shrink-0 flex-col items-center justify-center py-4 text-white sm:w-20" style={{ background: color }}>
                <span className="text-[30px] font-extrabold leading-none">{tier}</span>
                <span className="mt-1 text-[9px] font-semibold uppercase tracking-wider opacity-80">{gens.length}</span>
              </div>
              <div className="min-w-0 flex-1 p-3">
                <div className="mb-2 text-[11px] font-semibold uppercase tracking-wide text-zinc-400">{blurb}</div>
                <div className="flex flex-wrap gap-1.5">
                  {gens.map(g => {
                    const own = ownedSet(g);
                    const dim = ownedOnly && !own;
                    return (
                      <div key={g.name + g.type} className={`flex items-center gap-1.5 rounded-lg border px-2 py-1 transition-opacity ${dim ? 'opacity-30' : ''}`}
                        style={{ borderColor: own ? color : 'var(--tl-border)', background: own ? color + '12' : 'var(--tl-chip)' }}
                        title={`${g.name} · ${g.type} · ${g.totAtk}% atk`}>
                        <span className="h-2 w-2 rounded-full" style={{ background: TL_TYPE_COLOR[g.type] }}></span>
                        <span className="text-[12.5px] font-medium text-zinc-800 dark:text-zinc-100">{g.name}</span>
                        {own && <Icon name="check" size={11} className="text-emerald-500" stroke={3} />}
                      </div>
                    );
                  })}
                  {gens.length === 0 && <span className="text-[12px] text-zinc-400">—</span>}
                </div>
              </div>
            </div>
          </Card>
        );
      })}

      <style>{`:root{--tl-chip:#fafafa;--tl-border:#e4e4e7;} html.dark{--tl-chip:#19213a;--tl-border:#2a3551;}`}</style>
      <p className="px-1 text-[11.5px] text-zinc-400">Tiers are computed from each general's combat stats and covenant value within the selected troop type — a data-driven ranking, not a fixed opinion list. Owned generals are checked and outlined; toggle "Highlight only owned" to see your actual depth per tier.</p>
    </div>
  );
}
window.TierListPage = TierListPage;
