export function initGoogleConsentMode() {
  const CONSENT_KEY = 'decoda_consent';

  try {
    const stored = localStorage.getItem(CONSENT_KEY);
    let hasConsent = false;

    if (stored) {
      try {
        const data = JSON.parse(stored);
        hasConsent = data.accepted === true;
      } catch {
        hasConsent = false;
      }
    }

    window.dataLayer = window.dataLayer || [];

    function gtag() {
      window.dataLayer.push(arguments);
    }

    gtag('consent', 'default', {
      ad_personalization: hasConsent ? 'granted' : 'denied',
      ad_storage: hasConsent ? 'granted' : 'denied',
      ad_user_data: hasConsent ? 'granted' : 'denied',
      ad_user_id: hasConsent ? 'granted' : 'denied',
      analytics_storage: hasConsent ? 'granted' : 'denied',
      functionality_storage: hasConsent ? 'granted' : 'denied',
      personalization_storage: hasConsent ? 'granted' : 'denied',
      security_storage: 'granted',
    });

    return gtag;
  } catch (error) {
    console.error('Error initializing Google Consent Mode:', error);
    return null;
  }
}

export function updateGoogleConsent(hasConsent) {
  window.gtag = window.gtag || (() => {});

  window.gtag('consent', 'update', {
    ad_personalization: hasConsent ? 'granted' : 'denied',
    ad_storage: hasConsent ? 'granted' : 'denied',
    ad_user_data: hasConsent ? 'granted' : 'denied',
    ad_user_id: hasConsent ? 'granted' : 'denied',
    analytics_storage: hasConsent ? 'granted' : 'denied',
    functionality_storage: hasConsent ? 'granted' : 'denied',
    personalization_storage: hasConsent ? 'granted' : 'denied',
  });
}
