"use client"

import { useState, useEffect } from "react"
import type { FeatureFlags } from "./flags"
import { FLAG_DEFAULTS } from "./flags"

/**
 * Hook to fetch and access feature flags on the client side
 */
export function useFlags() {
  const [flags, setFlags] = useState<FeatureFlags>(FLAG_DEFAULTS)
  const [isLoading, setIsLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    const fetchFlags = async () => {
      try {
        setIsLoading(true)
        setError(null)
        const response = await fetch("/api/flags")

        if (!response.ok) {
          throw new Error("Failed to load feature flags")
        }

        const data = await response.json()
        setFlags(data.flags || FLAG_DEFAULTS)
      } catch (err) {
        console.error("[useFlags] Error fetching flags:", err)
        setError(err instanceof Error ? err.message : "Unknown error")
        // Fallback to defaults on error
        setFlags(FLAG_DEFAULTS)
      } finally {
        setIsLoading(false)
      }
    }

    fetchFlags()
  }, [])

  return { flags, isLoading, error }
}
