/* === Autenticación (login simple) — sin bundler ===
   Usa el cliente de navegador de Convex (window.convexClient / window.convexApi).
   window.cdcAuth es la ÚNICA fuente del token (localStorage["cdc_session"]). */

const CDC_SESSION_KEY = "cdc_session";

const cdcAuth = {
  getToken() {
    try { return localStorage.getItem(CDC_SESSION_KEY) || null; } catch (e) { return null; }
  },
  setToken(t) {
    try { localStorage.setItem(CDC_SESSION_KEY, t); } catch (e) {}
  },
  clear() {
    try { localStorage.removeItem(CDC_SESSION_KEY); } catch (e) {}
  },
  _api() {
    if (!window.convexClient || !window.convexApi) throw new Error("Conexión no lista");
    return { c: window.convexClient, api: window.convexApi };
  },
  async login(email, password) {
    const { c, api } = this._api();
    const r = await c.mutation(api.auth.login, { email, password });
    if (r && r.token) { this.setToken(r.token); return r; }
    throw new Error("Credenciales inválidas");
  },
  async logout() {
    const t = this.getToken();
    try {
      if (t) { const { c, api } = this._api(); await c.mutation(api.auth.logout, { token: t }); }
    } catch (e) {
      // si falla la red, igual cerramos sesión localmente
    } finally {
      this.clear();
    }
  },
  async validate() {
    const t = this.getToken();
    if (!t) return null;
    const { c, api } = this._api();
    return await c.query(api.auth.validateSession, { token: t });
  },
  async changePassword(oldPassword, newPassword) {
    const t = this.getToken();
    if (!t) throw new Error("Sesión inválida");
    const { c, api } = this._api();
    return await c.mutation(api.auth.changePassword, { token: t, oldPassword, newPassword });
  },
  // --- admin ---
  async listAccounts() {
    const t = this.getToken();
    const { c, api } = this._api();
    return await c.query(api.auth.listAccounts, { token: t });
  },
  async upsertAccount(staffId, email, password) {
    const t = this.getToken();
    const { c, api } = this._api();
    return await c.mutation(api.auth.upsertAccount, { token: t, staffId, email, password });
  },
  async removeAccount(staffId) {
    const t = this.getToken();
    const { c, api } = this._api();
    return await c.mutation(api.auth.removeAccount, { token: t, staffId });
  },
};
window.cdcAuth = cdcAuth;

/* ---------- UI ---------- */

const cdcAuthStyles = {
  screen: {
    position: "fixed", inset: 0, display: "flex", alignItems: "center", justifyContent: "center",
    background: "var(--cdc-bg)", padding: 20, zIndex: 500,
  },
  card: {
    width: "100%", maxWidth: 380, background: "var(--cdc-panel)", borderRadius: 18,
    border: "1px solid var(--cdc-border)", boxShadow: "var(--cdc-shadow-lg, 0 20px 50px rgba(0,0,0,.12))",
    padding: 32, boxSizing: "border-box",
  },
  logo: { width: 56, height: 56, borderRadius: 14, objectFit: "cover", display: "block", margin: "0 auto 14px" },
  title: { fontFamily: "var(--cdc-display)", fontSize: 26, fontWeight: 600, color: "var(--cdc-ink)", textAlign: "center", margin: 0 },
  subtitle: { fontSize: 13.5, color: "var(--cdc-ink-3)", textAlign: "center", margin: "6px 0 22px" },
  label: { display: "block", fontSize: 12.5, fontWeight: 600, color: "var(--cdc-ink-2)", margin: "0 0 6px" },
  input: {
    width: "100%", boxSizing: "border-box", padding: "11px 13px", fontSize: 14.5,
    border: "1px solid var(--cdc-border)", borderRadius: 10, background: "var(--cdc-bg-soft)",
    color: "var(--cdc-ink)", marginBottom: 14, outline: "none",
  },
  button: {
    width: "100%", padding: "12px 16px", fontSize: 14.5, fontWeight: 700, color: "#fff",
    background: "var(--cdc-coral)", border: "none", borderRadius: 10, cursor: "pointer",
  },
  buttonDisabled: { opacity: 0.6, cursor: "default" },
  error: {
    background: "var(--cdc-urgent-bg)", color: "var(--cdc-urgent)", fontSize: 13,
    padding: "9px 12px", borderRadius: 9, marginBottom: 14, textAlign: "center",
  },
};

const LoginScreen = ({ onLogin }) => {
  const [email, setEmail] = React.useState("");
  const [password, setPassword] = React.useState("");
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState("");

  const submit = async (e) => {
    e.preventDefault();
    if (loading) return;            // bloqueo de doble submit
    setError("");
    setLoading(true);
    try {
      const r = await cdcAuth.login(email.trim().toLowerCase(), password);
      onLogin(r.staffId);
    } catch (err) {
      setError("Correo o contraseña incorrectos.");
      setLoading(false);
    }
  };

  return (
    <div style={cdcAuthStyles.screen}>
      <form style={cdcAuthStyles.card} onSubmit={submit}>
        <img src="assets/casa-de-casas-logo.jpg" alt="Casa de Casas" style={cdcAuthStyles.logo} />
        <h1 style={cdcAuthStyles.title}>Casa de Casas</h1>
        <p style={cdcAuthStyles.subtitle}>Inicia sesión para continuar</p>
        {error && <div style={cdcAuthStyles.error}>{error}</div>}
        <label style={cdcAuthStyles.label}>Correo</label>
        <input
          style={cdcAuthStyles.input} type="email" autoComplete="username"
          value={email} onChange={(e) => setEmail(e.target.value)} disabled={loading} required
        />
        <label style={cdcAuthStyles.label}>Contraseña</label>
        <input
          style={cdcAuthStyles.input} type="password" autoComplete="current-password"
          value={password} onChange={(e) => setPassword(e.target.value)} disabled={loading} required
        />
        <button
          type="submit" disabled={loading}
          style={{ ...cdcAuthStyles.button, ...(loading ? cdcAuthStyles.buttonDisabled : {}) }}
        >
          {loading ? "Entrando…" : "Entrar"}
        </button>
      </form>
    </div>
  );
};

