// ViG Command Center — searchable general picker (shared)
const { useState: useStateP, useMemo: useMemoP, useRef: useRefP, useEffect: useEffectP } = React;

function GeneralPicker({ value, onChange, pool, placeholder = 'Select a general', ownedOnly }) {
  const { isOwned } = useOwn();
  const [open, setOpen] = useStateP(false);
  const [q, setQ] = useStateP('');
  const ref = useRefP(null);
  useEffectP(() => {
    const h = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', h); return () => document.removeEventListener('mousedown', h);
  }, []);
  const list = useMemoP(() => {
    const ql = q.trim().toLowerCase();
    return (pool || window.VIG.generals)
      .filter(g => !ownedOnly || isOwned(g))
      .filter(g => !ql || g.name.toLowerCase().includes(ql))
      .slice(0, 60);
  }, [q, pool, ownedOnly, isOwned]);

  return (
    <div className="relative" ref={ref}>
      <button onClick={() => setOpen(o => !o)}
        className="flex h-11 w-full items-center gap-2.5 rounded-lg border border-zinc-200 bg-white px-3 text-left transition-colors hover:border-zinc-300 dark:border-zinc-700 dark:bg-zinc-900">
        {value ? <Avatar name={value.name} size={28} /> : <span className="flex h-7 w-7 items-center justify-center rounded-lg bg-zinc-100 text-zinc-400 dark:bg-zinc-800"><Icon name="plus" size={16} /></span>}
        <span className={`flex-1 truncate text-[14px] ${value ? 'font-medium text-zinc-900 dark:text-white' : 'text-zinc-400'}`}>{value ? value.name : placeholder}</span>
        {value && <TypeTag type={value.type} />}
        <Icon name="chevron" size={16} className={`text-zinc-300 transition-transform ${open ? 'rotate-90' : ''}`} />
      </button>
      {open && (
        <div className="absolute z-30 mt-1.5 w-full overflow-hidden rounded-xl border border-zinc-200 bg-white shadow-xl dark:border-zinc-700 dark:bg-zinc-900">
          <div className="border-b border-zinc-100 p-2 dark:border-zinc-800"><SearchInput value={q} onChange={setQ} placeholder="Search…" /></div>
          <div className="max-h-64 overflow-y-auto p-1">
            {list.map(g => (
              <button key={g.name + g.type} onClick={() => { onChange(g); setOpen(false); setQ(''); }}
                className="flex w-full items-center gap-2.5 rounded-lg px-2 py-1.5 text-left hover:bg-zinc-50 dark:hover:bg-zinc-800">
                <Avatar name={g.name} size={26} />
                <span className="flex-1 truncate text-[13px] text-zinc-800 dark:text-zinc-100">{g.name}</span>
                <span className="text-[11px] tabular-nums text-zinc-400">{g.power}</span>
                <TypeTag type={g.type} />
              </button>
            ))}
            {list.length === 0 && <div className="py-6 text-center text-[13px] text-zinc-400">No matches</div>}
          </div>
        </div>
      )}
    </div>
  );
}
window.GeneralPicker = GeneralPicker;

