"use client";

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

interface ModalProps {
    open: boolean;
    onClose: () => void;
    title?: string;
    children: React.ReactNode;
    footer?: React.ReactNode;
    maxWidth?: string;
}

export default function Modal({
    open,
    onClose,
    title,
    children,
    footer,
    maxWidth = "max-w-[480px] xl:max-w-[580px]",
}: ModalProps) {
    useEffect(() => {
        if (open) {
            document.body.style.overflow = "hidden";
        } else {
            document.body.style.overflow = "";
        }

        return () => {
            document.body.style.overflow = "";
        };
    }, [open]);

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

    return createPortal(
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-light/20 backdrop-blur-[6px] p-4">
            <div
                className={`relative w-full ${maxWidth} rounded-2xl bg-theme-bg p-5 pt-10 md:pt-15 md:p-7.5 shadow-2xl`}
            >
                {/* Close button */}
                <button
                    onClick={onClose}
                    className="absolute top-3 right-3 md:right-6 md:top-6 text-light text-2xl hover:text-primary transition cursor-pointer"
                >
                    ✕
                </button>

                {/* Title */}
                {title && (
                    <h2 className="text-center text-xl md:text-2xl xl:text-3xl 2xl:text-4xl font-bold text-light mb-3">
                        {title}
                    </h2>
                )}

                {/* Content */}
                <div>{children}</div>

                {/* Footer */}
                {footer && (
                    <div className="mt-7 2xl:mt-10 flex justify-center gap-4">
                        {footer}
                    </div>
                )}
            </div>
        </div>,
        document.body
    );
}
