// ViG Command Center — Dashboard
const { useState: useStateD, useMemo: useMemoD } = React;

function KpiCard({ label, value, sub, icon, accent }) {
  return (
    <Card className="p-4">
      <div className="flex items-start justify-between">
        <div className="text-[12px] font-medium uppercase tracking-wide text-zinc-400">{label}</div>
        <div className={`flex h-7 w-7 items-center justify-center rounded-lg ${accent ? 'bg-brand/10 text-brand' : 'bg-zinc-100 text-zinc-500 dark:bg-zinc-800 dark:text-zinc-400'}`}>
          <Icon name={icon} size={15} />
        </div>
      </div>
      <div className="mt-2 text-[30px] font-semibold leading-none tabular-nums text-zinc-900 dark:text-white">{typeof value === 'number' ? <CountUp value={value} /> : value}</div>
      {sub && <div className="mt-1.5 text-[12px] text-zinc-400">{sub}</div>}
    </Card>
  );
}

function DashboardPage({ go }) {
  const V = window.VIG;
  const { isOwned, ownedByName } = useOwn();
  const TYPES = ['Ground', 'Mounted', 'Ranged', 'Siege'];

  const stats = useMemoD(() => {
    const total = V.generals.length;
    const owned = V.generals.filter(isOwned).length;
    const byType = TYPES.map(t => {
      const arr = V.generals.filter(g => g.type === t);
      return { type: t, total: arr.length, owned: arr.filter(isOwned).length, color: TYPE_COLOR[t] };
    });
    const covs = V.covenants.map(c => CALC.covenantStatus(c, ownedByName));
    const covComplete = covs.filter(c => c.complete).length;
    const covPartial = covs.filter(c => !c.complete && c.ownedCount > 0).length;
    const covPct = Math.round(covs.reduce((a, c) => a + c.pct, 0) / covs.length);
    return { total, owned, byType, covComplete, covPartial, covPct, covTotal: V.covenants.length };
  }, [isOwned, ownedByName]);

  const topPicks = useMemoD(() => CALC.optimizeCovenants(ownedByName, 5), [ownedByName]);
  const maxType = Math.max(...stats.byType.map(b => b.total));

  return (
    <div className="space-y-5">
      <div className="grid grid-cols-2 gap-4 lg:grid-cols-4">
        <KpiCard label="Generals" value={stats.total} sub="across 4 troop types" icon="database" />
        <KpiCard label="Owned" value={stats.owned} sub={`${Math.round(stats.owned / stats.total * 100)}% of roster`} icon="check" accent />
        <KpiCard label="Covenants active" value={stats.covComplete} sub={`of ${stats.covTotal} · ${stats.covPartial} in progress`} icon="link" />
        <KpiCard label="Covenant coverage" value={stats.covPct + '%'} sub="avg completion" icon="target" />
      </div>

      <div className="grid grid-cols-1 gap-5 lg:grid-cols-3">
        <Card className="p-5 lg:col-span-1">
          <h3 className="text-sm font-semibold text-zinc-900 dark:text-white">Type distribution</h3>
          <p className="text-[12px] text-zinc-400">Owned generals by troop class</p>
          <div className="mt-4 flex items-center gap-5">
            <Donut size={130} thickness={18}
              segments={stats.byType.map(b => ({ value: b.owned || 0.01, color: b.color }))}
              center={<div className="text-center"><div className="text-[22px] font-semibold tabular-nums text-zinc-900 dark:text-white">{stats.owned}</div><div className="text-[10px] uppercase tracking-wide text-zinc-400">owned</div></div>} />
            <div className="flex-1 space-y-2">
              {stats.byType.map(b => (
                <div key={b.type} className="flex items-center gap-2 text-[13px]">
                  <span className="h-2.5 w-2.5 rounded-sm" style={{ background: b.color }}></span>
                  <span className="text-zinc-600 dark:text-zinc-300">{b.type}</span>
                  <span className="ml-auto font-medium tabular-nums text-zinc-900 dark:text-white">{b.owned}<span className="text-zinc-400">/{b.total}</span></span>
                </div>
              ))}
            </div>
          </div>
        </Card>

        <Card className="p-5 lg:col-span-2">
          <div className="flex items-center justify-between">
            <div>
              <h3 className="text-sm font-semibold text-zinc-900 dark:text-white">Ownership by type</h3>
              <p className="text-[12px] text-zinc-400">Collection depth per troop class</p>
            </div>
            <Btn variant="outline" size="sm" onClick={() => go('generals')}>Open database<Icon name="arrow" size={14} /></Btn>
          </div>
          <div className="mt-5 space-y-4">
            {stats.byType.map(b => (
              <div key={b.type}>
                <div className="mb-1.5 flex items-center justify-between text-[13px]">
                  <TypeTag type={b.type} />
                  <span className="tabular-nums text-zinc-500">{b.owned} / {b.total} · {Math.round(b.owned / b.total * 100)}%</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: (b.owned / b.total * 100) + '%', background: b.color }}></div>
                </div>
              </div>
            ))}
          </div>
        </Card>
      </div>

      <div className="grid grid-cols-1 gap-5 lg:grid-cols-3">
        <Card className="p-5 lg:col-span-2">
          <div className="flex items-center justify-between">
            <div>
              <h3 className="text-sm font-semibold text-zinc-900 dark:text-white">Recommended next covenants</h3>
              <p className="text-[12px] text-zinc-400">Highest-value sets closest to completion</p>
            </div>
            <Btn variant="ghost" size="sm" onClick={() => go('optimizer')}>Optimizer<Icon name="arrow" size={14} /></Btn>
          </div>
          <div className="mt-3 divide-y divide-zinc-100 dark:divide-zinc-800">
            {topPicks.length === 0 ? (
              <div className="py-8 text-center text-[13px] text-zinc-400">Every covenant is complete. 🎉</div>
            ) : topPicks.map(({ cov, status }, i) => (
              <button key={cov.main} onClick={() => go('covenants')} className="flex w-full items-center gap-3 py-2.5 text-left">
                <span className="w-5 text-[13px] font-semibold tabular-nums text-brand">{i + 1}</span>
                <div className="min-w-0 flex-1">
                  <div className="truncate text-[13px] font-medium text-zinc-900 dark:text-white">{cov.main}</div>
                  <div className="truncate text-[12px] text-zinc-400">needs {status.missing.join(', ')}</div>
                </div>
                <Ring pct={status.pct} size={38} thickness={4} />
              </button>
            ))}
          </div>
        </Card>

        <Card className="p-5">
          <h3 className="text-sm font-semibold text-zinc-900 dark:text-white">Quick actions</h3>
          <div className="mt-3 grid gap-2">
            {[
              { label: 'Build a march', icon: 'flame', page: 'march' },
              { label: 'Compare generals', icon: 'scale', page: 'compare' },
              { label: 'Assign dragons', icon: 'star', page: 'dragons' },
              { label: 'Covenant optimizer', icon: 'target', page: 'optimizer' },
            ].map(a => (
              <button key={a.page} onClick={() => go(a.page)}
                className="flex items-center gap-3 rounded-lg border border-zinc-200 bg-white px-3 py-2.5 text-left text-[13px] font-medium text-zinc-700 transition-colors hover:border-brand/40 hover:bg-brand/[0.03] dark:border-zinc-800 dark:bg-zinc-900 dark:text-zinc-200 dark:hover:bg-zinc-800">
                <span className="flex h-7 w-7 items-center justify-center rounded-md bg-zinc-100 text-zinc-500 dark:bg-zinc-800"><Icon name={a.icon} size={15} /></span>
                {a.label}
                <Icon name="chevron" size={15} className="ml-auto text-zinc-300" />
              </button>
            ))}
          </div>
        </Card>
      </div>
    </div>
  );
}
window.DashboardPage = DashboardPage;
