/* ============ MAKI — App principal ============ */

const NAV = [
  { id: "consola",   label: "Consola",          icon: "headphones", desc: "Atención de chats · balanceo y validación" },
  { id: "bandeja",   label: "Bandeja",           icon: "inbox",      desc: "Todos los pedidos, todos los canales" },
  { id: "tablero",   label: "Tablero",           icon: "board",      desc: "Flujo operativo por estado" },
  { id: "clientes",  label: "Clientes",          icon: "users",      desc: "Cuentas B2B y particulares" },
  { id: "cocina",    label: "Cocina (KDS)",      icon: "flame",      desc: "Pantalla de comandas para cocina" },
  { id: "auditoria", label: "Auditoría en vivo", icon: "activity",   desc: "Dashboard de socios · métricas en tiempo real" },
  { id: "metricas",  label: "Métricas",          icon: "chart",      desc: "Rendimiento y multi-cadena" },
  { id: "cliente",   label: "Vista cliente",     icon: "truck",      desc: "Seguimiento que ve el cliente" },
  { id: "admin",     label: "Admin",             icon: "shield",     desc: "Gestión de usuarios · permisos · sistema" },
];

const INCOMING = [
  { client: "Coworking Nodo",  chain: "sakura",  channel: "whatsapp", clientType: "empresa" },
  { client: "Martín Cabezas",  chain: "edomaki", channel: "delivery", clientType: "particular" },
  { client: "Bar Náutico",     chain: "niji",    channel: "telefono", clientType: "empresa" },
];

/* —— Panel de notificaciones —— */
function NotificationsPanel({ notifs, onClear, onClose }) {
  const TYPE_COLORS = { vip: "#E8694A", error: "#EF4444", ok: cv("--wasabi"), log: cv("--ink-3") };
  const TYPE_BG     = { vip: "#FEF0EB", error: "#FEF2F2", ok: cv("--wasabi-soft"), log: cv("--bg") };
  const TYPE_ICONS  = { vip: "star", error: "wifiOff", ok: "check", log: "activity" };

  return (
    <div style={{
      position: "fixed", top: 68, right: 16, zIndex: 60, width: 340,
      background: cv("--surface"), borderRadius: 16, boxShadow: "var(--sh-pop)",
      border: `1px solid ${cv("--line")}`, animation: "maki-rise .2s cubic-bezier(.22,1,.36,1)",
      overflow: "hidden",
    }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "14px 16px 12px", borderBottom: `1px solid ${cv("--line")}` }}>
        <div style={{ fontSize: 14, fontWeight: 800 }}>Notificaciones</div>
        <div style={{ display: "flex", gap: 6 }}>
          {notifs.length > 0 && <button onClick={onClear} style={{ fontSize: 11.5, fontWeight: 700, color: cv("--ink-3"), background: "none", border: "none", cursor: "pointer", padding: "2px 6px" }}>Limpiar</button>}
          <button onClick={onClose} style={{ width: 26, height: 26, borderRadius: 7, border: `1px solid ${cv("--line")}`, background: cv("--bg"), cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name="x" size={13} /></button>
        </div>
      </div>
      <div style={{ maxHeight: 380, overflowY: "auto" }}>
        {notifs.length === 0 && (
          <div style={{ padding: "28px 16px", textAlign: "center", color: cv("--ink-3"), fontSize: 13 }}>Sin notificaciones</div>
        )}
        {notifs.map(n => (
          <div key={n.id} style={{ display: "flex", gap: 10, padding: "11px 16px", borderBottom: `1px solid ${cv("--line")}`, background: n.read ? cv("--surface") : (TYPE_BG[n.type] || cv("--bg")) }}>
            <span style={{ width: 28, height: 28, borderRadius: 8, flexShrink: 0, background: TYPE_BG[n.type] || cv("--bg"), display: "flex", alignItems: "center", justifyContent: "center" }}>
              <Icon name={TYPE_ICONS[n.type] || "bell"} size={14} color={TYPE_COLORS[n.type] || cv("--ink-3")} />
            </span>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 12.5, fontWeight: 650, lineHeight: 1.35 }}>{n.text}</div>
              <div style={{ fontSize: 11, color: cv("--ink-3"), fontWeight: 600, marginTop: 2 }}>{n.at}</div>
            </div>
            {!n.read && <span style={{ width: 7, height: 7, borderRadius: "50%", background: cv("--primary"), flexShrink: 0, marginTop: 4 }} />}
          </div>
        ))}
      </div>
    </div>
  );
}

