import { useConfirmStore } from '../stores/ConfirmStore';
import { useFocusTrap } from '../hooks/useFocusTrap';
import { Button } from './Button';
import styles from './ConfirmDialog.module.css';

/**
 * Renders the active confirmation request from ConfirmStore (one global
 * instance, mounted once at the app root). The in-app replacement for
 * `window.confirm` — see docs/architecture/03 → "Confirmation & alert dialogs".
 *
 * Dismissal follows Carbon's transactional-modal rule: the user must pick an
 * action. Escape and the Cancel button resolve `false`; a backdrop click does
 * NOT dismiss (unlike passive feature modals) so a destructive choice is never
 * made by an accidental outside click. For `danger` requests, focus defaults to
 * Cancel so a stray Enter can't destroy anything.
 */
export function ConfirmDialog() {
  const request = useConfirmStore((s) => s.request);
  const resolve = useConfirmStore((s) => s.resolve);

  // Focus Cancel first for destructive prompts, the primary action otherwise.
  const initialFocus = request?.danger ? `.${styles.cancel}` : `.${styles.confirm}`;
  const trapRef = useFocusTrap<HTMLDivElement>(request !== null, initialFocus);

  if (!request) return null;

  const { title, message, confirmLabel, cancelLabel, danger } = request;

  return (
    <div className={styles.backdrop} onKeyDown={(e) => e.key === 'Escape' && resolve(false)}>
      <div
        ref={trapRef}
        className={styles.dialog}
        role="alertdialog"
        aria-modal="true"
        aria-labelledby="confirm-title"
        aria-describedby="confirm-message"
      >
        <h2 id="confirm-title" className={styles.title}>
          {title}
        </h2>
        <p id="confirm-message" className={styles.message}>
          {message}
        </p>
        <div className={styles.actions}>
          <Button size="lg" className={styles.cancel} onClick={() => resolve(false)}>
            {cancelLabel ?? 'Cancel'}
          </Button>
          <Button
            size="lg"
            variant={danger ? 'danger' : 'primary'}
            className={styles.confirm}
            onClick={() => resolve(true)}
          >
            {confirmLabel ?? 'Confirm'}
          </Button>
        </div>
      </div>
    </div>
  );
}
