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

// Check that the Enzuzo script has loaded
// Polling is the only option for global variables that are not part of React
function useEnzuzoLoaded() {
  const [isLoaded, setIsLoaded] = useState(false);

  useEffect(() => {
    if (isLoaded) return;
    const interval = setInterval(() => {
      if (typeof window !== "undefined" && window.__ENZUZO_STARTED__) {
        setIsLoaded(true);
        clearInterval(interval);
      }
    }, 1_000);
    return () => clearInterval(interval);
  }, [isLoaded]);

  return isLoaded;
}

// Hook to capture a single element
function useCapturedElement<T extends HTMLElement>(selector: string) {
  const [element, setElement] = useState<T | null>(null);
  const [content, setContent] = useState<string>("");
  const isEnzuzoLoaded = useEnzuzoLoaded();

  useEffect(() => {
    if (!isEnzuzoLoaded) return;
    const el = document.querySelector(selector) as T | null;
    if (!el) return;
    setElement(el);
    setContent(el.textContent?.trim() || "");
  }, [selector, isEnzuzoLoaded]);

  const trigger = useCallback(() => {
    if (!element || !("click" in element)) return;
    const event = new MouseEvent("click", {
      bubbles: true,
      cancelable: true,
      view: window
    });
    element.dispatchEvent(event);
  }, [element]);

  return { element, content, trigger };
}

function AcceptButton() {
  const selector = "#ez-cookie-notification__accept";
  const { content, trigger } = useCapturedElement<HTMLButtonElement>(selector);
  return <button onClick={trigger}>{content}</button>;
}

function DeclineButton() {
  const selector = "#ez-cookie-notification__decline";
  const { content, trigger } = useCapturedElement<HTMLButtonElement>(selector);
  return <button onClick={trigger}>{content}</button>;
}

function SettingsButton() {
  const selector = "#notificationManagerLink";
  const { content, trigger } = useCapturedElement<HTMLButtonElement>(selector);
  return <button onClick={trigger}>{content}</button>;
}

function CloseButton() {
  const selector = "#close-notification";
  const { content, trigger } = useCapturedElement<HTMLButtonElement>(selector);
  return <button onClick={trigger}>{content}</button>;
}

function PrivacyPolicyLink() {
  const selector = "#notificationPolicyLink";
  const { element, content } = useCapturedElement<HTMLAnchorElement>(selector);
  return <a href={element?.href}>{content}</a>;
}

function CookieBannerText() {
  const selector = ".enzuzo-notification-desc p";
  const { content } = useCapturedElement<HTMLElement>(selector);
  return <p>{content}</p>;
}

export function CookieBanner() {
  const [isOpen, setIsOpen] = useState(true);
  const { element } = useCapturedElement<HTMLDivElement>("#ez-cookie-notification");

  useEffect(() => {
    if (!element) return;
    if (element.style.display !== "none") setIsOpen(true);
    element.style.display = "none";
  }, [element]);

  if (!isOpen) return null;

  const bannerStyles = {
    position: "fixed" as const,
    top: "16px",
    right: "16px",
    width: "500px",
    backgroundColor: "white",
    borderRadius: "8px",
    boxShadow: "0 25px 50px -12px rgba(0, 0, 0, 0.25)",
    border: "2px solid red",
    padding: "24px",
    zIndex: 2147483647
  };

  return (
    <div style={bannerStyles}>
      <CloseButton />
      <CookieBannerText />
      <PrivacyPolicyLink />
      <SettingsButton />
      <AcceptButton />
      <DeclineButton />
    </div>
  );
}
