import { jsx, Fragment } from 'react/jsx-runtime';
import { createContext, useState, useEffect, useContext } from 'react';

const AuthContext = createContext({
  user: null,
  loading: true,
  login: async () => false,
  logout: () => {
  },
  token: null
});
function useAuth() {
  return useContext(AuthContext);
}
function AuthProvider({ children }) {
  const [user, setUser] = useState(null);
  const [token, setToken] = useState(null);
  const [loading, setLoading] = useState(true);
  useEffect(() => {
    const saved = localStorage.getItem("admin_token");
    if (saved) {
      setToken(saved);
      fetch("/api/admin/auth/session", { headers: { Authorization: `Bearer ${saved}` } }).then((r) => r.ok ? r.json() : null).then((data) => {
        if (data?.authenticated) setUser(data.user);
        else localStorage.removeItem("admin_token");
      }).catch(() => localStorage.removeItem("admin_token")).finally(() => setLoading(false));
    } else {
      setLoading(false);
    }
  }, []);
  const login = async (email, password) => {
    const res = await fetch("/api/admin/auth/login", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ email, password })
    });
    if (!res.ok) return false;
    const data = await res.json();
    setToken(data.token);
    setUser(data.user);
    localStorage.setItem("admin_token", data.token);
    return true;
  };
  const logout = () => {
    setUser(null);
    setToken(null);
    localStorage.removeItem("admin_token");
    document.cookie = "admin_token=; Path=/; Max-Age=0";
  };
  return /* @__PURE__ */ jsx(AuthContext.Provider, { value: { user, loading, login, logout, token }, children });
}
function AuthGuard({ children }) {
  const { user, loading } = useAuth();
  if (loading) return /* @__PURE__ */ jsx("div", { className: "flex items-center justify-center min-h-screen bg-[#0A0A0A]", children: /* @__PURE__ */ jsx("div", { className: "w-8 h-8 border-2 border-[#00FF6A] border-t-transparent rounded-full animate-spin" }) });
  if (!user) {
    window.location.href = "/admin/login";
    return null;
  }
  return /* @__PURE__ */ jsx(Fragment, { children });
}

export { AuthProvider as A, AuthGuard as a, useAuth as u };
