// ViG Command Center — Roster Analytics (ownership analytics + actionable recommendations)
const { useState: useStateRA, useMemo: useMemoRA } = React;

const RA_TYPES = ['Ground', 'Mounted', 'Ranged', 'Siege'];
const RA_TYPE_COLOR = { Ground: '#2563eb', Mounted: '#dc2626', Ranged: '#16a34a', Siege: '#9333ea' };

function RosterAnalyticsPage({ go }) {
  const V = window.VIG;
  const { isOwned, ownedByName } = (window.useOwn && useOwn()) || { isOwned: () => false, ownedByName: () => false };

  const a = useMemoRA(() => {
    const gens = V.generals.filter(g => RA_TYPES.includes(g.type));
    const owned = gens.filter(isOwned);
    const totalPow = gens.reduce((s, g) => s + (g.totAtk || 0), 0);
    const ownedPow = owned.reduce((s, g) => s + (g.totAtk || 0), 0);
    const progress = totalPow ? Math.round(ownedPow / totalPow * 100) : 0;

    const byType = RA_TYPES.map(t => {
      const pool = gens.filter(g => g.type === t);
      const own = pool.filter(isOwned);
      // missing meta = top unowned by attack
      const missing = pool.filter(g => !isOwned(g)).sort((x, y) => (y.totAtk || 0) - (x.totAtk || 0)).slice(0, 4);
      return { type: t, total: pool.length, owned: own.length, pct: pool.length ? Math.round(own.length / pool.length * 100) : 0, missing };
    });

    let covReady = [], covNext = [];
    try {
      const opt = window.CALC.optimizeCovenants(ownedByName, 75) || [];
      covReady = opt.filter(o => o.status.missing.length === 1).slice(0, 6);
      covNext = opt.filter(o => o.status.missing.length > 1).slice(0, 4);
    } catch (e) {}

    return { total: gens.length, owned: owned.length, progress, byType, covReady, covNext, ownedPow, totalPow };
  }, [isOwned, ownedByName]);

  const ring = (pct, size = 92, color = '#FF6B00') => {
    const r = (size - 10) / 2, c = 2 * Math.PI * r;
    return (
      <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} className="-rotate-90">
        <circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke="currentColor" strokeWidth="8" className="text-zinc-200 dark:text-zinc-800" />
        <circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke={color} strokeWidth="8" strokeLinecap="round" strokeDasharray={c} strokeDashoffset={c * (1 - pct / 100)} />
      </svg>
    );
  };

  return (
    <div className="space-y-4">
      {/* top: progress + coverage */}
      <div className="grid grid-cols-1 gap-4 lg:grid-cols-3">
        <Card className="flex items-center gap-4 p-5">
          <div className="relative shrink-0">
            {ring(a.progress)}
            <div className="absolute inset-0 flex flex-col items-center justify-center"><span className="text-[24px] font-bold tabular-nums text-zinc-900 dark:text-white">{a.progress}</span><span className="text-[9px] uppercase tracking-wide text-zinc-400">score</span></div>
          </div>
          <div>
            <h3 className="text-[14px] font-bold text-zinc-900 dark:text-white">Roster strength</h3>
            <p className="mt-1 text-[12.5px] text-zinc-500 dark:text-zinc-400">Power-weighted ownership across all combat generals.</p>
            <div className="mt-2 text-[12.5px] font-semibold text-brand">{a.owned} / {a.total} generals owned</div>
          </div>
        </Card>
        <Card className="p-5 lg:col-span-2">
          <h3 className="mb-3 text-[13px] font-bold uppercase tracking-wide text-zinc-400">Coverage by troop type</h3>
          <div className="space-y-2.5">
            {a.byType.map(t => (
              <div key={t.type} className="flex items-center gap-3">
                <span className="w-16 text-[12.5px] font-semibold" style={{ color: RA_TYPE_COLOR[t.type] }}>{t.type}</span>
                <div className="h-2.5 flex-1 overflow-hidden rounded-full bg-zinc-100 dark:bg-zinc-800"><div className="h-full rounded-full" style={{ width: Math.max(2, t.pct) + '%', background: RA_TYPE_COLOR[t.type] }}></div></div>
                <span className="w-20 text-right text-[12px] tabular-nums text-zinc-500 dark:text-zinc-400">{t.owned}/{t.total} · {t.pct}%</span>
              </div>
            ))}
          </div>
        </Card>
      </div>

      {/* covenant-ready: most actionable */}
      <Card className="overflow-hidden">
        <div className="flex items-center gap-2 border-b border-zinc-100 px-4 py-3 dark:border-zinc-800">
          <Icon name="link" size={16} className="text-brand" />
          <span className="text-[13px] font-bold uppercase tracking-wide text-zinc-900 dark:text-white">Covenants one general away</span>
          <span className="rounded-full bg-brand/15 px-2 py-0.5 text-[11px] font-bold text-brand">{a.covReady.length}</span>
          <button onClick={() => go('optimizer')} className="ml-auto text-[12px] font-semibold text-brand hover:underline">Open Optimizer →</button>
        </div>
        {a.covReady.length ? (
          <div className="grid grid-cols-1 gap-px bg-zinc-100 dark:bg-zinc-800 sm:grid-cols-2 lg:grid-cols-3">
            {a.covReady.map(o => (
              <div key={o.cov.main} className="bg-white p-3.5 dark:bg-zinc-900">
                <div className="text-[13px] font-semibold text-zinc-900 dark:text-white">{o.cov.main}</div>
                <div className="mt-1 flex items-center gap-1.5 text-[12px]"><span className="text-zinc-400">Need:</span><span className="rounded bg-amber-400/15 px-1.5 py-0.5 font-semibold text-amber-600 dark:text-amber-300">{o.status.missing[0]}</span></div>
                <div className="mt-1.5 text-[11.5px] text-zinc-500 dark:text-zinc-400">{o.cov.buff1}{o.cov.buff2 ? ' · ' + o.cov.buff2 : ''}</div>
              </div>
            ))}
          </div>
        ) : <div className="px-4 py-8 text-center text-[13px] text-zinc-400">No covenants are one general away yet — own more generals to unlock quick completions.</div>}
      </Card>

      {/* missing meta per type */}
      <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
        <Card className="p-4">
          <h3 className="mb-2 flex items-center gap-2 text-[13px] font-bold uppercase tracking-wide text-zinc-900 dark:text-white"><Icon name="target" size={15} className="text-brand" />Top missing generals</h3>
          <p className="mb-3 text-[12px] text-zinc-500 dark:text-zinc-400">Highest-attack generals you don't own yet, by type.</p>
          <div className="space-y-3">
            {a.byType.map(t => t.missing.length > 0 && (
              <div key={t.type}>
                <div className="mb-1 text-[11px] font-semibold uppercase tracking-wide" style={{ color: RA_TYPE_COLOR[t.type] }}>{t.type}</div>
                <div className="flex flex-wrap gap-1.5">
                  {t.missing.map(g => (
                    <span key={g.name} className="flex items-center gap-1.5 rounded-lg border border-zinc-200 px-2 py-1 text-[12px] dark:border-zinc-700" title={`${g.totAtk}% attack`}>
                      <span className="h-1.5 w-1.5 rounded-full" style={{ background: RA_TYPE_COLOR[t.type] }}></span>
                      {g.name}
                    </span>
                  ))}
                </div>
              </div>
            ))}
          </div>
        </Card>
        <Card className="p-4">
          <h3 className="mb-2 flex items-center gap-2 text-[13px] font-bold uppercase tracking-wide text-zinc-900 dark:text-white"><Icon name="bolt" size={15} className="text-brand" />Best next covenants</h3>
          <p className="mb-3 text-[12px] text-zinc-500 dark:text-zinc-400">Highest-value sets to work toward (2+ generals away), ranked by buff value &amp; proximity.</p>
          <div className="space-y-2">
            {a.covNext.map((o, i) => (
              <div key={o.cov.main} className="flex items-center gap-3 rounded-lg border border-zinc-100 p-2.5 dark:border-zinc-800">
                <span className="flex h-6 w-6 shrink-0 items-center justify-center rounded-md bg-brand/10 text-[11px] font-bold text-brand">{i + 1}</span>
                <div className="min-w-0 flex-1">
                  <div className="truncate text-[12.5px] font-semibold text-zinc-900 dark:text-white">{o.cov.main}</div>
                  <div className="truncate text-[11px] text-zinc-400">{o.status.missing.length} needed · {o.cov.buff1}</div>
                </div>
                <span className="shrink-0 text-[12px] font-bold tabular-nums text-brand">{o.score}</span>
              </div>
            ))}
            {!a.covNext.length && <div className="py-6 text-center text-[12.5px] text-zinc-400">Nothing pending — great coverage!</div>}
          </div>
        </Card>
      </div>

      <div className="flex flex-wrap gap-2">
        <button onClick={() => go('tierlist')} className="inline-flex items-center gap-1.5 rounded-lg border border-zinc-200 px-3 py-2 text-[12.5px] font-semibold text-zinc-600 hover:border-brand hover:text-brand dark:border-zinc-700 dark:text-zinc-300"><Icon name="trophy" size={14} />View Tier List</button>
        <button onClick={() => go('generals')} className="inline-flex items-center gap-1.5 rounded-lg border border-zinc-200 px-3 py-2 text-[12.5px] font-semibold text-zinc-600 hover:border-brand hover:text-brand dark:border-zinc-700 dark:text-zinc-300"><Icon name="database" size={14} />Edit ownership</button>
        <button onClick={() => go('ai')} className="inline-flex items-center gap-1.5 rounded-lg border border-zinc-200 px-3 py-2 text-[12.5px] font-semibold text-zinc-600 hover:border-brand hover:text-brand dark:border-zinc-700 dark:text-zinc-300"><Icon name="sparkle" size={14} />Ask the AI what to chase</button>
      </div>
    </div>
  );
}
window.RosterAnalyticsPage = RosterAnalyticsPage;
