/* ============ MAKI — Clientes (B2B / particulares) ============ */
/* B4 editar cliente · B5a recurrentes · B5b auto-detección · B6 nuevo pedido · B7 crear cliente */

const WEEKDAYS = ["Lun", "Mar", "Mié", "Jue", "Vie", "Sáb", "Dom"];
const PRICE_LISTS = [
  { id: "minorista",  label: "Minorista" },
  { id: "mayorista",  label: "Mayorista" },
  { id: "corporativo", label: "Corporativo" },
];

/* —— Modal genérico —— */
function CModal({ title, sub, icon, onClose, children, width = 460 }) {
  return (
    <div style={{ position: "fixed", inset: 0, zIndex: 80, display: "flex", alignItems: "center", justifyContent: "center" }}>
      <div onClick={onClose} style={{ position: "absolute", inset: 0, background: "rgba(25,32,28,.42)", animation: "maki-fade .16s ease" }} />
      <div style={{ position: "relative", width, maxWidth: "94vw", maxHeight: "90vh", overflowY: "auto", background: cv("--surface"), borderRadius: 18, boxShadow: "var(--sh-pop)", padding: 22, animation: "maki-rise .24s cubic-bezier(.22,1,.36,1)" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 11, marginBottom: 18 }}>
          {icon && <span style={{ width: 40, height: 40, borderRadius: 11, background: cv("--primary-tint"), color: cv("--primary-700"), display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}><Icon name={icon} size={20} stroke={2.2} /></span>}
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 16, fontWeight: 800 }}>{title}</div>
            {sub && <div style={{ fontSize: 12.5, color: cv("--ink-3"), fontWeight: 600 }}>{sub}</div>}
          </div>
          <button onClick={onClose} style={{ background: cv("--bg"), border: "none", borderRadius: 9, width: 30, height: 30, cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center", color: cv("--ink-3") }}><Icon name="x" size={16} /></button>
        </div>
        {children}
      </div>
    </div>
  );
}

/* —— Campo de formulario —— */
function CField({ label, children, hint }) {
  return (
    <div style={{ marginBottom: 13 }}>
      <label style={{ fontSize: 11, fontWeight: 800, color: cv("--ink-3"), textTransform: "uppercase", letterSpacing: ".03em", display: "block", marginBottom: 5 }}>{label}</label>
      {children}
      {hint && <div style={{ fontSize: 11, color: cv("--ink-3"), fontWeight: 600, marginTop: 4 }}>{hint}</div>}
    </div>
  );
}
const inputStyle = { width: "100%", boxSizing: "border-box", padding: "10px 12px", borderRadius: 10, border: `1px solid ${cv("--line-2")}`, fontSize: 13.5, fontFamily: "inherit", fontWeight: 550, color: cv("--ink"), background: cv("--bg"), outline: "none" };

/* —— Selector de ítems compacto —— */
function ItemPicker({ items, onChange }) {
  const [pick, setPick] = useState("");
  const menuNames = Object.keys(MAKI.MENU);
  const add = (name) => {
    if (!name) return;
    const ex = items.find(i => i.name === name);
    if (ex) onChange(items.map(i => i.name === name ? { ...i, qty: i.qty + 1 } : i));
    else onChange([...items, { name, qty: 1, price: MAKI.MENU[name].p }]);
    setPick("");
  };
  const setQty = (name, q) => onChange(q <= 0 ? items.filter(i => i.name !== name) : items.map(i => i.name === name ? { ...i, qty: q } : i));
  const total = items.reduce((s, i) => s + i.price * i.qty, 0);
  const stepBtn = { width: 24, height: 24, borderRadius: 6, border: `1px solid ${cv("--line-2")}`, background: cv("--surface"), cursor: "pointer", fontSize: 14, fontWeight: 800, color: cv("--ink-2"), display: "flex", alignItems: "center", justifyContent: "center", lineHeight: 1 };
  return (
    <div style={{ border: `1px solid ${cv("--line")}`, borderRadius: 11, overflow: "hidden" }}>
      {items.length === 0 && <div style={{ padding: 11, fontSize: 12, 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: 8, padding: "8px 11px", borderBottom: `1px solid ${cv("--line")}` }}>
          <button onClick={() => setQty(it.name, it.qty - 1)} style={stepBtn}>−</button>
          <span style={{ minWidth: 20, textAlign: "center", fontSize: 12.5, fontWeight: 800 }}>{it.qty}</span>
          <button onClick={() => setQty(it.name, it.qty + 1)} style={stepBtn}>+</button>
          <span style={{ flex: 1, fontSize: 12, fontWeight: 600, minWidth: 0 }}>{it.name}</span>
          <span style={{ fontSize: 12, color: cv("--ink-2"), fontWeight: 650 }}>{MAKI.money(it.price * it.qty)}</span>
        </div>
      ))}
      <div style={{ padding: "9px 11px", borderBottom: items.length ? `1px solid ${cv("--line")}` : "none" }}>
        <select value={pick} onChange={e => add(e.target.value)} style={{ ...inputStyle, cursor: "pointer" }}>
          <option value="">+ Agregar del menú…</option>
          {menuNames.map(n => <option key={n} value={n}>{n} · {MAKI.money(MAKI.MENU[n].p)}</option>)}
        </select>
      </div>
      {items.length > 0 && (
        <div style={{ display: "flex", justifyContent: "space-between", padding: "9px 11px" }}>
          <span style={{ fontSize: 13, fontWeight: 800 }}>Total</span>
          <span style={{ fontSize: 14.5, fontWeight: 800, color: cv("--primary-700") }}>{MAKI.money(total)}</span>
        </div>
      )}
    </div>
  );
}

