/* CookieBanner.jsx — DSGVO-konformer Cookie-Banner mit Granular-Settings, DE/EN */

const CONSENT_STORAGE_KEY = 'cawi-cookie-consent-v1';
const CONSENT_EVENT = 'cawi-consent-changed';

/* Helper: localStorage lesen/schreiben */
const readConsent = () => {
  try {
    const raw = localStorage.getItem(CONSENT_STORAGE_KEY);
    if (!raw) return null;
    return JSON.parse(raw);
  } catch (e) { return null; }
};
const writeConsent = (consent) => {
  try {
    localStorage.setItem(CONSENT_STORAGE_KEY, JSON.stringify({
      ...consent,
      version: 1,
      timestamp: new Date().toISOString(),
    }));
    /* Forward to Google Consent Mode v2 (set up in tracking.js) */
    if (typeof window.gtag === 'function') {
      window.gtag('consent', 'update', {
        'analytics_storage': consent.statistics ? 'granted' : 'denied',
        'ad_storage': consent.marketing ? 'granted' : 'denied',
        'ad_user_data': consent.marketing ? 'granted' : 'denied',
        'ad_personalization': consent.marketing ? 'granted' : 'denied',
      });
    }
    window.dispatchEvent(new CustomEvent(CONSENT_EVENT, { detail: consent }));
  } catch (e) {}
};

/* Helper: Sprache aus URL detektieren */
/* Vercel strips trailing slashes, so '/en' and '/en/' must both count as EN. */
const isEnglish = () => typeof window !== 'undefined' && (window.location.pathname === '/en' || window.location.pathname.startsWith('/en/'));

/* i18n-Texte */
const T = {
  de: {
    title: 'Wir nutzen Cookies',
    body: 'Diese Seite nutzt Cookies, um die Terminbuchung über Cal.com zu ermöglichen und die Nutzung statistisch auszuwerten. Notwendige Cookies sind immer aktiv. Mehr Infos in unserer ',
    privacyLinkText: 'Datenschutzerklärung',
    acceptAll: 'Alle akzeptieren',
    details: 'Details',
    saveSelection: 'Auswahl speichern',
    necessaryLabel: 'Notwendig',
    necessaryDesc: 'Speicherung Ihrer Cookie-Einstellungen. Immer aktiv.',
    functionalLabel: 'Funktional',
    functionalDesc: 'Cal.com-Terminbuchung. Ohne diese Cookies können Sie keinen Termin direkt auf der Seite buchen.',
    statisticsLabel: 'Statistik',
    statisticsDesc: 'Google Analytics 4 (über Google Tag Manager, anonymisiert via Consent Mode). Hilft uns zu verstehen, welche Inhalte ankommen.',
    marketingLabel: 'Marketing',
    marketingDesc: 'Tracking für Werbe-Optimierung (z.B. Meta-Pixel) — aktuell nicht aktiv, wird mit künftigen Kampagnen verfügbar.',
    detailsTitle: 'Cookie-Einstellungen',
    detailsIntro: 'Wählen Sie individuell, welche Kategorien Sie zulassen möchten.',
    closeAria: 'Schließen',
  },
  en: {
    title: 'We use cookies',
    body: 'This site uses cookies to enable Cal.com appointment booking and to analyze usage. Necessary cookies are always active. More info in our ',
    privacyLinkText: 'privacy policy',
    acceptAll: 'Accept all',
    details: 'Details',
    saveSelection: 'Save selection',
    necessaryLabel: 'Necessary',
    necessaryDesc: 'Stores your cookie preferences. Always active.',
    functionalLabel: 'Functional',
    functionalDesc: 'Cal.com appointment booking. Without these cookies you cannot book an appointment directly on the site.',
    statisticsLabel: 'Statistics',
    statisticsDesc: 'Google Analytics 4 (via Google Tag Manager, anonymized via Consent Mode). Helps us understand which content resonates.',
    marketingLabel: 'Marketing',
    marketingDesc: 'Tracking for ad optimization (e.g. Meta Pixel) — currently inactive, will become available with future campaigns.',
    detailsTitle: 'Cookie settings',
    detailsIntro: 'Choose individually which categories you allow.',
    closeAria: 'Close',
  },
};

