// ViG Command Center — Dragon 2.0: Pairing Matrix + value ranking
const { useState: useStateDM, useMemo: useMemoDM } = React;

const DM_TROOPS = [['totGround', 'Ground', '#2563eb'], ['totMounted', 'Mounted', '#dc2626'], ['totRanged', 'Ranged', '#16a34a'], ['totSiege', 'Siege', '#9333ea']];

function dmValue(d) {
  return (d.totGround || 0) + (d.totMounted || 0) + (d.totRanged || 0) + (d.totSiege || 0) + (d.totMS || 0) * 0.5 + ((d.atk || 0) + (d.def || 0) + (d.ldr || 0)) / 30;
}
function dmBestTroop(d) {
  let best = null, max = -1;
  DM_TROOPS.forEach(([k, label, color]) => { if ((d[k] || 0) > max) { max = d[k] || 0; best = { label, color, v: d[k] || 0 }; } });
  return best && best.v > 0 ? best : null;
}

function DragonMatrixPage() {
  const all = (window.VIG && VIG.dragons) || [];
  const assign = LS.get('vig2_dragon_assign', {});
  const [sort, setSort] = useStateDM('value');

  const colMax = useMemoDM(() => {
    const m = {};
    DM_TROOPS.forEach(([k]) => { m[k] = Math.max(1, ...all.map(d => d[k] || 0)); });
    return m;
  }, [all]);

  const ranked = useMemoDM(() => {
    const arr = all.map(d => ({ d, value: dmValue(d), best: dmBestTroop(d) }));
    if (sort === 'value') arr.sort((a, b) => b.value - a.value);
    else arr.sort((a, b) => a.d.rank - b.d.rank);
    return arr;
  }, [all, sort]);

  const maxValue = Math.max(...ranked.map(r => r.value));
  const cell = (v, k) => {
    const t = (v || 0) / colMax[k];
    const color = DM_TROOPS.find(x => x[0] === k)[2];
    return (
      <td key={k} className="px-1.5 py-1 text-center">
        {v > 0 ? (
          <span className="inline-flex h-7 min-w-[40px] items-center justify-center rounded-md text-[11.5px] font-bold tabular-nums" style={{ background: color + Math.round(20 + t * 60).toString(16).padStart(2, '0'), color: t > 0.5 ? '#fff' : color }}>{v}</span>
        ) : <span className="text-zinc-300 dark:text-zinc-700">·</span>}
      </td>
    );
  };

  return (
    <div className="space-y-4">
      {/* best-per-troop summary */}
      <div className="grid grid-cols-2 gap-3 lg:grid-cols-4">
        {DM_TROOPS.map(([k, label, color]) => {
          const top = [...all].sort((a, b) => (b[k] || 0) - (a[k] || 0))[0];
          return (
            <Card key={k} className="p-4">
              <div className="flex items-center gap-1.5 text-[11px] font-bold uppercase tracking-wide" style={{ color }}><span className="h-2 w-2 rounded-full" style={{ background: color }}></span>{label}</div>
              <div className="mt-1.5 text-[15px] font-bold text-zinc-900 dark:text-white">{top && top[k] > 0 ? top.name : '—'}</div>
              <div className="text-[11.5px] text-zinc-400">{top && top[k] > 0 ? `+${top[k]} ${label.toLowerCase()} buff` : 'no buff'}</div>
            </Card>
          );
        })}
      </div>

      {/* matrix + ranking */}
      <Card className="overflow-hidden">
        <div className="flex flex-wrap items-center gap-2 border-b border-zinc-100 px-4 py-3 dark:border-zinc-800">
          <Icon name="flame" size={16} className="text-brand" />
          <span className="text-[13px] font-bold uppercase tracking-wide text-zinc-900 dark:text-white">Pairing matrix &amp; value ranking</span>
          <div className="ml-auto flex items-center gap-1">
            <span className="text-[11px] text-zinc-400">Sort</span>
            <Segmented options={[{ value: 'value', label: 'Value' }, { value: 'rank', label: 'Tier rank' }]} value={sort} onChange={setSort} />
          </div>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full min-w-[640px] text-[13px]">
            <thead>
              <tr className="border-b border-zinc-100 text-[10.5px] uppercase tracking-wide text-zinc-400 dark:border-zinc-800">
                <th className="px-4 py-2.5 text-left font-semibold">Dragon</th>
                <th className="px-3 py-2.5 text-left font-semibold">Source</th>
                {DM_TROOPS.map(([k, label, color]) => <th key={k} className="px-1.5 py-2.5 text-center font-semibold" style={{ color }}>{label}</th>)}
                <th className="px-2 py-2.5 text-center font-semibold">March spd</th>
                <th className="px-4 py-2.5 text-right font-semibold">Value</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-zinc-50 dark:divide-zinc-800/60">
              {ranked.map(({ d, value, best }) => {
                const assigned = Object.values(assign).includes(d.name);
                return (
                  <tr key={d.name} className="transition-colors hover:bg-zinc-50 dark:hover:bg-zinc-800/40">
                    <td className="px-4 py-2">
                      <div className="flex items-center gap-2">
                        <span className="text-[13px] font-semibold text-zinc-900 dark:text-white">{d.name}</span>
                        {best && <span className="h-2 w-2 rounded-full" style={{ background: best.color }} title={`Best for ${best.label}`}></span>}
                        {assigned && <span className="rounded bg-brand/15 px-1.5 py-0.5 text-[9px] font-bold uppercase tracking-wide text-brand">Assigned</span>}
                      </div>
                      <div className="text-[10.5px] text-zinc-400">{d.effect1}{d.effect2 ? ' · ' + d.effect2 : ''}</div>
                    </td>
                    <td className="px-3 py-2 text-[11.5px] text-zinc-500 dark:text-zinc-400">{d.source}</td>
                    {DM_TROOPS.map(([k]) => cell(d[k], k))}
                    <td className="px-2 py-2 text-center text-[11.5px] tabular-nums text-zinc-500 dark:text-zinc-400">{d.totMS ? '+' + d.totMS : '·'}</td>
                    <td className="px-4 py-2">
                      <div className="flex items-center justify-end gap-2">
                        <div className="hidden h-1.5 w-16 overflow-hidden rounded-full bg-zinc-100 dark:bg-zinc-800 sm:block"><div className="h-full rounded-full bg-brand" style={{ width: (value / maxValue * 100) + '%' }}></div></div>
                        <span className="w-9 text-right text-[13px] font-bold tabular-nums text-brand">{Math.round(value)}</span>
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </Card>

      <p className="px-1 text-[11.5px] text-zinc-400">The matrix shows each dragon's buff to every troop type (brighter = stronger); the colored dot marks its best fit. <b>Value</b> combines all troop buffs, march speed and base stats into one score — sort by it to find the most impactful dragons, or by tier rank for the canonical order. Dragons you've assigned in the Dragon Center are tagged.</p>
    </div>
  );
}
window.DragonMatrixPage = DragonMatrixPage;