/* —— Modal: editar cliente (B4) —— */
function EditClientModal({ client, onClose, onSave }) {
  const [name, setName] = useState(client.name);
  const [contact, setContact] = useState(client.contact === "—" ? "" : client.contact);
  const [tier, setTier] = useState(client.tier);
  return (
    <CModal title="Editar cliente" sub={client.phone} icon="edit" onClose={onClose}>
      <CField label="Nombre / Razón social"><input value={name} onChange={e => setName(e.target.value)} style={inputStyle} /></CField>
      <CField label="Contacto"><input value={contact} onChange={e => setContact(e.target.value)} style={inputStyle} placeholder="Persona de contacto" /></CField>
      <CField label="Categoría / Tier"><input value={tier} onChange={e => setTier(e.target.value)} style={inputStyle} /></CField>
      <CField label="Teléfono (no editable)" hint="Vinculado 100% a la cuenta de WhatsApp">
        <div style={{ ...inputStyle, display: "flex", alignItems: "center", gap: 8, color: cv("--ink-3"), background: cv("--surface") }}>
          <Icon name="lock" size={14} color={cv("--ink-3")} /> {client.phone}
        </div>
      </CField>
      <div style={{ display: "flex", gap: 10, marginTop: 18 }}>
        <Btn variant="outline" style={{ flex: 1 }} onClick={onClose}>Cancelar</Btn>
        <Btn variant="primary" icon="check" style={{ flex: 1.4 }} onClick={() => onSave({ ...client, name, contact: contact || "—", tier })}>Guardar cambios</Btn>
      </div>
    </CModal>
  );
}

