"use client"

import { createContext, useContext, useEffect, useMemo, useState } from "react"

type AudienceMode = "research" | "policy"

interface AudienceModeContextValue {
  mode: AudienceMode
  setMode: (mode: AudienceMode) => void
}

const AudienceModeContext = createContext<AudienceModeContextValue | null>(null)

const STORAGE_KEY = "eval-cards-audience-mode"

export function AudienceModeProvider({ children }: { children: React.ReactNode }) {
  const [mode, setModeState] = useState<AudienceMode>("research")

  useEffect(() => {
    const storedMode = window.localStorage.getItem(STORAGE_KEY)
    if (storedMode === "research" || storedMode === "policy") {
      setModeState(storedMode)
    }
  }, [])

  const setMode = (nextMode: AudienceMode) => {
    setModeState(nextMode)
    window.localStorage.setItem(STORAGE_KEY, nextMode)
  }

  const value = useMemo(() => ({ mode, setMode }), [mode])

  return (
    <AudienceModeContext.Provider value={value}>
      {children}
    </AudienceModeContext.Provider>
  )
}

export function useAudienceMode() {
  const context = useContext(AudienceModeContext)

  if (!context) {
    throw new Error("useAudienceMode must be used within an AudienceModeProvider")
  }

  return context
}
