"use client";

import { useEffect, useRef, useState } from "react";
import { getCookie, setCookie } from "../../../utils/cookie";
import { TypeComponentRichTextFields } from "./type";

import { MaterialIcon } from "@shared/components/material-icon";
import { Button } from "@shared/contentful/blocks/button";

export default function CookieBanner({
  content,
}: {
  content: TypeComponentRichTextFields;
}) {
  let marginBottom = 3;
  const [isBannerVisible, setIsBannerVisible] = useState(false);
  const [isStickyFooterPresent, setStickyFooterPresent] = useState(false);
  const bannerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const cookieBannerClosed = getCookie("cookieBannerClosed");
    if (cookieBannerClosed === "true") {
      setIsBannerVisible(false);
    } else {
      setIsBannerVisible(true);
    }
  }, []);

  useEffect(() => {
    const checkElementPresence = () => {
      const element = document.getElementById("anchored-banner");
      setStickyFooterPresent(!!element);
    };
    checkElementPresence();
  }, []);

  // Add body class and calculate height for chat positioning
  useEffect(() => {
    if (isBannerVisible) {
      window?.document?.body?.classList.add("cookie-banner-visible");
    } else {
      window?.document?.body?.classList.remove("cookie-banner-visible");
    }

    return () => {
      window?.document?.body?.classList.remove("cookie-banner-visible");
    };
  }, [isBannerVisible]);

  // Calculate cookie banner height and set CSS custom property
  useEffect(() => {
    if (!isBannerVisible) return;

    const calculateCookieBannerHeight = () => {
      if (bannerRef.current) {
        const rect = bannerRef.current.getBoundingClientRect();
        const viewportHeight = window.innerHeight;

        // Calculate how much space the banner occupies from the bottom of the viewport
        // This is: viewport height - distance from top
        const spaceFromBottom = viewportHeight - rect.top;

        document.documentElement.style.setProperty(
          "--cookie-banner-height",
          `${spaceFromBottom}px`
        );
      }
    };

    // Calculate initially after render and after a short delay to ensure layout is complete
    const timer1 = setTimeout(calculateCookieBannerHeight, 100);
    const timer2 = setTimeout(calculateCookieBannerHeight, 300);

    // Recalculate on window resize with debounce
    let resizeTimeout: ReturnType<typeof setTimeout>;
    const handleResize = () => {
      clearTimeout(resizeTimeout);
      resizeTimeout = setTimeout(calculateCookieBannerHeight, 150);
    };

    window.addEventListener("resize", handleResize);

    return () => {
      clearTimeout(timer1);
      clearTimeout(timer2);
      clearTimeout(resizeTimeout);
      window.removeEventListener("resize", handleResize);
      document.documentElement.style.removeProperty("--cookie-banner-height");
    };
  }, [isBannerVisible, isStickyFooterPresent]);

  const handleClose = () => {
    const expirationDate = new Date(Date.now() + 43200 * 60 * 1000);
    setIsBannerVisible(false);
    setCookie("cookieBannerClosed", true, {
      expires: expirationDate,
    });
  };
  if (isStickyFooterPresent) marginBottom = 14;

  // Calculate margin values in pixels for inline styles
  const marginBottomPx = marginBottom * 4; // Tailwind: 3 = 12px, 14 = 56px (each unit is 4px)
  const marginLeftPx = 12; // mx-3 = 12px

  if (!isBannerVisible) return null;

  return (
    <div
      id="cookie-banner"
      ref={bannerRef}
      className="fixed z-[1000] max-w-[350px] rounded-xl bg-white py-5 pl-6 pr-12 text-black shadow-lg ring-1 ring-gray-900/10 md:max-w-[656px]"
      style={{
        // maxWidth: maxWidth,
        bottom: "0px",
        right: "20px",
        marginBottom: `${marginBottomPx}px`,
        marginLeft: `${marginLeftPx}px`,
      }}
      aria-label="Cookie usage notification"
    >
      {" "}
      {
        <Button
          showButtonAs="unstyled"
          buttonClassName="absolute right-2 top-3 mr-2 mt-0 h-6 w-6 bg-white"
          onClick={handleClose}
        >
          <MaterialIcon name="close" />
        </Button>
      }
      {/* {content ? (
        <div className="my-4 mx-auto [&>a]:footnote">
          {renderContentfulRichText(
            toDocument(content.richText),
            false,
            "footnote",
            "footnote",
          )}
        </div>
      ) : null} */}
      {content.richText ? (
        <div className="mx-auto my-4 [&>a]:footnote">{content.richText}</div>
      ) : null}
    </div>
  );
}
