// HLP Raf — Modo interno (staff) sobre el catálogo público.
// Permite a un usuario interno armar un pedido como si fuera un cliente,
// con precios editables y cobro en efectivo. No reemplaza al panel Admin.

const STAFF_KEY = "hlpraf_staff_v1";
const STAFF_ROLES = { super_admin: "Super admin", branch_admin: "Sucursal", ventas: "Ventas" };

function staffSession() {
  try { return JSON.parse(sessionStorage.getItem(STAFF_KEY) || "null"); } catch (e) { return null; }
}
function setStaffSession(u) { sessionStorage.setItem(STAFF_KEY, JSON.stringify(u)); }
function clearStaffSession() { sessionStorage.removeItem(STAFF_KEY); }

// El rol y la sucursal salen de la BASE (staff_profiles), no del navegador.
function roleLabelOf(role) {
  return (window.hlprafAuth && window.hlprafAuth.roleLabel(role)) || STAFF_ROLES[role] || role || "";
}

function StaffGate({ accent, onLogin, onClose }) {
  const [email, setEmail] = React.useState("");
  const [password, setPassword] = React.useState("");
  const [error, setError] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const fld = { width: "100%", padding: "12px 14px", border: "1.5px solid #e8dcc8", borderRadius: 10, fontSize: 15, fontFamily: "'DM Sans', sans-serif", background: "#fff", boxSizing: "border-box" };

  const submit = async () => {
    if (busy) return;
    if (!window.hlprafAuth) { setError("No hay conexión con el servidor. Reintentá en unos segundos."); return; }
    setBusy(true); setError("");
    const r = await window.hlprafAuth.signIn(email, password);
    setBusy(false);
    if (r.error) { setError(r.error); return; }
    if (!window.hlprafAuth.can("interno", r.profile)) { setError("Este usuario no puede cargar pedidos"); return; }
    const sess = { email: r.profile.email, name: r.profile.name || r.profile.email, role: r.profile.role, branch_id: r.profile.branch_id || null };
    setStaffSession(sess);
    onLogin(sess);
  };

  return (
    <div style={{ position: "fixed", inset: 0, background: "rgba(20,12,4,0.72)", zIndex: 600, display: "flex", alignItems: "center", justifyContent: "center", padding: 20, backdropFilter: "blur(4px)" }} onClick={onClose}>
      <div style={{ background: "#fdfaf3", borderRadius: 18, padding: "26px 22px", width: "100%", maxWidth: 380, fontFamily: "'DM Sans', sans-serif" }} onClick={e => e.stopPropagation()}>
        <div style={{ fontSize: 11, fontWeight: 800, letterSpacing: "0.1em", textTransform: "uppercase", color: "#8a7a66" }}>Acceso interno</div>
        <h2 style={{ fontFamily: "'Bebas Neue', cursive", fontSize: 30, letterSpacing: "0.03em", margin: "4px 0 14px", color: "#1a1008" }}>Cargar pedido</h2>
        <div style={{ display: "grid", gap: 10 }}>
          <input value={email} onChange={e => { setEmail(e.target.value); setError(""); }} placeholder="Email" autoCapitalize="none" style={fld} />
          <input value={password} onChange={e => { setPassword(e.target.value); setError(""); }} onKeyDown={e => e.key === "Enter" && submit()} type="password" placeholder="Contraseña" style={fld} autoComplete="current-password" />
          {error && <div style={{ color: "#b91c1c", fontSize: 13, fontWeight: 600 }}>{error}</div>}
          <button onClick={submit} disabled={busy} style={{ background: "#1a1008", color: "#fff", border: "none", borderRadius: 10, padding: "13px 0", fontWeight: 800, fontSize: 15, cursor: busy ? "default" : "pointer", opacity: busy ? 0.6 : 1, fontFamily: "'DM Sans', sans-serif" }}>{busy ? "Entrando…" : "Entrar"}</button>
          <button onClick={onClose} style={{ background: "none", border: "none", color: "#8a7a66", fontSize: 13, cursor: "pointer", fontFamily: "'DM Sans', sans-serif" }}>Cancelar</button>
        </div>
      </div>
    </div>
  );
}

