/* ============ MAKI — Panel de Administración ============ */

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

const DEMO_USERS = [
  { id: "u-admin", email: "admin@masaca.com.ar",  displayName: "Admin",      role: "admin",      createdAt: "2026-01-01T00:00:00Z" },
  { id: "u-julio", email: "julio@masaca.com.ar",  displayName: "Julio",      role: "supervisor", createdAt: "2026-01-02T00:00:00Z" },
  { id: "u-op1",   email: "op1@masaca.com.ar",    displayName: "Valentina",  role: "operator",   createdAt: "2026-01-03T00:00:00Z" },
  { id: "u-op2",   email: "op2@masaca.com.ar",    displayName: "Rodrigo",    role: "operator",   createdAt: "2026-01-03T00:00:00Z" },
];

/* —— Modal crear/editar usuario —— */
function UserModal({ user, onSave, onClose }) {
  const isEdit = !!user?.id;
  const [form, setForm] = useState({
    displayName: user?.displayName || "",
    email: user?.email || "",
    role: user?.role || "operator",
    password: "",
  });
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState("");

  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const submit = async () => {
    if (!form.displayName.trim() || !form.email.trim()) { setError("Nombre y email son requeridos"); return; }
    if (!isEdit && !form.password) { setError("La contraseña es requerida para nuevos usuarios"); return; }
    setSaving(true); setError("");
    try {
      await onSave({ ...form, ...(user?.id ? { id: user.id } : {}) });
      onClose();
    } catch (e) {
      setError(e.message || "Error al guardar");
    } finally { setSaving(false); }
  };

  const field = (label, key, type = "text", placeholder = "") => (
    <div style={{ marginBottom: 14 }}>
      <label style={{ display: "block", fontSize: 11.5, fontWeight: 700, color: cv("--ink-3"), textTransform: "uppercase", letterSpacing: ".03em", marginBottom: 5 }}>{label}</label>
      <input
        type={type}
        value={form[key]}
        onChange={e => set(key, e.target.value)}
        placeholder={placeholder}
        style={{ width: "100%", boxSizing: "border-box", padding: "9px 12px", borderRadius: 9, border: `1px solid ${cv("--line-2")}`, fontSize: 13.5, fontFamily: "inherit", outline: "none", background: cv("--bg") }}
        onFocus={e => e.target.style.borderColor = "var(--primary)"}
        onBlur={e => e.target.style.borderColor = "var(--line-2)"}
      />
    </div>
  );

  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,.4)", animation: "maki-fade .18s ease" }} />
      <div style={{ position: "relative", width: 460, maxWidth: "92vw", background: cv("--surface"), borderRadius: 18, boxShadow: "var(--sh-pop)", padding: 26, animation: "maki-rise .24s cubic-bezier(.22,1,.36,1)" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 22 }}>
          <span style={{ width: 40, height: 40, borderRadius: 11, background: cv("--primary-tint"), display: "flex", alignItems: "center", justifyContent: "center" }}>
            <Icon name={isEdit ? "edit" : "user"} size={20} color={cv("--primary-700")} />
          </span>
          <div>
            <div style={{ fontSize: 16, fontWeight: 800 }}>{isEdit ? "Editar usuario" : "Nuevo usuario"}</div>
            <div style={{ fontSize: 12, color: cv("--ink-3"), fontWeight: 600 }}>Sistema de gestión Maki</div>
          </div>
        </div>

        {field("Nombre completo", "displayName", "text", "Ej: Valentina García")}
        {field("Email", "email", "email", "usuario@masaca.com.ar")}

        <div style={{ marginBottom: 14 }}>
          <label style={{ display: "block", fontSize: 11.5, fontWeight: 700, color: cv("--ink-3"), textTransform: "uppercase", letterSpacing: ".03em", marginBottom: 5 }}>Rol</label>
          <select value={form.role} onChange={e => set("role", e.target.value)} style={{ width: "100%", padding: "9px 12px", borderRadius: 9, border: `1px solid ${cv("--line-2")}`, fontSize: 13.5, fontFamily: "inherit", outline: "none", background: cv("--bg"), cursor: "pointer" }}>
            <option value="operator">Operador</option>
            <option value="supervisor">Supervisor</option>
            <option value="admin">Administrador</option>
          </select>
        </div>

        {field(isEdit ? "Nueva contraseña (dejar vacío para no cambiar)" : "Contraseña", "password", "password", "mínimo 8 caracteres")}

        {error && <div style={{ fontSize: 12.5, color: "#EF4444", fontWeight: 650, marginBottom: 12 }}>{error}</div>}

        <div style={{ display: "flex", gap: 10 }}>
          <Btn variant="outline" size="md" style={{ flex: 1 }} onClick={onClose}>Cancelar</Btn>
          <Btn variant="primary" size="md" icon={saving ? "clock" : "check"} style={{ flex: 1.4 }} onClick={submit}>
            {saving ? "Guardando…" : (isEdit ? "Guardar cambios" : "Crear usuario")}
          </Btn>
        </div>
      </div>
    </div>
  );
}

