/* ============ MAKI — KDS · Pantalla de cocina ============ */

function fmtElapsed(sec) {
  const m = Math.floor(sec / 60), s = Math.floor(sec % 60);
  return `${m}:${String(s).padStart(2, "0")}`;
}
// Color de urgencia según minutos transcurridos desde "Recibido"
function urgency(min) {
  if (min <= 15) return { c: "#5BD08A", bg: "rgba(91,208,138,.14)", label: "En tiempo" };
  if (min <= 28) return { c: "#F2B24B", bg: "rgba(242,178,75,.16)", label: "Atención" };
  return { c: "#FF6B57", bg: "rgba(255,107,87,.18)", label: "Demorado" };
}

function Ticket({ order, now, onStart, onReady }) {
  const elapsedSec = Math.max(0, -order.placedAt * 60 + (now % 60));
  const min = elapsedSec / 60;
  const u = urgency(min);
  const inPrep = order.state === "preparacion";
  const ch = MAKI.CHANNELS[order.channel];
  return (
    <div style={{
      width: 280, flexShrink: 0, background: "#FBF8F3", borderRadius: 14, overflow: "hidden",
      display: "flex", flexDirection: "column", boxShadow: "0 10px 30px rgba(0,0,0,.35)",
      borderTop: `5px solid ${u.c}`,
    }}>
      {/* Header */}
      <div style={{ padding: "12px 14px 11px", borderBottom: "1px solid #E8E0D3" }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 7 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <span style={{ fontSize: 17, fontWeight: 800, letterSpacing: "-0.02em" }}>{order.id}</span>
            <span style={{ display: "inline-flex", alignItems: "center", justifyContent: "center", width: 22, height: 22, borderRadius: 6, background: cv(ch.bg), color: cv(ch.color) }}>
              <Icon name={ch.icon} size={12} stroke={2.4} />
            </span>
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 6, padding: "3px 9px", borderRadius: 99, background: u.bg, color: u.c }}>
            <Icon name="clock" size={13} stroke={2.6} />
            <span style={{ fontSize: 14, fontWeight: 800, fontVariantNumeric: "tabular-nums" }}>{fmtElapsed(elapsedSec)}</span>
          </div>
        </div>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
          <span style={{ fontSize: 12.5, fontWeight: 700, color: "#586059" }}>{order.client}</span>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 11.5, fontWeight: 800, color: order.mode === "Retiro" ? "#7A66CC" : "#E0732B", textTransform: "uppercase", letterSpacing: ".03em" }}>
            <Icon name={order.mode === "Retiro" ? "store" : "moped"} size={13} stroke={2.4} /> {order.mode}
          </span>
        </div>
      </div>

      {/* Items */}
      <div style={{ flex: 1, padding: "10px 14px" }}>
        {order.items.map((it, i) => (
          <div key={i} style={{ display: "flex", alignItems: "baseline", gap: 10, padding: "6px 0", borderBottom: i < order.items.length - 1 ? "1px dashed #E8E0D3" : "none" }}>
            <span style={{ fontSize: 19, fontWeight: 800, color: "#BF441F", minWidth: 34, fontVariantNumeric: "tabular-nums" }}>{it.qty}×</span>
            <span style={{ fontSize: 14.5, fontWeight: 700, lineHeight: 1.25, color: "#1E2823" }}>{it.name}</span>
          </div>
        ))}
        {order.note && (
          <div style={{ marginTop: 10, padding: "8px 11px", background: "#FBEFD6", borderRadius: 9, fontSize: 12.5, fontWeight: 700, color: "#7A5410", lineHeight: 1.4 }}>
            ⚠ {order.note}
          </div>
        )}
      </div>

      {/* Bump bar */}
      <button onClick={() => inPrep ? onReady(order) : onStart(order)}
        style={{
          border: "none", cursor: "pointer", padding: "14px", fontFamily: "inherit",
          fontSize: 14.5, fontWeight: 800, letterSpacing: ".01em", color: "#fff",
          background: inPrep ? "#1B9E8F" : "#D58A1E",
          display: "flex", alignItems: "center", justifyContent: "center", gap: 8,
        }}>
        <Icon name={inPrep ? "checkCheck" : "flame"} size={18} stroke={2.4} />
        {inPrep ? "Marcar listo" : "Iniciar preparación"}
      </button>
    </div>
  );
}

