"use client";

import { useEffect, useRef, type ReactNode } from "react";
import { Icon } from "./Icon";

/** Native <dialog> modal: focus trapping, Esc to close and the backdrop come from the browser. */
export function Modal({ title, onClose, children, wide }: { title: string; onClose: () => void; children: ReactNode; wide?: boolean }) {
  const ref = useRef<HTMLDialogElement>(null);
  const closeRef = useRef(onClose);
  useEffect(() => {
    closeRef.current = onClose;
  });

  useEffect(() => {
    const d = ref.current;
    if (!d) return;
    d.showModal();
    const onCancel = (e: Event) => {
      e.preventDefault();
      closeRef.current();
    };
    d.addEventListener("cancel", onCancel);
    return () => {
      d.removeEventListener("cancel", onCancel);
      if (d.open) d.close();
    };
  }, []);

  return (
    <dialog ref={ref} className={`modal${wide ? " wide" : ""}`} aria-labelledby="modal-title" onClick={(e) => e.target === ref.current && onClose()}>
      <div className="modal-h">
        <h3 id="modal-title">{title}</h3>
        <button type="button" className="icon-btn" aria-label="Close" onClick={onClose}>
          <Icon name="x" />
        </button>
      </div>
      <div className="modal-b">{children}</div>
    </dialog>
  );
}

export function ConfirmDialog({
  title,
  children,
  confirmLabel,
  danger,
  busy,
  onConfirm,
  onClose,
}: {
  title: string;
  children: ReactNode;
  confirmLabel: string;
  danger?: boolean;
  busy?: boolean;
  onConfirm: () => void;
  onClose: () => void;
}) {
  return (
    <Modal title={title} onClose={onClose}>
      <div className="confirm-text">{children}</div>
      <div className="modal-actions">
        <button type="button" className="btn btn-outline btn-sm" onClick={onClose}>
          Cancel
        </button>
        <button type="button" className={`btn btn-sm ${danger ? "btn-danger" : "btn-primary"}`} disabled={busy} onClick={onConfirm}>
          {busy ? <span className="spin" aria-label="Working" /> : confirmLabel}
        </button>
      </div>
    </Modal>
  );
}