/* —— Modal: crear cliente manual (B7) —— */
function NewClientModal({ onClose, onCreate }) {
  const [name, setName] = useState("");
  const [type, setType] = useState("particular");
  const [phone, setPhone] = useState("");
  const [contact, setContact] = useState("");
  const [origin, setOrigin] = useState("sucursal");
  const ORIGINS = [["sucursal", "En sucursal", "store"], ["telefono", "Telefónico", "phone"]];
  const valid = name.trim() && phone.trim();
  return (
    <CModal title="Registrar cliente manual" sub="Cliente fuera de canales automáticos" icon="user" onClose={onClose}>
      <CField label="Origen del registro">
        <div style={{ display: "flex", gap: 8 }}>
          {ORIGINS.map(([id, lbl, ic]) => (
            <button key={id} onClick={() => setOrigin(id)} style={{
              flex: 1, display: "flex", alignItems: "center", justifyContent: "center", gap: 7, padding: "10px", borderRadius: 10, cursor: "pointer",
              border: `1.5px solid ${origin === id ? cv("--primary") : cv("--line-2")}`, background: origin === id ? cv("--primary-tint") : cv("--bg"),
              fontSize: 13, fontWeight: 700, color: origin === id ? cv("--primary-700") : cv("--ink-2"),
            }}><Icon name={ic} size={15} /> {lbl}</button>
          ))}
        </div>
      </CField>
      <CField label="Tipo de cliente">
        <div style={{ display: "flex", gap: 8 }}>
          {[["particular", "Particular"], ["empresa", "Empresa"]].map(([id, lbl]) => (
            <button key={id} onClick={() => setType(id)} style={{
              flex: 1, padding: "9px", borderRadius: 10, cursor: "pointer",
              border: `1.5px solid ${type === id ? cv("--primary") : cv("--line-2")}`, background: type === id ? cv("--primary-tint") : cv("--bg"),
              fontSize: 13, fontWeight: 700, color: type === id ? cv("--primary-700") : cv("--ink-2"),
            }}>{lbl}</button>
          ))}
        </div>
      </CField>
      <CField label={type === "empresa" ? "Razón social" : "Nombre y apellido"}><input value={name} onChange={e => setName(e.target.value)} style={inputStyle} autoFocus /></CField>
      <CField label="Teléfono / WhatsApp" hint="Será el identificador único del cliente"><input value={phone} onChange={e => setPhone(e.target.value)} style={inputStyle} placeholder="+54 11 ____-____" /></CField>
      <CField label="Contacto (opcional)"><input value={contact} onChange={e => setContact(e.target.value)} style={inputStyle} placeholder="Persona de contacto" /></CField>
      <div style={{ display: "flex", gap: 10, marginTop: 18 }}>
        <Btn variant="outline" style={{ flex: 1 }} onClick={onClose}>Cancelar</Btn>
        <Btn variant="primary" icon="check" style={{ flex: 1.4, opacity: valid ? 1 : .45, pointerEvents: valid ? "auto" : "none" }}
          onClick={() => onCreate({
            id: "manual-" + Date.now(), name: name.trim(), type, tier: type === "empresa" ? "Corporativo" : "Nuevo",
            contact: contact.trim() || "—", phone: phone.trim(), since: String(new Date().getFullYear()), orders: 0, avgTicket: 0, origin,
          })}>Crear cliente</Btn>
      </div>
    </CModal>
  );
}

