import { createContext, useContext, useState, useEffect, useCallback } from 'react'
import api from '../utils/api'

const AuthContext = createContext(null)

export function AuthProvider({ children }) {
  const [user, setUser] = useState(null)
  const [loading, setLoading] = useState(true)

  const checkAuth = useCallback(async () => {
    const token = localStorage.getItem('authToken')
    if (!token) {
      setLoading(false)
      return
    }

    try {
      const profile = await api.getCurrentProfile()
      setUser(profile)
    } catch (err) {
      console.error('Auth check failed:', err)
      localStorage.removeItem('authToken')
    } finally {
      setLoading(false)
    }
  }, [])

  useEffect(() => {
    checkAuth()
  }, [checkAuth])

  /** Fallback, falls ohne checkAuth gesetzt wird (Legacy / Token-Injektion) */
  const login = (payload) => {
    if (payload?.profile != null) {
      setUser(payload.profile)
      return
    }
    const p = payload
    if (p?.profile_id != null || p?.id != null) {
      setUser({
        id: p.profile_id ?? p.id,
        name: p.name ?? null,
        email: p.email ?? null,
        role: p.role ?? 'user',
        tier: p.tier ?? 'free',
      })
      return
    }
    setUser(payload)
  }

  const logout = () => {
    setUser(null)
    localStorage.removeItem('authToken')
  }

  const value = {
    user,
    isAuthenticated: !!user,
    loading,
    login,
    logout,
    checkAuth
  }

  return (
    <AuthContext.Provider value={value}>
      {children}
    </AuthContext.Provider>
  )
}

export function useAuth() {
  const context = useContext(AuthContext)
  if (!context) {
    throw new Error('useAuth must be used within AuthProvider')
  }
  return context
}

export default AuthContext