/* —— Modal de settings del usuario —— */
function SettingsModal({ onClose, onLogout }) {
  const user = window.API ? API.user : null;
  const [status, setStatus] = useState("available");
  const [saved, setSaved] = useState(false);

  const handleStatusChange = (s) => {
    setStatus(s);
    if (window.API && API.isAuthenticated()) {
      API.setOperatorStatus(s).catch(() => {});
    }
    setSaved(true);
    setTimeout(() => setSaved(false), 1500);
  };

  const ROLE_LABELS = { admin: "Administrador", supervisor: "Supervisor", operator: "Operador" };
  const ROLE_COLORS = { admin: "#E8694A", supervisor: "#7A66CC", operator: "#1B9E8F" };

  return (
    <div style={{ position: "fixed", inset: 0, zIndex: 70, display: "flex", alignItems: "flex-end", justifyContent: "flex-start", padding: "0 0 78px 14px" }}>
      <div onClick={onClose} style={{ position: "absolute", inset: 0 }} />
      <div style={{
        position: "relative", width: 280, background: cv("--surface"), borderRadius: 16,
        boxShadow: "var(--sh-pop)", border: `1px solid ${cv("--line")}`,
        animation: "maki-rise .2s cubic-bezier(.22,1,.36,1)", overflow: "hidden",
      }}>
        {/* User info */}
        <div style={{ padding: "16px 16px 14px", borderBottom: `1px solid ${cv("--line")}`, background: cv("--bg") }}>
          <div style={{ display: "flex", alignItems: "center", gap: 11 }}>
            <Avatar name={user?.displayName || "Demo"} size={40} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 14, fontWeight: 800, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{user?.displayName || "Operador Demo"}</div>
              <div style={{ fontSize: 12, color: cv("--ink-3"), fontWeight: 600, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{user?.email || "demo@masaca.com.ar"}</div>
            </div>
          </div>
          {user?.role && (
            <div style={{ marginTop: 10 }}>
              <span style={{ display: "inline-block", fontSize: 11.5, fontWeight: 800, padding: "3px 10px", borderRadius: 99, background: ROLE_COLORS[user.role] + "18", color: ROLE_COLORS[user.role] || cv("--ink-3") }}>
                {ROLE_LABELS[user.role] || user.role}
              </span>
            </div>
          )}
        </div>

        {/* Status */}
        <div style={{ padding: "12px 16px", borderBottom: `1px solid ${cv("--line")}` }}>
          <div style={{ fontSize: 11.5, fontWeight: 800, color: cv("--ink-3"), textTransform: "uppercase", letterSpacing: ".04em", marginBottom: 8 }}>Estado de disponibilidad</div>
          {[
            { id: "available", label: "Disponible",   color: cv("--wasabi") },
            { id: "busy",      label: "Ocupado",      color: cv("--st-preparacion") },
            { id: "offline",   label: "Desconectado", color: cv("--ink-3") },
          ].map(s => (
            <button key={s.id} onClick={() => handleStatusChange(s.id)} style={{
              display: "flex", alignItems: "center", gap: 9, width: "100%", padding: "7px 9px", borderRadius: 8, marginBottom: 4,
              border: "none", cursor: "pointer", textAlign: "left",
              background: status === s.id ? cv("--surface-2") : "transparent",
              color: cv("--ink"), fontSize: 13, fontWeight: status === s.id ? 750 : 600,
            }}>
              <span style={{ width: 8, height: 8, borderRadius: "50%", background: s.color, flexShrink: 0 }} />
              {s.label}
              {status === s.id && <Icon name="check" size={13} color={cv("--wasabi")} style={{ marginLeft: "auto" }} />}
            </button>
          ))}
          {saved && <div style={{ fontSize: 11.5, color: cv("--wasabi"), fontWeight: 700, marginTop: 4 }}>✓ Estado actualizado</div>}
        </div>

        {/* Actions */}
        <div style={{ padding: "10px 10px" }}>
          <button onClick={onLogout} style={{
            display: "flex", alignItems: "center", gap: 9, width: "100%", padding: "9px 12px", borderRadius: 9,
            border: "none", cursor: "pointer", background: "#FEF2F2", color: "#EF4444", fontSize: 13.5, fontWeight: 750,
          }}>
            <Icon name="logout" size={16} color="#EF4444" />
            Cerrar sesión
          </button>
        </div>
      </div>
    </div>
  );
}

/* —— App principal —— */
/* —— Modal de carga manual de pedido (telefónico / sucursal) —— */
function ManualOrderModal({ onClose, onCreate }) {
  const [name, setName] = useState("");
  const [phone, setPhone] = useState("");
  const [address, setAddress] = useState("");
  const [reference, setReference] = useState("");
  const [altPhone, setAltPhone] = useState("");
  const [payment, setPayment] = useState("Efectivo");
  const [clientType, setClientType] = useState("particular");
  const [vip, setVip] = useState(false);
  const [items, setItems] = useState([]);
  const menuKeys = Object.keys(MAKI.MENU);
  const [pick, setPick] = useState(menuKeys[0]);
  const [qty, setQty] = useState(1);

  const PAYMENTS = ["Efectivo", "Transferencia", "Tarjeta", "Mercado Pago"];
  const total = items.reduce((s, i) => s + i.price * i.qty, 0);
  const canSave = name.trim() && items.length > 0;

  const addItem = () => {
    if (!pick) return;
    const price = MAKI.MENU[pick].p;
    setItems(its => {
      const ex = its.find(i => i.name === pick);
      if (ex) return its.map(i => i.name === pick ? { ...i, qty: i.qty + qty } : i);
      return [...its, { name: pick, qty, price }];
    });
    setQty(1);
  };
  const removeItem = (n) => setItems(its => its.filter(i => i.name !== n));

  const lbl = { fontSize: 11.5, fontWeight: 800, letterSpacing: ".03em", textTransform: "uppercase", color: cv("--ink-3"), marginBottom: 5, display: "block" };
  const inp = { width: "100%", border: `1px solid ${cv("--line-2")}`, borderRadius: 9, padding: "9px 11px", fontSize: 13.5, fontFamily: "inherit", outline: "none", background: cv("--surface"), color: cv("--ink"), boxSizing: "border-box" };

  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, zIndex: 120, background: "rgba(15,23,20,.45)", display: "flex", alignItems: "center", justifyContent: "center", padding: 20 }}>
      <div onClick={e => e.stopPropagation()} style={{ width: 560, maxHeight: "90vh", overflowY: "auto", background: cv("--surface"), borderRadius: 18, boxShadow: "var(--sh-pop)", padding: 24 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 4 }}>
          <span style={{ width: 36, height: 36, borderRadius: 10, background: cv("--primary-tint"), color: cv("--primary-700"), display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name="plus" size={20} stroke={2.4} /></span>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 16, fontWeight: 850 }}>Cargar pedido manual</div>
            <div style={{ fontSize: 12, color: cv("--ink-3"), fontWeight: 600 }}>Telefónico · sucursal · otro canal</div>
          </div>
          <button onClick={onClose} style={{ background: "none", border: "none", cursor: "pointer", color: cv("--ink-3"), padding: 4 }}><Icon name="x" size={20} /></button>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginTop: 16 }}>
          <div style={{ gridColumn: "1 / -1" }}>
            <label style={lbl}>Nombre del cliente *</label>
            <input value={name} onChange={e => setName(e.target.value)} style={inp} placeholder="Nombre y apellido" />
          </div>
          <div>
            <label style={lbl}>Teléfono</label>
            <input value={phone} onChange={e => setPhone(e.target.value)} style={inp} placeholder="+54 11 ____-____" />
          </div>
          <div>
            <label style={lbl}>Teléfono alternativo</label>
            <input value={altPhone} onChange={e => setAltPhone(e.target.value)} style={inp} placeholder="Opcional" />
          </div>
          <div style={{ gridColumn: "1 / -1" }}>
            <label style={lbl}>Dirección de entrega</label>
            <input value={address} onChange={e => setAddress(e.target.value)} style={inp} placeholder="Vacío = retiro en local" />
          </div>
          <div style={{ gridColumn: "1 / -1" }}>
            <label style={lbl}>Referencia</label>
            <input value={reference} onChange={e => setReference(e.target.value)} style={inp} placeholder="Ej: Timbre 2B · portero · entre calles" />
          </div>
          <div style={{ gridColumn: "1 / -1" }}>
            <label style={lbl}>Tipo de cliente</label>
            <div style={{ display: "flex", gap: 7, alignItems: "center", flexWrap: "wrap" }}>
              {[["particular", "Particular"], ["empresa", "Empresa / B2B"]].map(([k, l]) => (
                <button key={k} onClick={() => setClientType(k)} style={{ padding: "7px 13px", borderRadius: 99, cursor: "pointer", fontSize: 12.5, fontWeight: 700, fontFamily: "inherit", border: `1.5px solid ${clientType === k ? cv("--primary") : cv("--line")}`, background: clientType === k ? cv("--primary-tint") : cv("--surface"), color: clientType === k ? cv("--primary-700") : cv("--ink-2") }}>{l}</button>
              ))}
              <div style={{ flex: 1 }} />
              <button onClick={() => setVip(v => !v)} style={{ display: "flex", alignItems: "center", gap: 7, padding: "7px 13px", borderRadius: 99, cursor: "pointer", fontSize: 12.5, fontWeight: 700, fontFamily: "inherit", border: `1.5px solid ${vip ? "#D4AF37" : cv("--line")}`, background: vip ? "#FBF6E7" : cv("--surface"), color: vip ? "#9A7B1A" : cv("--ink-2") }}>
                <span style={{ width: 14, height: 14, borderRadius: 4, border: `1.5px solid ${vip ? "#D4AF37" : cv("--ink-3")}`, background: vip ? "#D4AF37" : "transparent", display: "flex", alignItems: "center", justifyContent: "center" }}>{vip && <Icon name="check" size={10} stroke={3} color="#fff" />}</span>
                ⭐ Cliente VIP
              </button>
            </div>
          </div>
          <div style={{ gridColumn: "1 / -1" }}>
            <label style={lbl}>Pago</label>
            <div style={{ display: "flex", gap: 7, flexWrap: "wrap" }}>
              {PAYMENTS.map(p => (
                <button key={p} onClick={() => setPayment(p)} style={{ padding: "7px 13px", borderRadius: 99, cursor: "pointer", fontSize: 12.5, fontWeight: 700, fontFamily: "inherit", border: `1.5px solid ${payment === p ? cv("--primary") : cv("--line")}`, background: payment === p ? cv("--primary-tint") : cv("--surface"), color: payment === p ? cv("--primary-700") : cv("--ink-2") }}>{p}</button>
              ))}
            </div>
          </div>
        </div>

        {/* Pedido */}
        <div style={{ marginTop: 18 }}>
          <label style={lbl}>Pedido *</label>
          <div style={{ display: "flex", gap: 8, marginBottom: 10 }}>
            <select value={pick} onChange={e => setPick(e.target.value)} style={{ ...inp, flex: 1 }}>
              {menuKeys.map(k => <option key={k} value={k}>{k} — {MAKI.money(MAKI.MENU[k].p)}</option>)}
            </select>
            <input type="number" min={1} value={qty} onChange={e => setQty(Math.max(1, parseInt(e.target.value) || 1))} style={{ ...inp, width: 64, flex: "none" }} />
            <Btn variant="outline" size="sm" icon="plus" onClick={addItem}>Agregar</Btn>
          </div>
          <div style={{ border: `1px solid ${cv("--line")}`, borderRadius: 12, overflow: "hidden" }}>
            {items.length === 0 && <div style={{ padding: 14, fontSize: 12.5, color: cv("--ink-3"), textAlign: "center" }}>Sin ítems — agregá del menú</div>}
            {items.map((it, i) => (
              <div key={i} style={{ display: "flex", alignItems: "center", gap: 10, padding: "9px 12px", borderBottom: `1px solid ${cv("--line")}` }}>
                <span style={{ minWidth: 28, height: 24, borderRadius: 6, background: cv("--primary-tint"), color: cv("--primary-700"), fontSize: 12.5, fontWeight: 800, display: "flex", alignItems: "center", justifyContent: "center", padding: "0 7px" }}>{it.qty}×</span>
                <span style={{ flex: 1, fontSize: 12.5, fontWeight: 600 }}>{it.name}</span>
                <span style={{ fontSize: 12.5, color: cv("--ink-2"), fontWeight: 650 }}>{MAKI.money(it.price * it.qty)}</span>
                <button onClick={() => removeItem(it.name)} style={{ background: "none", border: "none", cursor: "pointer", color: cv("--ink-3"), padding: 2 }}><Icon name="x" size={15} /></button>
              </div>
            ))}
            {items.length > 0 && (
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "10px 12px" }}>
                <span style={{ fontSize: 13, fontWeight: 800 }}>Total</span>
                <span style={{ fontSize: 15.5, fontWeight: 800, color: cv("--primary-700") }}>{MAKI.money(total)}</span>
              </div>
            )}
          </div>
        </div>

        <div style={{ display: "flex", gap: 10, marginTop: 20 }}>
          <Btn variant="ghost" style={{ flex: 1 }} onClick={onClose}>Cancelar</Btn>
          <Btn variant="primary" icon="check" style={{ flex: 2, opacity: canSave ? 1 : .5, pointerEvents: canSave ? "auto" : "none" }} onClick={() => canSave && onCreate({ name, phone, address, reference, altPhone, payment, clientType, vip, items })}>Cargar pedido</Btn>
        </div>
      </div>
    </div>
  );
}

