"use client"

import { useState, useEffect } from 'react'
import { clientFetch } from '@/lib/api/api-client'

interface Vendor {
  _id: string;
  username: string;
  storeId: string;
  pgpKey: string;
  __v: number;
}

interface User {
  vendor: Vendor;
}

export function useUser() {
  const [user, setUser] = useState<User | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    const fetchUser = async () => {
      try {
        setLoading(true)
        const userData = await clientFetch<User>("/auth/me")
        setUser(userData)
        setError(null)
      } catch (err) {
        console.error("Failed to fetch user:", err)
        setError("Failed to fetch user data")
        setUser(null)
      } finally {
        setLoading(false)
      }
    }

    fetchUser()
  }, [])

  const isAdmin = user?.vendor?.username === 'admin1'

  return {
    user,
    loading,
    error,
    isAdmin
  }
}
