"use client";

/**
 * کشوی کناری / برگه پایینی (روی موبایل از پایین، روی دسکتاپ از کنار).
 * با Escape بسته می‌شود و اسکرول صفحه پشت آن قفل می‌شود.
 * در body رندر می‌شود (portal)، چون والدی با backdrop-blur (مثل هدر) موقعیت fixed را به خودش محدود می‌کند.
 */
import { useEffect, type ReactNode } from "react";
import { createPortal } from "react-dom";
import { Icon } from "./Icon";

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

export function Sheet({ open, onClose, title, children, footer, side = "bottom" }: Props) {
  useEffect(() => {
    if (!open) return;
    const onKey = (e: KeyboardEvent) => e.key === "Escape" && onClose();
    document.addEventListener("keydown", onKey);
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => {
      document.removeEventListener("keydown", onKey);
      document.body.style.overflow = prev;
    };
  }, [open, onClose]);

  if (!open) return null;

  const panel =
    side === "bottom"
      ? "inset-x-0 bottom-0 max-h-[88dvh] rounded-t-3xl animate-slide-up md:inset-y-0 md:start-0 md:bottom-auto md:h-dvh md:max-h-none md:w-[420px] md:rounded-none md:animate-fade-in"
      : "inset-y-0 start-0 h-dvh w-[88vw] max-w-[420px] animate-fade-in";

  return createPortal(
    <div className="fixed inset-0 z-50" role="dialog" aria-modal="true" aria-label={title}>
      <button aria-label="بستن" className="absolute inset-0 animate-fade-in bg-ink/40" onClick={onClose} />
      <div className={`absolute flex flex-col bg-paper ${panel}`}>
        <div className="flex h-14 shrink-0 items-center justify-between border-b border-line px-5">
          <h2 className="text-base font-bold">{title}</h2>
          <button onClick={onClose} aria-label="بستن" className="-me-2 p-2">
            <Icon name="close" />
          </button>
        </div>
        <div className="flex-1 overflow-y-auto overscroll-contain">{children}</div>
        {footer && <div className="pb-safe shrink-0 border-t border-line p-4">{footer}</div>}
      </div>
    </div>,
    document.body,
  );
}
