import { createContext, useContext, useEffect, useState } from 'react';
import { api } from '@/api';

const AuthContext = createContext(null);

export function AuthProvider({ children }) {
  const [user, setUser]           = useState(undefined); // undefined = loading
  const [singleUserMode, setSUM]  = useState(false);

  useEffect(() => {
    // Check if single-user mode first (bypasses login)
    api.authMode().then(d => {
      if (d.auth_mode === 'single') setSUM(true);
    }).catch(() => {});

    api.me()
      .then(d => { setUser(d.user); setSUM(d.single_user_mode || false); })
      .catch(() => setUser(null));
  }, []);

  const logout = async () => {
    await api.logout();
    setUser(null);
    setSUM(false);
  };

  const refresh = () => {
    api.me()
      .then(d => {
        setUser(d.user);
        setSUM(d.single_user_mode || false);
      })
      .catch(() => {
        setUser(null);
        setSUM(false);
      });
  };

  return (
    <AuthContext.Provider value={{ user, singleUserMode, setUser, logout, refresh }}>
      {children}
    </AuthContext.Provider>
  );
}

export function useAuth() {
  return useContext(AuthContext) || { user: null, setUser: () => {}, logout: () => {}, refresh: () => {}, singleUserMode: false };
}
