/* ============ MAKI — Drawer de detalle de pedido ============ */

function StateStepper({ order, onSet }) {
  const states = MAKI.STATES;
  const idx = states.findIndex(s => s.id === order.state);
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 0 }}>
      {states.map((s, i) => {
        const done = i < idx, current = i === idx;
        const c = done || current ? cv(s.color) : cv("--line-2");
        return (
          <React.Fragment key={s.id}>
            <button onClick={() => onSet(s.id)} title={s.label}
              style={{
                display: "flex", flexDirection: "column", alignItems: "center", gap: 6,
                background: "none", border: "none", cursor: "pointer", padding: 0, flexShrink: 0,
              }}>
              <span style={{
                width: 26, height: 26, borderRadius: "50%",
                background: current ? cv(s.color) : done ? cv(s.bg) : cv("--surface-2"),
                border: `2px solid ${c}`, display: "flex", alignItems: "center", justifyContent: "center",
                color: current ? "#fff" : c, transition: "all .15s",
              }}>
                {done ? <Icon name="check" size={13} stroke={3} /> :
                  <span style={{ width: 7, height: 7, borderRadius: "50%", background: current ? "#fff" : c }} />}
              </span>
              <span style={{ fontSize: 10.5, fontWeight: current ? 800 : 600, color: current ? cv(s.color) : cv("--ink-3"), whiteSpace: "nowrap" }}>{s.short}</span>
            </button>
            {i < states.length - 1 && <span style={{ flex: 1, height: 2, background: i < idx ? cv(states[i].color) : cv("--line"), margin: "0 4px", marginBottom: 18, minWidth: 14 }} />}
          </React.Fragment>
        );
      })}
    </div>
  );
}

function OrderDrawer({ order, onClose, onSet, onAdvance }) {
  const [tab, setTab] = useState("detalle");
  const [reply, setReply] = useState("");
  if (!order) return null;
  const client = MAKI.CLIENTS.find(c => c.name === order.client);
  const idx = MAKI.STATES.findIndex(s => s.id === order.state);
  const next = MAKI.STATES[idx + 1];

  return (
    <div style={{ position: "fixed", inset: 0, zIndex: 60, display: "flex", justifyContent: "flex-end" }}>
      <div onClick={onClose} style={{ position: "absolute", inset: 0, background: "rgba(25,32,28,.34)", animation: "maki-fade .18s ease" }} />
      <div style={{
        position: "relative", width: 480, maxWidth: "94vw", height: "100%", background: cv("--surface"),
        boxShadow: "var(--sh-pop)", animation: "maki-slide-in .26s cubic-bezier(.22,1,.36,1)",
        display: "flex", flexDirection: "column",
      }}>
        {/* Header */}
        <div style={{ padding: "18px 22px 16px", borderBottom: `1px solid ${cv("--line")}` }}>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 14 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
              <span style={{ fontSize: 19, fontWeight: 800, letterSpacing: "-0.02em" }}>{order.id}</span>
              <ChannelTag channel={order.channel} />
              <span style={{ fontSize: 12.5, color: cv("--ink-3"), fontWeight: 600 }}>{order.mode}</span>
            </div>
            <button onClick={onClose} style={{ background: cv("--surface-2"), border: "none", borderRadius: 9, width: 32, height: 32, display: "flex", alignItems: "center", justifyContent: "center", cursor: "pointer", color: cv("--ink-2") }}>
              <Icon name="x" size={17} />
            </button>
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 11 }}>
            <Avatar name={order.client} type={order.clientType} size={40} />
            <div style={{ flex: 1 }}>
              <div style={{ fontWeight: 750, fontSize: 15 }}>{order.client}</div>
              <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 2 }}>
                <ChainTag chainId={order.chain} />
                <span style={{ color: cv("--ink-3") }}>·</span>
                <span style={{ fontSize: 12.5, color: cv("--ink-3"), fontWeight: 600 }}>{order.clientType === "empresa" ? "Empresarial" : "Particular"}</span>
              </div>
            </div>
            <SlaChip min={order.slaMin} />
          </div>
        </div>

        {/* Stepper */}
        <div style={{ padding: "18px 22px", borderBottom: `1px solid ${cv("--line")}`, background: cv("--bg") }}>
          <StateStepper order={order} onSet={onSet} />
        </div>

        {/* Tabs */}
        <div style={{ display: "flex", gap: 4, padding: "12px 22px 0", borderBottom: `1px solid ${cv("--line")}` }}>
          {[["detalle", "Detalle"], ["hilo", `Conversación${order.thread.length ? " · " + order.thread.length : ""}`]].map(([id, lbl]) => (
            <button key={id} onClick={() => setTab(id)} style={{
              background: "none", border: "none", padding: "8px 4px 12px", marginRight: 10, cursor: "pointer",
              fontSize: 13.5, fontWeight: 700, color: tab === id ? cv("--ink") : cv("--ink-3"),
              borderBottom: `2px solid ${tab === id ? cv("--primary") : "transparent"}`, marginBottom: -1,
            }}>{lbl}</button>
          ))}
        </div>

        {/* Body */}
        <div style={{ flex: 1, overflowY: "auto", padding: "20px 22px" }}>
          {tab === "detalle" ? (
            <React.Fragment>
              {/* Entrega */}
              <Section title="Entrega">
                <Row icon="clock" label="Horario objetivo" value={order.due} />
                {order.mode === "Envío"
                  ? <Row icon="pin" label="Dirección" value={order.address} />
                  : <Row icon="store" label="Modalidad" value="Retiro en local" />}
                <Row icon="user" label="Asignado a" value={order.assignee || "Sin asignar"} />
              </Section>

              {/* Items */}
              <Section title={`Pedido · ${order.items.reduce((s, i) => s + i.qty, 0)} ítems`}>
                <div style={{ display: "flex", flexDirection: "column", gap: 1, background: cv("--line"), borderRadius: 12, overflow: "hidden", border: `1px solid ${cv("--line")}` }}>
                  {order.items.map((it, i) => (
                    <div key={i} style={{ display: "flex", alignItems: "center", gap: 12, padding: "11px 14px", background: cv("--surface") }}>
                      <span style={{ minWidth: 30, height: 26, borderRadius: 7, background: cv("--primary-tint"), color: cv("--primary-700"), fontSize: 13, fontWeight: 800, display: "flex", alignItems: "center", justifyContent: "center", padding: "0 8px" }}>{it.qty}×</span>
                      <span style={{ flex: 1, fontSize: 13.5, fontWeight: 600 }}>{it.name}</span>
                      <span style={{ fontSize: 13, color: cv("--ink-2"), fontWeight: 600 }}>{MAKI.money(it.price * it.qty)}</span>
                    </div>
                  ))}
                  <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "12px 14px", background: cv("--surface") }}>
                    <span style={{ fontSize: 13.5, fontWeight: 800 }}>Total</span>
                    <span style={{ fontSize: 16, fontWeight: 800, color: cv("--primary-700") }}>{MAKI.money(order.total)}</span>
                  </div>
                </div>
              </Section>

              {order.note && (
                <Section title="Nota del pedido">
                  <div style={{ padding: "11px 14px", background: cv("--st-preparacion-bg"), borderRadius: 10, fontSize: 13, color: "#7A5410", fontWeight: 600, lineHeight: 1.5 }}>
                    {order.note}
                  </div>
                </Section>
              )}
            </React.Fragment>
          ) : (
            <Thread order={order} reply={reply} setReply={setReply} />
          )}
        </div>

        {/* Footer acción */}
        <div style={{ padding: "14px 22px", borderTop: `1px solid ${cv("--line")}`, display: "flex", gap: 10, background: cv("--surface") }}>
          <Btn variant="outline" icon="dots" size="md" />
          {next ? (
            <Btn variant="primary" size="md" style={{ flex: 1 }} icon="chevR" onClick={() => onAdvance(order)}>
              Pasar a "{next.label}"
            </Btn>
          ) : (
            <Btn variant="solid" size="md" style={{ flex: 1 }} icon="checkCheck">Pedido completado</Btn>
          )}
        </div>
      </div>
    </div>
  );
}