function KdsScreen({ orders, onStart, onReady }) {
  const [now, setNow] = useState(0);
  useEffect(() => {
    const t = setInterval(() => setNow(n => n + 1), 1000);
    return () => clearInterval(t);
  }, []);

  const cola = orders
    .filter(o => o.state === "confirmado" || o.state === "preparacion")
    .sort((a, b) => a.placedAt - b.placedAt); // más viejos (más urgentes) primero

  const enPrep = cola.filter(o => o.state === "preparacion").length;
  const porIniciar = cola.filter(o => o.state === "confirmado").length;
  const clock = new Date(Date.now()).toLocaleTimeString("es-AR", { hour: "2-digit", minute: "2-digit" });

  return (
    <div style={{ height: "100%", background: "#141C18", display: "flex", flexDirection: "column" }}>
      {/* Barra superior cocina */}
      <div style={{ padding: "14px 24px", display: "flex", alignItems: "center", gap: 20, borderBottom: "1px solid rgba(255,255,255,.08)" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <Icon name="flame" size={20} color="#FF6B57" stroke={2.2} />
          <span style={{ color: "#fff", fontSize: 17, fontWeight: 800, letterSpacing: "-0.01em" }}>Cocina · Comandas</span>
        </div>
        <div style={{ display: "flex", gap: 10 }}>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 7, padding: "5px 12px", borderRadius: 99, background: "rgba(242,178,75,.16)", color: "#F2B24B", fontSize: 13, fontWeight: 800 }}>
            <span style={{ width: 8, height: 8, borderRadius: "50%", background: "#F2B24B" }} /> {porIniciar} por iniciar
          </span>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 7, padding: "5px 12px", borderRadius: 99, background: "rgba(91,208,138,.14)", color: "#5BD08A", fontSize: 13, fontWeight: 800 }}>
            <span style={{ width: 8, height: 8, borderRadius: "50%", background: "#5BD08A" }} /> {enPrep} en preparación
          </span>
        </div>
        <div style={{ flex: 1 }} />
        <a href="cocina.html" target="_blank" rel="noopener" style={{ display: "inline-flex", alignItems: "center", gap: 7, padding: "6px 13px", borderRadius: 9, background: "#FF6B57", color: "#fff", textDecoration: "none", fontSize: 12.5, fontWeight: 800 }}>
          <Icon name="store" size={14} stroke={2.3} color="#fff" /> Abrir en tablet / monitor
        </a>
        <span style={{ color: "rgba(255,255,255,.55)", fontSize: 13.5, fontWeight: 700, fontVariantNumeric: "tabular-nums" }}>{clock} · {cola.length} comandas activas</span>
      </div>

      {/* Grilla de tickets */}
      <div style={{ flex: 1, overflowY: "auto", padding: 22, display: "flex", flexWrap: "wrap", gap: 16, alignContent: "flex-start" }}>
        {cola.map(o => <Ticket key={o.id} order={o} now={now} onStart={onStart} onReady={onReady} />)}
        {cola.length === 0 && (
          <div style={{ width: "100%", textAlign: "center", padding: "80px 0", color: "rgba(255,255,255,.4)" }}>
            <Icon name="checkCheck" size={42} color="rgba(255,255,255,.3)" stroke={1.8} />
            <div style={{ fontSize: 16, fontWeight: 700, marginTop: 14 }}>Cocina al día — sin comandas pendientes</div>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { KdsScreen });
