"use client"

import { useEffect } from "react"
import Script from "next/script"

export default function Analytics() {
  useEffect(() => {
    // Listen for consent event
    const handleConsentGranted = () => {
      // Initialize GA when consent is granted
      if (window.gtag) {
        window.gtag("consent", "update", {
          analytics_storage: "granted",
        })
      }
    }

    window.addEventListener("consentGranted", handleConsentGranted)

    // Check if consent was previously granted
    try {
      const consentState = localStorage.getItem("qv-cc-state")
      if (consentState) {
        const { analytics } = JSON.parse(consentState)
        if (analytics) {
          // Dispatch event to initialize GA
          window.dispatchEvent(new Event("consentGranted"))
        }
      }
    } catch (error) {
      console.error("Error checking consent state:", error)
    }

    return () => {
      window.removeEventListener("consentGranted", handleConsentGranted)
    }
  }, [])

  return (
    <>
      {/* Google Analytics Script */}
      <Script
        strategy="lazyOnload"
        src={`https://www.googletagmanager.com/gtag/js?id=${process.env.NEXT_PUBLIC_GA_ID}`}
      />
      <Script
        id="gtag-init"
        strategy="lazyOnload"
        dangerouslySetInnerHTML={{
          __html: `
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            
            // Default to denied until consent is given
            gtag('consent', 'default', {
              'analytics_storage': 'denied'
            });
            
            gtag('config', '${process.env.NEXT_PUBLIC_GA_ID}', {
              page_path: window.location.pathname,
            });
          `,
        }}
      />
    </>
  )
}