function Section({ title, children }) {
  return (
    <div style={{ marginBottom: 22 }}>
      <div style={{ fontSize: 11.5, fontWeight: 800, letterSpacing: "0.04em", textTransform: "uppercase", color: cv("--ink-3"), marginBottom: 10 }}>{title}</div>
      {children}
    </div>
  );
}
function Row({ icon, label, value }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 11, padding: "7px 0" }}>
      <Icon name={icon} size={16} color={cv("--ink-3")} stroke={2} />
      <span style={{ fontSize: 13, color: cv("--ink-3"), fontWeight: 600, minWidth: 120 }}>{label}</span>
      <span style={{ fontSize: 13.5, color: cv("--ink"), fontWeight: 650, flex: 1, textAlign: "right" }}>{value}</span>
    </div>
  );
}

function Thread({ order, reply, setReply }) {
  const ch = MAKI.CHANNELS[order.channel];
  return (
    <div style={{ display: "flex", flexDirection: "column", height: "100%" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 8, padding: "8px 12px", background: cv(ch.bg), borderRadius: 10, marginBottom: 16, fontSize: 12.5, fontWeight: 650, color: cv(ch.color) }}>
        <Icon name={ch.icon} size={15} stroke={2.2} /> Conversación unificada · {ch.label}
      </div>
      <div style={{ flex: 1, display: "flex", flexDirection: "column", gap: 10 }}>
        {order.thread.length === 0 && (
          <div style={{ textAlign: "center", color: cv("--ink-3"), fontSize: 13, padding: "30px 0" }}>
            Pedido cargado por {ch.label}.<br />No hay mensajes todavía.
          </div>
        )}
        {order.thread.map((m, i) => {
          const mine = m.from === "agent";
          return (
            <div key={i} style={{ display: "flex", justifyContent: mine ? "flex-end" : "flex-start" }}>
              <div style={{
                maxWidth: "78%", padding: "9px 13px", borderRadius: 14,
                borderBottomLeftRadius: mine ? 14 : 4, borderBottomRightRadius: mine ? 4 : 14,
                background: mine ? cv("--primary") : cv("--surface-2"), color: mine ? "#fff" : cv("--ink"),
                fontSize: 13.5, fontWeight: 500, lineHeight: 1.45,
              }}>
                {m.text}
                <div style={{ fontSize: 10.5, opacity: .6, marginTop: 3, textAlign: "right" }}>{m.at}</div>
              </div>
            </div>
          );
        })}
      </div>
      <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 16, padding: 6, border: `1px solid ${cv("--line-2")}`, borderRadius: 12, background: cv("--surface") }}>
        <input value={reply} onChange={e => setReply(e.target.value)} placeholder={`Responder por ${ch.label}…`}
          style={{ flex: 1, border: "none", outline: "none", fontSize: 13.5, padding: "6px 8px", background: "transparent", fontFamily: "inherit" }} />
        <Btn variant="primary" size="sm" icon="send" />
      </div>
    </div>
  );
}

Object.assign(window, { OrderDrawer, StateStepper });
