"use client";

import { ReactNode, useEffect } from "react";

interface SheetProps {
  open: boolean;
  onClose: () => void;
  children: ReactNode;
  title?: string;
  side?: "bottom" | "right";
}

export function Sheet({ open, onClose, children, title, side = "bottom" }: SheetProps) {
  useEffect(() => {
    if (!open) return;
    const handle = (e: KeyboardEvent) => { if (e.key === "Escape") onClose(); };
    document.addEventListener("keydown", handle);
    return () => document.removeEventListener("keydown", handle);
  }, [open, onClose]);

  if (!open) return null;

  const sheetClass = side === "bottom"
    ? "bottom-0 left-0 right-0 rounded-t-2xl max-h-[85vh]"
    : "right-0 top-0 bottom-0 rounded-l-2xl w-80";

  return (
    <div className="fixed inset-0 z-50">
      <div className="fixed inset-0 bg-black/50" onClick={onClose} />
      <div className={`fixed bg-white dark:bg-gray-800 shadow-xl overflow-y-auto ${sheetClass}`}>
        <div className="p-4">
          {side === "bottom" && (
            <div className="w-10 h-1 bg-gray-200 dark:bg-gray-600 rounded-full mx-auto mb-4" />
          )}
          {title && (
            <div className="flex items-center justify-between mb-4">
              <h2 className="font-semibold text-gray-900 dark:text-white">{title}</h2>
              <button onClick={onClose} className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-200 text-xl leading-none">×</button>
            </div>
          )}
          {children}
        </div>
      </div>
    </div>
  );
}
