import React from "react";

export function Dialog({ 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, { __dialog: ctx }) : child))}</>;
}

export function DialogTrigger({ __dialog, children }) {
  return React.cloneElement(children, { onClick: () => __dialog && __dialog.setOpen(true) });
}

export function DialogPopup({ __dialog, showCloseButton = true, className = "", children, ...props }) {
  if (!__dialog || !__dialog.open) return null;
  return (
    <>
      <div className="o-backdrop" data-slot="dialog-backdrop" onClick={() => __dialog.setOpen(false)} />
      <div className="o-viewport" data-slot="dialog-viewport">
        <div role="dialog" aria-modal="true" className={["o-dialog", className].filter(Boolean).join(" ")} data-slot="dialog-popup" {...props}>
          {children}
          {showCloseButton ? (
            <button type="button" className="o-btn o-btn--ghost o-btn--icon o-dialog__close" aria-label="Close" onClick={() => __dialog.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>
      </div>
    </>
  );
}

export function DialogHeader({ className = "", children, ...props }) {
  return <div className={["o-dialog__header", className].filter(Boolean).join(" ")} data-slot="dialog-header" {...props}>{children}</div>;
}
export function DialogTitle({ className = "", children, ...props }) {
  return <h2 className={["o-dialog__title", className].filter(Boolean).join(" ")} data-slot="dialog-title" {...props}>{children}</h2>;
}
export function DialogDescription({ className = "", children, ...props }) {
  return <p className={["o-dialog__description", className].filter(Boolean).join(" ")} data-slot="dialog-description" {...props}>{children}</p>;
}
export function DialogPanel({ className = "", children, ...props }) {
  return <div className={["o-dialog__panel o-scroll", className].filter(Boolean).join(" ")} data-slot="dialog-panel" {...props}>{children}</div>;
}
export function DialogFooter({ variant = "default", className = "", children, ...props }) {
  const cls = ["o-dialog__footer", variant === "bare" ? "o-dialog__footer--bare" : "", className].filter(Boolean).join(" ");
  return <div className={cls} data-slot="dialog-footer" {...props}>{children}</div>;
}
export function DialogClose({ __dialog, children }) {
  return React.cloneElement(children, { onClick: () => __dialog && __dialog.setOpen(false) });
}
