import React from "react";

export function Drawer({ open, defaultOpen = false, onOpenChange, children }) {
  const [internal, setInternal] = React.useState(defaultOpen);
  const isOpen = open !== undefined ? open : internal;
  const set = (v) => { if (open === undefined) setInternal(v); if (onOpenChange) onOpenChange(v); };
  const ctx = { open: isOpen, setOpen: set };
  return <>{React.Children.map(children, (child) => (React.isValidElement(child) ? React.cloneElement(child, { __sheet: ctx }) : child))}</>;
}
export function DrawerTrigger({ __sheet, children }) {
  return React.cloneElement(children, { onClick: () => __sheet && __sheet.setOpen(true) });
}
export function DrawerPopup({ __sheet, className = "", children, ...props }) {
  if (!__sheet || !__sheet.open) return null;
  return (
    <>
      <div className="o-backdrop" data-slot="drawer-backdrop" onClick={() => __sheet.setOpen(false)} />
      <div role="dialog" aria-modal="true" className={["o-sheet o-sheet--bottom", className].filter(Boolean).join(" ")} data-slot="drawer-popup" {...props}>
        <span className="o-drawer__handle" data-slot="drawer-handle" aria-hidden="true" />
        {children}
      </div>
    </>
  );
}
export function DrawerHeader({ className = "", children, ...props }) {
  return <div className={["o-sheet__header", className].filter(Boolean).join(" ")} data-slot="drawer-header" {...props}>{children}</div>;
}
export function DrawerTitle({ className = "", children, ...props }) {
  return <h2 className={["o-dialog__title", className].filter(Boolean).join(" ")} data-slot="drawer-title" {...props}>{children}</h2>;
}
export function DrawerPanel({ className = "", children, ...props }) {
  return <div className={["o-sheet__panel o-scroll", className].filter(Boolean).join(" ")} data-slot="drawer-panel" {...props}>{children}</div>;
}
export function DrawerClose({ __sheet, children }) {
  return React.cloneElement(children, { onClick: () => __sheet && __sheet.setOpen(false) });
}
