"use client";

import { createContext, useCallback, useContext, useEffect, useState } from "react";
import Script from "next/script";
import { track } from "@/lib/analytics";
import type { ConsentCopy } from "@/lib/consentCopy";

export type Consent = { analytics: boolean; marketing: boolean };

const STORAGE_KEY = "alterra-consent-v1";
const GA_ID = process.env.NEXT_PUBLIC_GA4_ID;
const PIXEL_ID = process.env.NEXT_PUBLIC_META_PIXEL_ID;

type ConsentState = { consent: Consent | null; save: (c: Consent) => void; openPreferences: () => void };
const ConsentContext = createContext<ConsentState>({ consent: null, save: () => {}, openPreferences: () => {} });
export const useConsent = () => useContext(ConsentContext);

const read = (): Consent | null => {
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    if (!raw) return null;
    const parsed = JSON.parse(raw) as Partial<Consent>;
    return { analytics: parsed.analytics === true, marketing: parsed.marketing === true };
  } catch {
    return null;
  }
};

/**
 * Stores the visitor's cookie choice and loads GA4 / Meta Pixel only for accepted categories.
 * Nothing optional runs before a choice is made, and rejecting is as easy as accepting.
 */
export default function ConsentProvider({ copy, privacyHref, children }: { copy: ConsentCopy; privacyHref: string; children: React.ReactNode }) {
  const [consent, setConsent] = useState<Consent | null>(null);
  const [ready, setReady] = useState(false);
  const [open, setOpen] = useState(false);
  const [custom, setCustom] = useState(false);
  const [draft, setDraft] = useState<Consent>({ analytics: false, marketing: false });

  useEffect(() => {
    const saved = read();
    setConsent(saved);
    setOpen(!saved);
    setReady(true);
  }, []);

  const save = useCallback((next: Consent) => {
    const withdrawn = consent && ((consent.analytics && !next.analytics) || (consent.marketing && !next.marketing));
    try {
      localStorage.setItem(STORAGE_KEY, JSON.stringify({ ...next, at: new Date().toISOString() }));
    } catch {}
    setConsent(next);
    setOpen(false);
    setCustom(false);
    // Scripts already running cannot be unloaded: reload so a withdrawal takes effect immediately.
    if (withdrawn) window.location.reload();
  }, [consent]);

  const openPreferences = useCallback(() => {
    setDraft(consent ?? { analytics: false, marketing: false });
    setCustom(true);
    setOpen(true);
  }, [consent]);

  // WhatsApp clicks anywhere on the site.
  useEffect(() => {
    const onClick = (e: MouseEvent) => {
      if ((e.target as HTMLElement).closest('a[href^="https://wa.me/"]')) track({ name: "Contact", method: "whatsapp" });
    };
    document.addEventListener("click", onClick);
    return () => document.removeEventListener("click", onClick);
  }, []);

  return (
    <ConsentContext.Provider value={{ consent, save, openPreferences }}>
      {children}

      {consent?.analytics && GA_ID && (
        <>
          <Script src={`https://www.googletagmanager.com/gtag/js?id=${GA_ID}`} strategy="afterInteractive" />
          <Script id="ga4" strategy="afterInteractive">
            {`window.dataLayer=window.dataLayer||[];window.gtag=function(){dataLayer.push(arguments);};gtag('js',new Date());gtag('config','${GA_ID}');`}
          </Script>
        </>
      )}
      {consent?.marketing && PIXEL_ID && (
        <Script id="meta-pixel" strategy="afterInteractive">
          {`!function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod?n.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0;t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window,document,'script','https://connect.facebook.net/en_US/fbevents.js');fbq('init','${PIXEL_ID}');fbq('track','PageView');`}
        </Script>
      )}

      {ready && open && (
        <div role="dialog" aria-modal="false" aria-labelledby="consent-title" className="fixed inset-x-3 bottom-3 z-[80] mx-auto max-w-xl border border-ink/10 bg-cream p-6 text-ink shadow-2xl md:inset-x-auto md:left-6 md:bottom-6">
          <p id="consent-title" className="font-serif text-2xl">
            {copy.title}
          </p>
          <p className="mt-2 text-sm leading-relaxed text-stone">
            {copy.text}{" "}
            <a href={privacyHref} className="underline underline-offset-2 hover:text-gold-ink">
              {copy.policy}
            </a>
          </p>

          {custom && (
            <div className="mt-5 space-y-3 border-t border-ink/10 pt-4 text-sm">
              <label className="flex items-start gap-3 opacity-70">
                <input type="checkbox" checked disabled className="mt-1" />
                <span>
                  <span className="font-medium">{copy.necessary}</span>
                  <span className="block text-xs text-stone">{copy.necessaryText}</span>
                </span>
              </label>
              {(["analytics", "marketing"] as const).map((key) => (
                <label key={key} className="flex cursor-pointer items-start gap-3">
                  <input
                    type="checkbox"
                    checked={draft[key]}
                    onChange={(e) => setDraft((d) => ({ ...d, [key]: e.target.checked }))}
                    className="mt-1 accent-[var(--color-forest)]"
                  />
                  <span>
                    <span className="font-medium">{copy[key]}</span>
                    <span className="block text-xs text-stone">{copy[`${key}Text`]}</span>
                  </span>
                </label>
              ))}
            </div>
          )}

          <div className="mt-5 flex flex-wrap gap-2">
            {custom ? (
              <button type="button" onClick={() => save(draft)} className="bg-ink px-5 py-2.5 text-xs tracking-[0.14em] uppercase text-cream hover:bg-forest">
                {copy.save}
              </button>
            ) : (
              <button type="button" onClick={() => setCustom(true)} className="border border-ink/25 px-5 py-2.5 text-xs tracking-[0.14em] uppercase hover:border-ink">
                {copy.customize}
              </button>
            )}
            <button type="button" onClick={() => save({ analytics: false, marketing: false })} className="border border-ink/25 px-5 py-2.5 text-xs tracking-[0.14em] uppercase hover:border-ink">
              {copy.rejectAll}
            </button>
            <button type="button" onClick={() => save({ analytics: true, marketing: true })} className="bg-forest px-5 py-2.5 text-xs tracking-[0.14em] uppercase text-cream hover:bg-ink">
              {copy.acceptAll}
            </button>
          </div>
        </div>
      )}
    </ConsentContext.Provider>
  );
}

/** Footer link to reopen the cookie preferences. */
export function CookiePreferencesButton({ label }: { label: string }) {
  const { openPreferences } = useConsent();
  return (
    <button type="button" onClick={openPreferences} className="transition hover:text-gold-light">
      {label}
    </button>
  );
}

/** Fires a ViewContent event once (property detail pages). */
export function TrackView({ referenceCode, title, value, currency }: { referenceCode: string; title: string; value?: number; currency?: string }) {
  const { consent } = useConsent();
  useEffect(() => {
    if (!consent) return;
    // Give the tag scripts a moment to initialise after consent.
    const id = window.setTimeout(() => track({ name: "ViewContent", referenceCode, title, value, currency }), 800);
    return () => window.clearTimeout(id);
  }, [consent, referenceCode, title, value, currency]);
  return null;
}
