/* ============ MAKI · MASACA — Dashboard de Auditoría en Vivo (iPad) ============ */
/* RF-3.1 WebSocket full-duplex (simulado) · RF-3.2 ART / cola / abandono / ventas
   RF-3.3 corte diario · solo lectura para socios, no interfiere con la operación.   */

function fmtSec(s) {
  if (s == null) return "—";
  if (s < 60) return s + "s";
  return Math.floor(s / 60) + "m " + (s % 60) + "s";
}

/* —— KPI grande —— */
function LiveKpi({ icon, label, value, sub, tone = "--ink", accent }) {
  return (
    <div style={{ background: cv("--surface"), borderRadius: 16, padding: "18px 20px", border: `1px solid ${cv("--line")}`, boxShadow: "var(--sh-1)", display: "flex", flexDirection: "column", gap: 10, position: "relative", overflow: "hidden" }}>
      {accent && <div style={{ position: "absolute", top: 0, left: 0, width: "100%", height: 3, background: accent }} />}
      <div style={{ display: "flex", alignItems: "center", gap: 9 }}>
        <span style={{ width: 32, height: 32, borderRadius: 9, background: cv("--surface-2"), display: "flex", alignItems: "center", justifyContent: "center", color: accent || cv("--ink-2") }}><Icon name={icon} size={17} stroke={2.2} /></span>
        <span style={{ fontSize: 12.5, fontWeight: 700, color: cv("--ink-3"), textTransform: "uppercase", letterSpacing: ".03em" }}>{label}</span>
      </div>
      <div style={{ fontSize: 38, fontWeight: 800, lineHeight: 1, color: cv(tone), letterSpacing: "-0.02em", fontVariantNumeric: "tabular-nums" }}>{value}</div>
      {sub && <div style={{ fontSize: 12.5, color: cv("--ink-3"), fontWeight: 600 }}>{sub}</div>}
    </div>
  );
}

/* —— Barra ART por operador —— */
function OpBar({ op, sec, max }) {
  const pct = Math.max(6, (sec / max) * 100);
  const tone = sec < 40 ? cv("--wasabi") : sec < 50 ? cv("--st-preparacion") : "#EF4444";
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 11 }}>
      <span style={{ width: 110, fontSize: 12.5, fontWeight: 650, color: cv("--ink-2"), whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{op}</span>
      <div style={{ flex: 1, height: 9, borderRadius: 99, background: cv("--surface-2"), overflow: "hidden" }}>
        <div style={{ width: pct + "%", height: "100%", borderRadius: 99, background: tone, transition: "width .6s cubic-bezier(.22,1,.36,1)" }} />
      </div>
      <span style={{ width: 46, textAlign: "right", fontSize: 12.5, fontWeight: 800, color: cv("--ink"), fontVariantNumeric: "tabular-nums" }}>{sec}s</span>
    </div>
  );
}

/* —— Gráfico de ventas por franja —— */
function SalesChart({ data }) {
  const max = Math.max(...data);
  return (
    <div style={{ display: "flex", alignItems: "flex-end", gap: 6, height: 90 }}>
      {data.map((v, i) => (
        <div key={i} style={{ flex: 1, display: "flex", flexDirection: "column", justifyContent: "flex-end", height: "100%" }}>
          <div style={{ height: Math.max(8, (v / max) * 100) + "%", borderRadius: "5px 5px 0 0", background: i === data.length - 1 ? cv("--primary") : cv("--primary-soft"), transition: "height .6s cubic-bezier(.22,1,.36,1)" }} />
        </div>
      ))}
    </div>
  );
}

