"use client";

import Script from "next/script";
import { usePathname } from "next/navigation";
import { useCallback, useEffect, useRef, useState } from "react";
import { connectAnalytics, trackPageView, type ConsentAPI } from "./analytics";

// Replace both values. Enable the Analytics category in Polimeo first.
const SERVICE_ID = "YOUR_SERVICE_ID";
const GA_ID = "G-YOURMEASUREMENTID";
const getAPI = () =>
  (window as Window & { PremexConsent?: ConsentAPI }).PremexConsent;

export default function PolimeoConsent() {
  const pathname = usePathname();
  const cleanup = useRef<(() => void) | undefined>(undefined);
  const [ready, setReady] = useState(false);
  const [failed, setFailed] = useState(false);
  const connect = useCallback(() => {
    const api = getAPI();
    if (!api || cleanup.current) return;
    cleanup.current = connectAnalytics(api, GA_ID);
  }, []);

  useEffect(() => {
    // Also reconnect after a development Strict Mode remount.
    connect();
    return () => {
      cleanup.current?.();
      cleanup.current = undefined;
    };
  }, [connect]);
  useEffect(() => {
    if (pathname) trackPageView(pathname);
  }, [pathname]);

  return (
    <>
      <Script
        id="polimeo-consent"
        src={`https://polimeo.com/widget/${SERVICE_ID}`}
        strategy="afterInteractive"
        onReady={() => {
          connect();
          setReady(Boolean(getAPI()));
          setFailed(false);
        }}
        onError={() => setFailed(true)}
      />
      <button type="button" disabled={!ready} onClick={() => getAPI()?.showBanner()}>
        Cookie settings
      </button>
      {failed && <p role="status">Cookie settings could not load. Reload to retry.</p>}
    </>
  );
}
