/* ============ MAKI — Bandeja omnicanal unificada ============ */

function InboxScreen({ orders, onOpen, filters, setFilters }) {
  const channels = ["todos", ...Object.keys(MAKI.CHANNELS)];
  const filtered = orders.filter(o =>
    (filters.channel === "todos" || o.channel === filters.channel) &&
    (filters.type === "todos" || o.clientType === filters.type) &&
    (!filters.q || o.client.toLowerCase().includes(filters.q.toLowerCase()) || o.id.includes(filters.q))
  );
  const active = orders.filter(o => !["entregado"].includes(o.state));

  return (
    <div style={{ height: "100%", display: "flex", flexDirection: "column" }}>
      {/* Barra de filtros */}
      <div style={{ padding: "16px 24px", borderBottom: `1px solid ${cv("--line")}`, display: "flex", alignItems: "center", gap: 12, flexWrap: "wrap", background: cv("--surface") }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8, background: cv("--bg"), border: `1px solid ${cv("--line-2")}`, borderRadius: 10, padding: "7px 12px", minWidth: 240 }}>
          <Icon name="search" size={16} color={cv("--ink-3")} />
          <input value={filters.q} onChange={e => setFilters({ ...filters, q: e.target.value })} placeholder="Buscar cliente o N° de pedido…"
            style={{ border: "none", outline: "none", background: "transparent", fontSize: 13.5, fontFamily: "inherit", flex: 1, color: cv("--ink") }} />
        </div>
        <div style={{ display: "flex", gap: 4, background: cv("--surface-2"), borderRadius: 10, padding: 3 }}>
          {channels.map(c => {
            const on = filters.channel === c;
            const ch = MAKI.CHANNELS[c];
            return (
              <button key={c} onClick={() => setFilters({ ...filters, channel: c })} style={{
                display: "flex", alignItems: "center", gap: 6, padding: "6px 11px", borderRadius: 8, border: "none", cursor: "pointer",
                background: on ? cv("--surface") : "transparent", boxShadow: on ? "var(--sh-1)" : "none",
                fontSize: 12.5, fontWeight: 700, color: on ? cv("--ink") : cv("--ink-3"),
              }}>
                {ch && <Icon name={ch.icon} size={13} stroke={2.2} color={on ? cv(ch.color) : cv("--ink-3")} />}
                {c === "todos" ? "Todos" : ch.label}
              </button>
            );
          })}
        </div>
        <div style={{ flex: 1 }} />
        <div style={{ display: "flex", gap: 4, background: cv("--surface-2"), borderRadius: 10, padding: 3 }}>
          {[["todos", "Todos"], ["empresa", "Empresariales"], ["particular", "Particulares"]].map(([id, lbl]) => (
            <button key={id} onClick={() => setFilters({ ...filters, type: id })} style={{
              padding: "6px 11px", borderRadius: 8, border: "none", cursor: "pointer",
              background: filters.type === id ? cv("--surface") : "transparent", boxShadow: filters.type === id ? "var(--sh-1)" : "none",
              fontSize: 12.5, fontWeight: 700, color: filters.type === id ? cv("--ink") : cv("--ink-3"),
            }}>{lbl}</button>
          ))}
        </div>
      </div>

      {/* Lista */}
      <div style={{ flex: 1, overflowY: "auto", padding: "16px 24px" }}>
        <div style={{ fontSize: 12.5, fontWeight: 700, color: cv("--ink-3"), marginBottom: 12 }}>
          {filtered.length} pedidos · {active.length} activos en el día
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          {filtered.map(o => <InboxRow key={o.id} order={o} onOpen={onOpen} />)}
        </div>
      </div>
    </div>
  );
}

function InboxRow({ order, onOpen }) {
  const [h, setH] = useState(false);
  const itemsCount = order.items.reduce((s, i) => s + i.qty, 0);
  const lastMsg = order.thread[order.thread.length - 1];
  return (
    <div onClick={() => onOpen(order)} onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)}
      style={{
        display: "grid", gridTemplateColumns: "auto 1fr auto auto auto", alignItems: "center", gap: 16,
        padding: "13px 16px", background: cv("--surface"), borderRadius: 13,
        border: `1px solid ${h ? cv("--line-2") : cv("--line")}`, boxShadow: h ? "var(--sh-2)" : "var(--sh-1)",
        cursor: "pointer", transition: "box-shadow .14s, border-color .14s",
      }}>
      <div style={{ position: "relative" }}>
        <Avatar name={order.client} type={order.clientType} size={42} />
        <span style={{ position: "absolute", bottom: -3, right: -3, width: 20, height: 20, borderRadius: 7, background: cv(MAKI.CHANNELS[order.channel].bg), border: `2px solid ${cv("--surface")}`, display: "flex", alignItems: "center", justifyContent: "center", color: cv(MAKI.CHANNELS[order.channel].color) }}>
          <Icon name={MAKI.CHANNELS[order.channel].icon} size={11} stroke={2.4} />
        </span>
      </div>
      <div style={{ minWidth: 0 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 9 }}>
          <span style={{ fontSize: 14, fontWeight: 750 }}>{order.client}</span>
          <span style={{ fontSize: 12, fontWeight: 700, color: cv("--ink-3") }}>{order.id}</span>
          {order.clientType === "empresa" && <span style={{ fontSize: 10.5, fontWeight: 800, letterSpacing: "0.03em", color: cv("--st-confirmado"), background: cv("--st-confirmado-bg"), padding: "1px 7px", borderRadius: 5 }}>B2B</span>}
        </div>
        <div style={{ fontSize: 12.5, color: cv("--ink-2"), fontWeight: 500, marginTop: 2, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
          {lastMsg ? <span style={{ fontStyle: "italic" }}>"{lastMsg.text}"</span> : `${itemsCount} ítems · ${order.items[0].name}${order.items.length > 1 ? " +" + (order.items.length - 1) : ""}`}
        </div>
      </div>
      <ChainTag chainId={order.chain} />
      <div style={{ textAlign: "right", minWidth: 92 }}>
        <div style={{ fontSize: 14, fontWeight: 800, color: cv("--ink") }}>{MAKI.money(order.total)}</div>
        <div style={{ marginTop: 3 }}><SlaChip min={order.slaMin} /></div>
      </div>
      <StatusPill state={order.state} />
    </div>
  );
}

Object.assign(window, { InboxScreen });