/* —— Modal: nuevo pedido manual (B6) —— */
function NewOrderModal({ client, onClose, onCreate }) {
  const [items, setItems] = useState([]);
  const [mode, setMode] = useState("Envío");
  const [channel, setChannel] = useState("telefono");
  const [address, setAddress] = useState("");
  const [note, setNote] = useState("");
  const total = items.reduce((s, i) => s + i.price * i.qty, 0);
  const valid = items.length > 0 && (mode === "Retiro" || address.trim());
  return (
    <CModal title="Nuevo pedido manual" sub={client.name} icon="bag" width={500} onClose={onClose}>
      <CField label="Canal de ingreso">
        <select value={channel} onChange={e => setChannel(e.target.value)} style={{ ...inputStyle, cursor: "pointer" }}>
          <option value="telefono">Teléfono</option>
          <option value="sucursal">En sucursal</option>
          <option value="whatsapp">WhatsApp</option>
        </select>
      </CField>
      <CField label="Modalidad">
        <div style={{ display: "flex", gap: 8 }}>
          {["Envío", "Retiro"].map(m => (
            <button key={m} onClick={() => setMode(m)} style={{
              flex: 1, padding: "9px", borderRadius: 10, cursor: "pointer",
              border: `1.5px solid ${mode === m ? cv("--primary") : cv("--line-2")}`, background: mode === m ? cv("--primary-tint") : cv("--bg"),
              fontSize: 13, fontWeight: 700, color: mode === m ? cv("--primary-700") : cv("--ink-2"),
            }}>{m}</button>
          ))}
        </div>
      </CField>
      {mode === "Envío" && <CField label="Dirección de entrega"><input value={address} onChange={e => setAddress(e.target.value)} style={inputStyle} placeholder="Calle, número, localidad" /></CField>}
      <CField label="Ítems del pedido"><ItemPicker items={items} onChange={setItems} /></CField>
      <CField label="Nota (opcional)"><input value={note} onChange={e => setNote(e.target.value)} style={inputStyle} placeholder="Aclaraciones, alergias…" /></CField>
      <div style={{ display: "flex", gap: 10, marginTop: 18 }}>
        <Btn variant="outline" style={{ flex: 1 }} onClick={onClose}>Cancelar</Btn>
        <Btn variant="primary" icon="check" style={{ flex: 1.4, opacity: valid ? 1 : .45, pointerEvents: valid ? "auto" : "none" }}
          onClick={() => onCreate({
            id: "#M" + Math.floor(1000 + Math.random() * 9000), client: client.name, clientType: client.type,
            chain: "sakura", channel, state: "recibido", items, total,
            placedAt: 0, due: "—", mode, address: address.trim(), note: note.trim(), assignee: null, thread: [], slaMin: 30, _manual: true,
          })}>Registrar pedido · {MAKI.money(total)}</Btn>
      </div>
    </CModal>
  );
}

/* —— Modal: gestionar pedido recurrente (B5a) —— */
function RecurringModal({ client, config, onClose, onSave }) {
  const [active, setActive] = useState(config?.active ?? true);
  const [days, setDays] = useState(config?.days ?? []);
  const [time, setTime] = useState(config?.time ?? "13:30");
  const [list, setList] = useState(config?.list ?? "mayorista");
  const toggleDay = (i) => setDays(d => d.includes(i) ? d.filter(x => x !== i) : [...d, i].sort());
  return (
    <CModal title="Pedido recurrente" sub={client.name} icon="repeat" onClose={onClose}>
      <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "11px 14px", borderRadius: 11, background: cv("--bg"), marginBottom: 16 }}>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 13, fontWeight: 750 }}>Recurrencia activa</div>
          <div style={{ fontSize: 12, color: cv("--ink-3"), fontWeight: 600 }}>El sistema generará el pedido automáticamente</div>
        </div>
        <button onClick={() => setActive(a => !a)} style={{
          width: 44, height: 26, borderRadius: 99, border: "none", cursor: "pointer", position: "relative",
          background: active ? cv("--wasabi") : cv("--line-2"), transition: "background .15s",
        }}>
          <span style={{ position: "absolute", top: 3, left: active ? 21 : 3, width: 20, height: 20, borderRadius: "50%", background: "#fff", transition: "left .15s", boxShadow: "0 1px 3px rgba(0,0,0,.2)" }} />
        </button>
      </div>
      <CField label="Días de la semana">
        <div style={{ display: "flex", gap: 5 }}>
          {WEEKDAYS.map((d, i) => (
            <button key={i} onClick={() => toggleDay(i)} disabled={!active} style={{
              flex: 1, padding: "9px 0", borderRadius: 9, cursor: active ? "pointer" : "not-allowed",
              border: `1.5px solid ${days.includes(i) ? cv("--primary") : cv("--line-2")}`,
              background: days.includes(i) ? cv("--primary") : cv("--bg"),
              color: days.includes(i) ? "#fff" : cv("--ink-3"), fontSize: 11.5, fontWeight: 800, opacity: active ? 1 : .5,
            }}>{d}</button>
          ))}
        </div>
      </CField>
      <div style={{ display: "flex", gap: 12 }}>
        <CField label="Horario"><input type="time" value={time} onChange={e => setTime(e.target.value)} disabled={!active} style={{ ...inputStyle, opacity: active ? 1 : .5 }} /></CField>
        <div style={{ flex: 1 }}>
          <CField label="Lista de precios">
            <select value={list} onChange={e => setList(e.target.value)} disabled={!active} style={{ ...inputStyle, cursor: "pointer", opacity: active ? 1 : .5 }}>
              {PRICE_LISTS.map(p => <option key={p.id} value={p.id}>{p.label}</option>)}
            </select>
          </CField>
        </div>
      </div>
      <div style={{ display: "flex", gap: 10, marginTop: 14 }}>
        <Btn variant="outline" style={{ flex: 1 }} onClick={onClose}>Cancelar</Btn>
        <Btn variant="primary" icon="check" style={{ flex: 1.4 }} onClick={() => onSave({ active, days, time, list })}>Guardar recurrencia</Btn>
      </div>
    </CModal>
  );
}

