'use client';

import { createContext, useContext, useState, useEffect, useCallback, type ReactNode } from 'react';
import { setTokens, clearTokens, initAuth, isLoggedIn, apiLogout, getToken } from './auth';

interface AuthContextType {
  isLoggedIn: boolean;
  initialized: boolean;
  login: (token: string, refreshToken?: string) => void;
  logout: () => void;
}

const AuthContext = createContext<AuthContextType>({
  isLoggedIn: false,
  initialized: false,
  login: () => {},
  logout: () => {},
});

export function AuthProvider({ children }: { children: ReactNode }) {
  const [initialized, setInitialized] = useState(false);

  useEffect(() => {
    initAuth().then(() => setInitialized(true));
  }, []);

  const login = useCallback((token: string, refreshTk?: string) => {
    setTokens(token, refreshTk);
  }, []);

  const logout = useCallback(() => {
    apiLogout();
  }, []);

  return (
    <AuthContext.Provider value={{ isLoggedIn: isLoggedIn() || !!getToken(), initialized, login, logout }}>
      {children}
    </AuthContext.Provider>
  );
}

export function useAuth() {
  return useContext(AuthContext);
}
