/* global React, VendusAtoms, VendusData */
const { I, Chip, Btn, Card, Eyebrow, SectionTitle, AreaChart, Bars, Donut, Sparkline, EmptyState, brl, brlShort, pct } = window.VendusAtoms;
const { STORES, REVENUE_MONTH, COSTS_MONTH, REVENUE_DAYS, TOP_PRODUCTS, RECENT_SALES, SUPPLIERS, COSTS, CASHFLOW_30D, PAYMENT_ALERTS, INSIGHTS, GOALS } = window.VendusData;
const { useState, useMemo, useEffect, useRef } = React;

function saudacao() {
  const h = new Date().getHours();
  return h < 12 ? "Bom dia" : h < 18 ? "Boa tarde" : "Boa noite";
}

/* =====================================================
   PAGE: Dashboard
===================================================== */
function DashboardPage({ navigate, user = {} }) {
  const [period, setPeriod] = useState("month");
  const [storeFilter, setStoreFilter] = useState("all");
  const [dateOpen, setDateOpen]   = useState(false);
  const [chartMenuOpen, setChartMenuOpen] = useState(false);
  const [dateLabel, setDateLabel] = useState("01/05 – 15/05");
  const dateRef  = useRef(null);
  const chartRef = useRef(null);

  useEffect(() => {
    const onDoc = (e) => {
      if (dateRef.current && !dateRef.current.contains(e.target)) setDateOpen(false);
      if (chartRef.current && !chartRef.current.contains(e.target)) setChartMenuOpen(false);
    };
    document.addEventListener("mousedown", onDoc);
    return () => document.removeEventListener("mousedown", onDoc);
  }, []);

  const PERIODS = {
    week:    { label: "Semana",    dateLabel: "09/05 – 15/05", days: 7,   mult: 0.232, ordersBase: 660,   chartCount: 7,  chartLabels:["Sáb","Dom","Seg","Ter","Qua","Qui","Sex"] },
    month:   { label: "Mês",       dateLabel: "01/05 – 15/05", days: 30,  mult: 1,     ordersBase: 2_847, chartCount: 12, chartLabels:["Jun","Jul","Ago","Set","Out","Nov","Dez","Jan","Fev","Mar","Abr","Mai"] },
    quarter: { label: "Trimestre", dateLabel: "01/03 – 15/05", days: 90,  mult: 2.85,  ordersBase: 8_110, chartCount: 12, chartLabels:["Sem 1","Sem 2","Sem 3","Sem 4","Sem 5","Sem 6","Sem 7","Sem 8","Sem 9","Sem 10","Sem 11","Sem 12"] },
    year:    { label: "Ano",       dateLabel: "01/01 – 15/05", days: 365, mult: 11.4,  ordersBase: 32_460,chartCount: 12, chartLabels:["Jun","Jul","Ago","Set","Out","Nov","Dez","Jan","Fev","Mar","Abr","Mai"] },
  };
  const P = PERIODS[period];

  // Share por canal (Shopee/ML/TT/Própria) — soma 100%
  const STORE_SHARES = { s1: 0.399, s2: 0.293, s3: 0.167, s4: 0.141 };
  const storeShare = storeFilter === "all" ? 1 : (STORE_SHARES[storeFilter] || 1);
  const activeStore = STORES.find(s => s.id === storeFilter);

  // Sync dateLabel quando o período muda (somente se usuário não escolheu manualmente)
  useEffect(() => { setDateLabel(P.dateLabel); }, [period]);

  const baseRevenue = 246_800;
  const baseCosts   = 162_120;
  const totalRevenue = Math.round(baseRevenue * P.mult * storeShare);
  const totalCosts   = Math.round(baseCosts   * P.mult * storeShare);
  const profit       = totalRevenue - totalCosts;
  const margin       = totalRevenue ? (profit / totalRevenue) * 100 : 0;
  const totalOrders  = Math.round(P.ordersBase * storeShare);
  const ticket       = totalOrders ? totalRevenue / totalOrders : 0;
  const stockValue   = storeFilter === "all" ? 184_320 : Math.round(184_320 * storeShare * 1.08);
  const overdueValue = PAYMENT_ALERTS.filter(a => a.type === "overdue").reduce((s, a) => s + a.value, 0);
  const deltaRevenue = { week: 4.8, month: 18.4, quarter: 22.1, year: 34.6 }[period];
  const deltaProfit  = { week: 3.2, month: 12.1, quarter: 15.8, year: 28.4 }[period];
  const deltaOrders  = { week: 2.1, month: 8.6,  quarter: 11.4, year: 19.2 }[period];

  // Receita por canal — quando uma loja é selecionada, mostra só ela
  const channelData = storeFilter === "all"
    ? [
        { name: "Shopee",        value: Math.round(totalRevenue * 0.399), color: "#FB923C", pct: 39.9, id:"s1" },
        { name: "Mercado Livre", value: Math.round(totalRevenue * 0.293), color: "#FFD93D", pct: 29.3, id:"s2" },
        { name: "TikTok Shop",   value: Math.round(totalRevenue * 0.167), color: "#EC4899", pct: 16.7, id:"s3" },
        { name: "Loja Própria",  value: Math.round(totalRevenue * 0.141), color: "#8B5CF6", pct: 14.1, id:"s4" },
      ]
    : (() => {
        const s = STORES.find(x => x.id === storeFilter);
        // Subcanais de marketing para a loja selecionada
        return [
          { name: "Orgânico",  value: Math.round(totalRevenue * 0.52), color: s.color,              pct: 52.0 },
          { name: "Ads pago",  value: Math.round(totalRevenue * 0.31), color: s.color+"CC",         pct: 31.0 },
          { name: "Influencer",value: Math.round(totalRevenue * 0.12), color: s.color+"99",         pct: 12.0 },
          { name: "Recompra",  value: Math.round(totalRevenue * 0.05), color: s.color+"66",         pct:  5.0 },
        ];
      })();

  // Série do gráfico — escala por período
  const revenueSeries = useMemo(() => {
    if (period === "week") {
      // 7 dias × valor diário aproximado em milhares
      return REVENUE_DAYS.slice(-7).map(v => Math.round(v * 10 * storeShare));
    }
    if (period === "quarter") {
      // 12 semanas — total ≈ 700k, ~58k/semana
      return REVENUE_MONTH.map((_, i) => Math.round((45 + Math.sin(i*.6)*12 + Math.cos(i*.4)*8 + i*1.4) * storeShare));
    }
    if (period === "year") {
      // 12 meses ao longo de 1 ano — soma ≈ 2.8M
      return REVENUE_MONTH.map(v => Math.round(v * 0.95 * storeShare));
    }
    // month — 12 meses até o atual
    return REVENUE_MONTH.map(v => Math.round(v * storeShare));
  }, [period, storeShare]);

  const costsSeries = useMemo(() => {
    if (period === "week") {
      return REVENUE_DAYS.slice(-7).map(v => Math.round(v * 10 * 0.66 * storeShare));
    }
    if (period === "quarter") {
      return REVENUE_MONTH.map((_, i) => Math.round((30 + Math.sin(i*.6)*8 + Math.cos(i*.4)*5 + i*.9) * storeShare));
    }
    if (period === "year") {
      return COSTS_MONTH.map(v => Math.round(v * 0.95 * storeShare));
    }
    return COSTS_MONTH.map(v => Math.round(v * storeShare));
  }, [period, storeShare]);

  // Top produtos — quando filtro de loja ativo, escala a receita por share e mostra subset
  const filteredProducts = useMemo(() => {
    if (storeFilter === "all") return TOP_PRODUCTS;
    // Mapeamento simples de produtos -> store dominante
    const storeProductMap = {
      s1: ["CAP-IP15-PRO-AZ","LED-RGB-3M","PWR-20K-FAST","GAMER-MS-PRO"],
      s2: ["FONE-BT-XT-PRD","SMART-WTH-R7","PWR-20K-FAST","GAMER-MS-PRO"],
      s3: ["CAP-IP15-PRO-AZ","LED-RGB-3M"],
      s4: ["SMART-WTH-R7","FONE-BT-XT-PRD","CAP-IP15-PRO-AZ"],
    };
    const skus = storeProductMap[storeFilter] || [];
    return TOP_PRODUCTS.filter(p => skus.includes(p.sku))
      .map(p => ({ ...p,
        revenue: Math.round(p.revenue * storeShare * 1.4),
        units: Math.round(p.units * storeShare * 1.4)
      }));
  }, [storeFilter]);

  // Vendas recentes — filtra por loja
  const filteredSales = useMemo(() => {
    if (storeFilter === "all") return RECENT_SALES;
    const channel = STORES.find(s => s.id === storeFilter)?.channel;
    return RECENT_SALES.filter(s => s.store.startsWith(channel));
  }, [storeFilter]);

  // Metas — escalam com período
  const scaledGoals = useMemo(() => {
    return GOALS.map(g => {
      if (g.suffix === "%" || g.name.includes("Ticket")) return g; // margem e ticket não escalam
      const factor = P.mult * (storeFilter === "all" ? 1 : storeShare);
      return { ...g,
        current: Math.round(g.current * factor * 100) / 100,
        target:  Math.round(g.target  * factor * 100) / 100,
      };
    });
  }, [period, storeFilter, storeShare]);

  // Alertas — quando loja selecionada, filtra fornecedores relevantes (mock)
  const filteredAlerts = useMemo(() => {
    if (storeFilter === "all") return PAYMENT_ALERTS;
    const map = { s1: ["Tech","Iluminação"], s2: ["Tech"], s3: ["Beauty"], s4: ["Tech","Beauty"] };
    const keys = map[storeFilter] || [];
    return PAYMENT_ALERTS.filter(a => keys.some(k => a.supplier.startsWith(k)));
  }, [storeFilter]);
  const filteredOverdue = filteredAlerts.filter(a => a.type === "overdue").reduce((s,a) => s + a.value, 0);

  // Usuário sem dados (loja recém-criada) → onboarding em vez de números de exemplo
  const primeiroNome = String(user.name || "").trim().split(/\s+/)[0] || "";
  if (!STORES.length && !RECENT_SALES.length && !TOP_PRODUCTS.length) {
    return (
      <div className="page fade-in">
        <div className="page-header">
          <div>
            <Eyebrow>Visão geral</Eyebrow>
            <h1 className="page-title">{saudacao()}{primeiroNome ? `, ${primeiroNome}` : ""} 👋</h1>
            <div className="page-sub">Vamos preparar sua loja. Conecte um canal de vendas para ver seus números aqui.</div>
          </div>
        </div>
        <EmptyState icon="store" title="Sua loja está pronta para começar"
          desc="Conecte sua conta do Mercado Livre (ou outro canal) para o Vendus puxar seus pedidos, produtos e métricas automaticamente — e o Copiloto começar a analisar."
          cta="Conectar uma loja" onCta={() => navigate("settings")} />
      </div>
    );
  }

  return (
    <div className="page fade-in">
      <div className="page-header">
        <div>
          <Eyebrow>Visão geral</Eyebrow>
          <h1 className="page-title">Bom dia, Rafael 👋</h1>
          <div className="page-sub">
            {storeFilter === "all"
              ? `Aqui está como suas ${STORES.length} lojas estão performando — ${P.label.toLowerCase()} corrente, 15 de maio de 2026.`
              : `Performance de ${activeStore?.channel} no ${P.label.toLowerCase()} corrente, 15 de maio de 2026.`}
          </div>
        </div>
        <div style={{ display: "flex", gap: 10 }}>
          <div className="seg">
            {[["week","Semana"],["month","Mês"],["quarter","Trimestre"],["year","Ano"]].map(([k,l]) =>
              <button key={k} onClick={() => setPeriod(k)} className={period===k?"active":""}>{l}</button>
            )}
          </div>
          <div ref={dateRef} style={{ position: "relative" }}>
            <Btn variant="outline" onClick={() => setDateOpen(o => !o)}>
              <I name="calendar" size={14}/> {dateLabel}
              <I name="chevron-down" size={12}/>
            </Btn>
            {dateOpen && (
              <div style={{
                position:"absolute", right: 0, top: 44, zIndex: 20, width: 240,
                background:"var(--bg-surface)", border:"1px solid var(--border)",
                borderRadius: 12, boxShadow:"var(--shadow-3)", padding: 6
              }}>
                {[
                  { l:"Hoje", r:"15/05" },
                  { l:"Últimos 7 dias", r:"09/05 – 15/05" },
                  { l:"Mês corrente", r:"01/05 – 15/05" },
                  { l:"Últimos 30 dias", r:"16/04 – 15/05" },
                  { l:"Trimestre", r:"01/03 – 15/05" },
                  { l:"Ano corrente", r:"01/01 – 15/05" },
                ].map(o => (
                  <button key={o.l} onClick={() => { setDateLabel(o.r); setDateOpen(false); window.vendusToast && window.vendusToast(`Período: ${o.l}`, { icon:"calendar", tone:"info" }); }}
                    className="navbtn" style={{ padding:"8px 12px", borderRadius: 8, justifyContent:"space-between" }}>
                    <span style={{ fontSize: 12.5 }}>{o.l}</span>
                    <span className="text-faint" style={{ fontSize: 11, fontFamily:"Space Grotesk" }}>{o.r}</span>
                  </button>
                ))}
                <div style={{ borderTop:"1px solid var(--border)", marginTop: 4, paddingTop: 4 }}>
                  <button onClick={() => { setDateOpen(false); window.vendusToast && window.vendusToast("Seletor de data personalizada aberto", { icon:"calendar-days", tone:"violet" }); }}
                    className="navbtn" style={{ padding:"8px 12px", borderRadius: 8 }}>
                    <I name="calendar-days" size={14} className="icon"/>
                    <span style={{ fontSize: 12.5 }}>Personalizado…</span>
                  </button>
                </div>
              </div>
            )}
          </div>
          <Btn variant="primary" onClick={() => navigate("sales")}><I name="plus" size={14}/> Nova venda</Btn>
        </div>
      </div>

      {/* Store filter row */}
      <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 20, flexWrap: "wrap" }}>
        <span className="text-faint" style={{ fontSize: 12, fontWeight: 600, letterSpacing: ".06em", textTransform: "uppercase", fontFamily: "Space Grotesk" }}>Filtrar por loja</span>
        <button onClick={() => setStoreFilter("all")} className={`chip ${storeFilter==="all"?"chip-orange":""}`} style={{ cursor:"pointer", border:0 }}>
          Todas as lojas <span className="text-faint">({STORES.length})</span>
        </button>
        {STORES.map(s => (
          <button key={s.id} onClick={() => setStoreFilter(s.id)} className={`chip ${storeFilter===s.id?"chip-violet":""}`} style={{ cursor:"pointer", border:0 }}>
            <span style={{ width:8, height:8, borderRadius:999, background:s.color }}></span> {s.channel}
          </button>
        ))}
        <div style={{ flex: 1 }}></div>
        <Btn variant="secondary" size="sm" onClick={() => navigate("strategic")}><I name="sparkles" size={13}/> Insights IA</Btn>
        <Btn variant="ghost" size="sm" iconOnly title="Exportar relatório"
          onClick={() => window.vendusToast && window.vendusToast("Relatório exportado em PDF", { icon:"download", tone:"success" })}><I name="download" size={14}/></Btn>
      </div>

      {/* KPI row */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 16, marginBottom: 20 }}>
        <Card className="kpi kpi-orange" padding={0}>
          <div className="kpi" style={{ padding: "18px" }}>
            <div className="kpi-icon"><I name="trending-up" size={18}/></div>
            <div className="kpi-label">Receita líquida</div>
            <div className="kpi-value">{brl(totalRevenue)}</div>
            <div className="kpi-delta up"><I name="arrow-up-right" size={12}/> {pct(deltaRevenue)} <span className="text-faint" style={{ fontWeight:500, marginLeft:4 }}>vs {period==="week"?"semana ant.":period==="month"?"abr/26":period==="quarter"?"trimestre ant.":"ano ant."}</span></div>
            <div style={{ marginTop: 14 }}>
              <Sparkline values={period==="week" ? revenueSeries : REVENUE_DAYS.slice(-14).map(v => v * storeShare)} color="var(--primary)" width={220} height={32}/>
            </div>
          </div>
        </Card>
        <Card className="kpi kpi-success" padding={0}>
          <div className="kpi" style={{ padding: "18px" }}>
            <div className="kpi-icon"><I name="wallet" size={18}/></div>
            <div className="kpi-label">Lucro líquido</div>
            <div className="kpi-value">{brl(profit)}</div>
            <div className="kpi-delta up"><I name="arrow-up-right" size={12}/> {pct(deltaProfit)} <span className="text-faint" style={{ fontWeight:500, marginLeft:4 }}>margem {margin.toFixed(1).replace(".",",")}%</span></div>
            <div style={{ marginTop: 14 }}>
              <div className="bar-track" style={{ height: 6 }}>
                <div className="bar-fill" style={{ width: `${margin}%`, background: "linear-gradient(90deg, var(--primary), var(--violet-500))" }}></div>
              </div>
              <div style={{ display:"flex", justifyContent:"space-between", marginTop:6, fontSize:11 }}>
                <span className="text-faint">Meta de margem</span>
                <span className="text-muted">38%</span>
              </div>
            </div>
          </div>
        </Card>
        <Card className="kpi kpi-info" padding={0}>
          <div className="kpi" style={{ padding: "18px" }}>
            <div className="kpi-icon"><I name="shopping-cart" size={18}/></div>
            <div className="kpi-label">Pedidos no período</div>
            <div className="kpi-value">{totalOrders.toLocaleString("pt-BR")}</div>
            <div className="kpi-delta up"><I name="arrow-up-right" size={12}/> {pct(deltaOrders)} <span className="text-faint" style={{ fontWeight:500, marginLeft:4 }}>ticket médio {brl(ticket)}</span></div>
            <div style={{ marginTop: 12, display:"flex", gap: 8 }}>
              {STORES.map(s => (
                <div key={s.id} title={s.channel} style={{ flex:1, height: 24, borderRadius: 6, background: s.color, opacity: storeFilter==="all" || storeFilter===s.id ? .85 : .2, position:"relative", overflow:"hidden", transition: "opacity .2s" }}>
                  <div style={{ position:"absolute", inset:0, background: "linear-gradient(180deg, rgba(255,255,255,.2), transparent)" }}></div>
                </div>
              ))}
            </div>
          </div>
        </Card>
        <Card className="kpi" padding={0}>
          <div className="kpi" style={{ padding: "18px" }}>
            <div className="kpi-icon"><I name="package" size={18}/></div>
            <div className="kpi-label">Valor de estoque</div>
            <div className="kpi-value">{brl(stockValue)}</div>
            <div className="kpi-delta down"><I name="arrow-down-right" size={12}/> 3 SKUs em ruptura</div>
            <div style={{ marginTop: 12, display:"flex", justifyContent: "space-between", alignItems:"center" }}>
              <Chip tone="warning" leading={<I name="alert-triangle" size={11}/>}>Atenção</Chip>
              <button onClick={() => navigate("products")} className="text-orange" style={{ fontSize: 12, fontWeight: 600, border: 0, background: "transparent", cursor: "pointer" }}>Ver produtos →</button>
            </div>
          </div>
        </Card>
      </div>

      {/* Revenue chart + Channel donut */}
      <div style={{ display: "grid", gridTemplateColumns: "1.7fr 1fr", gap: 16, marginBottom: 20 }}>
        <Card>
          <SectionTitle
            title="Receita vs Custos"
            sub="Últimos 12 meses · em milhares de reais"
            action={
              <div style={{ display:"flex", gap:14, alignItems:"center" }}>
                <span style={{ display:"inline-flex", alignItems:"center", gap:6, fontSize:12 }}><span style={{width:10,height:10,borderRadius:3,background:"var(--primary)"}}></span>Receita</span>
                <span style={{ display:"inline-flex", alignItems:"center", gap:6, fontSize:12 }}><span style={{width:10,height:10,borderRadius:3,background:"var(--violet-500)"}}></span>Custos</span>
                <div ref={chartRef} style={{ position:"relative" }}>
                  <Btn variant="ghost" size="sm" iconOnly onClick={() => setChartMenuOpen(o => !o)}><I name="more-horizontal" size={14}/></Btn>
                  {chartMenuOpen && (
                    <div style={{
                      position:"absolute", right: 0, top: 36, zIndex: 20, width: 220,
                      background:"var(--bg-surface)", border:"1px solid var(--border)",
                      borderRadius: 10, boxShadow:"var(--shadow-3)", padding: 6
                    }}>
                      {[
                        ["Exportar PNG","image","success","Gráfico exportado em PNG"],
                        ["Exportar CSV","file-spreadsheet","info","Dados exportados em CSV"],
                        ["Comparar períodos","git-compare","violet",null,"comparatives"],
                        ["Ver análise completa","line-chart","default",null,"reports"],
                      ].map(([l, ic, tone, msg, dest]) => (
                        <button key={l} className="navbtn"
                          onClick={() => {
                            setChartMenuOpen(false);
                            if (dest) navigate(dest);
                            else if (msg) window.vendusToast && window.vendusToast(msg, { icon: ic, tone });
                          }}
                          style={{ padding:"8px 10px", borderRadius: 8 }}>
                          <I name={ic} size={14} className="icon"/>
                          <span style={{ fontSize: 12.5 }}>{l}</span>
                        </button>
                      ))}
                    </div>
                  )}
                </div>
              </div>
            }
          />
          <AreaChart
            height={260}
            series={[
              { label: "Receita", values: revenueSeries },
              { label: "Custos",  values: costsSeries },
            ]}
          />
          <div style={{ display:"flex", justifyContent:"space-between", marginTop: 6 }}>
            {P.chartLabels.map(m => (
              <span key={m} style={{ fontSize: 10.5, color: "var(--fg-3)", fontFamily:"Space Grotesk", letterSpacing:".06em" }}>{m}</span>
            ))}
          </div>
        </Card>

        <Card>
          <SectionTitle title={storeFilter === "all" ? "Receita por canal" : `${activeStore?.channel} · origem do tráfego`} sub={`${P.label} corrente`} />
          <div style={{ display:"flex", alignItems:"center", gap: 20, marginTop: 6 }}>
            <Donut
              slices={channelData.map(c => ({ value: c.value, color: c.color }))}
              center={
                <div>
                  <div className="font-display" style={{ fontSize: 22, fontWeight: 700 }}>{brlShort(totalRevenue)}</div>
                  <div style={{ fontSize: 11, color: "var(--fg-3)" }}>{totalOrders.toLocaleString("pt-BR")} pedidos</div>
                </div>
              }
            />
            <div style={{ flex: 1, display:"flex", flexDirection:"column", gap: 10 }}>
              {channelData.map(c => (
                <div key={c.name}>
                  <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12, marginBottom: 4 }}>
                    <span style={{ display:"flex", gap:8, alignItems:"center" }}>
                      <span style={{ width:8, height:8, borderRadius:2, background: c.color }}></span> {c.name}
                    </span>
                    <span className="mono-numeric font-display" style={{ fontWeight:600 }}>{brlShort(c.value)}</span>
                  </div>
                  <div className="bar-track"><div className="bar-fill" style={{ width: c.pct + "%", background: c.color }}></div></div>
                </div>
              ))}
            </div>
          </div>
        </Card>
      </div>

      {/* Insights + Alerts */}
      <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 16, marginBottom: 20 }}>
        <Card>
          <SectionTitle
            title="Insights automáticos"
            sub="O Vendus analisa suas vendas continuamente"
            action={<Chip tone="violet" leading={<I name="sparkles" size={11}/>}>IA</Chip>}
          />
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
            {INSIGHTS.map((ins, i) => (
              <div key={i} className="card card-hover" style={{ padding: 14, display:"flex", gap: 12 }}>
                <div style={{
                  width: 36, height: 36, borderRadius: 10,
                  background: ins.tone === "success" ? "rgba(34,197,94,.15)"
                            : ins.tone === "warning" ? "rgba(250,204,21,.15)"
                            : ins.tone === "danger" ? "rgba(239,68,68,.15)"
                            : "rgba(139,92,246,.15)",
                  color:    ins.tone === "success" ? "#4ADE80"
                            : ins.tone === "warning" ? "#FACC15"
                            : ins.tone === "danger" ? "#FCA5A5"
                            : "#C4B5FD",
                  display: "grid", placeItems: "center", flexShrink: 0
                }}>
                  <I name={ins.icon} size={16}/>
                </div>
                <div>
                  <div style={{ fontWeight: 600, fontSize: 13.5, marginBottom: 2 }}>{ins.title}</div>
                  <div className="text-muted" style={{ fontSize: 12.5, lineHeight: 1.45 }}>{ins.desc}</div>
                </div>
              </div>
            ))}
          </div>
        </Card>

        <Card>
          <SectionTitle
            title="Alertas de pagamento"
            sub={`${filteredAlerts.length} fornecedores · ${brl(filteredOverdue)} em atraso`}
            action={<Btn variant="ghost" size="sm" onClick={()=>navigate("suppliers")}>Ver todos</Btn>}
          />
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            {filteredAlerts.length === 0 ? (
              <div style={{ padding: "32px 16px", textAlign:"center" }}>
                <div style={{ fontSize: 13, color:"var(--fg-2)" }}>Nenhum alerta para {activeStore?.channel}.</div>
              </div>
            ) : filteredAlerts.map((a, i) => (
              <div key={i} style={{ display:"flex", alignItems:"center", justifyContent:"space-between", padding: "10px 12px", border: "1px solid var(--border)", borderRadius: 10, background: a.type==="overdue" ? "rgba(239,68,68,.06)" : "rgba(250,204,21,.06)" }}>
                <div style={{ display:"flex", alignItems:"center", gap: 12, minWidth: 0 }}>
                  <Chip tone={a.type === "overdue" ? "danger" : "warning"} dot={a.type === "overdue" ? "err" : "warn"}>
                    {a.type === "overdue" ? `${-a.days}d atraso` : `${a.days}d`}
                  </Chip>
                  <div style={{ minWidth: 0 }}>
                    <div style={{ fontWeight: 600, fontSize: 13, whiteSpace:"nowrap", overflow:"hidden", textOverflow:"ellipsis" }}>{a.supplier}</div>
                    <div className="text-faint" style={{ fontSize: 11.5, whiteSpace:"nowrap", overflow:"hidden", textOverflow:"ellipsis" }}>{a.desc}</div>
                  </div>
                </div>
                <div className="font-display mono-numeric" style={{ fontWeight: 700, fontSize: 14, textAlign:"right", whiteSpace:"nowrap" }}>{brl(a.value)}</div>
              </div>
            ))}
          </div>
        </Card>
      </div>

      {/* Top products + Recent transactions */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, marginBottom: 20 }}>
        <Card>
          <SectionTitle title="Top produtos" sub={`Por receita${storeFilter==="all"?"":" · "+activeStore?.channel} · ${P.label.toLowerCase()}`} action={<Btn variant="ghost" size="sm" onClick={()=>navigate("products")}>Ver todos →</Btn>}/>
          <div style={{ display:"flex", flexDirection:"column", gap: 4 }}>
            {filteredProducts.length === 0 ? (
              <div style={{ padding: "20px 8px", textAlign:"center", color:"var(--fg-3)", fontSize: 12.5 }}>
                Nenhum produto associado a esta loja.
              </div>
            ) : filteredProducts.slice(0,5).map((p,i) => (
              <div key={p.sku} className="row" style={{ padding: "10px 8px" }}
                   onClick={() => navigate("products")}
                   role="button" tabIndex={0}>
                <div style={{ width: 22, color: "var(--fg-3)", fontWeight:700, fontFamily:"Space Grotesk", fontSize: 12, textAlign:"center" }}>0{i+1}</div>
                <div className="prod-thumb">{p.cover}</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontWeight: 600, fontSize: 13, whiteSpace:"nowrap", overflow:"hidden", textOverflow:"ellipsis" }}>{p.name}</div>
                  <div className="text-faint" style={{ fontSize: 11 }}>{p.units} unid · {p.cat}</div>
                </div>
                <Sparkline values={p.trend} color="var(--violet-400)" width={56} height={20} />
                <div style={{ textAlign: "right", minWidth: 90 }}>
                  <div className="font-display mono-numeric" style={{ fontWeight: 700, fontSize: 13 }}>{brl(p.revenue)}</div>
                  <div className="text-success" style={{ fontSize: 11, fontWeight: 600 }}>{p.margin.toFixed(1).replace(".",",")}% margem</div>
                </div>
              </div>
            ))}
          </div>
        </Card>

        <Card>
          <SectionTitle title="Vendas recentes" sub={storeFilter==="all"?"Últimas 2 horas":`${activeStore?.channel} · últimas 2 horas`} action={<Btn variant="ghost" size="sm" onClick={()=>navigate("sales")}>Ver todas →</Btn>}/>
          <div style={{ display:"flex", flexDirection:"column", gap: 4 }}>
            {filteredSales.length === 0 ? (
              <div style={{ padding: "20px 8px", textAlign:"center", color:"var(--fg-3)", fontSize: 12.5 }}>
                Nenhuma venda recente para esta loja.
              </div>
            ) : filteredSales.slice(0,6).map(s => (
              <div key={s.id} className="row" style={{ padding: "10px 8px" }}
                   onClick={() => navigate("sales")}
                   role="button" tabIndex={0}>
                <div className="prod-thumb" style={{ width: 36, height: 36, fontSize: 10, background: "var(--bg-elev)" }}>{(s.id.split("-")[1] || s.id).slice(-3)}</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display:"flex", gap: 8, alignItems:"center" }}>
                    <span style={{ fontWeight: 600, fontSize: 13, whiteSpace:"nowrap", overflow:"hidden", textOverflow:"ellipsis" }}>{s.product}</span>
                  </div>
                  <div className="text-faint" style={{ fontSize: 11, display: "flex", gap: 8, alignItems:"center" }}>
                    <span>{s.store}</span>·<span>{s.payment}</span>·<span>{s.time}</span>
                  </div>
                </div>
                <Chip tone={
                  s.status==="paid"?"success":
                  s.status==="shipped"?"info":
                  s.status==="pending"?"warning":"danger"
                }>
                  {s.status==="paid"?"Pago":s.status==="shipped"?"Enviado":s.status==="pending"?"Pendente":"Devolvido"}
                </Chip>
                <div className="font-display mono-numeric" style={{ fontWeight: 700, fontSize: 13.5, minWidth: 80, textAlign:"right" }}>{brl(s.total)}</div>
              </div>
            ))}
          </div>
        </Card>
      </div>

      {/* Bottom: goals + suppliers */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1.3fr", gap: 16 }}>
        <Card>
          <SectionTitle title={`Metas do ${P.label.toLowerCase()}`} sub={`${scaledGoals.filter(g => g.current/g.target >= 0.6).length} de ${scaledGoals.length} no caminho certo`}/>
          <div style={{ display:"flex", flexDirection:"column", gap: 14 }}>
            {scaledGoals.map(g => {
              const ratio = Math.min(1, g.current / g.target);
              const fmt = v => g.money ? brl(v) : (g.suffix ? v.toFixed(1).replace(".",",")+g.suffix : v.toLocaleString("pt-BR"));
              return (
                <div key={g.name}>
                  <div style={{ display:"flex", justifyContent:"space-between", marginBottom: 6 }}>
                    <div style={{ display:"flex", alignItems:"center", gap: 8 }}>
                      <div style={{
                        width: 26, height: 26, borderRadius: 7,
                        background: g.tone==="orange"?"rgba(249,115,22,.16)":g.tone==="violet"?"rgba(139,92,246,.16)":g.tone==="success"?"rgba(34,197,94,.16)":"rgba(120,155,255,.16)",
                        color: g.tone==="orange"?"var(--primary)":g.tone==="violet"?"var(--violet-400)":g.tone==="success"?"#4ADE80":"#93B4FF",
                        display:"grid", placeItems:"center"
                      }}><I name={g.icon} size={14}/></div>
                      <div>
                        <div style={{ fontWeight: 600, fontSize: 13 }}>{g.name}</div>
                        <div className="text-faint" style={{ fontSize: 11 }}>{g.period}</div>
                      </div>
                    </div>
                    <div style={{ textAlign: "right" }}>
                      <div className="font-display mono-numeric" style={{ fontWeight: 700, fontSize: 13 }}>
                        <span className={ratio >= 0.9 ? "text-success" : ratio >= 0.6 ? "" : "text-danger"}>{fmt(g.current)}</span>
                        <span className="text-faint" style={{ fontWeight: 500 }}> / {fmt(g.target)}</span>
                      </div>
                      <div className="text-faint" style={{ fontSize: 11 }}>{(ratio*100).toFixed(0)}% concluído</div>
                    </div>
                  </div>
                  <div className="bar-track">
                    <div className="bar-fill" style={{ width: (ratio*100)+"%", background: ratio>=0.9?"#4ADE80":"linear-gradient(90deg,var(--primary),var(--violet-500))" }}></div>
                  </div>
                </div>
              );
            })}
          </div>
        </Card>

        <Card>
          <SectionTitle title="Performance de fornecedores" sub="Top 5 por volume comprado" action={<Btn variant="ghost" size="sm" onClick={()=>navigate("suppliers")}>Gerenciar →</Btn>}/>
          <table className="tbl">
            <thead>
              <tr>
                <th>Fornecedor</th>
                <th className="num">Produtos</th>
                <th className="num">Total comprado</th>
                <th className="num">Pendente</th>
                <th className="num">Nota</th>
              </tr>
            </thead>
            <tbody>
              {SUPPLIERS.map(s => (
                <tr key={s.cnpj}>
                  <td>
                    <div style={{ fontWeight: 600 }}>{s.name}</div>
                    <div className="text-faint" style={{ fontSize: 11 }}>{s.cnpj}</div>
                  </td>
                  <td className="num">{s.products}</td>
                  <td className="num mono-numeric font-display" style={{ fontWeight: 600 }}>{brl(s.totalBuy)}</td>
                  <td className="num">{s.pending > 0 ? <span className="text-danger mono-numeric font-display" style={{ fontWeight: 600 }}>{brl(s.pending)}</span> : <span className="text-success">—</span>}</td>
                  <td className="num">
                    <span style={{ display:"inline-flex", alignItems:"center", gap: 4, color: "var(--warning)", fontWeight: 600 }}>
                      <I name="star" size={12} stroke={2.4}/> {s.score.toFixed(1).replace(".",",")}
                    </span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
      </div>
    </div>
  );
}

window.VendusDashboard = DashboardPage;
