"use client";

import { useEffect, type ReactNode } from "react";
import { X } from "lucide-react";

/**
 * Mobile bottom sheet: slides up from the bottom with a backdrop. Used to host
 * the studio/editor side panels (which are desktop side-docks) on phones.
 */
export function BottomSheet({
  open,
  onClose,
  title,
  children,
  heightClass = "max-h-[72vh]",
}: {
  open: boolean;
  onClose: () => void;
  title?: ReactNode;
  children: ReactNode;
  heightClass?: string;
}) {
  // Lock body scroll while open.
  useEffect(() => {
    if (!open) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => {
      document.body.style.overflow = prev;
    };
  }, [open]);

  return (
    <div
      className={`fixed inset-0 z-50 transition-opacity ${open ? "opacity-100" : "pointer-events-none opacity-0"}`}
      aria-hidden={!open}
    >
      <div className="absolute inset-0 bg-black/50" onClick={onClose} />
      <div
        role="dialog"
        aria-modal="true"
        className={`absolute inset-x-0 bottom-0 flex flex-col rounded-t-2xl border-t border-gray-200 bg-white shadow-2xl transition-transform duration-200 ${heightClass} ${open ? "translate-y-0" : "translate-y-full"}`}
      >
        <div className="flex items-center justify-between border-b border-gray-100 px-4 py-2.5">
          <div className="mx-auto h-1 w-10 rounded-full bg-gray-300" aria-hidden />
        </div>
        {title && (
          <div className="flex items-center justify-between border-b border-gray-100 px-4 py-2">
            <span className="text-sm font-semibold text-gray-900">{title}</span>
            <button
              type="button"
              onClick={onClose}
              aria-label="close"
              className="rounded-lg p-1 text-gray-500 hover:bg-gray-100"
            >
              <X className="h-5 w-5" aria-hidden />
            </button>
          </div>
        )}
        <div className="min-h-0 flex-1 overflow-y-auto overscroll-contain">{children}</div>
      </div>
    </div>
  );
}