function App() {
  const [view, setView] = useState("consola");
  const [orders, setOrders] = useState(() => (window.MakiSync ? MakiSync.load() : MAKI.ORDERS.map(o => ({ ...o }))));
  const [selId, setSelId] = useState(null);
  const [filters, setFilters] = useState({ q: "", channel: "todos", type: "todos" });
  const [chain, setChain] = useState("todas");
  const [toast, setToast] = useState(null);
  const [notifs, setNotifs] = useState([
    { id: 1, type: "vip",   text: "Cliente VIP Antonieta Sarmiento en cola", at: "20:41", read: false },
    { id: 2, type: "ok",    text: "Sistema Maxirest conectado correctamente", at: "20:15", read: true },
    { id: 3, type: "log",   text: "Valentina inició sesión · operador disponible", at: "20:00", read: true },
  ]);
  const [notifOpen, setNotifOpen] = useState(false);
  const [settingsOpen, setSettingsOpen] = useState(false);
  const [onlineCount, setOnlineCount] = useState(2);
  const [manualOpen, setManualOpen] = useState(false);
  const incRef = useRef(0);

  // Listen for notifications from child screens
  useEffect(() => {
    const handler = (e) => {
      setNotifs(prev => [{ id: Date.now() + Math.random(), ...e.detail, read: false }, ...prev].slice(0, 60));
    };
    window.addEventListener("maki:notif", handler);
    return () => window.removeEventListener("maki:notif", handler);
  }, []);

  // Bus en vivo: refleja cambios de la cocina (KDS) y el rider en el panel madre
  useEffect(() => {
    if (!window.MakiSync) return;
    const STATE_LABEL = { recibido: "recibido", confirmado: "confirmado", preparacion: "en preparación", listo: "listo", despachado: "despachado", entregado: "entregado" };
    const unsub = MakiSync.subscribe((msg) => {
      setOrders(MakiSync.load());
      if (msg && msg.type === "state" && msg.evt) {
        const at = new Date().toLocaleTimeString("es-AR", { hour: "2-digit", minute: "2-digit" });
        const done = msg.evt.state === "entregado";
        if (done || msg.evt.state === "listo" || msg.evt.state === "despachado") {
          window.dispatchEvent(new CustomEvent("maki:notif", { detail: {
            type: done ? "ok" : "log",
            text: `Pedido ${msg.evt.id} · ${STATE_LABEL[msg.evt.state] || msg.evt.state}${done ? " — ciclo completo ✓" : ""}`,
            at,
          } }));
        }
      }
    });
    return () => unsub && unsub();
  }, []);

  // Get live operator count from API
  useEffect(() => {
    if (!window.API || !API.isAuthenticated()) return;
    API.getOperators().then(ops => {
      if (ops && ops.length > 0) setOnlineCount(ops.filter(o => o.status !== "offline").length);
    }).catch(() => {});
  }, []);

  const unreadCount = notifs.filter(n => !n.read).length;

  const selected = orders.find(o => o.id === selId) || null;
  const visible = chain === "todas" ? orders : orders.filter(o => o.chain === chain);

  const setOrderState = (order, stateId) => {
    if (window.MakiSync) MakiSync.setState(order.id, stateId);
    else setOrders(os => os.map(o => o.id === order.id ? { ...o, state: stateId } : o));
  };
  const advance = (order) => {
    const i = MAKI.STATES.findIndex(s => s.id === order.state);
    if (i < MAKI.STATES.length - 1) setOrderState(order, MAKI.STATES[i + 1].id);
  };

  const simulate = () => {
    const tpl = INCOMING[incRef.current % INCOMING.length]; incRef.current++;
    const id = "#" + (1100 + incRef.current);
    const menuKeys = Object.keys(MAKI.MENU);
    const its = [0, 1].map(() => { const n = menuKeys[Math.floor(Math.random() * menuKeys.length)]; return { name: n, qty: 1 + Math.floor(Math.random() * 3), price: MAKI.MENU[n].p }; });
    const newOrder = {
      id, client: tpl.client, clientType: tpl.clientType, chain: tpl.chain, channel: tpl.channel,
      state: "recibido", items: its, total: its.reduce((s, i) => s + i.price * i.qty, 0),
      mode: Math.random() > .4 ? "Envío" : "Retiro", address: "Av. Santa Fe 2100, CABA", due: "14:15",
      note: "", assignee: null, slaMin: 45, thread: [{ from: "client", at: "ahora", text: "Hola! Quería hacer un pedido 🍣" }],
    };
    if (window.MakiSync) MakiSync.addOrder(newOrder); else setOrders(os => [newOrder, ...os]);
    setToast({ ...newOrder });
    setTimeout(() => setToast(t => t && t.id === id ? null : t), 5200);
  };

  const createManualOrder = (data) => {
    incRef.current++;
    // id único: max numérico existente + 1 (evita colisión con seed/simulados)
    const existing = (window.MakiSync ? MakiSync.load() : orders);
    const maxNum = existing.reduce((m, o) => Math.max(m, parseInt(String(o.id).replace(/\D/g, "")) || 0), 1100);
    const id = "#" + (maxNum + 1);
    const total = data.items.reduce((s, i) => s + i.price * i.qty, 0);
    const noteParts = [];
    if (data.vip) noteParts.push("⭐ VIP");
    if (data.reference) noteParts.push(`Ref: ${data.reference}`);
    if (data.altPhone) noteParts.push(`Tel. alt: ${data.altPhone}`);
    if (data.payment) noteParts.push(`Pago: ${data.payment}`);
    const segment = data.vip ? "VIP" : (data.clientType === "empresa" ? "B2B_CORPORATE" : "B2C_REGULAR");
    const newOrder = {
      id, client: data.name || "Cliente", clientType: data.clientType || "particular", chain: chain === "todas" ? "sakura" : chain,
      channel: "telefono", state: "recibido", items: data.items, total,
      mode: data.address ? "Envío" : "Retiro", address: data.address || "", phone: data.phone || "",
      due: new Date(Date.now() + 45 * 60000).toLocaleTimeString("es-AR", { hour: "2-digit", minute: "2-digit", hour12: false }),
      note: noteParts.join(" · "), assignee: null, slaMin: 45,
      payment: data.payment || "Efectivo", segment, vip: !!data.vip,
      thread: [{ from: "agent", at: "ahora", text: "Pedido cargado manualmente (telefónico / sucursal)" }],
    };
    if (window.MakiSync) MakiSync.addOrder(newOrder); else setOrders(os => [newOrder, ...os]);
    setManualOpen(false);
    setToast({ ...newOrder });
    setTimeout(() => setToast(t => t && t.id === id ? null : t), 5200);
    window.dispatchEvent(new CustomEvent("maki:notif", { detail: { type: "ok", text: `Pedido manual cargado: ${newOrder.client} · ${MAKI.money(total)}`, at: new Date().toLocaleTimeString("es-AR", { hour: "2-digit", minute: "2-digit" }) } }));
  };

  const handleLogout = () => {
    if (window.API) API.clearToken();
    window.location.reload();
  };

  const screen = () => {
    switch (view) {
      case "consola":   return <ConsolaScreen chain={chain} />;
      case "auditoria": return <AuditScreen />;
      case "bandeja":   return <InboxScreen orders={visible} onOpen={o => setSelId(o.id)} filters={filters} setFilters={setFilters} />;
      case "tablero":   return <BoardScreen orders={visible} onOpen={o => setSelId(o.id)} onMove={setOrderState} />;
      case "clientes":  return <ClientsScreen orders={orders} onOpen={o => setSelId(o.id)} />;
      case "cocina":    return <KdsScreen orders={visible} onStart={(o) => setOrderState(o, "preparacion")} onReady={(o) => setOrderState(o, "listo")} />;
      case "metricas":  return <MetricsScreen />;
      case "cliente":   return <TrackingScreen orders={orders} />;
      case "admin":     return <AdminScreen />;
      default:          return null;
    }
  };

  const nuevos = orders.filter(o => o.state === "recibido").length;
  const current = NAV.find(n => n.id === view);

  return (
    <div style={{ display: "flex", height: "100vh", overflow: "hidden" }}>
      {/* Sidebar */}
      <aside style={{ width: 224, flexShrink: 0, background: cv("--surface"), borderRight: `1px solid ${cv("--line")}`, display: "flex", flexDirection: "column", padding: "18px 14px" }}>
        <div style={{ padding: "4px 8px 22px" }}><Logo size={30} /></div>
        <Btn variant="primary" icon="plus" style={{ width: "100%", marginBottom: 18 }} onClick={() => setManualOpen(true)}>Pedido entrante</Btn>
        <nav style={{ display: "flex", flexDirection: "column", gap: 3, flex: 1, overflowY: "auto" }}>
          {NAV.map(n => {
            const on = view === n.id;
            return (
              <button key={n.id} onClick={() => setView(n.id)} style={{
                display: "flex", alignItems: "center", gap: 11, padding: "10px 12px", borderRadius: 10, border: "none", cursor: "pointer",
                background: on ? cv("--primary-tint") : "transparent", color: on ? cv("--primary-700") : cv("--ink-2"),
                fontSize: 13.5, fontWeight: on ? 750 : 650, textAlign: "left", transition: "background .12s",
              }}>
                <Icon name={n.icon} size={18} stroke={on ? 2.3 : 2} />
                <span style={{ flex: 1 }}>{n.label}</span>
                {n.id === "bandeja" && nuevos > 0 && (
                  <span style={{ fontSize: 11, fontWeight: 800, color: "#fff", background: cv("--primary"), borderRadius: 99, padding: "1px 7px", minWidth: 20, textAlign: "center" }}>{nuevos}</span>
                )}
                {n.id === "admin" && (
                  <span style={{ width: 6, height: 6, borderRadius: "50%", background: "#E8694A", flexShrink: 0 }} />
                )}
              </button>
            );
          })}
        </nav>
        {/* Operators online status */}
        <div style={{ padding: "12px", borderRadius: 12, background: cv("--bg"), border: `1px solid ${cv("--line")}`, marginBottom: 10, marginTop: 10 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 6 }}>
            <span style={{ width: 8, height: 8, borderRadius: "50%", background: cv("--wasabi") }} />
            <span style={{ fontSize: 12, fontWeight: 700, color: cv("--ink-2") }}>{onlineCount} operario{onlineCount !== 1 ? "s" : ""} en línea</span>
          </div>
          <div style={{ fontSize: 11.5, color: cv("--ink-3"), fontWeight: 600, lineHeight: 1.4 }}>
            {MAKI.OPERATORS.filter(o => o.status !== "offline").map(o => o.name).join(", ")} conectados
          </div>
        </div>
        {/* User button */}
        <button onClick={() => { setSettingsOpen(o => !o); setNotifOpen(false); }} style={{ display: "flex", alignItems: "center", gap: 10, padding: "8px 10px", border: "none", background: settingsOpen ? cv("--surface-2") : "transparent", cursor: "pointer", borderRadius: 10 }}>
          <Avatar name={window.API?.user?.displayName || "Operador Demo"} size={32} />
          <div style={{ textAlign: "left", flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 12.5, fontWeight: 700, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{window.API?.user?.displayName || "Operador Demo"}</div>
            <div style={{ fontSize: 11, color: cv("--ink-3"), fontWeight: 600, textTransform: "capitalize" }}>{window.API?.user?.role || "Administrador"}</div>
          </div>
          <Icon name="settings" size={16} color={cv("--ink-3")} />
        </button>
      </aside>

      {/* Main */}
      <main style={{ flex: 1, display: "flex", flexDirection: "column", minWidth: 0 }}>
        <header style={{ height: 64, flexShrink: 0, borderBottom: `1px solid ${cv("--line")}`, background: cv("--surface"), display: "flex", alignItems: "center", padding: "0 24px", gap: 16 }}>
          <div>
            <h1 style={{ margin: 0, fontSize: 18, fontWeight: 800, letterSpacing: "-0.02em" }}>{current.label}</h1>
            <div style={{ fontSize: 12, color: cv("--ink-3"), fontWeight: 600 }}>{current.desc}</div>
          </div>
          <div style={{ flex: 1 }} />
          {/* Filtro de cadena */}
          <div style={{ display: "flex", alignItems: "center", gap: 7, background: cv("--bg"), border: `1px solid ${cv("--line-2")}`, borderRadius: 10, padding: "7px 10px" }}>
            <Icon name="store" size={15} color={cv("--ink-3")} />
            <select value={chain} onChange={e => setChain(e.target.value)} style={{ border: "none", background: "transparent", fontSize: 13, fontWeight: 700, fontFamily: "inherit", color: cv("--ink"), outline: "none", cursor: "pointer" }}>
              <option value="todas">Todas las cadenas</option>
              {MAKI.CHAINS.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
            </select>
          </div>
          {/* Bell */}
          <button onClick={() => { setNotifOpen(o => !o); setSettingsOpen(false); if (!notifOpen) setNotifs(ns => ns.map(n => ({ ...n, read: true }))); }} style={{ position: "relative", width: 40, height: 40, borderRadius: 10, border: `1px solid ${cv("--line-2")}`, background: notifOpen ? cv("--surface-2") : cv("--surface"), cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center" }}>
            <Icon name="bell" size={18} color={cv("--ink-2")} />
            {unreadCount > 0 && (
              <span style={{ position: "absolute", top: 7, right: 8, width: 8, height: 8, borderRadius: "50%", background: cv("--primary"), border: `2px solid ${cv("--surface")}` }} />
            )}
          </button>
        </header>

        <div style={{ flex: 1, minHeight: 0, background: cv("--bg") }}>{screen()}</div>
      </main>

      {/* Notifications panel */}
      {notifOpen && (
        <NotificationsPanel
          notifs={notifs}
          onClear={() => setNotifs([])}
          onClose={() => setNotifOpen(false)}
        />
      )}

      {/* Settings modal */}
      {settingsOpen && (
        <SettingsModal onClose={() => setSettingsOpen(false)} onLogout={handleLogout} />
      )}

      {/* Order drawer */}
      {selected && <OrderDrawer order={selected} onClose={() => setSelId(null)} onSet={(s) => setOrderState(selected, s)} onAdvance={(o) => advance(o)} />}

      {/* Modal carga manual de pedido */}
      {manualOpen && <ManualOrderModal onClose={() => setManualOpen(false)} onCreate={createManualOrder} />}

      {/* Toast pedido entrante */}
      {toast && (
        <div onClick={() => { setView("bandeja"); setSelId(toast.id); setToast(null); }} style={{
          position: "fixed", bottom: 22, right: 22, zIndex: 80, width: 330, background: cv("--surface"),
          borderRadius: 14, boxShadow: "var(--sh-pop)", border: `1px solid ${cv("--line")}`, padding: 14,
          cursor: "pointer", animation: "maki-rise .3s cubic-bezier(.22,1,.36,1)",
        }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 9 }}>
            <span style={{ width: 8, height: 8, borderRadius: "50%", background: cv("--primary"), animation: "maki-pulse-dot 1.2s infinite" }} />
            <span style={{ fontSize: 12, fontWeight: 800, letterSpacing: "0.02em", color: cv("--primary-700") }}>NUEVO PEDIDO</span>
            <div style={{ flex: 1 }} />
            <ChannelTag channel={toast.channel} compact />
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <Avatar name={toast.client} type={toast.clientType} size={36} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 13.5, fontWeight: 750 }}>{toast.client}</div>
              <div style={{ fontSize: 12, color: cv("--ink-3"), fontWeight: 600 }}>{toast.id} · {MAKI.money(toast.total)}</div>
            </div>
            <Icon name="chevR" size={18} color={cv("--ink-3")} />
          </div>
        </div>
      )}
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
