'use client';
import React,{createContext,useCallback,useContext,useEffect,useMemo,useState} from 'react';import{ThemeProvider}from 'next-themes';import{Toaster,toast}from 'sonner';import type{Collection,Project,UserView}from '@/lib/models';
type State={user:UserView|null;loading:boolean;projects:Project[];favorites:string[];collections:Collection[];recent:string[];refresh:()=>Promise<void>;refreshData:()=>Promise<void>;logout:()=>Promise<void>;favorite:(slug:string)=>Promise<void>;createFrom:(slug:string)=>Promise<Project|null>;recordUse:(slug:string)=>void};
const C=createContext<State|null>(null);
export function useAccount(){const a=useContext(C);if(!a)throw Error('Account provider not mounted');return a}
async function api(url:string,options?:RequestInit){const r=await fetch(url,{credentials:'same-origin',...options,headers:{'Content-Type':'application/json',...(options?.headers||{})}});const data=await r.json().catch(()=>({}));if(!r.ok)throw Error(data.error||'Something went wrong');return data}
export {api};
function AccountProvider({children}:{children:React.ReactNode}){
 const[user,setUser]=useState<UserView|null>(null);const[loading,setLoading]=useState(true);const[projects,setProjects]=useState<Project[]>([]);const[favorites,setFavorites]=useState<string[]>([]);const[collections,setCollections]=useState<Collection[]>([]);const[recent,setRecent]=useState<string[]>([]);
 const refreshData=useCallback(async()=>{
   try {const x=await api('/api/bootstrap');setProjects(x.projects||[]);setFavorites(x.favorites||[]);setCollections(x.collections||[]);setRecent(x.recent||[])}catch{}
 },[]);
 const refresh=useCallback(async()=>{
   try {const x=await api('/api/bootstrap');setUser(x.user||null);setProjects(x.projects||[]);setFavorites(x.favorites||[]);setCollections(x.collections||[]);setRecent(x.recent||[])}
   catch {setUser(null);setProjects([]);setFavorites([]);setCollections([]);setRecent([])}
   finally {setLoading(false)}
 },[]);
 useEffect(()=>{void refresh()},[refresh]);
 const logout=useCallback(async()=>{await api('/api/auth/logout',{method:'POST'});setUser(null);setProjects([]);setFavorites([]);setCollections([]);setRecent([]);toast.success('You signed out')},[]);
 const favorite=useCallback(async(slug:string)=>{if(!user){toast.info('Sign in to save favorites');return}try{const r=await api('/api/favorites',{method:'POST',body:JSON.stringify({slug,enabled:!favorites.includes(slug)})});setFavorites(r.favorites)}catch(e){toast.error((e as Error).message)}},[user,favorites]);
 const createFrom=useCallback(async(slug:string)=>{if(!user)return null;try{const r=await api('/api/projects',{method:'POST',body:JSON.stringify({templateSlug:slug})});setProjects(old=>[r.project,...old]);return r.project as Project}catch(e){toast.error((e as Error).message);return null}},[user]);
 const recordUse=useCallback((slug:string)=>{if(!user)return;void api('/api/usage',{method:'POST',body:JSON.stringify({slug})}).then(x=>setRecent(x.recent)).catch(()=>{})},[user]);
 const value=useMemo(()=>({user,loading,projects,favorites,collections,recent,refresh,refreshData,logout,favorite,createFrom,recordUse}),[user,loading,projects,favorites,collections,recent,refresh,refreshData,logout,favorite,createFrom,recordUse]);
 return <C.Provider value={value}>{children}</C.Provider>;
}
export function Providers({children}:{children:React.ReactNode}){return <ThemeProvider attribute="class" defaultTheme="dark" enableSystem disableTransitionOnChange><AccountProvider>{children}<Toaster richColors position="top-right"/></AccountProvider></ThemeProvider>}
