/* screens-overview.jsx — Home, Visão Geral, Fechamento do Dia, Análise de Produtos */

// Deterministic mock data — no client refs
const MOCK = (() => {
  const series = (n, base, vol = 0.15, trend = 0) =>
    Array.from({ length: n }, (_, i) => Math.max(0, base * (1 + trend * i / n + (Math.sin(i * 1.3) + Math.cos(i * 2.1)) * vol)));
  return {
    salesTrend: series(30, 48000, 0.18, 0.4),
    salesLY:    series(30, 42000, 0.16, 0.25),
    storesKPI: PH.stores.slice(0, 6).map((s, i) => ({
      cod: i + 1,
      loja: s,
      vlr: 220000 - i * 28000 + (i % 2 ? 14000 : 0),
      qtd: 1400 - i * 160,
      yoy: [12.4, 8.7, -2.1, 5.6, -6.3, 2.0][i],
      mkp: 2.42 + i * 0.04,
      pa:  1.62 - i * 0.03,
      tkm: 412 + i * 8,
      pm:  255 - i * 4,
      cli: 540 - i * 60,
    })),
    weekly: ["S1","S2","S3","S4","S5","S6","S7","S8","S9","S10","S11","S12"].map((w, i) => ({
      label: w, atual: 180000 + i * 7000 + (i % 3) * 9000, prev: 165000 + i * 5500 + (i % 4) * 7000,
    })),
    topProducts: PH.products.slice(0, 8).map((p, i) => ({
      rank: i + 1,
      nome: p,
      vlr: 92000 - i * 8400,
      qtd: 280 - i * 22,
      yoy: [22.4, 18.1, 11.3, 7.2, 3.5, -1.8, -5.6, -11.0][i],
    })),
    sellers: ["Operadora A","Operadora B","Operadora C","Operadora D","Operadora E"].map((n, i) => ({
      nome: n, loja: PH.stores[i % 4], vlr: 88000 - i * 7400, yoy: [16.8, 12.3, 5.4, -1.2, -8.6][i],
    })),
    forecast: Array.from({ length: 16 }, (_, i) => ({
      sem: `S${i + 1}`,
      real:    i < 9 ? 180000 + i * 7000 + (i % 3) * 9000 : null,
      previsto: i >= 7 ? 195000 + i * 6500 + Math.sin(i) * 8000 : null,
      lo:       i >= 7 ? 175000 + i * 6500 + Math.sin(i) * 8000 : null,
      hi:       i >= 7 ? 215000 + i * 6500 + Math.sin(i) * 8000 : null,
    })),
    coverage: PH.stores.slice(0, 6).map((s, i) => ({
      loja: s,
      rupturaPct: [3.2, 4.8, 7.1, 2.4, 9.2, 5.6][i],
      coberturaDias: [42, 28, 18, 56, 14, 32][i],
      skusCriticos: [12, 18, 27, 8, 41, 19][i],
      faturamentoRisco: [12400, 28900, 51200, 8200, 78400, 31800][i],
    })),
  };
})();

