import { useEffect } from "react";

interface OffcanvasProps {
    open: boolean;
    title: string;
    onClose: () => void;
    children: React.ReactNode;
    footer?: React.ReactNode;
    width?: string; // optional (default 400px)
}

const Offcanvas = ({
    open,
    title,
    onClose,
    children,
    footer,
    width = "400px",
}: OffcanvasProps) => {
    // close on ESC
    useEffect(() => {
        const handleEsc = (e: KeyboardEvent) => {
            if (e.key === "Escape") onClose();
        };

        if (open) {
            document.addEventListener("keydown", handleEsc);
        }

        return () => document.removeEventListener("keydown", handleEsc);
    }, [open, onClose]);

    if (!open) return null;

    return (
        <div className="fixed inset-0 z-[9999] flex">

            {/* Backdrop */}
            <div
                className="fixed inset-0 bg-black/40"
                onClick={onClose}
            />

            {/* Panel */}
            <div
                className="ml-auto h-full bg-white shadow-xl flex flex-col transform transition-transform duration-300"
                style={{ width }}
            >
                {/* Header */}
                <div className="flex items-center justify-between px-4 py-3 border-b">
                    <h2 className="text-lg font-semibold">{title}</h2>

                    <button
                        onClick={onClose}
                        className="text-gray-500 hover:text-black text-xl"
                    >
                        ✕
                    </button>
                </div>

                {/* Body */}
                <div className="flex-1 overflow-y-auto p-4">
                    {children}
                </div>

                {/* Footer (optional) */}
                {footer && (
                    <div className="border-t p-3 bg-gray-50">
                        {footer}
                    </div>
                )}
            </div>
        </div>
    );
};

export default Offcanvas;