'use client';

import { useCallback, useEffect, useState } from 'react';

import ReactGA from 'react-ga4';

import { CookieConsent, CookieType } from '@/types/Cookies';

const GA_TRACKING_ID = 'G-EX80K31YPE';

export function useCookieConsent() {
  const [consent, setConsent] = useState<CookieConsent | null>(null);
  const [showModal, setShowModal] = useState(false);

  const COOKIE_NAME = 'azopus-cookie-consent';

  // Google Analytics
  const handleGA = useCallback((keyList: CookieType[]) => {
    if (!keyList || keyList.indexOf('STATISTICS') === -1) {
      console.log('Disable GA');
      if (typeof window !== 'undefined' && ReactGA.ga) {
        ReactGA.ga('set', 'allowGoogleAnalytics', false);
      }
    } else {
      console.log('Enable GA');
      if (typeof window !== 'undefined') {
        ReactGA.initialize(GA_TRACKING_ID);
      }
    }
  }, []);

  const saveConsent = useCallback(
    (keyList: CookieType[]) => {
      handleGA(keyList);

      const cookie = keyList.toString() + '@' + Date.now();
      localStorage.setItem(COOKIE_NAME, cookie);
      window.dispatchEvent(new Event('cookie-consent-accepted'));
      setShowModal(false);

      const consentData: CookieConsent = {
        accepted: keyList,
        timestamp: Date.now(),
      };
      setConsent(consentData);

      // re-check YouTube embeds after saving cookies
      setTimeout(() => {
        // Trigger a global function that any observer can listen to
        window.dispatchEvent(new CustomEvent('reCheckYouTubeEmbeds'));
      }, 100);
    },
    [handleGA]
  );

  // Load consent on mount
  useEffect(() => {
    const cookieConsent = localStorage.getItem(COOKIE_NAME);
    if (cookieConsent) {
      const keyList = cookieConsent.split('@')[0].split(',') as CookieType[];
      handleGA(keyList);

      setConsent({
        accepted: keyList,
        timestamp: parseInt(cookieConsent.split('@')[1]) || Date.now(),
      });
    }

    const showPopup = cookieConsent ? false : true;
    if (showPopup) setTimeout(() => setShowModal(true), 3000);
  }, [handleGA]);

  return {
    consent,
    showModal,
    setShowModal,
    saveConsent,
  };
}