/* ================= COMPARISON ================= */
function ComparePage() {
  const [a, setA] = useStateP(window.VIG.generals[0]);
  const [b, setB] = useStateP(window.VIG.generals.find(g => g.type === 'Ground' && g.rank === 2) || window.VIG.generals[1]);

  const metrics = [
    { key: 'power', label: 'Power score', suffix: '', hi: true },
    { key: 'totAtk', label: 'Attack buff', suffix: '%' },
    { key: 'totDef', label: 'Defense buff', suffix: '%' },
    { key: 'totLdr', label: 'Leadership buff', suffix: '%' },
    { key: 'atkPct', label: 'Skill ATK', suffix: '%' },
    { key: 'defPct', label: 'Skill DEF', suffix: '%' },
    { key: 'hpPct', label: 'Skill HP', suffix: '%' },
    { key: 'msPct', label: 'March speed', suffix: '%' },
  ];
  const wins = (m) => {
    if (!a || !b) return 0;
    const av = a[m.key], bv = b[m.key];
    if (av === bv) return 0; return av > bv ? -1 : 1;
  };
  const tallyA = metrics.filter(m => wins(m) === -1).length;
  const tallyB = metrics.filter(m => wins(m) === 1).length;

  const Slot = ({ g, set, win }) => (
    <div className="flex-1">
      <GeneralPicker value={g} onChange={set} />
      {g && (
        <div className={`mt-3 rounded-xl border p-4 text-center ${win ? 'border-brand/40 bg-brand/[0.03]' : 'border-zinc-200 dark:border-zinc-800'}`}>
          <Avatar name={g.name} size={52} />
          <div className="mt-2 text-[15px] font-semibold text-zinc-900 dark:text-white">{g.name}</div>
          <div className="mt-1.5 flex items-center justify-center gap-2"><TypeTag type={g.type} /><Pill tone="zinc">#{g.rank}</Pill></div>
          {win && <Pill tone="brand" className="mt-2"><Icon name="trophy" size={11} />Overall winner</Pill>}
        </div>
      )}
    </div>
  );

  return (
    <div className="mx-auto max-w-3xl space-y-5">
      <div className="flex items-start gap-3">
        <Slot g={a} set={setA} win={tallyA > tallyB} />
        <div className="flex flex-col items-center pt-2.5"><div className="flex h-11 w-11 items-center justify-center rounded-full border border-zinc-200 bg-white text-[12px] font-bold text-zinc-400 dark:border-zinc-700 dark:bg-zinc-900">VS</div></div>
        <Slot g={b} set={setB} win={tallyB > tallyA} />
      </div>

      {a && b && (
        <Card className="overflow-hidden">
          <div className="flex items-center justify-between border-b border-zinc-100 px-4 py-2.5 dark:border-zinc-800">
            <span className="text-[12px] font-semibold uppercase tracking-wide text-zinc-400">Head to head</span>
            <span className="text-[12px] tabular-nums text-zinc-500">{tallyA} <span className="text-zinc-300">·</span> {tallyB}</span>
          </div>
          <div className="divide-y divide-zinc-50 dark:divide-zinc-800/60">
            {metrics.map(m => {
              const w = wins(m), av = a[m.key], bv = b[m.key], max = Math.max(av, bv) || 1;
              return (
                <div key={m.key} className="grid grid-cols-[1fr_auto_1fr] items-center gap-3 px-4 py-2.5">
                  <div className="flex items-center justify-end gap-2">
                    <div className="h-1.5 w-20 overflow-hidden rounded-full bg-zinc-100 dark:bg-zinc-800"><div className={`ml-auto h-full rounded-full ${w === -1 ? 'bg-brand' : 'bg-zinc-300 dark:bg-zinc-600'}`} style={{ width: (av / max * 100) + '%', float: 'right' }}></div></div>
                    <span className={`w-12 text-right text-[13px] tabular-nums ${w === -1 ? 'font-semibold text-brand' : 'text-zinc-600 dark:text-zinc-300'}`}>{av}{m.suffix}</span>
                  </div>
                  <div className="w-24 text-center text-[11px] font-medium uppercase tracking-wide text-zinc-400">{m.label}</div>
                  <div className="flex items-center gap-2">
                    <span className={`w-12 text-[13px] tabular-nums ${w === 1 ? 'font-semibold text-brand' : 'text-zinc-600 dark:text-zinc-300'}`}>{bv}{m.suffix}</span>
                    <div className="h-1.5 w-20 overflow-hidden rounded-full bg-zinc-100 dark:bg-zinc-800"><div className={`h-full rounded-full ${w === 1 ? 'bg-brand' : 'bg-zinc-300 dark:bg-zinc-600'}`} style={{ width: (bv / max * 100) + '%' }}></div></div>
                  </div>
                </div>
              );
            })}
          </div>
        </Card>
      )}
    </div>
  );
}
window.ComparePage = ComparePage;
