"use client";

import { createContext, useContext, useEffect, useState } from "react";

export const AuthContext = createContext<any>(null);

export function AuthProvider({
  children,
}: {
  children: React.ReactNode;
}) {
  const [user, setUser] = useState<any>(null);
  const [clienttoken, setToken] = useState<string>("");
  const [loading, setLoading] = useState(true);

useEffect(() => {
  try {
    const storedUser = localStorage.getItem("customer");
    const cookieToken = getCookie("clienttoken");

    if (storedUser && storedUser !== "undefined" && storedUser !== "null") {
      setUser(JSON.parse(storedUser));
    }

    if (cookieToken) {
      setToken(cookieToken);
    }
  } catch (error) {
    console.error("Auth restore error:", error);
    setUser(null);
    setToken("");
  } finally {
    setLoading(false);
  }
}, []);

const login = (userData: any, authToken: string) => {
  setUser(userData);
  setToken(authToken);

  localStorage.setItem("customer", JSON.stringify(userData));

  const maxAge = 60 * 60 * 24 * 7;

  document.cookie = [
    `clienttoken=${authToken}`,
    "path=/",
    `max-age=${maxAge}`,
    "SameSite=Lax",
  ].join("; ");

  localStorage.removeItem("guestId");
};
  function getCookie(name: string) {
  if (typeof document === "undefined") return null;

  const value = `; ${document.cookie}`;
  const parts = value.split(`; ${name}=`);

  if (parts.length === 2) {
    return parts.pop()?.split(";").shift() || null;
  }

  return null;
}

const logout = () => {
  setUser(null);
  setToken("");

  localStorage.removeItem("customer");
  localStorage.removeItem("guestId");

  document.cookie =
    "clienttoken=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
};

  return (
    <AuthContext.Provider
      value={{
        user,
        clienttoken,
        loading,
        setUser,
        setToken,
        login,
        logout,
        isAuthenticated: !!clienttoken,
      }}
    >
      {children}
    </AuthContext.Provider>
  );
}

export function useAuthContext() {
  const context = useContext(AuthContext);

  if (!context) {
    throw new Error("useAuthContext must be used inside AuthProvider");
  }

  return context;
}
