import { forwardRef } from "react";

/**
 * Dialog
 *
 * Control imperatively: dialogRef.current.showModal() / .close()
 *
 * title:         string | ReactNode - header title rendered in <h2>
 * bordered:      boolean - adds borders between header, body, and footer
 * actions:       ReactNode - footer action buttons
 * closeLabel:    string - aria-label for the × button (default: "Close")
 * onClose:       function - called when the native close event fires
 * backdropClose: boolean - close on backdrop click and Escape (default: true)
 */
const Dialog = forwardRef(function Dialog(
  {
    title,
    bordered = false,
    actions,
    closeLabel = "Close",
    onClose,
    backdropClose = true,
    className = "",
    children,
    ...props
  },
  ref
) {
  // backdropClose=false → closedby="none" (disables backdrop + Escape natively)
  // Don't override if the consumer passed closedby explicitly
  const closedby = "closedby" in props
    ? undefined               // already in ...props, don't double-set
    : backdropClose
      ? undefined             // default browser behaviour
      : "none";

  const classes = [
    "prs-dialog",
    bordered && "prs-dialog-bordered",
    className,
  ]
    .filter(Boolean)
    .join(" ");

  return (
    <dialog
      ref={ref}
      className={classes}
      onClose={onClose}
      {...(closedby ? { closedby } : {})}
      {...props}
    >
      <div className="prs-dialog-box">

        {/* Header */}
        {title != null && (
          <div className="prs-dialog-header">
            <h2>{title}</h2>
            <button
              type="button"
              className="prs-dialog-close"
              aria-label={closeLabel}
              onClick={() => ref?.current?.close()}
            >
              <CloseIcon />
            </button>
          </div>
        )}

        {/* Body */}
        <div className="prs-dialog-body">{children}</div>

        {/* Actions */}
        {actions != null && (
          <div className="prs-dialog-action">{actions}</div>
        )}

      </div>

      {/* Backdrop - clicking closes unless backdropClose=false */}
      <form method="dialog" className="prs-dialog-backdrop">
        {backdropClose && <button aria-label="Close dialog" />}
      </form>
    </dialog>
  );
});

export default Dialog;

// Internal close icon - always decorative
const CloseIcon = () => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} width="20" height="20" aria-hidden="true">
    <path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" />
  </svg>
);