const ChangePasswordModal = ({ onClose }) => {
  const [oldp, setOldp] = React.useState("");
  const [newp, setNewp] = React.useState("");
  const [confirm, setConfirm] = React.useState("");
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState("");
  const [done, setDone] = React.useState(false);

  const submit = async (e) => {
    e.preventDefault();
    if (loading) return;
    setError("");
    if (newp.length < 8) { setError("La nueva contraseña debe tener al menos 8 caracteres."); return; }
    if (newp !== confirm) { setError("Las contraseñas no coinciden."); return; }
    setLoading(true);
    try {
      await cdcAuth.changePassword(oldp, newp);
      setDone(true);
    } catch (err) {
      setError("No se pudo cambiar. Revisa tu contraseña actual.");
      setLoading(false);
    }
  };

  return (
    <div style={{ ...cdcAuthStyles.screen, background: "rgba(0,0,0,.4)", zIndex: 600 }} onClick={onClose}>
      <form style={cdcAuthStyles.card} onSubmit={submit} onClick={(e) => e.stopPropagation()}>
        <h1 style={{ ...cdcAuthStyles.title, fontSize: 22 }}>Cambiar contraseña</h1>
        <p style={cdcAuthStyles.subtitle}>Tu sesión actual seguirá activa; las demás se cerrarán.</p>
        {error && <div style={cdcAuthStyles.error}>{error}</div>}
        {done ? (
          <>
            <div style={{ ...cdcAuthStyles.error, background: "var(--cdc-done-bg)", color: "var(--cdc-done)" }}>
              Contraseña actualizada.
            </div>
            <button type="button" style={cdcAuthStyles.button} onClick={onClose}>Listo</button>
          </>
        ) : (
          <>
            <label style={cdcAuthStyles.label}>Contraseña actual</label>
            <input style={cdcAuthStyles.input} type="password" value={oldp} onChange={(e) => setOldp(e.target.value)} disabled={loading} required />
            <label style={cdcAuthStyles.label}>Nueva contraseña</label>
            <input style={cdcAuthStyles.input} type="password" value={newp} onChange={(e) => setNewp(e.target.value)} disabled={loading} required />
            <label style={cdcAuthStyles.label}>Confirmar nueva contraseña</label>
            <input style={cdcAuthStyles.input} type="password" value={confirm} onChange={(e) => setConfirm(e.target.value)} disabled={loading} required />
            <div style={{ display: "flex", gap: 10 }}>
              <button type="button" onClick={onClose} disabled={loading}
                style={{ ...cdcAuthStyles.button, background: "var(--cdc-bg-soft)", color: "var(--cdc-ink-2)", border: "1px solid var(--cdc-border)" }}>
                Cancelar
              </button>
              <button type="submit" disabled={loading}
                style={{ ...cdcAuthStyles.button, ...(loading ? cdcAuthStyles.buttonDisabled : {}) }}>
                {loading ? "Guardando…" : "Cambiar"}
              </button>
            </div>
          </>
        )}
      </form>
    </div>
  );
};

const Splash = ({ text, retry }) => (
  <div style={cdcAuthStyles.screen}>
    <div style={{ textAlign: "center" }}>
      <img src="assets/casa-de-casas-logo.jpg" alt="" style={{ ...cdcAuthStyles.logo, opacity: 0.9 }} />
      <div style={{ fontFamily: "var(--cdc-display)", fontSize: 20, color: "var(--cdc-ink)" }}>{text}</div>
      {retry && (
        <button style={{ ...cdcAuthStyles.button, width: "auto", marginTop: 16, padding: "9px 20px" }} onClick={retry}>
          Reintentar
        </button>
      )}
    </div>
  </div>
);

const AuthGate = ({ App }) => {
  const [status, setStatus] = React.useState("checking"); // checking | login | authed | error
  const [staffId, setStaffId] = React.useState(null);

  const check = React.useCallback(async () => {
    setStatus("checking");
    const token = cdcAuth.getToken();
    if (!token) { setStatus("login"); return; }
    try {
      const res = await cdcAuth.validate();
      if (res && res.staffId) { setStaffId(res.staffId); setStatus("authed"); }
      else { cdcAuth.clear(); setStatus("login"); }
    } catch (err) {
      // Error de red/conexión: NO borramos la sesión, ofrecemos reintento.
      setStatus("error");
    }
  }, []);

  React.useEffect(() => {
    if (window.convexClient) { check(); return; }
    const onReady = () => { window.removeEventListener("convex-ready", onReady); check(); };
    window.addEventListener("convex-ready", onReady);
    return () => window.removeEventListener("convex-ready", onReady);
  }, [check]);

  const handleLogin = (id) => { setStaffId(id); setStatus("authed"); };
  const handleLogout = async () => {
    try { await cdcAuth.logout(); } catch (e) {}
    setStaffId(null);
    setStatus("login");
  };

  if (status === "checking") return <Splash text="Cargando…" />;
  if (status === "error") return <Splash text="No se pudo conectar." retry={check} />;
  if (status === "login") return <LoginScreen onLogin={handleLogin} />;
  return <App authUserId={staffId} onLogout={handleLogout} />;
};

Object.assign(window, { AuthGate, LoginScreen, ChangePasswordModal });