/* —— Tabla de usuarios —— */
function UsersTab() {
  const [users, setUsers] = useState(DEMO_USERS);
  const [editUser, setEditUser] = useState(null);
  const [showCreate, setShowCreate] = useState(false);
  const [delConfirm, setDelConfirm] = useState(null);
  const [loaded, setLoaded] = useState(false);

  useEffect(() => {
    if (!window.API || !API.isAuthenticated()) return;
    API.getAdminUsers().then(u => {
      if (u && u.length > 0) { setUsers(u); setLoaded(true); }
    }).catch(() => {});
  }, []);

  const handleSave = async (data) => {
    if (data.id) {
      // Edit
      if (window.API && API.isAuthenticated()) {
        const updated = await API.updateAdminUser(data.id, data);
        setUsers(us => us.map(u => u.id === updated.id ? updated : u));
      } else {
        setUsers(us => us.map(u => u.id === data.id ? { ...u, ...data } : u));
      }
    } else {
      // Create
      if (window.API && API.isAuthenticated()) {
        const created = await API.createAdminUser(data);
        setUsers(us => [...us, created]);
      } else {
        setUsers(us => [...us, { id: "u-" + Date.now(), createdAt: new Date().toISOString(), ...data }]);
      }
    }
  };

  const handleDelete = async (id) => {
    if (window.API && API.isAuthenticated()) {
      await API.deleteAdminUser(id).catch(() => {});
    }
    setUsers(us => us.filter(u => u.id !== id));
    setDelConfirm(null);
  };

  const ROLE_BG = { admin: "#FEF0EB", supervisor: "#F3F0FF", operator: "#EDFBF8", system: "#F5F5F5" };

  return (
    <div>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 18 }}>
        <div>
          <div style={{ fontSize: 15, fontWeight: 800 }}>Usuarios del sistema</div>
          <div style={{ fontSize: 12, color: cv("--ink-3"), fontWeight: 600, marginTop: 2 }}>{users.length} usuario{users.length !== 1 ? "s" : ""} registrado{users.length !== 1 ? "s" : ""}</div>
        </div>
        <Btn variant="primary" size="sm" icon="plus" onClick={() => setShowCreate(true)}>Nuevo usuario</Btn>
      </div>

      <div style={{ border: `1px solid ${cv("--line")}`, borderRadius: 14, overflow: "hidden" }}>
        {/* Header */}
        <div style={{ display: "grid", gridTemplateColumns: "1fr 180px 120px 100px 72px", padding: "10px 16px", background: cv("--bg"), borderBottom: `1px solid ${cv("--line")}`, fontSize: 10.5, fontWeight: 800, color: cv("--ink-3"), textTransform: "uppercase", letterSpacing: ".04em", gap: 8 }}>
          <span>Usuario</span><span>Email</span><span>Rol</span><span>Alta</span><span style={{ textAlign: "right" }}>Acción</span>
        </div>
        {users.map((u, i) => (
          <div key={u.id} style={{ display: "grid", gridTemplateColumns: "1fr 180px 120px 100px 72px", padding: "12px 16px", borderBottom: i < users.length - 1 ? `1px solid ${cv("--line")}` : "none", alignItems: "center", gap: 8, background: cv("--surface") }}>
            <div style={{ display: "flex", alignItems: "center", gap: 10, minWidth: 0 }}>
              <Avatar name={u.displayName} size={30} />
              <div style={{ minWidth: 0 }}>
                <div style={{ fontSize: 13, fontWeight: 750, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{u.displayName}</div>
                <div style={{ fontSize: 11, color: cv("--ink-3"), fontWeight: 600 }}>ID: {u.id.substring(0, 8)}…</div>
              </div>
            </div>
            <div style={{ fontSize: 12.5, color: cv("--ink-2"), whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{u.email}</div>
            <div>
              <span style={{ display: "inline-block", padding: "3px 9px", borderRadius: 99, fontSize: 11.5, fontWeight: 800, background: ROLE_BG[u.role] || "#F5F5F5", color: ROLE_COLORS[u.role] || cv("--ink-3") }}>
                {ROLE_LABELS[u.role] || u.role}
              </span>
            </div>
            <div style={{ fontSize: 12, color: cv("--ink-3") }}>{new Date(u.createdAt).toLocaleDateString("es-AR")}</div>
            <div style={{ display: "flex", justifyContent: "flex-end", gap: 5 }}>
              <button onClick={() => setEditUser(u)} title="Editar" style={{ width: 28, height: 28, borderRadius: 7, border: `1px solid ${cv("--line-2")}`, background: cv("--bg"), cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center", color: cv("--ink-3") }}>
                <Icon name="edit" size={13} />
              </button>
              <button onClick={() => setDelConfirm(u.id)} title="Eliminar" style={{ width: 28, height: 28, borderRadius: 7, border: "1px solid #FCA5A5", background: "#FEF2F2", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center", color: "#EF4444" }}>
                <Icon name="trash" size={13} />
              </button>
            </div>
          </div>
        ))}
      </div>

      {/* Delete confirm */}
      {delConfirm && (
        <div style={{ position: "fixed", inset: 0, zIndex: 90, display: "flex", alignItems: "center", justifyContent: "center" }}>
          <div onClick={() => setDelConfirm(null)} style={{ position: "absolute", inset: 0, background: "rgba(25,32,28,.4)" }} />
          <div style={{ position: "relative", width: 380, background: cv("--surface"), borderRadius: 16, boxShadow: "var(--sh-pop)", padding: 24, animation: "maki-rise .22s cubic-bezier(.22,1,.36,1)" }}>
            <div style={{ fontSize: 16, fontWeight: 800, marginBottom: 10 }}>¿Eliminar usuario?</div>
            <div style={{ fontSize: 13, color: cv("--ink-3"), marginBottom: 20, lineHeight: 1.5 }}>Esta acción no se puede deshacer. El usuario perderá el acceso al sistema.</div>
            <div style={{ display: "flex", gap: 10 }}>
              <Btn variant="outline" size="md" style={{ flex: 1 }} onClick={() => setDelConfirm(null)}>Cancelar</Btn>
              <button onClick={() => handleDelete(delConfirm)} style={{ flex: 1, padding: "9px 15px", borderRadius: 10, background: "#EF4444", color: "#fff", border: "none", cursor: "pointer", fontSize: 13.5, fontWeight: 800 }}>Eliminar</button>
            </div>
          </div>
        </div>
      )}

      {(showCreate || editUser) && (
        <UserModal
          user={editUser || null}
          onSave={handleSave}
          onClose={() => { setShowCreate(false); setEditUser(null); }}
        />
      )}
    </div>
  );
}

/* —— Probador de WhatsApp en vivo (Meta Cloud API) —— */
function WhatsappTestCard() {
  const [status, setStatus] = useState(null); // null=cargando, true/false
  const [to, setTo] = useState("");
  const [text, setText] = useState("¡Hola! Te escribimos desde Masaca Sushi 🍣 Tu pedido está en preparación.");
  const [busy, setBusy] = useState(false);
  const [result, setResult] = useState(null); // {ok, msg}

  useEffect(() => {
    if (!window.API || !API.isAuthenticated()) { setStatus(false); return; }
    API.whatsappStatus().then(s => setStatus(!!(s && s.configured))).catch(() => setStatus(false));
  }, []);

  const send = (kind) => {
    if (!to.trim()) { setResult({ ok: false, msg: "Ingresá un número (ej: 5491168762301)" }); return; }
    setBusy(true); setResult(null);
    const p = kind === "template" ? API.sendWhatsappTemplate(to.trim()) : API.sendWhatsapp(to.trim(), text);
    p.then(r => {
      if (r && r.simulated) setResult({ ok: true, msg: "Simulado (faltan credenciales en Railway)" });
      else setResult({ ok: true, msg: "✓ Enviado · ID " + ((r.messages && r.messages[0] && r.messages[0].id) || "—").slice(0, 22) });
    }).catch(e => setResult({ ok: false, msg: "Error: " + (e.message || "no se pudo enviar") }))
      .finally(() => setBusy(false));
  };

  const inStyle = { width: "100%", boxSizing: "border-box", padding: "9px 12px", borderRadius: 9, border: `1px solid ${cv("--line-2")}`, fontSize: 13.5, fontFamily: "inherit", outline: "none", background: cv("--bg") };

  return (
    <div style={{ border: `1px solid ${cv("--line")}`, borderRadius: 14, padding: 18, marginTop: 18, background: cv("--surface") }}>
      <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 4 }}>
        <span style={{ width: 34, height: 34, borderRadius: 9, background: "#E7F8EF", color: "#1FA855", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name="whatsapp" size={18} stroke={2.2} /></span>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 14.5, fontWeight: 800 }}>WhatsApp en vivo</div>
          <div style={{ fontSize: 12, color: cv("--ink-3"), fontWeight: 600 }}>Meta Cloud API · enviar mensaje de prueba</div>
        </div>
        <span style={{ fontSize: 11.5, fontWeight: 800, padding: "3px 10px", borderRadius: 99,
          background: status ? cv("--wasabi-soft") : "#FEF2F2", color: status ? cv("--wasabi") : "#EF4444" }}>
          {status === null ? "…" : status ? "Conectado" : "No configurado"}
        </span>
      </div>
      {!status && status !== null && (
        <div style={{ fontSize: 12, color: cv("--ink-3"), fontWeight: 600, margin: "8px 0 12px", lineHeight: 1.5 }}>
          Cargá <strong>WHATSAPP_TOKEN</strong> y <strong>WHATSAPP_PHONE_NUMBER_ID</strong> en Railway y redeploy. Sin eso, los envíos quedan en modo simulado.
        </div>
      )}
      <div style={{ display: "flex", flexDirection: "column", gap: 9, marginTop: 12 }}>
        <input value={to} onChange={e => setTo(e.target.value)} style={inStyle} placeholder="Número destino (E.164, ej: 5491168762301)" />
        <textarea value={text} onChange={e => setText(e.target.value)} rows={2} style={{ ...inStyle, resize: "vertical" }} />
        <div style={{ display: "flex", gap: 9 }}>
          <Btn variant="primary" size="sm" icon="send" style={{ flex: 1, opacity: busy ? .6 : 1, pointerEvents: busy ? "none" : "auto" }} onClick={() => send("text")}>Enviar texto</Btn>
          <Btn variant="outline" size="sm" style={{ flex: 1, opacity: busy ? .6 : 1, pointerEvents: busy ? "none" : "auto" }} onClick={() => send("template")}>Enviar plantilla (hello_world)</Btn>
        </div>
        <div style={{ fontSize: 11, color: cv("--ink-3"), fontWeight: 600, lineHeight: 1.45 }}>
          Texto libre solo funciona si el cliente escribió primero (ventana 24h). Para primer contacto sin respuesta previa, usá la plantilla.
        </div>
        {result && (
          <div style={{ fontSize: 12.5, fontWeight: 700, padding: "8px 11px", borderRadius: 9,
            background: result.ok ? cv("--wasabi-soft") : "#FEF2F2", color: result.ok ? cv("--wasabi") : "#EF4444" }}>{result.msg}</div>
        )}
      </div>
    </div>
  );
}

/* —— Tab configuración —— */
function ConfigTab() {
  const configs = [
    { label: "Intentos de reintento Maxirest", desc: "Cantidad de reintentos antes de falla permanente", value: "8 intentos", icon: "repeat" },
    { label: "Delay inicial de reintento", desc: "Tiempo base en minutos entre reintentos (backoff exponencial)", value: "1 minuto", icon: "zap" },
    { label: "Exportación diaria", desc: "Hora de envío del reporte diario por email", value: "23:59 ART", icon: "mail" },
  ];
  return (
    <div>
      <div style={{ fontSize: 15, fontWeight: 800, marginBottom: 4 }}>Configuración del sistema</div>
      <div style={{ fontSize: 12, color: cv("--ink-3"), fontWeight: 600, marginBottom: 18 }}>Parámetros operativos de Maki · Masaca Sushi</div>
      <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
        {configs.map(c => (
          <div key={c.label} style={{ display: "flex", alignItems: "center", gap: 14, padding: "14px 16px", border: `1px solid ${cv("--line")}`, borderRadius: 12, background: cv("--surface") }}>
            <span style={{ width: 38, height: 38, borderRadius: 10, background: cv("--bg"), display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
              <Icon name={c.icon} size={18} color={cv("--ink-3")} />
            </span>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13.5, fontWeight: 750 }}>{c.label}</div>
              <div style={{ fontSize: 12, color: cv("--ink-3"), fontWeight: 600, marginTop: 1 }}>{c.desc}</div>
            </div>
            <span style={{ fontSize: 13, fontWeight: 800, color: cv("--primary-700"), background: cv("--primary-tint"), padding: "4px 12px", borderRadius: 8, whiteSpace: "nowrap" }}>{c.value}</span>
          </div>
        ))}
      </div>
      <WhatsappTestCard />

      <div style={{ marginTop: 18, padding: "12px 16px", borderRadius: 11, background: cv("--bg"), border: `1px solid ${cv("--line")}`, fontSize: 12.5, color: cv("--ink-3"), fontWeight: 600 }}>
        Para modificar estos valores editá las variables de entorno en Railway y redeploya el servicio.
      </div>
    </div>
  );
}

/* —— Tab SLA por niveles (C8) —— */
const SLA_DEFAULT = [
  { id: "gold",   label: "Gold",   color: "#D4AF37", bg: "#FBF6E7", from: 0, to: 2,   action: "none",       desc: "Respuesta inmediata" },
  { id: "silver", label: "Silver", color: "#8B95A1", bg: "#F1F3F5", from: 2, to: 3,   action: "alert_op",   desc: "Alertar al operador" },
  { id: "bronze", label: "Bronze", color: "#B45309", bg: "#FBF1E7", from: 3, to: null, action: "escalate",   desc: "Escalar a supervisor" },
];
const SLA_ACTIONS = {
  none:           "Solo registrar",
  alert_op:       "Alertar al operador",
  alert_sup:      "Alertar al supervisor",
  escalate:       "Escalar prioridad + supervisor",
};

function SlaTab() {
  const [levels, setLevels] = useState(SLA_DEFAULT);
  const [saved, setSaved] = useState(false);
  const set = (id, k, v) => { setLevels(ls => ls.map(l => l.id === id ? { ...l, [k]: v } : l)); setSaved(false); };
  const save = () => { setSaved(true); window.dispatchEvent(new CustomEvent("maki:notif", { detail: { type: "ok", text: "Niveles de SLA actualizados", at: new Date().toLocaleTimeString("es-AR", { hour: "2-digit", minute: "2-digit" }) } })); };

  return (
    <div>
      <div style={{ fontSize: 15, fontWeight: 800, marginBottom: 4 }}>Niveles de SLA</div>
      <div style={{ fontSize: 12, color: cv("--ink-3"), fontWeight: 600, marginBottom: 18 }}>Tiempo de primera respuesta por nivel · define la acción automática al superar cada umbral</div>

      <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
        {levels.map((l, i) => (
          <div key={l.id} style={{ border: `1px solid ${cv("--line")}`, borderLeft: `4px solid ${l.color}`, borderRadius: 12, padding: "15px 18px", background: cv("--surface") }}>
            <div style={{ display: "flex", alignItems: "center", gap: 11, marginBottom: 13 }}>
              <span style={{ width: 34, height: 34, borderRadius: 9, background: l.bg, color: l.color, display: "flex", alignItems: "center", justifyContent: "center", fontWeight: 900, fontSize: 15 }}>★</span>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 14.5, fontWeight: 800, color: l.color }}>{l.label}</div>
                <div style={{ fontSize: 11.5, color: cv("--ink-3"), fontWeight: 600 }}>{SLA_ACTIONS[l.action]}</div>
              </div>
              <span style={{ fontSize: 12.5, fontWeight: 800, color: cv("--ink-2"), background: cv("--bg"), padding: "4px 11px", borderRadius: 8 }}>
                {l.to === null ? `${l.from}+ min` : `${l.from}–${l.to} min`}
              </span>
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1.4fr", gap: 10 }}>
              <div>
                <label style={{ fontSize: 10.5, fontWeight: 800, color: cv("--ink-3"), textTransform: "uppercase", display: "block", marginBottom: 4 }}>Desde (min)</label>
                <input type="number" min="0" step="0.5" value={l.from} onChange={e => set(l.id, "from", parseFloat(e.target.value) || 0)} style={{ width: "100%", boxSizing: "border-box", padding: "8px 10px", borderRadius: 9, border: `1px solid ${cv("--line-2")}`, fontSize: 13.5, fontFamily: "inherit", outline: "none", background: cv("--bg") }} />
              </div>
              <div>
                <label style={{ fontSize: 10.5, fontWeight: 800, color: cv("--ink-3"), textTransform: "uppercase", display: "block", marginBottom: 4 }}>Hasta (min)</label>
                <input type="number" min="0" step="0.5" value={l.to === null ? "" : l.to} placeholder="∞" onChange={e => set(l.id, "to", e.target.value === "" ? null : (parseFloat(e.target.value) || 0))} style={{ width: "100%", boxSizing: "border-box", padding: "8px 10px", borderRadius: 9, border: `1px solid ${cv("--line-2")}`, fontSize: 13.5, fontFamily: "inherit", outline: "none", background: cv("--bg") }} />
              </div>
              <div>
                <label style={{ fontSize: 10.5, fontWeight: 800, color: cv("--ink-3"), textTransform: "uppercase", display: "block", marginBottom: 4 }}>Acción al superar</label>
                <select value={l.action} onChange={e => set(l.id, "action", e.target.value)} style={{ width: "100%", boxSizing: "border-box", padding: "8px 10px", borderRadius: 9, border: `1px solid ${cv("--line-2")}`, fontSize: 13, fontFamily: "inherit", outline: "none", background: cv("--bg"), cursor: "pointer" }}>
                  {Object.entries(SLA_ACTIONS).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
                </select>
              </div>
            </div>
          </div>
        ))}
      </div>

      <div style={{ display: "flex", alignItems: "center", gap: 12, marginTop: 18 }}>
        <Btn variant="primary" size="md" icon={saved ? "check" : "zap"} onClick={save}>{saved ? "Guardado ✓" : "Guardar niveles de SLA"}</Btn>
        <span style={{ fontSize: 12, color: cv("--ink-3"), fontWeight: 600 }}>Los umbrales aplican al tiempo de primera respuesta de cada chat.</span>
      </div>
    </div>
  );
}

/* —— Tab Reglas de negocio / Automatizaciones (C9) —— */
const RULE_TRIGGERS = {
  chat_vip_in:       "Entra un chat VIP",
  sla_breach:        "Se vence el SLA sin respuesta",
  maxirest_down:     "Maxirest cae offline",
  payment_verified:  "Se verifica un pago",
  order_ready:       "Cocina marca pedido LISTO (KDS)",
  order_dispatched:  "Pedido despachado por el rider",
  order_delivered:   "Pedido entregado",
  recurring_due:     "Llega el día de un pedido recurrente",
  new_customer:      "Se registra un cliente nuevo",
};
const RULE_ACTIONS = {
  assign_op:         "Asignar al operador con menos carga",
  notify_supervisor: "Notificar al supervisor",
  send_macro:        "Enviar macro al cliente",
  escalate:          "Escalar prioridad",
  tag:               "Etiquetar la conversación",
  webhook:           "Disparar webhook externo",
  notify_customer:   "Avisar al cliente (seguimiento)",
};

const RULES_SEED = [
  { id: "r1", name: "VIP al tope", active: true, trigger: "chat_vip_in", action: "escalate", note: "Reenruta y alerta al iPad" },
  { id: "r2", name: "Pedido listo → aviso cliente", active: true, trigger: "order_ready", action: "notify_customer", note: "Push al panel de seguimiento" },
  { id: "r3", name: "Maxirest caído → supervisor", active: true, trigger: "maxirest_down", action: "notify_supervisor", note: "Cola de reintento" },
  { id: "r4", name: "Recurrente → recordatorio", active: false, trigger: "recurring_due", action: "send_macro", note: "Macro 'Tu pedido de siempre'" },
];

const MACROS_SEED = [
  { id: "m1", name: "Saludo inicial", text: "¡Hola! Gracias por escribir a Masaca Sushi 🍣 ¿En qué te ayudamos hoy?" },
  { id: "m2", name: "Pedir medio de pago", text: "¿Con qué medio vas a abonar? Efectivo, transferencia, tarjeta o Mercado Pago 🙏" },
  { id: "m3", name: "Tu pedido de siempre", text: "¡Hola! ¿Querés repetir tu pedido habitual para hoy? Respondé SÍ y lo dejamos listo 😊" },
];

function RuleModal({ rule, onClose, onSave }) {
  const isEdit = !!rule?.id;
  const [name, setName] = useState(rule?.name || "");
  const [trigger, setTrigger] = useState(rule?.trigger || "chat_vip_in");
  const [action, setAction] = useState(rule?.action || "assign_op");
  const [note, setNote] = useState(rule?.note || "");
  const selStyle = { width: "100%", boxSizing: "border-box", padding: "10px 12px", borderRadius: 10, border: `1px solid ${cv("--line-2")}`, fontSize: 13.5, fontFamily: "inherit", outline: "none", background: cv("--bg"), cursor: "pointer" };
  const inStyle = { ...selStyle, cursor: "text" };
  const lbl = { fontSize: 11, fontWeight: 800, color: cv("--ink-3"), textTransform: "uppercase", letterSpacing: ".03em", display: "block", marginBottom: 5 };
  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: 480, maxWidth: "94vw", background: cv("--surface"), borderRadius: 18, boxShadow: "var(--sh-pop)", padding: 24, animation: "maki-rise .24s cubic-bezier(.22,1,.36,1)" }}>
        <div style={{ fontSize: 16, fontWeight: 800, marginBottom: 4 }}>{isEdit ? "Editar regla" : "Nueva regla de negocio"}</div>
        <div style={{ fontSize: 12.5, color: cv("--ink-3"), fontWeight: 600, marginBottom: 18 }}>Automatización condicional dentro de la plataforma</div>

        <div style={{ marginBottom: 13 }}><label style={lbl}>Nombre de la regla</label><input value={name} onChange={e => setName(e.target.value)} style={inStyle} placeholder="Ej: VIP al tope" autoFocus /></div>
        <div style={{ marginBottom: 13 }}>
          <label style={lbl}>CUANDO (disparador)</label>
          <select value={trigger} onChange={e => setTrigger(e.target.value)} style={selStyle}>
            {Object.entries(RULE_TRIGGERS).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
          </select>
        </div>
        <div style={{ display: "flex", justifyContent: "center", margin: "-4px 0 9px" }}><Icon name="chevD" size={18} color={cv("--ink-3")} /></div>
        <div style={{ marginBottom: 13 }}>
          <label style={lbl}>ENTONCES (acción)</label>
          <select value={action} onChange={e => setAction(e.target.value)} style={selStyle}>
            {Object.entries(RULE_ACTIONS).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
          </select>
        </div>
        <div style={{ marginBottom: 18 }}><label style={lbl}>Nota (opcional)</label><input value={note} onChange={e => setNote(e.target.value)} style={inStyle} placeholder="Detalle interno" /></div>

        <div style={{ display: "flex", gap: 10 }}>
          <Btn variant="outline" size="md" style={{ flex: 1 }} onClick={onClose}>Cancelar</Btn>
          <Btn variant="primary" size="md" icon="check" style={{ flex: 1.4, opacity: name.trim() ? 1 : .45, pointerEvents: name.trim() ? "auto" : "none" }}
            onClick={() => onSave({ id: rule?.id || "r-" + Date.now(), name: name.trim(), trigger, action, note, active: rule?.active ?? true })}>
            {isEdit ? "Guardar regla" : "Crear regla"}
          </Btn>
        </div>
      </div>
    </div>
  );
}

function MacroModal({ macro, onClose, onSave }) {
  const isEdit = !!macro?.id;
  const [name, setName] = useState(macro?.name || "");
  const [text, setText] = useState(macro?.text || "");
  const inStyle = { width: "100%", boxSizing: "border-box", padding: "10px 12px", borderRadius: 10, border: `1px solid ${cv("--line-2")}`, fontSize: 13.5, fontFamily: "inherit", outline: "none", background: cv("--bg") };
  const lbl = { fontSize: 11, fontWeight: 800, color: cv("--ink-3"), textTransform: "uppercase", letterSpacing: ".03em", display: "block", marginBottom: 5 };
  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: 460, maxWidth: "94vw", background: cv("--surface"), borderRadius: 18, boxShadow: "var(--sh-pop)", padding: 24, animation: "maki-rise .24s cubic-bezier(.22,1,.36,1)" }}>
        <div style={{ fontSize: 16, fontWeight: 800, marginBottom: 18 }}>{isEdit ? "Editar macro" : "Nueva macro"}</div>
        <div style={{ marginBottom: 13 }}><label style={lbl}>Nombre</label><input value={name} onChange={e => setName(e.target.value)} style={inStyle} placeholder="Ej: Saludo inicial" autoFocus /></div>
        <div style={{ marginBottom: 18 }}><label style={lbl}>Mensaje</label><textarea value={text} onChange={e => setText(e.target.value)} rows={4} style={{ ...inStyle, resize: "vertical" }} placeholder="Texto que se enviará al cliente…" /></div>
        <div style={{ display: "flex", gap: 10 }}>
          <Btn variant="outline" size="md" style={{ flex: 1 }} onClick={onClose}>Cancelar</Btn>
          <Btn variant="primary" size="md" icon="check" style={{ flex: 1.4, opacity: (name.trim() && text.trim()) ? 1 : .45, pointerEvents: (name.trim() && text.trim()) ? "auto" : "none" }}
            onClick={() => onSave({ id: macro?.id || "m-" + Date.now(), name: name.trim(), text: text.trim() })}>{isEdit ? "Guardar" : "Crear macro"}</Btn>
        </div>
      </div>
    </div>
  );
}

