import { createContext, useContext, useState, useEffect } from 'react' import type { ReactNode } from 'react' import axios from 'axios' import type { User } from '../types' const TOKEN_KEY = 'sd_token' // Service Desk specific key interface AuthContextType { user: User | null loading: boolean setToken: (token: string) => void logout: () => void } const AuthContext = createContext(undefined) export function AuthProvider({ children }: { children: ReactNode }) { const [user, setUser] = useState(null) const [loading, setLoading] = useState(true) useEffect(() => { // Check for token in URL (from platform iframe) const params = new URLSearchParams(window.location.search) const urlToken = params.get('token') if (urlToken) { localStorage.setItem(TOKEN_KEY, urlToken) // Clean URL but keep the path window.history.replaceState({}, '', window.location.pathname) } const token = localStorage.getItem(TOKEN_KEY) if (!token) { setLoading(false) return } axios.get('/api/v1/auth/me', { headers: { Authorization: `Bearer ${token}` } }) .then(res => setUser(res.data)) .catch(() => { localStorage.removeItem(TOKEN_KEY) setUser(null) }) .finally(() => setLoading(false)) }, []) const setToken = (token: string) => { localStorage.setItem(TOKEN_KEY, token) axios.get('/api/v1/auth/me', { headers: { Authorization: `Bearer ${token}` } }) .then(res => setUser(res.data)) .catch(() => { localStorage.removeItem(TOKEN_KEY) setUser(null) }) } const logout = () => { localStorage.removeItem(TOKEN_KEY) // Only remove SD token setUser(null) } return ( {children} ) } export function useAuth() { const ctx = useContext(AuthContext) if (!ctx) throw new Error('useAuth must be inside AuthProvider') return ctx }