import { createContext, useContext, useMemo, useState } from 'react'
import { readJson, writeJson, storageKeys } from '../lib/storage'

const AuthContext = createContext(null)

/**
 * Demo auth only — creates a local verified session.
 * No passwords are collected or stored. No remote credential endpoints.
 */
export function AuthProvider({ children }) {
  const [user, setUser] = useState(() => readJson(storageKeys.USER_KEY, null))

  const login = (provider) => {
    const next = {
      id: crypto.randomUUID(),
      name: `${provider} voter`,
      provider,
      verified: true,
      signedInAt: new Date().toISOString(),
    }
    writeJson(storageKeys.USER_KEY, next)
    setUser(next)
    return next
  }

  const logout = () => {
    localStorage.removeItem(storageKeys.USER_KEY)
    setUser(null)
  }

  const value = useMemo(() => ({ user, login, logout }), [user])

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

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