/* —— Auto-detección de patrón de pedido (B5b) —— */
function detectPattern(client, clientOrders) {
  // Mock determinista basado en nombre del cliente + historial
  if (client.orders < 3) return null;
  const seed = client.name.split("").reduce((s, c) => s + c.charCodeAt(0), 0);
  const day = WEEKDAYS[seed % 7];
  const hour = 18 + (seed % 5);
  const weeks = 3 + (seed % 2);
  const fav = clientOrders[0]?.items?.[0]?.name || Object.keys(MAKI.MENU)[seed % Object.keys(MAKI.MENU).length];
  return { day, time: `${hour}:00`, weeks, confidence: 70 + (seed % 25), fav };
}

function PatternCard({ pattern, onPromo }) {
  if (!pattern) return null;
  return (
    <div style={{ background: "linear-gradient(135deg, #FFF7ED, #FEF3F2)", border: "1px solid #FED7AA", borderRadius: 14, padding: "15px 18px", marginBottom: 16 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 9, marginBottom: 9 }}>
        <span style={{ width: 30, height: 30, borderRadius: 9, background: "#FB923C", color: "#fff", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name="activity" size={16} stroke={2.4} /></span>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 13.5, fontWeight: 800 }}>Patrón de compra detectado</div>
          <div style={{ fontSize: 11.5, color: cv("--ink-3"), fontWeight: 600 }}>Análisis automático del historial · {pattern.confidence}% confianza</div>
        </div>
      </div>
      <div style={{ fontSize: 12.5, color: cv("--ink-2"), fontWeight: 600, lineHeight: 1.5, marginBottom: 11 }}>
        Suele pedir los <strong>{pattern.day}</strong> alrededor de las <strong>{pattern.time}</strong> · {pattern.weeks} de las últimas 4 semanas.
        Producto favorito: <strong>{pattern.fav}</strong>.
      </div>
      <Btn variant="primary" size="sm" icon="send" onClick={onPromo}>Enviar acción de marketing</Btn>
    </div>
  );
}