function AuditScreen() {
  const base = MAKI.LIVE;
  const [live, setLive] = useState(() => JSON.parse(JSON.stringify(base)));
  const [clock, setClock] = useState(new Date());
  const [pulse, setPulse] = useState(false);

  // RF-3.1 — WebSocket real (con fallback a simulación si no hay auth)
  useEffect(() => {
    // Reloj siempre tickea
    const clockTick = setInterval(() => setClock(new Date()), 10000);

    const applyMetrics = (m) => {
      setLive(m);
      setPulse(true);
      setTimeout(() => setPulse(false), 600);
    };

    if (window.API && API.isAuthenticated()) {
      // Cargar snapshot inicial
      API.getMetrics().then(m => applyMetrics(API.mapMetrics(m))).catch(() => {});

      // Conectar WS dashboard
      API.connectDash((event, data) => {
        setClock(new Date());
        if (event === 'metrics:update') {
          applyMetrics(API.mapMetrics(data));
        }
        if (event === 'supervisor:vip_alert') {
          setLive(l => ({
            ...l,
            vipFeed: [
              { customer: (data.customer && [data.customer.firstName, data.customer.lastName].filter(Boolean).join(' ')) || 'VIP', at: new Date().toLocaleTimeString('es-AR', { hour: '2-digit', minute: '2-digit' }), by: 'Sin asignar' },
              ...(l.vipFeed || []).slice(0, 4),
            ],
          }));
        }
      });
    } else {
      // Fallback: simulación si no está autenticado
      const t = setInterval(() => {
        setClock(new Date());
        setLive(l => {
          const jit = (n, amp) => Math.max(0, Math.round(n + (Math.random() - 0.5) * amp));
          return {
            ...l,
            artGlobal: jit(base.artGlobal, 6),
            queueUnattended: Math.max(0, base.queueUnattended + (Math.random() > .6 ? (Math.random() > .5 ? 1 : -1) : 0)),
            abandonmentRate: jit(base.abandonmentRate, 2),
            artByOp: l.artByOp.map((o, i) => ({ ...o, sec: jit(base.artByOp[i].sec, 8) })),
            sales: {
              ...l.sales,
              b2c: l.sales.b2c + Math.round(Math.random() * 60000),
              b2cOrders: l.sales.b2cOrders + (Math.random() > .7 ? 1 : 0),
              b2b: l.sales.b2b + Math.round(Math.random() * 40000),
              b2bOrders: l.sales.b2bOrders + (Math.random() > .85 ? 1 : 0),
            },
          };
        });
        setPulse(true); setTimeout(() => setPulse(false), 600);
      }, 2600);
      return () => { clearInterval(clockTick); clearInterval(t); };
    }

    return () => { clearInterval(clockTick); if (window.API) API.disconnectDash(); };
  }, []);

  const totalSales = live.sales.b2c + live.sales.b2b;
  const maxArt = Math.max(...live.artByOp.map(o => o.sec), 1);
  const hh = clock.toLocaleTimeString("es-AR", { hour: "2-digit", minute: "2-digit" });

  return (
    <div style={{ height: "100%", overflowY: "auto", padding: "20px 24px", background: cv("--bg") }}>
      {/* encabezado de tablero */}
      <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 18 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8, padding: "6px 12px", borderRadius: 99, background: cv("--wasabi-soft"), color: cv("--wasabi") }}>
          <span style={{ width: 8, height: 8, borderRadius: "50%", background: cv("--wasabi"), animation: pulse ? "maki-pulse-dot .6s" : "maki-pulse-dot 1.6s infinite" }} />
          <span style={{ fontSize: 12.5, fontWeight: 800 }}>EN VIVO · WebSocket</span>
        </div>
        <span style={{ fontSize: 13, color: cv("--ink-3"), fontWeight: 600 }}>Masaca Pilar · {hh}</span>
        <div style={{ flex: 1 }} />
        <span style={{ fontSize: 12.5, color: cv("--ink-3"), fontWeight: 600, display: "inline-flex", alignItems: "center", gap: 6 }}>
          <Icon name="shield" size={14} color={cv("--ink-3")} /> Vista socios · solo lectura
        </span>
      </div>

      {/* fila de KPIs */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 14, marginBottom: 16 }}>
        <LiveKpi icon="activity" label="ART promedio" value={fmtSec(live.artGlobal)} sub={live.artGlobal <= 45 ? "Dentro del objetivo (<45s)" : "Sobre el objetivo (45s)"} accent={live.artGlobal <= 45 ? cv("--wasabi") : "#EF4444"} tone={live.artGlobal <= 45 ? "--wasabi" : "--st-cancelado"} />
        <LiveKpi icon="message" label="Cola sin atender" value={live.queueUnattended} sub={`${live.totalChats} chats hoy`} accent={live.queueUnattended > 3 ? "#EF4444" : cv("--st-preparacion")} tone={live.queueUnattended > 3 ? "--st-cancelado" : "--ink"} />
        <LiveKpi icon="alert" label="Tasa de abandono" value={live.abandonmentRate + "%"} sub={`${live.abandonedCount} chats >5min sin respuesta`} accent={live.abandonmentRate > 8 ? "#EF4444" : cv("--st-preparacion")} tone="--ink" />
        <LiveKpi icon="zap" label="Ventas del día" value={MAKI.money(totalSales)} sub={`${live.sales.b2cOrders + live.sales.b2bOrders} pedidos confirmados`} accent={cv("--primary")} tone="--primary-700" />
      </div>

      {/* grilla inferior */}
      <div style={{ display: "grid", gridTemplateColumns: "1.3fr 1fr", gap: 14 }}>
        {/* ART por operador */}
        <div style={{ background: cv("--surface"), borderRadius: 16, padding: 20, border: `1px solid ${cv("--line")}`, boxShadow: "var(--sh-1)" }}>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 16 }}>
            <span style={{ fontSize: 14.5, fontWeight: 800 }}>Tiempo de respuesta por operador</span>
            <span style={{ fontSize: 11.5, color: cv("--ink-3"), fontWeight: 650, display: "inline-flex", alignItems: "center", gap: 5 }}><Icon name="repeat" size={12} color={cv("--ink-3")} /> Round-robin</span>
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 13 }}>
            {live.artByOp.map(o => <OpBar key={o.op} op={o.op} sec={o.sec} max={maxArt} />)}
          </div>
        </div>

        {/* ventas B2C vs B2B */}
        <div style={{ background: cv("--surface"), borderRadius: 16, padding: 20, border: `1px solid ${cv("--line")}`, boxShadow: "var(--sh-1)" }}>
          <div style={{ fontSize: 14.5, fontWeight: 800, marginBottom: 16 }}>Ventas en vivo</div>
          <SalesChart data={live.salesSpark} />
          <div style={{ display: "flex", gap: 10, marginTop: 16 }}>
            {[["B2C · Delivery / Take away", live.sales.b2c, live.sales.b2cOrders, cv("--primary")], ["B2B · Eventos / Corporativo", live.sales.b2b, live.sales.b2bOrders, cv("--st-confirmado")]].map(([l, v, n, c]) => (
              <div key={l} style={{ flex: 1, padding: "11px 13px", borderRadius: 12, background: cv("--bg") }}>
                <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 6 }}>
                  <span style={{ width: 9, height: 9, borderRadius: 3, background: c }} />
                  <span style={{ fontSize: 11, fontWeight: 700, color: cv("--ink-3") }}>{l}</span>
                </div>
                <div style={{ fontSize: 19, fontWeight: 800, color: cv("--ink"), letterSpacing: "-0.02em" }}>{MAKI.money(v)}</div>
                <div style={{ fontSize: 11.5, color: cv("--ink-3"), fontWeight: 600 }}>{n} pedidos</div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* feed VIP + corte diario */}
      <div style={{ display: "grid", gridTemplateColumns: "1.3fr 1fr", gap: 14, marginTop: 14 }}>
        <div style={{ background: cv("--surface"), borderRadius: 16, padding: 20, border: `1px solid ${cv("--line")}`, boxShadow: "var(--sh-1)" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 7, marginBottom: 14 }}>
            <Icon name="star" size={15} fill={cv("--primary")} stroke={0} />
            <span style={{ fontSize: 14.5, fontWeight: 800 }}>Atención VIP / Corporativa</span>
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            {live.vipFeed.map((v, i) => (
              <div key={i} style={{ display: "flex", alignItems: "center", gap: 11, padding: "9px 11px", borderRadius: 11, background: i === 0 ? cv("--primary-tint") : cv("--bg") }}>
                <Avatar name={v.customer} size={32} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 700 }}>{v.customer}</div>
                  <div style={{ fontSize: 11.5, color: cv("--ink-3"), fontWeight: 600 }}>Atiende: {v.by}</div>
                </div>
                <span style={{ fontSize: 12, color: cv("--ink-3"), fontWeight: 650, fontVariantNumeric: "tabular-nums" }}>{v.at}</span>
                {i === 0 && <span style={{ fontSize: 10.5, fontWeight: 800, color: cv("--primary-700"), background: cv("--primary-soft"), padding: "2px 8px", borderRadius: 99 }}>Sin asignar</span>}
              </div>
            ))}
          </div>
        </div>

        {/* corte diario RF-3.3 */}
        <div style={{ background: cv("--ink"), borderRadius: 16, padding: 20, color: "#fff", display: "flex", flexDirection: "column" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 12 }}>
            <Icon name="clock" size={15} color="#fff" />
            <span style={{ fontSize: 14.5, fontWeight: 800 }}>Corte diario automático</span>
          </div>
          <div style={{ fontSize: 12.5, color: "rgba(255,255,255,.7)", fontWeight: 550, lineHeight: 1.5, marginBottom: 16 }}>
            Todos los días a las <strong style={{ color: "#fff" }}>23:59</strong> el sistema consolida pedidos, métodos de pago y comprobantes de transferencia validados, genera el Excel y lo envía por email a administración.
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 9, marginTop: "auto" }}>
            {[["Pedidos del día", live.sales.b2cOrders + live.sales.b2bOrders], ["Facturado", MAKI.money(totalSales)], ["Próximo envío", "Hoy 23:59 → adm@masaca"]].map(([l, v]) => (
              <div key={l} style={{ display: "flex", alignItems: "center", justifyContent: "space-between", paddingBottom: 9, borderBottom: "1px solid rgba(255,255,255,.1)" }}>
                <span style={{ fontSize: 12.5, color: "rgba(255,255,255,.6)", fontWeight: 600 }}>{l}</span>
                <span style={{ fontSize: 13.5, fontWeight: 800, fontVariantNumeric: "tabular-nums" }}>{v}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { AuditScreen });
