import { createContext, useContext, useState } from 'react'
import type { User, AuthSession } from '../types'
import { MOCK_USERS } from '../data/mockData'

interface AuthContextValue {
  session: AuthSession | null
  user: User | null
  login: (email: string, password: string) => Promise<User | null>
  logout: () => void
}

const AuthContext = createContext<AuthContextValue | null>(null)

export function AuthProvider({ children }: { children: React.ReactNode }) {
  const [session, setSession] = useState<AuthSession | null>(() => {
    const stored = sessionStorage.getItem('hotelsync-session')
    return stored ? JSON.parse(stored) : null
  })

  const login = async (email: string, _password: string): Promise<User | null> => {
    // Mock authentication — in production, call POST /auth/login
    await new Promise(r => setTimeout(r, 800))
    const user = MOCK_USERS.find(u => u.email.toLowerCase() === email.toLowerCase())
    if (!user) return null
    const s: AuthSession = { user, token: 'mock-jwt-token-' + user.id }
    setSession(s)
    sessionStorage.setItem('hotelsync-session', JSON.stringify(s))
    return user
  }

  const logout = () => {
    setSession(null)
    sessionStorage.removeItem('hotelsync-session')
  }

  return (
    <AuthContext.Provider value={{ session, user: session?.user ?? null, login, logout }}>
      {children}
    </AuthContext.Provider>
  )
}

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