'use client'

import { useState, useEffect, useCallback } from 'react'

export interface Investor {
  id: string
  email: string
  name: string | null
  company: string | null
  status: string
  last_login_at: string | null
  login_count: number
  created_at: string
  is_showcase: boolean
  preferred_lang: 'de' | 'en'
}

export function useAuth() {
  const [investor, setInvestor] = useState<Investor | null>(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    async function fetchMe() {
      try {
        const res = await fetch('/api/auth/me')
        if (res.ok) {
          const data = await res.json()
          setInvestor(data.investor)
        }
      } catch {
        // Not authenticated
      } finally {
        setLoading(false)
      }
    }
    fetchMe()
  }, [])

  const logout = useCallback(async () => {
    await fetch('/api/auth/logout', { method: 'POST' })
    window.location.href = '/auth'
  }, [])

  return { investor, loading, logout }
}