// ============================================================
// HOME — Executive summary with HealthScore + Narrative + Radar + dual YoY
// ============================================================
function HomeScreen({ onNavigate }) {
  const [period, setPeriod] = useState("Mês");
  const totalVendas = MOCK.salesTrend.reduce((a, b) => a + b, 0);
  const totalLY     = MOCK.salesLY.reduce((a, b) => a + b, 0);
  const yoy = ((totalVendas - totalLY) / totalLY) * 100;
  const now = new Date();
  const greeting = now.getHours() < 12 ? "Bom dia" : now.getHours() < 18 ? "Boa tarde" : "Boa noite";

  return (
    <div className="space-y-6">
      {/* Greeting + period pills */}
      <div className="flex items-end justify-between flex-wrap gap-3">
        <div>
          <div className="text-[11px] uppercase tracking-[0.18em] text-[var(--fg-muted)]">{now.toLocaleDateString("pt-BR", { month: "long", year: "numeric" })}</div>
          <h1 className="text-[26px] md:text-[30px] font-semibold tracking-tight leading-none mt-1.5">
            {greeting}, <span className="text-[var(--accent)]">Operador</span>. Aqui está o resumo de hoje.
          </h1>
        </div>
        <PeriodPills value={period} onChange={setPeriod} />
      </div>

      {/* HealthScore + Narrative side by side */}
      <div className="grid grid-cols-1 lg:grid-cols-[auto_1fr] gap-5 panel p-5">
        <div className="flex items-center gap-3">
          <HealthScore score={78} />
          <InfoDot
            side="bottom"
            width={300}
            content={
              <div>
                <div className="font-semibold text-[12px] mb-1">{GLOSSARY.health.title}</div>
                <div className="text-[var(--fg-muted)]">{GLOSSARY.health.desc}</div>
              </div>
            }
          />
        </div>
        <div className="flex flex-col gap-3 justify-center border-l border-[var(--border)] pl-5">
          <Narrative
            tone="positive"
            kicker="Resumo do dia"
            icon="sparkles"
            action={<Btn variant="ghost" icon="arrow-right">Ver detalhe</Btn>}
          >
            Vendas <span className="num font-semibold text-[var(--fg)]">{fmt.money(totalVendas, { compact: true })}</span> nos últimos 30 dias —{" "}
            <span className="num font-semibold text-[var(--pos)]">+{yoy.toFixed(1)}%</span> vs. 2025 e{" "}
            <span className="num font-semibold text-[var(--pos)]">+8,4%</span> vs. mês anterior. A meta do mês está em{" "}
            <span className="font-semibold">87% atingida</span>, com 6 dias úteis restantes.
          </Narrative>
          <Narrative
            tone="warn"
            kicker="Atenção"
            icon="shield-alert"
          >
            <span className="font-semibold text-[var(--fg)] num">125 SKUs</span> em ruptura colocam{" "}
            <span className="num font-semibold text-[var(--fg)]">{fmt.money(210900, { compact: true })}</span> em risco essa semana —
            priorize <span className="font-semibold">Filial 05</span> e <span className="font-semibold">Filial 03</span>.
          </Narrative>
        </div>
      </div>

      {/* KPI strip with dual YoY (vs prev + vs year) */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
        <KPIDual label="Faturamento"  icon="dollar-sign"  value={totalVendas} vsPrev={8.4}  vsYear={yoy}  accent format="money" />
        <KPIDual label="Peças"        icon="shopping-bag" value={28412}        vsPrev={4.2}  vsYear={8.7}  format="int" />
        <KPIDual label="Ticket médio" icon="trending-up"  value={412}          vsPrev={2.1}  vsYear={6.2}  format="money" info={GLOSSARY.tkm} />
        <KPIDual label="MKP"          icon="percent"      value="2,42×"        vsPrev={-0.3} vsYear={1.1}  info={GLOSSARY.mkp} />
      </div>

      {/* Performance Radar + Sales trend */}
      <div className="grid grid-cols-1 lg:grid-cols-[1fr_1.4fr] gap-5">
        <div className="panel p-5 chart-bg">
          <div className="flex items-center justify-between mb-3">
            <div>
              <h3 className="font-semibold text-[14px] flex items-center gap-2"><Icon name="radar" className="w-4 h-4 text-[var(--accent)]" /> Performance multi-dim</h3>
              <p className="text-[11px] text-[var(--fg-muted)] mt-0.5">Atual vs. meta · todas dimensões</p>
            </div>
            <div className="flex items-center gap-3 text-[10px]">
              <span className="flex items-center gap-1"><span className="w-2 h-2 rounded-sm bg-[var(--accent)]" /> Atual</span>
              <span className="flex items-center gap-1"><span className="w-2 h-2 rounded-sm bg-[var(--fg-muted)] opacity-60" style={{ borderTop: "1px dashed var(--fg-muted)" }} /> Meta</span>
            </div>
          </div>
          <div className="flex items-center justify-center pt-2">
            <RadarChart
              size={260}
              axes={[
                { key: "vendas", label: "Vendas",   max: 100 },
                { key: "meta",   label: "Meta",     max: 100 },
                { key: "mkp",    label: "MKP",      max: 100 },
                { key: "ticket", label: "Ticket",   max: 100 },
                { key: "conv",   label: "Conversão",max: 100 },
                { key: "pa",     label: "P.A.",     max: 100 },
              ]}
              value={{ vendas: 87, meta: 74, mkp: 92, ticket: 81, conv: 68, pa: 78 }}
              target={{ vendas: 80, meta: 80, mkp: 80, ticket: 80, conv: 80, pa: 80 }}
            />
          </div>
        </div>

        <div className="panel p-5 chart-bg">
          <div className="flex items-center justify-between mb-3">
            <div>
              <h3 className="font-semibold text-[14px] flex items-center gap-2"><Icon name="line-chart" className="w-4 h-4 text-[var(--accent)]" /> Vendas · {period.toLowerCase()}</h3>
              <p className="text-[11px] text-[var(--fg-muted)] mt-0.5">2026 vs. mesmo período de 2025</p>
            </div>
            <div className="flex items-center gap-3 text-[10px]">
              <span className="flex items-center gap-1"><span className="w-3 h-0.5 bg-[var(--accent)]" /> 2026</span>
              <span className="flex items-center gap-1"><span className="w-3 h-0.5 bg-[var(--accent-2)]" style={{ borderTop: "1px dashed var(--accent-2)" }} /> 2025</span>
            </div>
          </div>
          <LineChart
            labels={MOCK.weekly.map(w => w.label)}
            series={[
              { name: "Atual", data: MOCK.weekly.map(w => w.atual), color: "var(--accent)" },
              { name: "LY",    data: MOCK.weekly.map(w => w.prev),  color: "var(--accent-2)", dashed: true },
            ]}
            height={250}
          />
        </div>
      </div>

      {/* 3-col content */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-5">
        {/* Ranking lojas */}
        <div className="panel p-5">
          <div className="flex items-center justify-between mb-4">
            <h3 className="font-semibold text-[14px] flex items-center gap-2"><Icon name="trophy" className="w-4 h-4 text-[var(--accent)]" /> Ranking de filiais</h3>
            <button onClick={() => onNavigate("visao")} className="text-[10px] uppercase tracking-wider text-[var(--fg-muted)] hover:text-[var(--accent)] flex items-center gap-1">
              Detalhar <Icon name="arrow-right" className="w-3 h-3" />
            </button>
          </div>
          <div className="space-y-1.5">
            {MOCK.storesKPI.slice(0, 5).map((s, i) => (
              <div key={s.cod} className="flex items-center gap-3 px-2.5 py-2 rounded-lg hover:bg-[var(--panel-2)] transition-colors">
                <div className={`w-7 h-7 rounded-lg flex items-center justify-center text-[11px] font-bold border ${i === 0 ? "bg-[var(--accent-soft)] border-[var(--accent)] text-[var(--accent)]" : "bg-[var(--panel-2)] border-[var(--border)] text-[var(--fg-muted)]"}`}>
                  {i + 1}
                </div>
                <div className="flex-1 min-w-0">
                  <div className="text-[12.5px] font-medium truncate">{s.loja}</div>
                  <div className="text-[10px] text-[var(--fg-faint)]">{fmt.int(s.qtd)} peças</div>
                </div>
                <div className="text-right">
                  <div className="num text-[12.5px] font-mono font-medium">{fmt.money(s.vlr, { compact: true })}</div>
                  <Delta value={s.yoy} />
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Top produtos */}
        <div className="panel p-5">
          <div className="flex items-center justify-between mb-4">
            <h3 className="font-semibold text-[14px] flex items-center gap-2"><Icon name="package" className="w-4 h-4 text-[var(--accent-2)]" /> Top produtos</h3>
            <button onClick={() => onNavigate("produtos")} className="text-[10px] uppercase tracking-wider text-[var(--fg-muted)] hover:text-[var(--accent)] flex items-center gap-1">
              Ver todos <Icon name="arrow-right" className="w-3 h-3" />
            </button>
          </div>
          <div className="space-y-1.5">
            {MOCK.topProducts.slice(0, 6).map((p) => (
              <div key={p.nome} className="flex items-center gap-3 px-2.5 py-2 rounded-lg hover:bg-[var(--panel-2)] transition-colors">
                <span className="text-[10px] font-mono w-5 text-[var(--fg-faint)]">{p.rank.toString().padStart(2, "0")}</span>
                <div className="flex-1 min-w-0">
                  <div className="text-[11.5px] font-medium truncate">{p.nome}</div>
                  <div className="text-[10px] text-[var(--fg-faint)] num">{fmt.int(p.qtd)} pç</div>
                </div>
                <div className="text-right">
                  <div className="num text-[11.5px] font-mono">{fmt.money(p.vlr, { compact: true })}</div>
                  <Delta value={p.yoy} />
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* WOW · módulos de inteligência */}
        <div className="panel p-5 relative overflow-hidden">
          <div className="absolute -top-12 -right-12 w-40 h-40 rounded-full bg-[var(--accent-glow)] blur-3xl pointer-events-none" />
          <div className="flex items-center justify-between mb-4 relative">
            <h3 className="font-semibold text-[14px] flex items-center gap-2"><Icon name="brain-circuit" className="w-4 h-4 text-[var(--accent)]" /> Inteligência ativa</h3>
            <span className="badge badge-accent">WOW</span>
          </div>
          <div className="space-y-3 relative">
            <button onClick={() => onNavigate("forecast")} className="w-full text-left p-3 rounded-xl border border-[var(--border)] bg-[var(--panel-2)] hover:border-[var(--accent)] transition-colors">
              <div className="flex items-center justify-between mb-1.5">
                <div className="flex items-center gap-2"><Icon name="line-chart" className="w-3.5 h-3.5 text-[var(--accent)]" /> <span className="text-[12px] font-medium">Previsão</span></div>
                <span className="badge badge-accent text-[9px]">94% conf.</span>
              </div>
              <div className="num text-[18px] font-semibold">{fmt.money(2890000, { compact: true })}</div>
              <div className="text-[10px] text-[var(--fg-muted)]">próximas 4 semanas · horizon 30d</div>
            </button>
            <button onClick={() => onNavigate("ruptura")} className="w-full text-left p-3 rounded-xl border border-[var(--border)] bg-[var(--panel-2)] hover:border-[var(--accent)] transition-colors">
              <div className="flex items-center justify-between mb-1.5">
                <div className="flex items-center gap-2"><Icon name="shield-alert" className="w-3.5 h-3.5 text-[var(--warn)]" /> <span className="text-[12px] font-medium">Ruptura</span></div>
                <span className="badge badge-warn text-[9px]">125 SKUs</span>
              </div>
              <div className="num text-[18px] font-semibold text-[var(--warn)]">{fmt.pct(5.4)}</div>
              <div className="text-[10px] text-[var(--fg-muted)]">faturamento em risco · <span className="num">{fmt.money(210900, { compact: true })}</span></div>
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

// ============================================================
// VISÃO GERAL
// ============================================================
function VisaoGeralScreen() {
  const [activeKPI, setActiveKPI] = useState("vlr");
  const [period, setPeriod] = useState("Mês");
  const KPI_OPTS = [
    { id: "vlr", label: "Vendas", icon: "dollar-sign", format: "money", info: null },
    { id: "qtd", label: "Peças",  icon: "shopping-bag", format: "int" },
    { id: "cli", label: "Clientes", icon: "users", format: "int" },
    { id: "pm",  label: "P.M.", icon: "tag", format: "money", info: GLOSSARY.pm },
    { id: "tkm", label: "T.K.M.", icon: "trending-up", format: "money", info: GLOSSARY.tkm },
    { id: "pa",  label: "P.A.", icon: "bar-chart-3", format: "num", info: GLOSSARY.pa },
    { id: "mkp", label: "MKP", icon: "percent", format: "num", info: GLOSSARY.mkp },
  ];

  const filterChips = ["Filial: Todas", "Região: Todas", "Grupo: Todos", "Estação: Todas"];

  return (
    <div className="space-y-6">
      {/* Header bar with narrative + period pills */}
      <div className="flex items-end justify-between flex-wrap gap-3">
        <div>
          <div className="text-[11px] uppercase tracking-[0.18em] text-[var(--fg-muted)]">Performance comercial · todas filiais</div>
          <p className="text-[13px] text-[var(--fg-muted)] mt-1.5 max-w-2xl">
            Vendas <span className="font-semibold text-[var(--fg)] num">+12,4%</span> vs. 2025, com{" "}
            <span className="font-semibold text-[var(--fg)]">Filial 01</span> liderando o ranking.
            <span className="text-[var(--neg)] font-semibold ml-1">Filial 05</span> e <span className="text-[var(--neg)] font-semibold">Filial 03</span> negativas — atenção.
          </p>
        </div>
        <PeriodPills value={period} onChange={setPeriod} />
      </div>

      {/* Filter bar */}
      <div className="panel p-3 flex flex-wrap items-center gap-2">
        <div className="text-[11px] uppercase tracking-wider text-[var(--fg-muted)] mr-2 px-1">Filtros</div>
        {filterChips.map((f) => (
          <button key={f} className="badge hover:border-[var(--accent)] cursor-pointer">{f} <Icon name="chevron-down" className="w-3 h-3 inline" /></button>
        ))}
        <div className="flex-1" />
        <Btn variant="ghost" icon="eraser">Limpar</Btn>
        <Btn icon="download">Exportar</Btn>
        <Btn variant="primary" icon="play">Aplicar</Btn>
      </div>

      {/* KPI cards */}
      <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-7 gap-3">
        {KPI_OPTS.map((k) => {
          const store0 = MOCK.storesKPI[0];
          const total = MOCK.storesKPI.reduce((acc, s) => acc + s[k.id], 0);
          return (
            <button
              key={k.id}
              onClick={() => setActiveKPI(k.id)}
              className={`kpi text-left transition-all ${activeKPI === k.id ? "border-[var(--accent)] kpi-accent" : ""}`}
            >
              <div className="flex items-center gap-1.5 text-[10px] uppercase tracking-wider text-[var(--fg-muted)] font-medium">
                <Icon name={k.icon} className="w-3 h-3" /> <span>{k.label}</span>
                {k.info && <InfoDot content={<div><div className="font-semibold text-[12px] mb-1">{k.info.title}</div><div className="text-[var(--fg-muted)]">{k.info.desc}</div></div>} />}
              </div>
              <div className={`num font-semibold tracking-tight text-xl ${activeKPI === k.id ? "text-[var(--accent)]" : ""}`}>
                {k.format === "money" ? fmt.money(total, { compact: true }) : k.format === "int" ? fmt.int(total) : fmt.num(total / MOCK.storesKPI.length, 2)}
              </div>
              <Delta value={[12.4, 8.7, 2.1, 3.8, 6.2, -0.4, 1.1][KPI_OPTS.findIndex(x => x.id === k.id)]} />
            </button>
          );
        })}
      </div>

      {/* Chart + Table grid */}
      <div className="grid grid-cols-1 xl:grid-cols-[1.4fr_1fr] gap-5">
        <div className="panel p-5 chart-bg">
          <div className="flex items-center justify-between mb-4">
            <div>
              <h3 className="font-semibold text-[15px]">{KPI_OPTS.find(k => k.id === activeKPI).label} por filial</h3>
              <p className="text-[11px] text-[var(--fg-muted)] mt-0.5">Ordenado por código de loja · cor indica ranking</p>
            </div>
            <Tabs items={[{ id: "valor", label: "Valor" }, { id: "yoy", label: "YoY" }]} value="valor" onChange={() => {}} />
          </div>
          <VisaoBarChart kpi={activeKPI} />
        </div>

        <div className="panel p-5">
          <div className="flex items-center justify-between mb-4">
            <h3 className="font-semibold text-[15px]">Detalhamento</h3>
            <Btn variant="ghost" icon="filter">Colunas</Btn>
          </div>
          <div className="overflow-x-auto -mx-5 px-5">
            <table className="dm-table">
              <thead>
                <tr>
                  <th>Filial</th>
                  <th className="text-right">Vendas</th>
                  <th className="text-right">YoY</th>
                  <th className="text-right">MKP</th>
                </tr>
              </thead>
              <tbody>
                {MOCK.storesKPI.map((s) => (
                  <tr key={s.cod}>
                    <td>
                      <div className="flex items-center gap-2">
                        <div className="w-6 h-6 rounded bg-[var(--panel-2)] border border-[var(--border)] flex items-center justify-center text-[10px] font-mono">{String(s.cod).padStart(2, "0")}</div>
                        <span className="text-[12px] font-medium">{s.loja}</span>
                      </div>
                    </td>
                    <td className="text-right num font-mono">{fmt.money(s.vlr, { compact: true })}</td>
                    <td className="text-right"><Delta value={s.yoy} /></td>
                    <td className="text-right num font-mono">{s.mkp.toFixed(2)}×</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      </div>

      {/* Weekly comparison */}
      <div className="panel p-5">
        <div className="flex items-center justify-between mb-4">
          <div>
            <h3 className="font-semibold text-[15px]">Evolução semanal · 12 semanas</h3>
            <p className="text-[11px] text-[var(--fg-muted)] mt-0.5">Acumulado por semana — atual vs. ano anterior</p>
          </div>
          <div className="flex items-center gap-4 text-[11px]">
            <span className="flex items-center gap-1.5"><span className="w-3 h-0.5 rounded bg-[var(--accent)]" />Atual</span>
            <span className="flex items-center gap-1.5"><span className="w-3 h-0.5 rounded bg-[var(--accent-2)]" />Ano anterior</span>
          </div>
        </div>
        <LineChart
          labels={MOCK.weekly.map(w => w.label)}
          series={[
            { name: "Atual", data: MOCK.weekly.map(w => w.atual), color: "var(--accent)" },
            { name: "LY", data: MOCK.weekly.map(w => w.prev), color: "var(--accent-2)", dashed: true },
          ]}
          height={240}
        />
      </div>
    </div>
  );
}

let barData_idx_unused = 0; // legacy placeholder, unused

// helper sub-component because of mid-fn JSX const
function VisaoBarChart({ kpi }) {
  const data = MOCK.storesKPI.map((s, i) => {
    const v = kpi === "vlr" ? s.vlr : kpi === "qtd" ? s.qtd : kpi === "cli" ? s.cli : kpi === "pm" ? s.pm : kpi === "tkm" ? s.tkm : kpi === "pa" ? s.pa : s.mkp;
    return { label: s.loja.replace("Filial ", "F"), value: v };
  });
  // Color by rank (sort by value)
  const sorted = [...data].sort((a, b) => b.value - a.value);
  const colors = ["var(--accent)", "var(--accent-2)", "#7dd3fc", "#a78bfa", "#fbbf24", "#fb7185"];
  const colored = data.map((d) => ({ ...d, color: colors[sorted.findIndex(s => s.label === d.label)] || "var(--fg-faint)" }));
  return (
    <BarChart
      data={colored}
      height={260}
      format={(v) => kpi === "vlr" || kpi === "pm" || kpi === "tkm" ? fmt.money(v, { compact: true, currency: false }) : kpi === "pa" || kpi === "mkp" ? v.toFixed(2) : fmt.int(v)}
    />
  );
}

// ============================================================
// FECHAMENTO DO DIA
// ============================================================
function FechamentoScreen() {
  const [period, setPeriod] = useState("Dia");
  const today = new Date().toLocaleDateString("pt-BR", { weekday: "long", day: "numeric", month: "long" });
  return (
    <div className="space-y-6">
      <div className="flex items-end justify-between flex-wrap gap-3">
        <div>
          <div className="text-[11px] uppercase tracking-[0.18em] text-[var(--fg-muted)] capitalize">{today}</div>
          <p className="text-[13px] text-[var(--fg-muted)] mt-1.5 max-w-2xl">
            Vendas <span className="font-semibold text-[var(--fg)] num">+18,2%</span> vs. ontem e <span className="font-semibold text-[var(--fg)] num">+12,6%</span> vs. mesmo dia de 2025.
            A meta diária está <span className="font-semibold text-[var(--pos)]">113% atingida</span> com 3 filiais acima do plano.
          </p>
        </div>
        <PeriodPills value={period} onChange={setPeriod} options={["Dia", "Ontem", "Semana"]} />
      </div>

      <div className="panel p-6 relative overflow-hidden glow-accent">
        <div className="absolute -top-20 right-10 w-72 h-72 rounded-full bg-[var(--accent-glow)] blur-3xl pointer-events-none" />
        <div className="relative flex items-end justify-between flex-wrap gap-4">
          <div>
            <div className="flex items-center gap-2 mb-1.5">
              <Icon name="sun-medium" className="w-4 h-4 text-[var(--accent)]" />
              <span className="text-[11px] uppercase tracking-[0.16em] text-[var(--accent)] font-semibold">Fechamento do dia</span>
            </div>
            <div className="text-[20px] font-semibold tracking-tight capitalize">{today}</div>
            <p className="text-[12px] text-[var(--fg-muted)] mt-0.5">Resumo executivo para a direção · atualizado a cada 15 min</p>
          </div>
          <div className="flex items-center gap-3">
            <div className="text-right">
              <div className="text-[11px] text-[var(--fg-muted)]">Meta do dia</div>
              <div className="num text-[20px] font-semibold">{fmt.money(180000, { compact: true })}</div>
            </div>
            <Donut value={114} max={100} color="var(--accent)" label="114%" sub="meta" size={84} />
          </div>
        </div>
      </div>

      <div className="grid grid-cols-2 lg:grid-cols-4 gap-3">
        <KPI label="Vendas hoje" icon="dollar-sign" value={204120} delta={18.2} compact accent />
        <KPI label="Peças vendidas" icon="shopping-bag" value={3812} delta={11.4} compact format="int" />
        <KPI label="Atendimentos" icon="users" value={2104} delta={4.8} compact format="int" />
        <KPI label="% Meta" icon="target" value="113,4%" delta={6.1} compact />
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-5">
        <div className="panel p-5">
          <SectionHead title="Filiais · status do dia" icon="store" />
          <div className="space-y-2">
            {MOCK.storesKPI.map((s, i) => {
              const meta = 30000 - i * 1800;
              const real = s.vlr / 7;  // a "daily" sample
              const pct = (real / meta) * 100;
              return (
                <div key={s.cod} className="flex items-center gap-3 px-3 py-2.5 rounded-lg bg-[var(--panel-2)] border border-[var(--border-soft)]">
                  <div className="text-[10px] font-mono w-8 text-[var(--fg-faint)]">{String(s.cod).padStart(2,"0")}</div>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2">
                      <span className="text-[12.5px] font-medium truncate">{s.loja}</span>
                      <span className={`badge text-[9px] ${pct >= 100 ? "badge-pos" : pct >= 80 ? "badge-warn" : "badge-neg"}`}>{pct.toFixed(0)}% meta</span>
                    </div>
                    <Progress value={pct} max={120} height={4} color={pct >= 100 ? "var(--pos)" : pct >= 80 ? "var(--warn)" : "var(--neg)"} />
                  </div>
                  <div className="text-right min-w-[88px]">
                    <div className="num text-[12px] font-mono">{fmt.money(real, { compact: true })}</div>
                    <div className="text-[10px] text-[var(--fg-faint)] num">/ {fmt.money(meta, { compact: true })}</div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        <div className="panel p-5 chart-bg">
          <SectionHead title="Horário de pico" subtitle="Vendas acumuladas por hora · comparativo dia anterior" icon="clock" />
          <div className="flex items-end gap-1.5 h-[220px] mt-2">
            {Array.from({ length: 14 }, (_, i) => {
              const h = i + 9;
              const v = 30 + Math.sin(i * 0.55) * 25 + (i > 5 && i < 11 ? 30 : 0);
              const pv = 25 + Math.sin(i * 0.6 + 0.5) * 22 + (i > 4 && i < 10 ? 25 : 0);
              return (
                <div key={i} className="flex-1 flex flex-col items-center gap-1 min-w-0">
                  <div className="w-full flex items-end gap-0.5 h-full">
                    <div className="flex-1 rounded-t" style={{ height: `${v}%`, background: "var(--accent)", boxShadow: "0 0 8px var(--accent-glow)" }} />
                    <div className="flex-1 rounded-t" style={{ height: `${pv}%`, background: "var(--border)" }} />
                  </div>
                  <span className="text-[9px] font-mono text-[var(--fg-faint)]">{h}h</span>
                </div>
              );
            })}
          </div>
          <div className="flex items-center gap-4 text-[11px] mt-3">
            <span className="flex items-center gap-1.5"><span className="w-2.5 h-2.5 rounded bg-[var(--accent)]" />Hoje</span>
            <span className="flex items-center gap-1.5"><span className="w-2.5 h-2.5 rounded bg-[var(--border)]" />Ontem</span>
          </div>
        </div>
      </div>

      {/* Vendedoras */}
      <div className="panel p-5">
        <SectionHead title="Top vendedoras de hoje" subtitle="Ranking acumulado · atualizado em tempo real" icon="medal" />
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-3">
          {MOCK.sellers.map((v, i) => (
            <div key={v.nome} className="p-4 rounded-xl border border-[var(--border)] bg-[var(--panel-2)] relative overflow-hidden">
              {i === 0 && <div className="absolute -top-6 -right-6 w-20 h-20 rounded-full bg-[var(--accent-glow)] blur-2xl" />}
              <div className="flex items-center gap-2 mb-2 relative">
                <div className={`w-8 h-8 rounded-lg flex items-center justify-center text-[12px] font-bold ${i === 0 ? "bg-[var(--accent-soft)] text-[var(--accent)] border border-[var(--accent)]" : "bg-[var(--panel)] text-[var(--fg-muted)] border border-[var(--border)]"}`}>
                  {i + 1}
                </div>
                {i === 0 && <Icon name="crown" className="w-4 h-4 text-[var(--accent)]" />}
              </div>
              <div className="text-[12.5px] font-medium relative">{v.nome}</div>
              <div className="text-[10px] text-[var(--fg-faint)] relative">{v.loja}</div>
              <div className="mt-3 num text-[18px] font-semibold relative">{fmt.money(v.vlr, { compact: true })}</div>
              <Delta value={v.yoy} />
            </div>
          ))}
        </div>
      </div>

      {/* Calendário de meta diária */}
      <MetaCalendar />
    </div>
  );
}

// ============================================================
// MetaCalendar — daily meta achievement heatmap (current month)
// ============================================================
function MetaCalendar() {
  // Generate the current month's days with deterministic meta achievement
  const today = new Date();
  const year = today.getFullYear();
  const month = today.getMonth();
  const firstDay = new Date(year, month, 1).getDay();
  const daysInMonth = new Date(year, month + 1, 0).getDate();
  const todayDay = today.getDate();

  // Pseudo-random but deterministic meta % per day
  const dailyData = Array.from({ length: daysInMonth }, (_, i) => {
    const day = i + 1;
    const dow = new Date(year, month, day).getDay();
    const isWeekend = dow === 0 || dow === 6;
    if (day > todayDay) return { day, future: true };
    // Higher meta on weekends, mix of beat/miss
    const base = isWeekend ? 110 : 85;
    const wobble = Math.sin(i * 1.3) * 22 + Math.cos(i * 0.7) * 18;
    const pct = Math.max(40, Math.min(140, base + wobble));
    const real = (pct / 100) * (isWeekend ? 42000 : 28000);
    return { day, pct, real, isWeekend, future: false };
  });

  const padding = Array(firstDay).fill(null);
  const totalCells = [...padding, ...dailyData];

  // Header stats
  const completed = dailyData.filter(d => !d.future);
  const beat = completed.filter(d => d.pct >= 100).length;
  const missed = completed.filter(d => d.pct < 80).length;
  const totalReal = completed.reduce((acc, d) => acc + (d.real || 0), 0);

  const colorFor = (pct) => {
    if (pct == null) return null;
    if (pct >= 120) return "var(--pos)";
    if (pct >= 100) return "color-mix(in oklch, var(--pos) 70%, var(--bg))";
    if (pct >= 80)  return "var(--warn)";
    return "var(--neg)";
  };

  const monthName = today.toLocaleDateString("pt-BR", { month: "long", year: "numeric" });
  const weekdays = ["D", "S", "T", "Q", "Q", "S", "S"];

  return (
    <div className="panel p-5">
      <div className="flex items-center justify-between flex-wrap gap-3 mb-4">
        <div>
          <h3 className="font-semibold text-[15px] flex items-center gap-2 capitalize">
            <Icon name="calendar-days" className="w-4 h-4 text-[var(--accent)]" /> Calendário de meta · {monthName}
          </h3>
          <p className="text-[11px] text-[var(--fg-muted)] mt-0.5">Acompanhamento diário · verde = bateu meta · vermelho = abaixo</p>
        </div>
        <div className="flex items-center gap-2">
          <button className="w-8 h-8 rounded-lg border border-[var(--border)] flex items-center justify-center text-[var(--fg-muted)] hover:text-[var(--fg)] hover:bg-[var(--panel-2)]"><Icon name="chevron-left" className="w-3.5 h-3.5" /></button>
          <button className="w-8 h-8 rounded-lg border border-[var(--border)] flex items-center justify-center text-[var(--fg-muted)] hover:text-[var(--fg)] hover:bg-[var(--panel-2)]"><Icon name="chevron-right" className="w-3.5 h-3.5" /></button>
          <Btn icon="download">Exportar</Btn>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-[1.6fr_1fr] gap-5">
        {/* Calendar grid */}
        <div>
          <div className="grid grid-cols-7 gap-1.5">
            {weekdays.map((w, i) => (
              <div key={i} className="text-center text-[10px] uppercase tracking-wider text-[var(--fg-faint)] font-semibold pb-1">{w}</div>
            ))}
            {totalCells.map((cell, i) => {
              if (!cell) return <div key={i} className="aspect-square" />;
              if (cell.future) {
                return (
                  <div key={i} className="aspect-square rounded-md flex items-start justify-start p-1.5 text-[10px] text-[var(--fg-faint)] border border-dashed border-[var(--border)]">
                    {cell.day}
                  </div>
                );
              }
              const color = colorFor(cell.pct);
              const isToday = cell.day === todayDay;
              return (
                <Tooltip
                  key={i}
                  width={220}
                  content={
                    <div>
                      <div className="font-semibold text-[12px] mb-1">{cell.day.toString().padStart(2, "0")}/{(month + 1).toString().padStart(2, "0")}</div>
                      <div className="text-[var(--fg-muted)] space-y-0.5">
                        <div className="flex justify-between gap-3">
                          <span>Realizado:</span><span className="num font-mono font-semibold text-[var(--fg)]">{fmt.money(cell.real, { compact: true })}</span>
                        </div>
                        <div className="flex justify-between gap-3">
                          <span>% da meta:</span><span className="num font-mono font-semibold" style={{ color }}>{cell.pct.toFixed(0)}%</span>
                        </div>
                        <div className="text-[10px] mt-1">{cell.isWeekend ? "Final de semana — meta ampliada" : "Dia útil"}</div>
                      </div>
                    </div>
                  }
                >
                  <div
                    className={`aspect-square rounded-md flex flex-col items-start justify-between p-1.5 border cursor-help relative overflow-hidden transition-transform hover:scale-105 ${isToday ? "ring-2 ring-[var(--accent)]" : ""}`}
                    style={{ borderColor: "var(--border)", background: `color-mix(in oklch, ${color} 18%, var(--panel))` }}
                  >
                    <div className="text-[10px] font-semibold text-[var(--fg)]">{cell.day}</div>
                    <div className="num font-mono text-[9.5px]" style={{ color }}>{cell.pct.toFixed(0)}%</div>
                  </div>
                </Tooltip>
              );
            })}
          </div>
          {/* Legend */}
          <div className="mt-4 pt-3 border-t border-[var(--border)] flex items-center gap-3 flex-wrap text-[10.5px]">
            <span className="text-[var(--fg-muted)] uppercase tracking-wider">Legenda</span>
            <span className="flex items-center gap-1.5"><span className="w-3 h-3 rounded" style={{ background: "color-mix(in oklch, var(--pos) 22%, var(--panel))", border: "1px solid var(--border)" }} />≥ 120%</span>
            <span className="flex items-center gap-1.5"><span className="w-3 h-3 rounded" style={{ background: "color-mix(in oklch, color-mix(in oklch, var(--pos) 70%, var(--bg)) 22%, var(--panel))", border: "1px solid var(--border)" }} />100–119%</span>
            <span className="flex items-center gap-1.5"><span className="w-3 h-3 rounded" style={{ background: "color-mix(in oklch, var(--warn) 22%, var(--panel))", border: "1px solid var(--border)" }} />80–99%</span>
            <span className="flex items-center gap-1.5"><span className="w-3 h-3 rounded" style={{ background: "color-mix(in oklch, var(--neg) 22%, var(--panel))", border: "1px solid var(--border)" }} />&lt; 80%</span>
          </div>
        </div>

        {/* Side stats + narrative */}
        <div className="space-y-3">
          <Narrative tone={beat > missed ? "positive" : "warn"} icon="target" kicker="Resumo do mês">
            <span className="num font-semibold text-[var(--fg)]">{beat} de {completed.length}</span> dias bateram a meta —{" "}
            <span className="num font-semibold text-[var(--fg)]">{((beat / completed.length) * 100).toFixed(0)}%</span> de aderência.
            <span className="num font-semibold text-[var(--neg)] ml-1">{missed}</span> dias abaixo de 80% precisam de plano de recuperação.
          </Narrative>

          <div className="grid grid-cols-2 gap-2">
            <div className="p-3 rounded-lg bg-[var(--panel-2)] border border-[var(--border)]">
              <div className="text-[10px] uppercase tracking-wider text-[var(--fg-muted)]">Realizado · mês</div>
              <div className="num text-[18px] font-semibold mt-0.5">{fmt.money(totalReal, { compact: true })}</div>
              <Delta value={12.8} />
            </div>
            <div className="p-3 rounded-lg bg-[var(--panel-2)] border border-[var(--border)]">
              <div className="text-[10px] uppercase tracking-wider text-[var(--fg-muted)]">Meta restante</div>
              <div className="num text-[18px] font-semibold mt-0.5">{fmt.money(280000, { compact: true })}</div>
              <div className="text-[10px] text-[var(--fg-faint)]">faltam 6 dias úteis</div>
            </div>
            <div className="p-3 rounded-lg bg-[var(--panel-2)] border border-[var(--border)]">
              <div className="text-[10px] uppercase tracking-wider text-[var(--fg-muted)]">Melhor dia</div>
              <div className="num text-[18px] font-semibold mt-0.5 text-[var(--pos)]">142%</div>
              <div className="text-[10px] text-[var(--fg-faint)]">15/06 · sábado</div>
            </div>
            <div className="p-3 rounded-lg bg-[var(--panel-2)] border border-[var(--border)]">
              <div className="text-[10px] uppercase tracking-wider text-[var(--fg-muted)]">Pior dia</div>
              <div className="num text-[18px] font-semibold mt-0.5 text-[var(--neg)]">52%</div>
              <div className="text-[10px] text-[var(--fg-faint)]">04/06 · terça</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ============================================================
// ANÁLISE DE PRODUTOS — with deep drilldown drawer (key differentiator)
// ============================================================
// ============================================================
// CURVA ABC — Pareto / concentration of revenue by SKU classification
// ============================================================
function CurvaABC() {
  const dark = useDarkMode();
  const data = [
    { curva: "A", skus: 248, pctSkus: 20, vendas: 1245000, pctVendas: 62, color: "var(--accent)", desc: "Top 20% que faz 62% da receita — proteja a qualquer custo." },
    { curva: "B", skus: 372, pctSkus: 30, vendas: 542000,  pctVendas: 27, color: "var(--accent-2)", desc: "30% do catálogo, 27% da receita — gerencie com regularidade." },
    { curva: "C", skus: 620, pctSkus: 50, vendas: 224000,  pctVendas: 11, color: "var(--fg-muted)", desc: "Cauda longa — candidatos a phase-out se não complementarem mix." },
  ];
  const totalVendas = data.reduce((acc, d) => acc + d.vendas, 0);
  const size = 180, stroke = 22, r = (size - stroke) / 2;
  const c = 2 * Math.PI * r;
  let offset = 0;
  const segments = data.map((d) => {
    const dash = (d.pctVendas / 100) * c;
    const seg = { d, dash, offset };
    offset += dash;
    return seg;
  });

  return (
    <div className="panel p-5">
      <div className="flex items-center justify-between mb-4">
        <div>
          <h3 className="font-semibold text-[15px] flex items-center gap-2">
            <Icon name="layers" className="w-4 h-4 text-[var(--accent)]" /> Curva ABC
            <InfoDot content={
              <div>
                <div className="font-semibold text-[12px] mb-1">Classificação ABC (Pareto)</div>
                <div className="text-[var(--fg-muted)]">SKUs ordenados por receita e divididos em 3 grupos: A (top, ~80% da receita), B (médio), C (cauda).</div>
              </div>
            } width={300} />
          </h3>
          <p className="text-[11px] text-[var(--fg-muted)] mt-0.5">Concentração de receita por classe · 1.240 SKUs ativos</p>
        </div>
        <Tabs items={[{ id: "rede", label: "Rede" }, { id: "filial", label: "Filial" }, { id: "grupo", label: "Grupo" }]} value="rede" onChange={() => {}} />
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-[auto_1fr] gap-6 items-center">
        {/* Donut + center stat */}
        <div className="relative shrink-0 mx-auto" style={{ width: size, height: size }}>
          <svg width={size} height={size} className="-rotate-90">
            <circle cx={size / 2} cy={size / 2} r={r} stroke="var(--border)" strokeWidth={stroke} fill="none" />
            {segments.map((s, i) => (
              <circle
                key={i}
                cx={size / 2} cy={size / 2} r={r}
                stroke={s.d.color}
                strokeWidth={stroke}
                fill="none"
                strokeDasharray={`${s.dash} ${c - s.dash}`}
                strokeDashoffset={-s.offset}
                style={{ filter: dark ? `drop-shadow(0 0 6px ${s.d.color})` : "none" }}
              />
            ))}
          </svg>
          <div className="absolute inset-0 flex flex-col items-center justify-center">
            <span className="num text-[22px] font-semibold tracking-tight">{fmt.money(totalVendas, { compact: true })}</span>
            <span className="text-[9px] uppercase tracking-wider text-[var(--fg-muted)] mt-0.5">receita total</span>
          </div>
        </div>

        {/* Class breakdown */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
          {data.map((d) => (
            <div key={d.curva} className="p-4 rounded-xl border border-[var(--border)] bg-[var(--panel-2)] relative overflow-hidden">
              <div className="flex items-center gap-2 mb-2">
                <div className="w-9 h-9 rounded-lg flex items-center justify-center text-[14px] font-bold" style={{ background: `color-mix(in oklch, ${d.color} 14%, transparent)`, color: d.color, border: `1px solid color-mix(in oklch, ${d.color} 40%, transparent)` }}>
                  {d.curva}
                </div>
                <div className="flex-1">
                  <div className="text-[11px] uppercase tracking-wider text-[var(--fg-muted)]">Curva {d.curva}</div>
                  <div className="num text-[16px] font-semibold tracking-tight">{fmt.money(d.vendas, { compact: true })}</div>
                </div>
              </div>
              <div className="grid grid-cols-2 gap-2 pt-2 border-t border-[var(--border-soft)] text-[11px]">
                <div>
                  <div className="text-[10px] text-[var(--fg-faint)] uppercase">SKUs</div>
                  <div className="num font-mono font-semibold">{fmt.int(d.skus)} <span className="text-[var(--fg-faint)] font-normal">({d.pctSkus}%)</span></div>
                </div>
                <div className="text-right">
                  <div className="text-[10px] text-[var(--fg-faint)] uppercase">Da receita</div>
                  <div className="num font-mono font-semibold" style={{ color: d.color }}>{d.pctVendas}%</div>
                </div>
              </div>
              <div className="mt-2 text-[10.5px] text-[var(--fg-muted)] leading-snug">{d.desc}</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function ProdutosScreen() {
  const [q, setQ] = useState("");
  const [pivot, setPivot] = useState("sku");
  const [period, setPeriod] = useState("Mês");
  const [openProduct, setOpenProduct] = useState(null);
  const filtered = MOCK.topProducts.filter((p) => p.nome.toLowerCase().includes(q.toLowerCase()));

  return (
    <div className="space-y-6">
      {/* Header — narrative + period */}
      <div className="flex items-end justify-between flex-wrap gap-3">
        <div>
          <div className="text-[11px] uppercase tracking-[0.18em] text-[var(--fg-muted)]">Catálogo · 1.240 SKUs ativos</div>
          <p className="text-[13px] text-[var(--fg-muted)] mt-1.5 max-w-2xl">
            <span className="font-semibold text-[var(--fg)] num">+11,4%</span> de peças vendidas hoje vs. 2025.
            Curva A concentra <span className="font-semibold text-[var(--fg)] num">62%</span> da receita —
            <span className="font-semibold text-[var(--warn)] ml-1">125 SKUs</span> em ruptura precisam de reposição imediata.
          </p>
        </div>
        <PeriodPills value={period} onChange={setPeriod} />
      </div>

      {/* Filter + pivot pills */}
      <div className="panel p-4 flex flex-wrap items-center gap-3">
        <div className="relative flex-1 min-w-[240px] max-w-[400px]">
          <Icon name="search" className="w-3.5 h-3.5 absolute left-3 top-1/2 -translate-y-1/2 text-[var(--fg-faint)]" />
          <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Buscar SKU ou descrição…" className="input pl-9" />
        </div>
        <Tabs items={[
          { id: "sku", label: "SKU", count: 1240 },
          { id: "grupo", label: "Grupo", count: 24 },
          { id: "marca", label: "Marca", count: 38 },
          { id: "fornecedor", label: "Fornecedor", count: 12 },
        ]} value={pivot} onChange={setPivot} />
        <div className="flex-1" />
        <Btn icon="download">Exportar</Btn>
      </div>

      <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
        <KPI label="SKUs ativos" icon="package" value={1240} delta={3.2} compact format="int" />
        <KPI label="Vendidos hoje" icon="zap" value={418} delta={11.4} compact format="int" accent />
        <KPI label="Em ruptura" icon="alert-triangle" value="125" delta={-18.4} compact info={GLOSSARY.ruptura} />
        <KPI label="Top SKU vendas" icon="trophy" value={92340} delta={22.1} compact format="money" />
      </div>

      {/* Curva ABC module */}
      <CurvaABC />

      <div className="panel overflow-hidden">
        <div className="px-5 py-3 border-b border-[var(--border)] flex items-center justify-between">
          <h3 className="font-semibold text-[14px]">Detalhe por {pivot === "sku" ? "SKU" : pivot}</h3>
          <span className="text-[11px] text-[var(--fg-muted)] flex items-center gap-1">
            <Icon name="mouse-pointer-click" className="w-3 h-3" />
            Clique em uma linha para drilldown
          </span>
        </div>
        <table className="dm-table">
          <thead>
            <tr>
              <th className="w-[40px]">#</th>
              <th>Produto</th>
              <th>Grupo</th>
              <th className="text-right">Vendas</th>
              <th className="text-right">Peças</th>
              <th className="text-right">YoY</th>
              <th className="text-right">MKP</th>
              <th className="text-right">Cobertura</th>
              <th className="w-10"></th>
            </tr>
          </thead>
          <tbody>
            {filtered.map((p, i) => (
              <tr key={p.nome} onClick={() => setOpenProduct(p)} className="cursor-pointer">
                <td className="num font-mono text-[var(--fg-faint)]">{(p.rank).toString().padStart(2,"0")}</td>
                <td>
                  <div className="flex items-center gap-2.5">
                    <div className="w-9 h-9 rounded-md placeholder-stripes shrink-0" />
                    <div className="min-w-0">
                      <div className="text-[12.5px] font-medium truncate">{p.nome}</div>
                      <div className="text-[10px] font-mono text-[var(--fg-faint)]">SKU · {1000 + i * 137}</div>
                    </div>
                  </div>
                </td>
                <td><span className="badge">{PH.groups[i % PH.groups.length]}</span></td>
                <td className="text-right num font-mono">{fmt.money(p.vlr, { compact: true })}</td>
                <td className="text-right num font-mono">{fmt.int(p.qtd)}</td>
                <td className="text-right"><Delta value={p.yoy} /></td>
                <td className="text-right num font-mono">{(2.2 + i * 0.08).toFixed(2)}×</td>
                <td className="text-right num font-mono">
                  <span className={[12, 18, 24, 32, 42, 28, 8, 14][i % 8] < 20 ? "text-[var(--warn)]" : "text-[var(--fg-muted)]"}>
                    {[12, 18, 24, 32, 42, 28, 8, 14][i % 8]}d
                  </span>
                </td>
                <td><Icon name="chevron-right" className="w-4 h-4 text-[var(--fg-faint)]" /></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {/* Drilldown drawer */}
      {openProduct && <ProductDrilldown product={openProduct} onClose={() => setOpenProduct(null)} />}
    </div>
  );
}

// ============================================================
// PRODUCT DRILLDOWN — slide-in drawer with full breakdown
// ============================================================
function ProductDrilldown({ product, onClose }) {
  useEffect(() => {
    const onEsc = (e) => e.key === "Escape" && onClose();
    document.addEventListener("keydown", onEsc);
    return () => document.removeEventListener("keydown", onEsc);
  }, [onClose]);

  // Generated mock breakdowns for this product
  const sku = product.nome.split(" · ")[0];
  const name = product.nome.split(" · ")[1] || product.nome;
  const trend12 = Array.from({ length: 12 }, (_, i) => 4200 + i * 380 + Math.sin(i * 1.1) * 1800);
  const trendLY = Array.from({ length: 12 }, (_, i) => 3600 + i * 290 + Math.sin(i * 1.3 + 0.5) * 1600);
  const months = ["jul", "ago", "set", "out", "nov", "dez", "jan", "fev", "mar", "abr", "mai", "jun"];

  const byStore = PH.stores.slice(0, 6).map((s, i) => ({
    loja: s,
    vendas: 18400 - i * 2200,
    pecas: 64 - i * 7,
    estoque: [12, 28, 48, 8, 64, 22][i],
    cobertura: [9, 18, 32, 6, 42, 14][i],
    yoy: [22.4, 14.2, 8.6, -3.1, 18.4, 4.2][i],
  }));

  const totalVendas = byStore.reduce((acc, s) => acc + s.vendas, 0);
  const totalPecas  = byStore.reduce((acc, s) => acc + s.pecas, 0);
  const totalEstoque= byStore.reduce((acc, s) => acc + s.estoque, 0);

  const bySize = [
    { tam: "PP", v: 12, pct: 8 },
    { tam: "P",  v: 38, pct: 25 },
    { tam: "M",  v: 56, pct: 38 },
    { tam: "G",  v: 32, pct: 22 },
    { tam: "GG", v: 11, pct: 7 },
  ];

  const byColor = [
    { cor: "Preto",   pct: 42, color: "#0a0d18" },
    { cor: "Branco",  pct: 28, color: "#f4f4f5" },
    { cor: "Marinho", pct: 18, color: "#1e3a8a" },
    { cor: "Bordô",   pct: 8,  color: "#9f1239" },
    { cor: "Outras",  pct: 4,  color: "var(--fg-faint)" },
  ];

  const topSellers = ["Operadora A", "Operadora C", "Operadora B"].map((n, i) => ({
    nome: n, loja: PH.stores[i % 4], vendas: 8400 - i * 1600, pecas: 18 - i * 3,
  }));

  const orderHistory = [
    { tipo: "Recebimento", data: "12/06/2026", qtd: 120, status: "concluído", cor: "var(--pos)" },
    { tipo: "Pedido compra", data: "05/06/2026", qtd: 180, status: "produção", cor: "var(--accent-2)" },
    { tipo: "Recebimento", data: "22/05/2026", qtd: 80, status: "concluído", cor: "var(--pos)" },
    { tipo: "Pedido compra", data: "15/05/2026", qtd: 80, status: "concluído", cor: "var(--pos)" },
    { tipo: "Recebimento", data: "08/05/2026", qtd: 60, status: "concluído", cor: "var(--pos)" },
  ];

  return (
    <div className="fixed inset-0 z-50 flex justify-end fade-in" onClick={onClose}>
      <div className="absolute inset-0 bg-black/40 backdrop-blur-sm" />
      <div onClick={(e) => e.stopPropagation()} className="relative w-full max-w-[920px] h-full bg-[var(--bg)] border-l border-[var(--border)] shadow-[var(--shadow-lg)] flex flex-col overflow-hidden" style={{ animation: "slideUp .35s cubic-bezier(.2,.8,.2,1)" }}>
        {/* Header */}
        <div className="shrink-0 px-6 py-4 border-b border-[var(--border)] flex items-center gap-4 bg-[var(--panel)]">
          <button onClick={onClose} className="w-9 h-9 rounded-lg border border-[var(--border)] hover:bg-[var(--panel-2)] flex items-center justify-center">
            <Icon name="x" className="w-4 h-4" />
          </button>
          <div className="w-12 h-12 rounded-lg placeholder-stripes shrink-0" />
          <div className="flex-1 min-w-0">
            <div className="flex items-center gap-2">
              <span className="font-mono text-[11px] text-[var(--fg-faint)]">{sku}</span>
              <span className="badge">{PH.groups[product.rank % PH.groups.length]}</span>
              <span className="badge">Fornecedor 0{(product.rank % 4) + 1}</span>
            </div>
            <h2 className="text-[18px] font-semibold tracking-tight mt-0.5">{name}</h2>
          </div>
          <div className="flex items-center gap-2">
            <Btn variant="ghost" icon="image">Fotos</Btn>
            <Btn icon="file-plus-2">Criar pedido</Btn>
            <Btn variant="primary" icon="bell">Alerta personalizado</Btn>
          </div>
        </div>

        {/* Body */}
        <div className="flex-1 overflow-y-auto p-6 space-y-5">
          {/* Storytelling header — YoY narrative */}
          <div className="panel p-4 chart-bg">
            <div className="flex items-center gap-2 mb-1.5">
              <span className="neon-dot" />
              <span className="text-[10px] uppercase tracking-[0.18em] text-[var(--accent)] font-semibold">Resumo · ano vs. ano</span>
            </div>
            <p className="text-[13px] text-[var(--fg-muted)] leading-relaxed max-w-3xl">
              <span className="font-semibold text-[var(--fg)] num">{name}</span> vendeu{" "}
              <span className="font-semibold text-[var(--fg)] num">{fmt.money(product.vlr)}</span> nos últimos 30 dias —{" "}
              <span className={`font-semibold num ${product.yoy >= 0 ? "text-[var(--pos)]" : "text-[var(--neg)]"}`}>{product.yoy > 0 ? "+" : ""}{product.yoy.toFixed(1)}%</span>{" "}
              vs. o mesmo período de 2025. Concentração:{" "}
              <span className="font-semibold text-[var(--fg)]">Filial 01</span> responde por <span className="num font-semibold">31%</span> do volume.
              Cobertura média da rede: <span className="num font-semibold">18 dias</span>, com{" "}
              <span className="text-[var(--warn)] font-semibold">2 filiais críticas</span> abaixo de 10d.
            </p>
          </div>

          {/* KPI strip */}
          <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
            <KPI label="Vendas · 30d"  icon="dollar-sign" value={product.vlr}  delta={product.yoy} compact accent />
            <KPI label="Peças vendidas" icon="shopping-bag" value={product.qtd} delta={product.yoy - 2.4} compact format="int" />
            <KPI label="MKP"           icon="percent" value={`${(2.4 + product.rank * 0.05).toFixed(2)}×`} delta={1.6} compact />
            <KPI label="Estoque rede"  icon="package" value={totalEstoque} delta={-8.2} compact format="int" />
          </div>

          {/* Drilldown tabs */}
          <DrilldownTabs />

          {/* Trend chart 12m */}
          <div className="panel p-5">
            <div className="flex items-center justify-between mb-3">
              <div>
                <h3 className="font-semibold text-[14px]">Evolução · 12 meses</h3>
                <p className="text-[11px] text-[var(--fg-muted)] mt-0.5">Vendas mensais · atual vs. 2025</p>
              </div>
              <div className="flex items-center gap-3 text-[11px]">
                <span className="flex items-center gap-1.5"><span className="w-3 h-0.5 bg-[var(--accent)]" />2026</span>
                <span className="flex items-center gap-1.5"><span className="w-3 h-0.5 bg-[var(--accent-2)]" style={{ borderTop: "1px dashed var(--accent-2)" }} />2025</span>
              </div>
            </div>
            <LineChart
              labels={months}
              series={[
                { name: "Atual", data: trend12, color: "var(--accent)" },
                { name: "LY", data: trendLY, color: "var(--accent-2)", dashed: true },
              ]}
              height={200}
            />
          </div>

          {/* Breakdown by store */}
          <div className="panel overflow-hidden">
            <div className="px-5 py-3.5 border-b border-[var(--border)] flex items-center justify-between">
              <div className="flex items-center gap-2">
                <Icon name="store" className="w-4 h-4 text-[var(--fg-muted)]" />
                <h3 className="font-semibold text-[14px]">Por filial</h3>
              </div>
              <Tabs items={[{ id: "vendas", label: "Vendas" }, { id: "estoque", label: "Estoque" }, { id: "cob", label: "Cobertura" }]} value="vendas" onChange={() => {}} />
            </div>
            <table className="dm-table">
              <thead>
                <tr>
                  <th>Filial</th>
                  <th className="text-right">Vendas</th>
                  <th className="text-right">Peças</th>
                  <th>Participação</th>
                  <th className="text-right">YoY</th>
                  <th className="text-right">Estoque</th>
                  <th className="text-right">Cobertura</th>
                </tr>
              </thead>
              <tbody>
                {byStore.map((s) => {
                  const pct = (s.vendas / totalVendas) * 100;
                  return (
                    <tr key={s.loja}>
                      <td className="text-[12.5px] font-medium">{s.loja}</td>
                      <td className="text-right num font-mono">{fmt.money(s.vendas, { compact: true })}</td>
                      <td className="text-right num font-mono">{s.pecas}</td>
                      <td className="min-w-[160px]">
                        <div className="flex items-center gap-2">
                          <div className="flex-1"><Progress value={pct} max={40} height={4} color="var(--accent)" /></div>
                          <span className="num font-mono text-[11px] w-10 text-right">{pct.toFixed(0)}%</span>
                        </div>
                      </td>
                      <td className="text-right"><Delta value={s.yoy} /></td>
                      <td className="text-right num font-mono">{s.estoque}</td>
                      <td className="text-right num font-mono"><span style={{ color: s.cobertura < 14 ? "var(--warn)" : "var(--fg)" }}>{s.cobertura}d</span></td>
                    </tr>
                  );
                })}
                <tr style={{ background: "var(--panel-2)", fontWeight: 600 }}>
                  <td className="text-[11px] uppercase tracking-wider text-[var(--fg-muted)]">Total</td>
                  <td className="text-right num font-mono">{fmt.money(totalVendas, { compact: true })}</td>
                  <td className="text-right num font-mono">{totalPecas}</td>
                  <td></td>
                  <td className="text-right"><Delta value={product.yoy} /></td>
                  <td className="text-right num font-mono">{totalEstoque}</td>
                  <td></td>
                </tr>
              </tbody>
            </table>
          </div>

          {/* Side-by-side: by size + by color + top sellers */}
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-5">
            <div className="panel p-5">
              <h3 className="font-semibold text-[13px] flex items-center gap-2 mb-3"><Icon name="ruler" className="w-4 h-4 text-[var(--fg-muted)]" /> Por tamanho</h3>
              <div className="space-y-2">
                {bySize.map((s) => (
                  <div key={s.tam} className="flex items-center gap-2">
                    <span className="w-7 text-[11px] font-mono font-semibold">{s.tam}</span>
                    <div className="flex-1"><Progress value={s.pct} max={40} height={6} color="var(--accent)" /></div>
                    <span className="num font-mono text-[11px] w-10 text-right">{s.pct}%</span>
                    <span className="text-[10px] text-[var(--fg-faint)] w-8 text-right">{s.v}pç</span>
                  </div>
                ))}
              </div>
            </div>

            <div className="panel p-5">
              <h3 className="font-semibold text-[13px] flex items-center gap-2 mb-3"><Icon name="palette" className="w-4 h-4 text-[var(--fg-muted)]" /> Por cor</h3>
              <div className="flex h-3 rounded-full overflow-hidden border border-[var(--border)] mb-3">
                {byColor.map((c) => (
                  <div key={c.cor} style={{ width: `${c.pct}%`, background: c.color }} title={c.cor} />
                ))}
              </div>
              <div className="space-y-1.5">
                {byColor.map((c) => (
                  <div key={c.cor} className="flex items-center gap-2 text-[11.5px]">
                    <div className="w-3 h-3 rounded-sm border border-[var(--border)]" style={{ background: c.color }} />
                    <span className="flex-1">{c.cor}</span>
                    <span className="num font-mono">{c.pct}%</span>
                  </div>
                ))}
              </div>
            </div>

            <div className="panel p-5">
              <h3 className="font-semibold text-[13px] flex items-center gap-2 mb-3"><Icon name="users" className="w-4 h-4 text-[var(--fg-muted)]" /> Top vendedoras</h3>
              <div className="space-y-2">
                {topSellers.map((v, i) => (
                  <div key={v.nome} className="flex items-center gap-2.5">
                    <div className={`w-6 h-6 rounded-md flex items-center justify-center text-[10px] font-bold ${i === 0 ? "bg-[var(--accent-soft)] border border-[var(--accent)] text-[var(--accent)]" : "bg-[var(--panel-2)] border border-[var(--border)] text-[var(--fg-muted)]"}`}>{i + 1}</div>
                    <div className="flex-1 min-w-0">
                      <div className="text-[11.5px] font-medium truncate">{v.nome}</div>
                      <div className="text-[10px] text-[var(--fg-faint)]">{v.loja}</div>
                    </div>
                    <div className="text-right">
                      <div className="num font-mono text-[11px] font-semibold">{fmt.money(v.vendas, { compact: true })}</div>
                      <div className="text-[10px] text-[var(--fg-faint)] num">{v.pecas} pç</div>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>

          {/* Order history */}
          <div className="panel p-5">
            <h3 className="font-semibold text-[14px] flex items-center gap-2 mb-4"><Icon name="history" className="w-4 h-4 text-[var(--fg-muted)]" /> Histórico de movimentação</h3>
            <div className="space-y-2">
              {orderHistory.map((h, i) => (
                <div key={i} className="flex items-center gap-3 px-3 py-2.5 rounded-lg bg-[var(--panel-2)] border border-[var(--border-soft)]">
                  <div className="w-1 h-8 rounded-full" style={{ background: h.cor }} />
                  <Icon name={h.tipo === "Recebimento" ? "package-check" : "shopping-cart"} className="w-4 h-4 text-[var(--fg-muted)]" />
                  <div className="flex-1">
                    <div className="text-[12.5px] font-medium">{h.tipo}</div>
                    <div className="text-[10px] text-[var(--fg-faint)] num font-mono">{h.data}</div>
                  </div>
                  <div className="text-right">
                    <div className="num text-[12.5px] font-mono font-semibold">{h.qtd} pç</div>
                    <span className="badge text-[9px]" style={{ color: h.cor, borderColor: `color-mix(in oklch, ${h.cor} 40%, transparent)`, background: `color-mix(in oklch, ${h.cor} 12%, transparent)` }}>{h.status}</span>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function DrilldownTabs() {
  const [tab, setTab] = useState("vendas");
  return (
    <div className="flex items-center gap-1.5 overflow-x-auto pb-0.5 -mx-1 px-1">
      {[
        { id: "vendas",   label: "Vendas",          icon: "trending-up" },
        { id: "estoque",  label: "Estoque",         icon: "package" },
        { id: "preco",    label: "Preço & Margem",  icon: "tag" },
        { id: "clientes", label: "Clientes",        icon: "users" },
        { id: "fornec",   label: "Fornecedores",    icon: "truck" },
        { id: "campanha", label: "Campanhas",       icon: "megaphone" },
      ].map((t) => (
        <button key={t.id} onClick={() => setTab(t.id)} className={`px-3 py-1.5 text-[11.5px] font-medium rounded-lg whitespace-nowrap flex items-center gap-1.5 transition-colors ${tab === t.id ? "bg-[var(--accent-soft)] text-[var(--accent)] border border-[var(--accent)]" : "border border-[var(--border)] text-[var(--fg-muted)] hover:text-[var(--fg)]"}`}>
          <Icon name={t.icon} className="w-3 h-3" />
          {t.label}
        </button>
      ))}
    </div>
  );
}

Object.assign(window, { MOCK, HomeScreen, VisaoGeralScreen, FechamentoScreen, ProdutosScreen });
