import React, { createContext, useState, useContext, useEffect } from 'react';
import { studioClient } from '@/api/studioClient';
import { runtimeConfig } from '@/lib/runtime-config';
const AuthContext = createContext();
export const AuthProvider = ({ children }) => {
  const [user,setUser]=useState(null), [isAuthenticated,setAuthenticated]=useState(false), [isLoadingAuth,setLoading]=useState(true);
  useEffect(()=>{(async()=>{if(!runtimeConfig.requireAuth){setUser({id:'shire-user',full_name:'SHiRE Operator',role:'administrator'});setAuthenticated(true);setLoading(false);return;}try{const u=await studioClient.auth.me();setUser(u);setAuthenticated(true);}catch{}finally{setLoading(false);}})()},[]);
  const login=async(email,password)=>{const u=await studioClient.auth.loginViaEmailPassword(email,password);setUser(u);setAuthenticated(true);return u};
  const logout=(redirect=true)=>{studioClient.auth.logout(redirect?'/login':null);setUser(null);setAuthenticated(false)};
  return <AuthContext.Provider value={{user,isAuthenticated,isLoadingAuth,isLoadingPublicSettings:false,authError:null,appPublicSettings:{id:'self-hosted'},authChecked:!isLoadingAuth,login,logout,navigateToLogin:()=>location.assign('/login'),checkUserAuth:async()=>{},checkAppState:async()=>{}}}>{children}</AuthContext.Provider>;
};
export const useAuth=()=>{const c=useContext(AuthContext);if(!c)throw new Error('useAuth must be used within AuthProvider');return c};
