/* ============ MAKI — Métricas / multi-cadena ============ */

function Spark({ data, color }) {
  const max = Math.max(...data);
  const w = 100, h = 36;
  const pts = data.map((v, i) => `${(i / (data.length - 1)) * w},${h - (v / max) * (h - 4) - 2}`).join(" ");
  return (
    <svg viewBox={`0 0 ${w} ${h}`} width="100%" height={h} preserveAspectRatio="none">
      <polyline points={pts} fill="none" stroke={color} strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

function KpiCard({ label, value, sub, trend, color, spark }) {
  return (
    <div style={{ background: cv("--surface"), border: `1px solid ${cv("--line")}`, borderRadius: 16, padding: 18, boxShadow: "var(--sh-1)" }}>
      <div style={{ fontSize: 12.5, fontWeight: 700, color: cv("--ink-3"), marginBottom: 8 }}>{label}</div>
      <div style={{ fontSize: 28, fontWeight: 800, letterSpacing: "-0.025em", color: cv("--ink") }}>{value}</div>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginTop: 6 }}>
        <span style={{ fontSize: 12.5, fontWeight: 700, color: trend >= 0 ? cv("--wasabi") : cv("--st-cancelado") }}>
          {trend >= 0 ? "▲" : "▼"} {Math.abs(trend)}% {sub}
        </span>
        {spark && <div style={{ width: 80 }}><Spark data={spark} color={color || cv("--primary")} /></div>}
      </div>
    </div>
  );
}

function MetricsScreen() {
  const k = MAKI.KPIS;
  const maxFact = Math.max(...k.porCadena.map(c => c.fact));
  const days = ["Lun", "Mar", "Mié", "Jue", "Vie", "Sáb", "Dom"];
  const maxDay = Math.max(...k.semana);
  return (
    <div style={{ padding: "22px 24px", overflowY: "auto", height: "100%" }}>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 14, marginBottom: 22 }}>
        <KpiCard label="Pedidos hoy" value={k.hoy.pedidos} trend={12} sub="vs ayer" spark={k.semana} color={cv("--primary")} />
        <KpiCard label="Facturado hoy" value={MAKI.money(k.hoy.facturado)} trend={8} sub="vs ayer" spark={k.semana.map(v => v * 1.1)} color={cv("--wasabi")} />
        <KpiCard label="Ticket promedio" value={MAKI.money(k.hoy.ticket)} trend={-3} sub="vs ayer" />
        <KpiCard label="Cumplimiento SLA" value={k.hoy.sla + "%"} trend={5} sub="a tiempo" color={cv("--st-listo")} />
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 14, marginBottom: 22 }}>
        {/* Volumen semanal */}
        <div style={{ background: cv("--surface"), border: `1px solid ${cv("--line")}`, borderRadius: 16, padding: 20, boxShadow: "var(--sh-1)" }}>
          <div style={{ fontSize: 14.5, fontWeight: 800, marginBottom: 4 }}>Volumen de pedidos · últimos 7 días</div>
          <div style={{ fontSize: 12.5, color: cv("--ink-3"), fontWeight: 600, marginBottom: 20 }}>Total 296 pedidos · pico el sábado</div>
          <div style={{ display: "flex", alignItems: "flex-end", gap: 14, height: 150 }}>
            {k.semana.map((v, i) => (
              <div key={i} style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", gap: 8 }}>
                <div style={{ fontSize: 12, fontWeight: 700, color: cv("--ink-2") }}>{v}</div>
                <div style={{ width: "100%", height: (v / maxDay) * 110, background: i === 5 ? cv("--primary") : cv("--primary-soft"), borderRadius: "7px 7px 4px 4px", transition: "height .3s" }} />
                <div style={{ fontSize: 11.5, fontWeight: 700, color: cv("--ink-3") }}>{days[i]}</div>
              </div>
            ))}
          </div>
        </div>

        {/* Mix de canales */}
        <div style={{ background: cv("--surface"), border: `1px solid ${cv("--line")}`, borderRadius: 16, padding: 20, boxShadow: "var(--sh-1)" }}>
          <div style={{ fontSize: 14.5, fontWeight: 800, marginBottom: 18 }}>Pedidos por canal</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            {k.porCanal.map(c => {
              const ch = MAKI.CHANNELS[c.channel];
              return (
                <div key={c.channel}>
                  <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 5 }}>
                    <span style={{ display: "flex", alignItems: "center", gap: 7, fontSize: 13, fontWeight: 700 }}>
                      <Icon name={ch.icon} size={14} color={cv(ch.color)} stroke={2.2} /> {ch.label}
                    </span>
                    <span style={{ fontSize: 13, fontWeight: 800, color: cv("--ink-2") }}>{c.pct}%</span>
                  </div>
                  <div style={{ height: 9, background: cv("--surface-2"), borderRadius: 99, overflow: "hidden" }}>
                    <div style={{ width: c.pct + "%", height: "100%", background: cv(ch.color), borderRadius: 99 }} />
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>

      {/* Por cadena */}
      <div style={{ background: cv("--surface"), border: `1px solid ${cv("--line")}`, borderRadius: 16, padding: 20, boxShadow: "var(--sh-1)" }}>
        <div style={{ fontSize: 14.5, fontWeight: 800, marginBottom: 18 }}>Rendimiento por cadena · hoy</div>
        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          {MAKI.KPIS.porCadena.map((c, i) => {
            const chain = MAKI.CHAINS[i];
            return (
              <div key={c.chain} style={{ display: "grid", gridTemplateColumns: "180px 1fr 90px", alignItems: "center", gap: 16 }}>
                <span style={{ display: "flex", alignItems: "center", gap: 9, fontSize: 13.5, fontWeight: 700 }}>
                  <span style={{ width: 10, height: 10, borderRadius: 3, background: chain.color }} /> {c.chain}
                  <span style={{ fontSize: 11.5, color: cv("--ink-3"), fontWeight: 600 }}>· {chain.area}</span>
                </span>
                <div style={{ height: 26, background: cv("--surface-2"), borderRadius: 8, overflow: "hidden", position: "relative" }}>
                  <div style={{ width: (c.fact / maxFact) * 100 + "%", height: "100%", background: `${chain.color}26`, borderLeft: `3px solid ${chain.color}`, display: "flex", alignItems: "center", paddingLeft: 10 }}>
                    <span style={{ fontSize: 12, fontWeight: 800, color: cv("--ink") }}>{c.pedidos} pedidos</span>
                  </div>
                </div>
                <span style={{ fontSize: 13.5, fontWeight: 800, textAlign: "right" }}>{MAKI.money(c.fact)}</span>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { MetricsScreen });