/* —— Pantalla Clientes —— */
function ClientsScreen({ orders, onOpen }) {
  const [clients, setClients] = useState(() => MAKI.CLIENTS.map(c => ({ ...c })));
  const [sel, setSel] = useState(clients[1].id);
  const [manualOrders, setManualOrders] = useState([]);
  const [recurring, setRecurring] = useState({
    c1: { active: true, days: [1, 3], time: "13:30", list: "mayorista" },
    c2: { active: true, days: [0, 2, 4], time: "12:00", list: "corporativo" },
  });
  const [modal, setModal] = useState(null); // 'edit' | 'newClient' | 'newOrder' | 'recurring'

  const client = clients.find(c => c.id === sel) || clients[0];
  const clientOrders = [
    ...manualOrders.filter(o => o.client === client.name),
    ...orders.filter(o => o.client === client.name),
  ];
  const pattern = detectPattern(client, clientOrders);
  const rec = recurring[client.id];

  const notify = (text, type = "ok") => window.dispatchEvent(new CustomEvent("maki:notif", { detail: { type, text, at: new Date().toLocaleTimeString("es-AR", { hour: "2-digit", minute: "2-digit" }) } }));

  const recLabel = (r) => {
    if (!r || !r.active || !r.days.length) return null;
    const ds = r.days.map(i => WEEKDAYS[i]).join(", ");
    const pl = (PRICE_LISTS.find(p => p.id === r.list) || {}).label || r.list;
    return `${ds} · ${r.time} · lista ${pl.toLowerCase()}`;
  };

  return (
    <div style={{ display: "grid", gridTemplateColumns: "320px 1fr", height: "100%" }}>
      {/* Lista */}
      <div style={{ borderRight: `1px solid ${cv("--line")}`, overflowY: "auto", background: cv("--surface") }}>
        <div style={{ padding: "13px 14px", borderBottom: `1px solid ${cv("--line")}`, position: "sticky", top: 0, background: cv("--surface"), zIndex: 2 }}>
          <Btn variant="primary" size="sm" icon="plus" style={{ width: "100%" }} onClick={() => setModal("newClient")}>Registrar cliente</Btn>
        </div>
        {["empresa", "particular"].map(type => (
          <div key={type}>
            <div style={{ padding: "14px 18px 8px", fontSize: 11.5, fontWeight: 800, letterSpacing: "0.04em", textTransform: "uppercase", color: cv("--ink-3") }}>
              {type === "empresa" ? "Cuentas empresariales" : "Clientes particulares"}
            </div>
            {clients.filter(c => c.type === type).map(c => {
              const on = c.id === sel;
              return (
                <button key={c.id} onClick={() => setSel(c.id)} style={{
                  width: "100%", display: "flex", alignItems: "center", gap: 11, padding: "11px 18px", border: "none", cursor: "pointer",
                  background: on ? cv("--primary-tint") : "transparent", borderLeft: `3px solid ${on ? cv("--primary") : "transparent"}`, textAlign: "left",
                }}>
                  <Avatar name={c.name} type={c.type} size={38} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 13.5, fontWeight: 700, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{c.name}</div>
                    <div style={{ fontSize: 11.5, color: cv("--ink-3"), fontWeight: 600 }}>{c.tier} · {c.orders} pedidos</div>
                  </div>
                  {recurring[c.id]?.active && <Icon name="repeat" size={14} color={cv("--wasabi")} />}
                </button>
              );
            })}
          </div>
        ))}
      </div>

      {/* Detalle */}
      <div style={{ overflowY: "auto", padding: "24px 28px" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 16, marginBottom: 24 }}>
          <Avatar name={client.name} type={client.type} size={62} />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
              <h2 style={{ margin: 0, fontSize: 23, fontWeight: 800, letterSpacing: "-0.02em", whiteSpace: "nowrap" }}>{client.name}</h2>
              <span style={{ fontSize: 11, fontWeight: 800, letterSpacing: "0.03em", color: cv("--st-confirmado"), background: cv("--st-confirmado-bg"), padding: "2px 9px", borderRadius: 6 }}>{client.tier.toUpperCase()}</span>
              <button onClick={() => setModal("edit")} title="Editar cliente" style={{ background: cv("--bg"), border: `1px solid ${cv("--line")}`, borderRadius: 8, width: 30, height: 30, cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center", color: cv("--ink-2") }}><Icon name="edit" size={14} /></button>
            </div>
            <div style={{ fontSize: 13, color: cv("--ink-3"), fontWeight: 600, marginTop: 3 }}>{client.contact} · {client.phone} · Cliente desde {client.since}</div>
          </div>
          <Btn variant="primary" icon="plus" onClick={() => setModal("newOrder")}>Nuevo pedido</Btn>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 12, marginBottom: 22 }}>
          {[["Pedidos totales", client.orders], ["Ticket promedio", MAKI.money(client.avgTicket)], ["Facturación estimada", MAKI.money(client.avgTicket * client.orders)]].map(([l, v]) => (
            <div key={l} style={{ background: cv("--surface"), border: `1px solid ${cv("--line")}`, borderRadius: 14, padding: 16 }}>
              <div style={{ fontSize: 12, fontWeight: 700, color: cv("--ink-3"), marginBottom: 6 }}>{l}</div>
              <div style={{ fontSize: 22, fontWeight: 800, letterSpacing: "-0.02em" }}>{v}</div>
            </div>
          ))}
        </div>

        {/* Auto-detección (B5b) */}
        <PatternCard pattern={pattern} onPromo={() => notify(`Promo enviada a ${client.name} (${pattern.day} ${pattern.time})`, "ok")} />

        {/* Recurrente (B5a) */}
        <div style={{ background: rec?.active ? cv("--wasabi-soft") : cv("--bg"), border: `1px solid ${rec?.active ? cv("--wasabi") + "40" : cv("--line")}`, borderRadius: 14, padding: "14px 18px", marginBottom: 26, display: "flex", alignItems: "center", gap: 12 }}>
          <Icon name="repeat" size={20} color={rec?.active ? cv("--wasabi") : cv("--ink-3")} />
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 13.5, fontWeight: 750 }}>Pedido recurrente {rec?.active ? "activo" : "inactivo"}</div>
            <div style={{ fontSize: 12.5, color: cv("--ink-2"), fontWeight: 600 }}>{recLabel(rec) || "Sin recurrencia configurada"}</div>
          </div>
          <Btn variant="outline" size="sm" onClick={() => setModal("recurring")}>Gestionar</Btn>
        </div>

        <div style={{ fontSize: 14.5, fontWeight: 800, marginBottom: 12 }}>Pedidos recientes</div>
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          {clientOrders.length === 0 && <div style={{ color: cv("--ink-3"), fontSize: 13, padding: "20px 0" }}>Sin pedidos en el período actual.</div>}
          {clientOrders.map(o => (
            <div key={o.id} onClick={() => onOpen(o)} style={{ display: "flex", alignItems: "center", gap: 14, padding: "12px 16px", background: cv("--surface"), border: `1px solid ${o._manual ? cv("--primary") + "55" : cv("--line")}`, borderRadius: 12, cursor: "pointer" }}>
              <ChannelTag channel={o.channel} compact />
              <span style={{ fontSize: 13, fontWeight: 800 }}>{o.id}</span>
              <ChainTag chainId={o.chain} />
              {o._manual && <span style={{ fontSize: 10, fontWeight: 800, color: cv("--primary-700"), background: cv("--primary-tint"), padding: "1px 7px", borderRadius: 5 }}>MANUAL</span>}
              <span style={{ flex: 1, fontSize: 12.5, color: cv("--ink-3"), fontWeight: 600 }}>entrega {o.due}</span>
              <span style={{ fontSize: 13.5, fontWeight: 800 }}>{MAKI.money(o.total)}</span>
              <StatusPill state={o.state} size="sm" />
            </div>
          ))}
        </div>
      </div>

      {/* Modales */}
      {modal === "edit" && (
        <EditClientModal client={client} onClose={() => setModal(null)}
          onSave={(upd) => { setClients(cs => cs.map(c => c.id === upd.id ? upd : c)); setModal(null); notify(`Cliente actualizado: ${upd.name}`); }} />
      )}
      {modal === "newClient" && (
        <NewClientModal onClose={() => setModal(null)}
          onCreate={(nc) => { setClients(cs => [nc, ...cs]); setSel(nc.id); setModal(null); notify(`Cliente registrado: ${nc.name}`); }} />
      )}
      {modal === "newOrder" && (
        <NewOrderModal client={client} onClose={() => setModal(null)}
          onCreate={(ord) => {
            setManualOrders(os => [ord, ...os]);
            setClients(cs => cs.map(c => c.id === client.id ? { ...c, orders: c.orders + 1 } : c));
            setModal(null); notify(`Pedido manual registrado para ${client.name}`);
          }} />
      )}
      {modal === "recurring" && (
        <RecurringModal client={client} config={rec} onClose={() => setModal(null)}
          onSave={(cfg) => { setRecurring(r => ({ ...r, [client.id]: cfg })); setModal(null); notify(cfg.active ? `Recurrencia guardada para ${client.name}` : `Recurrencia desactivada`); }} />
      )}
    </div>
  );
}

Object.assign(window, { ClientsScreen });
