"use client";

import { useEffect } from "react";
import { createPortal } from "react-dom";
import { X } from "lucide-react";

import DemoForm from "@/components/demo/DemoForm";
import { demoCopy } from "@/components/demo/demo-copy";
import type { Locale } from "@/lib/locales";
import type { ProductSlug } from "@/lib/routes";

export default function DemoModal({
  locale,
  onClose,
  open,
  productSlug,
}: {
  locale: Locale;
  onClose: () => void;
  open: boolean;
  productSlug?: ProductSlug;
}) {
  const copy = demoCopy[locale];

  useEffect(() => {
    if (!open) return;
    function handleEscape(event: KeyboardEvent) {
      if (event.key === "Escape") onClose();
    }
    document.body.style.overflow = "hidden";
    document.addEventListener("keydown", handleEscape);
    return () => {
      document.body.style.overflow = "";
      document.removeEventListener("keydown", handleEscape);
    };
  }, [onClose, open]);

  if (!open || typeof document === "undefined") return null;

  return createPortal(
    <div className="fixed inset-0 z-[100] grid place-items-center overflow-y-auto bg-slate-950/45 p-4 backdrop-blur-sm" role="dialog" aria-label={copy.title} aria-modal="true">
      <button type="button" aria-label={copy.close} className="absolute inset-0 cursor-default" onClick={onClose} />
      <div className="relative my-auto w-full max-w-2xl">
        <button type="button" aria-label={copy.close} onClick={onClose} className="absolute right-3 top-3 z-10 grid h-9 w-9 place-items-center rounded-xl border border-[#e2e7f2] bg-white text-[#64708a] shadow-sm transition hover:text-[#253052]">
          <X size={18} />
        </button>
        <DemoForm locale={locale} onSuccess={onClose} productSlug={productSlug} />
      </div>
    </div>,
    document.body,
  );
}
