// ViG Command Center — March Builder
const { useState: useStateM2, useMemo: useMemoM2 } = React;

function MarchBuilderPage() {
  const V = window.VIG;
  const { isOwned } = useOwn();
  const [type, setType] = useStateM2('Ground');
  const [primary, setPrimary] = useStateM2(null);
  const [assist, setAssist] = useStateM2(null);
  const [dragonName, setDragonName] = useStateM2(null);

  const typePool = useMemoM2(() => V.generals.filter(g => g.type === type), [type]);
  const dragon = V.dragons.find(d => d.name === dragonName) || null;
  const stats = useMemoM2(() => CALC.marchStats({ primary, assist, dragon, type }), [primary, assist, dragon, type]);

  // reset picks when type changes if they don't match
  React.useEffect(() => {
    if (primary && primary.type !== type) setPrimary(null);
    if (assist && assist.type !== type) setAssist(null);
  }, [type]);

  const compat = primary && assist ? CALC.compatScore(primary, assist) : null;
  const suggestedPrimary = typePool.find(isOwned) || typePool[0];
  const suggestedDragon = CALC.bestDragons(type, 1)[0];

  const statCards = [
    { label: 'Attack', value: stats.atk, suffix: '%', color: '#dc2626' },
    { label: 'Defense', value: stats.def, suffix: '%', color: '#2563eb' },
    { label: 'HP / Leadership', value: stats.hp, suffix: '%', color: '#16a34a' },
    { label: 'March speed', value: stats.ms, suffix: '%', color: '#FF6B00' },
  ];
  const maxStat = Math.max(...statCards.map(s => s.value), 1);

  return (
    <div className="space-y-4">
      <div className="flex flex-wrap items-center gap-3">
        <Segmented options={['Ground', 'Mounted', 'Ranged', 'Siege']} value={type} onChange={setType} />
        <span className="text-[12px] text-zinc-400">Building a <span className="font-medium text-zinc-600 dark:text-zinc-300">{type}</span> march</span>
        {(!primary || !dragon) && suggestedPrimary && (
          <Btn variant="ghost" size="sm" className="ml-auto" onClick={() => { setPrimary(suggestedPrimary); setDragonName(suggestedDragon?.d.name); }}>
            <Icon name="bolt" size={14} />Auto-fill best
          </Btn>
        )}
      </div>

      <div className="grid grid-cols-1 gap-4 lg:grid-cols-5">
        <div className="space-y-3 lg:col-span-3">
          <Card className="p-4">
            <div className="mb-1.5 flex items-center gap-1.5 text-[12px] font-semibold uppercase tracking-wide text-zinc-400"><span className="flex h-4 w-4 items-center justify-center rounded bg-brand text-[10px] text-white">1</span>Primary general</div>
            <GeneralPicker value={primary} onChange={setPrimary} pool={typePool} placeholder={`Choose a ${type} general`} />
          </Card>
          <Card className="p-4">
            <div className="mb-1.5 flex items-center gap-1.5 text-[12px] font-semibold uppercase tracking-wide text-zinc-400"><span className="flex h-4 w-4 items-center justify-center rounded bg-zinc-400 text-[10px] text-white">2</span>Assistant general
              {compat != null && <Pill tone={compat >= 75 ? 'green' : compat >= 55 ? 'brand' : 'zinc'} className="ml-auto">{compat}% synergy</Pill>}
            </div>
            <GeneralPicker value={assist} onChange={setAssist} pool={typePool} placeholder="Choose an assistant" />
            {primary && !assist && (
              <div className="mt-2.5 flex flex-wrap gap-1.5">
                <span className="self-center text-[11px] text-zinc-400">Suggested:</span>
                {CALC.bestAssistants(primary, typePool, 3).map(({ g }) => (
                  <button key={g.name} onClick={() => setAssist(g)} className="rounded-md border border-zinc-200 px-2 py-1 text-[12px] text-zinc-600 hover:border-brand/40 hover:text-brand dark:border-zinc-700 dark:text-zinc-300">{g.name}</button>
                ))}
              </div>
            )}
          </Card>
          <Card className="p-4">
            <div className="mb-1.5 flex items-center gap-1.5 text-[12px] font-semibold uppercase tracking-wide text-zinc-400"><span className="flex h-4 w-4 items-center justify-center rounded bg-zinc-400 text-[10px] text-white">3</span>Dragon</div>
            <div className="flex flex-wrap gap-1.5">
              {CALC.bestDragons(type, window.VIG.dragons.length).map(({ d, fit }) => (
                <button key={d.name} onClick={() => setDragonName(dragonName === d.name ? null : d.name)}
                  className={`inline-flex items-center gap-1.5 rounded-lg border px-2.5 py-1.5 text-[12px] font-medium transition-colors ${dragonName === d.name ? 'border-brand bg-brand/10 text-brand' : 'border-zinc-200 text-zinc-600 hover:bg-zinc-50 dark:border-zinc-700 dark:text-zinc-300 dark:hover:bg-zinc-800'}`}>
                  <Icon name="star" size={13} />{d.name}<span className="text-[10px] opacity-60">{fit}%</span>
                </button>
              ))}
            </div>
          </Card>
        </div>

        <div className="lg:col-span-2">
          <Card className="sticky top-4 p-5">
            <div className="flex items-center justify-between">
              <h3 className="text-sm font-semibold text-zinc-900 dark:text-white">Live march stats</h3>
              <TypeTag type={type} />
            </div>
            {!primary ? (
              <div className="py-10 text-center text-[13px] text-zinc-400">Pick a primary general to calculate.</div>
            ) : (
              <>
                <div className="mt-4 space-y-3">
                  {statCards.map(s => (
                    <div key={s.label}>
                      <div className="mb-1 flex items-baseline justify-between"><span className="text-[12px] text-zinc-500">{s.label}</span><span className="text-[17px] font-semibold tabular-nums text-zinc-900 dark:text-white">+{s.value}{s.suffix}</span></div>
                      <div className="h-2 w-full overflow-hidden rounded-full bg-zinc-100 dark:bg-zinc-800"><div className="h-full rounded-full transition-all duration-500" style={{ width: (s.value / maxStat * 100) + '%', background: s.color }}></div></div>
                    </div>
                  ))}
                </div>
                <div className="mt-5 space-y-2 border-t border-zinc-100 pt-4 dark:border-zinc-800">
                  <div className="flex items-center gap-2.5 text-[13px]"><Avatar name={primary.name} size={26} /><span className="flex-1 truncate text-zinc-700 dark:text-zinc-200">{primary.name}</span><Pill tone="brand">Primary</Pill></div>
                  {assist && <div className="flex items-center gap-2.5 text-[13px]"><Avatar name={assist.name} size={26} /><span className="flex-1 truncate text-zinc-700 dark:text-zinc-200">{assist.name}</span><Pill tone="zinc">Assist</Pill></div>}
                  {dragon && <div className="flex items-center gap-2.5 text-[13px]"><span className="flex h-[26px] w-[26px] items-center justify-center rounded-lg bg-gradient-to-br from-brand to-orange-600 text-white"><Icon name="star" size={14} /></span><span className="flex-1 truncate text-zinc-700 dark:text-zinc-200">{dragon.name}</span><Pill tone="brand">Dragon</Pill></div>}
                </div>
              </>
            )}
          </Card>
        </div>
      </div>
    </div>
  );
}
window.MarchBuilderPage = MarchBuilderPage;
