/* Dashboard — KPIs e visão geral */

function Dashboard({ ctx }) {
  const [period, setPeriod] = useState({ kind: "day" });
  const refDate = DEFAULT_REF_DATE;
  const r = periodRange(period, refDate);
  const inP = (dateStr) => inPeriod(dateStr, period, refDate);

  const finance = ctx.state.finance;
  const trips = ctx.state.trips;
  const stock = ctx.state.stock;
  const inputs = ctx.state.inputs;
  const products = ctx.state.products;

  const periodFinance = finance.filter(f => inP(f.date));
  const dayIn  = periodFinance.filter(f => f.kind === "in").reduce((s, f) => s + f.value, 0);
  const dayOut = periodFinance.filter(f => f.kind === "out").reduce((s, f) => s + f.value, 0);
  // "A receber" agora vem dos sales pendentes + parciais (saldo não pago)
  const salesAReceber = ctx.state.sales.reduce((s, x) => s + Math.max(0, x.total - x.paid), 0);
  const purchasesAPagar = (ctx.state.inputPurchases || []).reduce((s, x) => s + Math.max(0, x.total - x.paid), 0);
  const aReceber = salesAReceber;
  const pendingCount = ctx.state.sales.filter(s => s.paid < s.total).length;
  const emRota = trips.filter(t => t.status === "em_rota");
  const criticalStock = stock.filter(s => s.units < s.minUnits).length;
  const criticalInputs = inputs.filter(i => i.stock < i.min).length;

  // Last 7 days sales (sempre, para sparkline)
  const last7 = [];
  for (let i = 6; i >= 0; i--) {
    const d = new Date(refDate); d.setDate(refDate.getDate() - i);
    const key = d.toISOString().slice(0,10);
    const v = finance.filter(f => f.date === key && f.kind === "in").reduce((s, f) => s + f.value, 0);
    last7.push({ label: d.toLocaleDateString("pt-BR", { weekday:"short" }).replace(".",""), value: v, hi: i === 0 });
  }

  // Top products from closed trips + recent sales
  const productSales = {};
  trips.filter(t => t.status === "fechado" && inP(t.date)).forEach(t => {
    (t.sold || []).forEach(s => {
      productSales[s.productId] = (productSales[s.productId] || 0) + s.qty;
    });
  });
  const topProducts = Object.entries(productSales)
    .map(([id, units]) => {
      const p = products.find(x => x.id === id);
      return p ? { id, units, value: units * p.price } : null;
    })
    .filter(Boolean)
    .sort((a,b)=>b.units-a.units)
    .slice(0, 5);

  // Top beaches from closed trips
  const beachSales = {};
  const beachTrips = {};
  trips.filter(t => t.status === "fechado" && inP(t.date)).forEach(t => {
    (t.beachesActual || []).forEach(bid => {
      beachSales[bid] = (beachSales[bid] || 0) + ((t.faturado || 0) / Math.max(1, (t.beachesActual || []).length));
      beachTrips[bid] = (beachTrips[bid] || 0) + 1;
    });
  });
  const topBeaches = Object.entries(beachSales)
    .map(([id, value]) => ({ id, value, trips: beachTrips[id] || 0 }))
    .sort((a,b)=>b.value-a.value)
    .slice(0, 3);

  // Mix do período
  const periodDistrib = periodFinance.filter(f => f.cat === "Venda Distribuidor").reduce((s, f) => s + f.value, 0);
  const periodPico    = periodFinance.filter(f => f.cat === "Retorno Picolezeiro").reduce((s, f) => s + f.value, 0);
  const periodOther   = dayIn - periodDistrib - periodPico;

  const totalWeek = last7.reduce((s, d) => s + d.value, 0);
  const periodLabel = r.label;

  return (
    <>
      <div className="page-head">
        <div>
          <h1>Bom dia, Renata 👋</h1>
          <p>{new Date().toLocaleDateString("pt-BR", { weekday:"long", day:"numeric", month:"long", year:"numeric" })} — operação ativa</p>
        </div>
        <div className="page-head__actions">
          <PeriodPicker value={period} onChange={setPeriod} refDate={refDate} />
          <Button variant="secondary" icon={<Icons.Download size={14} />} onClick={() => exportFinanceCsv(finance, period)}>Exportar</Button>
        </div>
      </div>

      <div className="grid-4" style={{ marginBottom: 18 }}>
        <KPI
          tone="success"
          label={"Entradas · " + periodLabel}
          value={fmtBRL(dayIn)}
          sub={`${periodFinance.filter(f => f.kind === "in").length} lançamento(s)`}
          medal={<Icons.ArrowDown size={18} strokeWidth={2}/>}
          sparkline={<Sparkline data={last7.map(d => d.value)} color="#15803D" />}
        />
        <KPI
          tone="danger"
          label={"Saídas · " + periodLabel}
          value={fmtBRL(dayOut)}
          sub={`${periodFinance.filter(f => f.kind === "out").length} lançamento(s)`}
          medal={<Icons.ArrowUp size={18} strokeWidth={2}/>}
        />
        <KPI
          tone="warning"
          label="Picolezeiros em rota"
          value={emRota.length + ""}
          sub={`${emRota.length} saída${emRota.length===1?"":"s"} pendente${emRota.length===1?"":"s"} de retorno`}
          medal={<Icons.Sun size={18} strokeWidth={2}/>}
        />
        <KPI
          tone="brand"
          label="A receber"
          value={fmtBRL(aReceber)}
          sub={`${pendingCount} venda${pendingCount===1?"":"s"} a prazo`}
          medal={<Icons.Wallet size={18} strokeWidth={2}/>}
        />
      </div>

      <div style={{ display:"grid", gridTemplateColumns:"2fr 1fr", gap:14, marginBottom: 14 }}>
        <Card
          title="Faturamento — últimos 7 dias"
          subtitle="Entradas confirmadas + a receber"
        >
          <BarChart data={last7.map(d => ({ label: d.label, value: d.value, alt: !d.hi }))} height={200} />
          <hr className="divider" />
          <div className="pill-row">
            <div className="pm"><strong>{fmtBRL(totalWeek)}</strong><span>Total da semana</span></div>
            <div className="pm"><strong>{fmtBRL(totalWeek/7)}</strong><span>Média/dia</span></div>
            <div className="pm"><strong>{topProducts.reduce((s, p) => s + p.units, 0)}</strong><span>Unidades vendidas</span></div>
            <div className="pm"><strong>{trips.filter(t => t.status === "fechado").length}</strong><span>Retornos fechados</span></div>
          </div>
        </Card>

        <Card title="Mix do período" subtitle={"Canal de venda · " + periodLabel}>
          {dayIn === 0 ? (
            <div className="empty"><p>Nenhuma entrada no período.</p></div>
          ) : (
          <>
          <div style={{ display:"flex", alignItems:"center", gap: 18, justifyContent:"center", padding:"6px 0 12px" }}>
            <Donut
              segments={[
                { value: Math.max(0, periodDistrib), color: "#D4310B" },
                { value: Math.max(0, periodPico),    color: "#1A1A1A" },
                { value: Math.max(0, periodOther),   color: "#A3A3A6" },
              ]}
              size={140}
            />
            <div style={{ display:"flex", flexDirection:"column", gap:10 }}>
              <LegendRow color="#D4310B" label="Distribuidores" value={fmtBRL(periodDistrib)} />
              <LegendRow color="#1A1A1A" label="Picolezeiros"   value={fmtBRL(periodPico)} />
              <LegendRow color="#A3A3A6" label="Outros"         value={fmtBRL(periodOther)} />
            </div>
          </div>
          <hr className="divider" />
          <div style={{ display:"flex", justifyContent:"space-between", fontSize:12.5 }}>
            <span className="muted">Total recebido no período</span>
            <strong className="numeric">{fmtBRL(dayIn)}</strong>
          </div>
          </>
          )}
        </Card>
      </div>

      <div style={{ display:"grid", gridTemplateColumns:"1.2fr 1fr", gap:14, marginBottom:14 }}>
        <Card title="Picolezeiros em rota" subtitle="Saídas aguardando retorno" action={<Button variant="ghost" size="sm" onClick={() => ctx.goTo("pdv-picolezeiros")}>Ver tudo →</Button>}>
          {emRota.length === 0 ? (
            <div className="empty"><p>Nenhum picolezeiro em rota.</p></div>
          ) : (
          <div className="list" style={{ margin: "-20px" }}>
            {emRota.map(t => {
              const pz = ctx.state.picolezeiros.find(p => p.id === t.picolezeiroId);
              const totalUnits = t.items.reduce((s, i) => s + i.qty, 0);
              const beaches = t.beachesPlanned.map(bid => ctx.state.beaches.find(b => b.id === bid)?.name).filter(Boolean).join(", ");
              return (
                <div key={t.id} className="list__row">
                  <div className="avatar" style={{ background: "linear-gradient(135deg, #333, #1a1a1a)" }}>{pz?.photo}</div>
                  <div style={{ flex:1, minWidth:0 }}>
                    <div style={{ fontWeight:600, color:"var(--ink-900)" }}>{pz?.name}</div>
                    <div className="subtle" style={{ display:"flex", alignItems:"center", gap:6 }}>
                      <Icons.MapPin size={11} /> {beaches}
                    </div>
                  </div>
                  <div className="text-right">
                    <div style={{ fontWeight:600, fontSize:13 }} className="numeric">{totalUnits} un</div>
                    <div className="subtle">{t.items.length} sabores</div>
                  </div>
                  <Chip tone="warning" dot>em rota</Chip>
                </div>
              );
            })}
          </div>
          )}
        </Card>

        <Card title="Alertas" subtitle="Itens que precisam de atenção">
          <div style={{ display:"flex", flexDirection:"column", gap:10 }}>
            {criticalStock > 0 && (
              <Alert tone="danger" icon={<Icons.AlertTriangle size={14}/>}
                title={`${criticalStock} sorvete${criticalStock===1?"":"s"} abaixo do mínimo`}
                hint="Reabasteça via produção" />
            )}
            {criticalInputs > 0 && (
              <Alert tone="warning" icon={<Icons.Snowflake size={14}/>}
                title={`${criticalInputs} insumo${criticalInputs===1?"":"s"} com estoque crítico`}
                hint="Veja em Fabricação → Insumos" />
            )}
            {aReceber > 0 && (
              <Alert tone="info" icon={<Icons.Calendar size={14}/>}
                title="Contas a receber"
                hint={`${fmtBRL(aReceber)} em vendas a prazo`} />
            )}
            {criticalStock === 0 && criticalInputs === 0 && aReceber === 0 && (
              <Alert tone="success" icon={<Icons.Check size={14}/>}
                title="Tudo em ordem"
                hint="Sem alertas ativos no momento" />
            )}
          </div>
        </Card>
      </div>

      <div style={{ display:"grid", gridTemplateColumns:"1.4fr 1fr", gap:14 }}>
        <Card title="Top 5 produtos" subtitle="Por unidades vendidas (histórico)">
          {topProducts.length === 0 ? (
            <div className="empty"><p>Sem vendas registradas ainda.</p></div>
          ) : (
          <table className="tbl" style={{ marginInline:"-20px", marginBlock:"-20px", width: "calc(100% + 40px)" }}>
            <thead>
              <tr>
                <th>Produto</th>
                <th>Linha</th>
                <th className="num">Unidades</th>
                <th className="num">Faturado</th>
                <th>Participação</th>
              </tr>
            </thead>
            <tbody>
              {topProducts.map((tp) => {
                const p = ctx.state.products.find(x => x.id === tp.id);
                return (
                  <tr key={tp.id}>
                    <td><span className="tag-flavor"><span className="sw" style={{ background: p?.color }} />{p?.flavor}</span></td>
                    <td className="muted">{p?.line}</td>
                    <td className="num strong">{fmtInt(tp.units)}</td>
                    <td className="num strong">{fmtBRL(tp.value)}</td>
                    <td style={{ width: 140 }}><ProgressBar value={tp.units} max={topProducts[0].units} /></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
          )}
        </Card>

        <Card title="Top 3 praias" subtitle="Faturamento por local">
          {topBeaches.length === 0 ? (
            <div className="empty"><p>Sem dados de praias.</p></div>
          ) : (
          <div style={{ display:"flex", flexDirection:"column", gap:14 }}>
            {topBeaches.map((tb, i) => {
              const b = ctx.state.beaches.find(x => x.id === tb.id);
              return (
                <div key={tb.id}>
                  <div style={{ display:"flex", justifyContent:"space-between", alignItems:"baseline", marginBottom:6 }}>
                    <div style={{ display:"flex", alignItems:"center", gap:8 }}>
                      <span style={{ fontFamily:"var(--font-display)", fontWeight:700, color:"var(--brand-600)", fontSize:18, width:22 }}>{i+1}</span>
                      <div>
                        <div style={{ fontWeight:600, color:"var(--ink-900)" }}>{b?.name}</div>
                        <div className="subtle">{b?.city} · {tb.trips} idas</div>
                      </div>
                    </div>
                    <strong className="numeric">{fmtBRL(tb.value)}</strong>
                  </div>
                  <ProgressBar value={tb.value} max={topBeaches[0].value} />
                </div>
              );
            })}
          </div>
          )}
        </Card>
      </div>
    </>
  );
}

function LegendRow({ color, label, value }) {
  return (
    <div style={{ display:"flex", alignItems:"center", gap:8 }}>
      <span style={{ width: 10, height: 10, borderRadius: 3, background: color, flexShrink: 0 }} />
      <span style={{ fontSize:12.5, color:"var(--ink-700)", flex:1 }}>{label}</span>
      <strong className="numeric" style={{ fontSize:12.5 }}>{value}</strong>
    </div>
  );
}

function Alert({ tone, icon, title, hint }) {
  const bg = { danger:"var(--danger-bg)", warning:"var(--warning-bg)", info:"var(--info-bg)", success:"var(--success-bg)" }[tone];
  const fg = { danger:"var(--danger)", warning:"var(--warning)", info:"var(--info)", success:"var(--success)" }[tone];
  return (
    <div style={{ display:"flex", gap:10, alignItems:"flex-start", padding:"10px 12px", background:bg, borderRadius:8 }}>
      <span style={{ width:24, height:24, borderRadius:6, background:"white", color:fg, display:"flex", alignItems:"center", justifyContent:"center", flexShrink:0 }}>{icon}</span>
      <div style={{ minWidth:0, flex:1 }}>
        <div style={{ fontSize:12.5, fontWeight:600, color:"var(--ink-900)" }}>{title}</div>
        <div className="subtle">{hint}</div>
      </div>
    </div>
  );
}

window.Dashboard = Dashboard;