function RulesTab() {
  const [rules, setRules] = useState(RULES_SEED);
  const [macros, setMacros] = useState(MACROS_SEED);
  const [ruleModal, setRuleModal] = useState(null);   // {} for new, rule for edit
  const [macroModal, setMacroModal] = useState(null);

  const saveRule = (r) => { setRules(rs => rs.some(x => x.id === r.id) ? rs.map(x => x.id === r.id ? r : x) : [...rs, r]); setRuleModal(null); };
  const saveMacro = (m) => { setMacros(ms => ms.some(x => x.id === m.id) ? ms.map(x => x.id === m.id ? m : x) : [...ms, m]); setMacroModal(null); };

  return (
    <div>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 18 }}>
        <div>
          <div style={{ fontSize: 15, fontWeight: 800 }}>Reglas de negocio</div>
          <div style={{ fontSize: 12, color: cv("--ink-3"), fontWeight: 600, marginTop: 2 }}>Automatizaciones internas · CUANDO → ENTONCES</div>
        </div>
        <Btn variant="primary" size="sm" icon="plus" onClick={() => setRuleModal({})}>Nueva regla</Btn>
      </div>

      <div style={{ display: "flex", flexDirection: "column", gap: 9, marginBottom: 30 }}>
        {rules.map(r => (
          <div key={r.id} style={{ display: "flex", alignItems: "center", gap: 13, padding: "13px 16px", border: `1px solid ${cv("--line")}`, borderRadius: 12, background: cv("--surface"), opacity: r.active ? 1 : .6 }}>
            <span style={{ width: 34, height: 34, borderRadius: 9, background: cv("--primary-tint"), color: cv("--primary-700"), display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}><Icon name="zap" size={16} /></span>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 13.5, fontWeight: 800 }}>{r.name}</div>
              <div style={{ fontSize: 12, color: cv("--ink-2"), fontWeight: 600, marginTop: 1 }}>
                <span style={{ color: cv("--ink-3") }}>CUANDO</span> {RULE_TRIGGERS[r.trigger]} <span style={{ color: cv("--ink-3") }}>→</span> {RULE_ACTIONS[r.action]}
              </div>
            </div>
            <button onClick={() => setRules(rs => rs.map(x => x.id === r.id ? { ...x, active: !x.active } : x))} style={{
              width: 42, height: 24, borderRadius: 99, border: "none", cursor: "pointer", position: "relative", flexShrink: 0,
              background: r.active ? cv("--wasabi") : cv("--line-2"),
            }}><span style={{ position: "absolute", top: 3, left: r.active ? 21 : 3, width: 18, height: 18, borderRadius: "50%", background: "#fff", transition: "left .15s", boxShadow: "0 1px 3px rgba(0,0,0,.2)" }} /></button>
            <button onClick={() => setRuleModal(r)} style={{ width: 28, height: 28, borderRadius: 7, border: `1px solid ${cv("--line-2")}`, background: cv("--bg"), cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center", color: cv("--ink-3") }}><Icon name="edit" size={13} /></button>
            <button onClick={() => setRules(rs => rs.filter(x => x.id !== r.id))} style={{ width: 28, height: 28, borderRadius: 7, border: "1px solid #FCA5A5", background: "#FEF2F2", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center", color: "#EF4444" }}><Icon name="trash" size={13} /></button>
          </div>
        ))}
      </div>

      {/* Macros */}
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 14 }}>
        <div>
          <div style={{ fontSize: 15, fontWeight: 800 }}>Macros / Respuestas rápidas</div>
          <div style={{ fontSize: 12, color: cv("--ink-3"), fontWeight: 600, marginTop: 2 }}>Plantillas reutilizables para operadores y automatizaciones</div>
        </div>
        <Btn variant="primary" size="sm" icon="plus" onClick={() => setMacroModal({})}>Nueva macro</Btn>
      </div>
      <div style={{ display: "flex", flexDirection: "column", gap: 9 }}>
        {macros.map(m => (
          <div key={m.id} style={{ display: "flex", alignItems: "flex-start", gap: 13, padding: "13px 16px", border: `1px solid ${cv("--line")}`, borderRadius: 12, background: cv("--surface") }}>
            <span style={{ width: 34, height: 34, borderRadius: 9, background: cv("--bg"), color: cv("--ink-3"), display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}><Icon name="message" size={16} /></span>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 13.5, fontWeight: 800 }}>{m.name}</div>
              <div style={{ fontSize: 12, color: cv("--ink-2"), fontWeight: 550, marginTop: 2, lineHeight: 1.4 }}>{m.text}</div>
            </div>
            <button onClick={() => setMacroModal(m)} style={{ width: 28, height: 28, borderRadius: 7, border: `1px solid ${cv("--line-2")}`, background: cv("--bg"), cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center", color: cv("--ink-3"), flexShrink: 0 }}><Icon name="edit" size={13} /></button>
            <button onClick={() => setMacros(ms => ms.filter(x => x.id !== m.id))} style={{ width: 28, height: 28, borderRadius: 7, border: "1px solid #FCA5A5", background: "#FEF2F2", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center", color: "#EF4444", flexShrink: 0 }}><Icon name="trash" size={13} /></button>
          </div>
        ))}
      </div>

      {ruleModal && <RuleModal rule={ruleModal.id ? ruleModal : null} onClose={() => setRuleModal(null)} onSave={saveRule} />}
      {macroModal && <MacroModal macro={macroModal.id ? macroModal : null} onClose={() => setMacroModal(null)} onSave={saveMacro} />}
    </div>
  );
}

/* —— Pantalla Admin —— */
function AdminScreen() {
  const [tab, setTab] = useState("usuarios");
  const TABS = [
    { id: "usuarios",  label: "Usuarios",       icon: "users" },
    { id: "sla",       label: "SLA",            icon: "clock" },
    { id: "reglas",    label: "Reglas",          icon: "zap" },
    { id: "config",    label: "Configuración",   icon: "settings" },
  ];

  return (
    <div style={{ padding: 28, maxWidth: 960, margin: "0 auto" }}>
      {/* Header */}
      <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 24 }}>
        <span style={{ width: 44, height: 44, borderRadius: 13, background: cv("--ink"), display: "flex", alignItems: "center", justifyContent: "center" }}>
          <Icon name="shield" size={22} color="#fff" />
        </span>
        <div>
          <div style={{ fontSize: 20, fontWeight: 800 }}>Administración</div>
          <div style={{ fontSize: 12.5, color: cv("--ink-3"), fontWeight: 600 }}>Gestión de usuarios · permisos · configuración del sistema</div>
        </div>
      </div>

      {/* Tabs */}
      <div style={{ display: "flex", gap: 6, marginBottom: 24, borderBottom: `1px solid ${cv("--line")}`, paddingBottom: 0 }}>
        {TABS.map(t => (
          <button key={t.id} onClick={() => setTab(t.id)} style={{
            display: "flex", alignItems: "center", gap: 7, padding: "9px 14px", borderRadius: "10px 10px 0 0",
            border: "none", cursor: "pointer", fontSize: 13.5, fontWeight: 750,
            background: tab === t.id ? cv("--surface") : "transparent",
            color: tab === t.id ? cv("--primary-700") : cv("--ink-3"),
            borderBottom: tab === t.id ? `2px solid ${cv("--primary")}` : "2px solid transparent",
            marginBottom: -1,
          }}>
            <Icon name={t.icon} size={15} stroke={2} />
            {t.label}
          </button>
        ))}
      </div>

      {/* Content */}
      {tab === "usuarios" && <UsersTab />}
      {tab === "sla"      && <SlaTab />}
      {tab === "reglas"   && <RulesTab />}
      {tab === "config"   && <ConfigTab />}
    </div>
  );
}

Object.assign(window, { AdminScreen });
