'use client'

import { useEffect, useState } from 'react'
import { OPEN_COOKIE_PREFERENCES_EVENT } from '@/lib/consent/cookie-consent'
import { useCookieConsent } from '@/hooks/use-cookie-consent'
import { CookieConsentBanner } from './cookie-consent-banner'
import { CookiePreferencesDialog } from './cookie-preferences-dialog'

export function CookieConsentRoot() {
  const { needsBanner, ready } = useCookieConsent()
  const [preferencesOpen, setPreferencesOpen] = useState(false)

  useEffect(() => {
    const open = () => setPreferencesOpen(true)
    window.addEventListener(OPEN_COOKIE_PREFERENCES_EVENT, open)
    return () => window.removeEventListener(OPEN_COOKIE_PREFERENCES_EVENT, open)
  }, [])

  if (!ready) return null

  return (
    <>
      {needsBanner && (
        <CookieConsentBanner
          onManage={() => setPreferencesOpen(true)}
        />
      )}
      <CookiePreferencesDialog open={preferencesOpen} onOpenChange={setPreferencesOpen} />
    </>
  )
}
