// NOTE: kept intentionally minimal to satisfy react-refresh rules.
// This file should only export React components.

import { useMemo, useState } from 'react'
import { authApi } from '../services/authApi.js'
import { clearToken, decodeUser, readToken, writeToken } from './authSession.js'
import { selectGlobalLoading, useGlobalStore } from './useGlobalStore.js'
import { AuthContext } from './AuthContext.js'

export function AuthProvider({ children }) {
  const [token, setToken] = useState(() => readToken())
  const [user, setUser] = useState(() => decodeUser(readToken()))
  const [loading] = useState(false)

  const globalLoading = useGlobalStore(selectGlobalLoading)

  const value = useMemo(() => {
    return {
      token,
      user,
      loading,
      isAuthenticated: Boolean(token),
      async login({ username, password }) {
        const res = await authApi.login({ username, password })
        const nextToken = res.token
        writeToken(nextToken)
        setToken(nextToken)
        setUser(decodeUser(nextToken))
      },
      async register({ username, password }) {
        await authApi.register({ username, password })
      },
      logout() {
        clearToken()
        setToken(null)
        setUser(null)
      },
      globalLoading,
    }
  }, [token, user, loading, globalLoading])

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


