import { createContext, useContext, useState, useEffect } from 'react'
import api from '../services/api.js'

const AuthContext = createContext()

export function useAuth() {
  return useContext(AuthContext)
}

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

  // Restore session from localStorage on mount
  useEffect(() => {
    const savedUser = localStorage.getItem('optiq_user')
    const savedToken = localStorage.getItem('optiq_token')
    if (savedUser && savedToken) {
      setUser(JSON.parse(savedUser))
      setToken(savedToken)
    }
    setLoading(false)
  }, [])

  // Keep api.js token in sync
  useEffect(() => {
    if (token) {
      api.setToken(token)
    }
  }, [token])

  const signIn = async (email, password) => {
    const res = await fetch('/api/auth/login', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email, password }),
    })
    const data = await res.json()
    if (!res.ok) throw new Error(data.detail || 'Failed to sign in')

    const userObj = { uid: data.user.uid, email: data.user.email, displayName: data.user.displayName }
    localStorage.setItem('optiq_user', JSON.stringify(userObj))
    localStorage.setItem('optiq_token', data.token)
    setUser(userObj)
    setToken(data.token)
    return userObj
  }

  const signUp = async (email, password, displayName) => {
    const res = await fetch('/api/auth/register', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email, password, display_name: displayName }),
    })
    const data = await res.json()
    if (!res.ok) throw new Error(data.detail || 'Failed to create account')

    const userObj = { uid: data.user.uid, email: data.user.email, displayName: data.user.displayName }
    localStorage.setItem('optiq_user', JSON.stringify(userObj))
    localStorage.setItem('optiq_token', data.token)
    setUser(userObj)
    setToken(data.token)
    return userObj
  }

  const signOut = async () => {
    localStorage.removeItem('optiq_user')
    localStorage.removeItem('optiq_token')
    setUser(null)
    setToken(null)
  }

  const value = {
    user,
    token,
    loading,
    isDemo: false,
    signIn,
    signUp,
    signInWithGoogle: null,   // not available with SQLite auth
    signOut
  }

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