import React from "react";

export function Sheet({ 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 SheetTrigger({ __sheet, children }) {
  return React.cloneElement(children, { onClick: () => __sheet && __sheet.setOpen(true) });
}
export function SheetPopup({ __sheet, side = "right", showCloseButton = true, className = "", children, ...props }) {
  if (!__sheet || !__sheet.open) return null;
  return (
    <>
      <div className="o-backdrop" data-slot="sheet-backdrop" onClick={() => __sheet.setOpen(false)} />
      <div role="dialog" aria-modal="true" className={["o-sheet", "o-sheet--" + side, className].filter(Boolean).join(" ")} data-slot="sheet-popup" data-side={side} {...props}>
        {children}
        {showCloseButton ? (
          <button type="button" className="o-btn o-btn--ghost o-btn--icon" aria-label="Close" style={{ position: "absolute", insetInlineEnd: "var(--space-2)", top: "var(--space-2)" }} onClick={() => __sheet.setOpen(false)}>
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M18 6 6 18" /><path d="m6 6 12 12" /></svg>
          </button>
        ) : null}
      </div>
    </>
  );
}
export function SheetHeader({ className = "", children, ...props }) {
  return <div className={["o-sheet__header", className].filter(Boolean).join(" ")} data-slot="sheet-header" {...props}>{children}</div>;
}
export function SheetTitle({ className = "", children, ...props }) {
  return <h2 className={["o-dialog__title", className].filter(Boolean).join(" ")} data-slot="sheet-title" {...props}>{children}</h2>;
}
export function SheetDescription({ className = "", children, ...props }) {
  return <p className={["o-dialog__description", className].filter(Boolean).join(" ")} data-slot="sheet-description" {...props}>{children}</p>;
}
export function SheetPanel({ className = "", children, ...props }) {
  return <div className={["o-sheet__panel o-scroll", className].filter(Boolean).join(" ")} data-slot="sheet-panel" {...props}>{children}</div>;
}
export function SheetClose({ __sheet, children }) {
  return React.cloneElement(children, { onClick: () => __sheet && __sheet.setOpen(false) });
}
