import React, { useEffect, useRef } from "react";
import { createPortal } from "react-dom";
export function Modal({ isOpen, onClose, children, className }) {
    const overlayRef = useRef(null);
    const containerRef = useRef(null);
    useEffect(() => {
        const handleClickOutside = (event) => {
            if (containerRef.current &&
                !containerRef.current.contains(event.target)) {
                onClose();
            }
        };
        if (isOpen)
            document.addEventListener("mousedown", handleClickOutside);
        return () => document.removeEventListener("mousedown", handleClickOutside);
    }, [isOpen, onClose]);
    useEffect(() => {
        if (isOpen) {
            const originalOverflow = document.body.style.overflow;
            document.body.style.overflow = "hidden";
            return () => {
                document.body.style.overflow = originalOverflow;
            };
        }
    }, [isOpen]);
    useEffect(() => {
        if (!isOpen || !containerRef.current)
            return;
        const container = containerRef.current;
        const focusableElements = container.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');
        const firstElement = focusableElements[0];
        const lastElement = focusableElements[focusableElements.length - 1];
        const handleTabKey = (e) => {
            if (e.key !== "Tab")
                return;
            if (e.shiftKey) {
                if (document.activeElement === firstElement) {
                    e.preventDefault();
                    lastElement?.focus();
                }
            }
            else {
                if (document.activeElement === lastElement) {
                    e.preventDefault();
                    firstElement?.focus();
                }
            }
        };
        container.addEventListener("keydown", handleTabKey);
        return () => container.removeEventListener("keydown", handleTabKey);
    }, [isOpen]);
    if (!isOpen || typeof document === "undefined")
        return null;
    const modalContent = (React.createElement("div", { ref: overlayRef, className: `seekora-docsearch-overlay${className ? ` ${className}` : ""}`, role: "dialog", "aria-modal": "true", "aria-label": "Search documentation" },
        React.createElement("div", { ref: containerRef, className: "seekora-docsearch-container" }, children)));
    return createPortal(modalContent, document.body);
}