const CookieBanner = () => {
  const [hasDecided, setHasDecided] = React.useState(true); /* default: nicht zeigen, bis localStorage geprüft */
  const [showDetails, setShowDetails] = React.useState(false);
  const [prefs, setPrefs] = React.useState({
    necessary: true,
    functional: false,
    statistics: false,
    marketing: false,
  });

  React.useEffect(() => {
    const consent = readConsent();
    if (!consent) setHasDecided(false);
  }, []);

  const lang = isEnglish() ? 'en' : 'de';
  const t = T[lang];
  const privacyHref = lang === 'en' ? '/en/datenschutz.html' : 'datenschutz.html';

  if (hasDecided) return null;

  const acceptAll = () => {
    writeConsent({ necessary: true, functional: true, statistics: true, marketing: true });
    setHasDecided(true);
  };
  const saveSelection = () => {
    writeConsent({ ...prefs, necessary: true });
    setHasDecided(true);
  };
  const togglePref = (key) => setPrefs(p => ({ ...p, [key]: !p[key] }));

  return (
    <>
      {!showDetails && (
        <div className="cookie-banner" role="dialog" aria-labelledby="cookie-banner-title">
          <div className="cookie-banner-inner">
            <div className="cookie-banner-text">
              <h2 id="cookie-banner-title">{t.title}</h2>
              <p>
                {t.body}
                <a href={privacyHref}>{t.privacyLinkText}</a>.
              </p>
            </div>
            <div className="cookie-banner-actions">
              <button type="button" className="cookie-btn cookie-btn-secondary" onClick={() => setShowDetails(true)}>
                {t.details}
              </button>
              <button type="button" className="cookie-btn cookie-btn-primary" onClick={acceptAll}>
                {t.acceptAll}
              </button>
            </div>
          </div>
        </div>
      )}

      {showDetails && (
        <div className="cookie-modal-backdrop" role="dialog" aria-modal="true" aria-labelledby="cookie-modal-title">
          <div className="cookie-modal">
            <div className="cookie-modal-header">
              <h2 id="cookie-modal-title">{t.detailsTitle}</h2>
              <p>{t.detailsIntro}</p>
            </div>
            <div className="cookie-modal-body">
              {[
                { key: 'necessary', label: t.necessaryLabel, desc: t.necessaryDesc, disabled: true },
                { key: 'functional', label: t.functionalLabel, desc: t.functionalDesc },
                { key: 'statistics', label: t.statisticsLabel, desc: t.statisticsDesc },
                { key: 'marketing', label: t.marketingLabel, desc: t.marketingDesc },
              ].map(cat => (
                <label key={cat.key} className="cookie-cat">
                  <div className="cookie-cat-text">
                    <div className="cookie-cat-label">{cat.label}</div>
                    <div className="cookie-cat-desc">{cat.desc}</div>
                  </div>
                  <span className={`cookie-toggle ${prefs[cat.key] ? 'on' : 'off'} ${cat.disabled ? 'disabled' : ''}`}>
                    <input
                      type="checkbox"
                      checked={prefs[cat.key]}
                      onChange={() => !cat.disabled && togglePref(cat.key)}
                      disabled={cat.disabled}
                      aria-label={cat.label}
                    />
                    <span className="cookie-toggle-thumb" />
                  </span>
                </label>
              ))}
            </div>
            <div className="cookie-modal-footer">
              <button type="button" className="cookie-btn cookie-btn-secondary" onClick={saveSelection}>
                {t.saveSelection}
              </button>
              <button type="button" className="cookie-btn cookie-btn-primary" onClick={acceptAll}>
                {t.acceptAll}
              </button>
            </div>
          </div>
        </div>
      )}
    </>
  );
};

/* Public helper: prüft ob Kategorie aktiv ist (für Cal.com etc.) */
window.cawiHasConsent = (category) => {
  const c = readConsent();
  if (!c) return false;
  if (category === 'necessary') return true;
  return Boolean(c[category]);
};
window.cawiOnConsentChange = (callback) => {
  window.addEventListener(CONSENT_EVENT, (e) => callback(e.detail));
};

window.CookieBanner = CookieBanner;