function StaffBar({ staff, branchName, onExit }) {
  return (
    <div style={{ background: "#1a1008", color: "#ffd166", padding: "7px 14px", display: "flex", alignItems: "center", gap: 10, fontFamily: "'DM Sans', sans-serif", fontSize: 12, fontWeight: 700, position: "sticky", top: 0, zIndex: 120 }}>
      <span style={{ background: "#ffd166", color: "#1a1008", padding: "2px 7px", borderRadius: 5, fontSize: 10, letterSpacing: "0.06em" }}>MODO INTERNO</span>
      <span style={{ flex: 1, color: "#f5ede1", fontWeight: 600, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
        {staff.name} · {roleLabelOf(staff.role)}{branchName ? " · " + branchName : ""}
      </span>
      <button onClick={onExit} style={{ background: "none", border: "1px solid #6b5d4e", color: "#f5ede1", borderRadius: 6, padding: "3px 9px", fontSize: 11, fontWeight: 700, cursor: "pointer", fontFamily: "'DM Sans', sans-serif" }}>Salir</button>
    </div>
  );
}

// Buscador de la agenda para autocompletar los datos del cliente.
function ClientPicker({ branchId, accent, onPick }) {
  const [q, setQ] = React.useState("");
  const [open, setOpen] = React.useState(false);
  const hits = findClients(q, branchId, 6);
  // NO se esconde cuando la agenda está vacía. Antes hacía `return null`, así
  // que cuando la agenda se pedía (ver data/clients.js) el buscador
  // DESAPARECÍA de la pantalla, y de afuera se veía igual que "dejó de
  // guardar clientes". Vacía, ahora lo dice.
  const vacia = !loadClients().length;
  return (
    <div style={{ position: "relative" }}>
      <input
        value={q}
        onChange={e => { setQ(e.target.value); setOpen(true); }}
        onFocus={() => setOpen(true)}
        placeholder={vacia ? "🔎 Agenda vacía — se llena al cargar pedidos" : "🔎 Buscar cliente en la agenda"}
        disabled={vacia}
        style={{ width: "100%", padding: "11px 14px", border: "1.5px dashed #c9b88f", borderRadius: 10, fontSize: 14, fontFamily: "'DM Sans', sans-serif", background: vacia ? "#f7f2e7" : "#fffdf7", color: vacia ? "#8a7a66" : "inherit", boxSizing: "border-box" }}
      />
      {open && !vacia && q.trim() && hits.length === 0 && (
        <div style={{ position: "absolute", top: "100%", left: 0, right: 0, marginTop: 4, background: "#fff", border: "1px solid #e8dcc8", borderRadius: 12, boxShadow: "0 8px 24px rgba(60,40,20,0.14)", zIndex: 30, padding: "10px 13px", fontSize: 12.5, color: "#8a7a66", fontFamily: "'DM Sans', sans-serif" }}>
          Sin resultados · se carga como cliente nuevo
        </div>
      )}
      {open && hits.length > 0 && (
        <div style={{ position: "absolute", top: "100%", left: 0, right: 0, marginTop: 4, background: "#fff", border: "1px solid #e8dcc8", borderRadius: 12, boxShadow: "0 8px 24px rgba(60,40,20,0.14)", zIndex: 30, overflow: "hidden" }}>
          {hits.map(c => (
            <button key={c.id} onClick={() => { onPick(c); setQ(""); setOpen(false); }} style={{ display: "block", width: "100%", textAlign: "left", background: "none", border: "none", borderBottom: "1px solid #f5ede1", padding: "10px 13px", cursor: "pointer", fontFamily: "'DM Sans', sans-serif" }}>
              <span style={{ display: "block", fontWeight: 700, fontSize: 14, color: "#1a1008" }}>{c.name || "(sin nombre)"}</span>
              <span style={{ display: "block", fontSize: 12, color: "#8a7a66" }}>{c.phone} · {c.street}</span>
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

Object.assign(window, { StaffGate, StaffBar, ClientPicker, staffSession, setStaffSession, clearStaffSession, STAFF_ROLES, roleLabelOf });
