// In-app replacement for window.confirm() on destructive actions.
//
// WHY this exists (real defect, found 2026-08-14): browsers let the user tick
// "Prevent this page from creating additional dialogs" (Firefox) / "Don't let
// this page create more dialogs" (Chrome) on any confirm() prompt. From that
// moment every window.confirm() in the tab returns FALSE for the rest of the
// page's life — so every guarded delete in the app silently does nothing, with
// no error, no feedback, and no clue for the user. A browser-owned dialog is
// the wrong place to put a guard rail on a product. This one is ours: it can't
// be suppressed, it's themed, and it's testable.
//
// Usage (the handler must be async):
//   if (!await confirmAction('Delete this task?')) return;
//   if (!await confirmAction({ title: 'Delete 3 files',
//                             message: 'This cannot be undone.',
//                             confirmLabel: 'Delete' })) return;

// Set by ConfirmHost when it mounts. Module-level on purpose: callers are
// plain async handlers all over the app, not React consumers of a context.
let _requestConfirm = null;

const confirmAction = (opts) => {
    const cfg = typeof opts === 'string' ? { message: opts } : (opts || {});
    // If the host somehow isn't mounted, fall back to the browser dialog
    // rather than resolving true — a missing prompt must never mean "yes".
    if (!_requestConfirm) {
        return Promise.resolve(window.confirm(cfg.message || 'Are you sure?'));
    }
    return new Promise((resolve) => _requestConfirm({ ...cfg, resolve }));
};

const ConfirmHost = () => {
    const [req, setReq] = React.useState(null);

    React.useEffect(() => {
        _requestConfirm = setReq;
        return () => { _requestConfirm = null; };
    }, []);

    // Every exit path resolves exactly once: the request is cleared before the
    // promise settles, so a double-click can't fire the action twice.
    const finish = (answer) => {
        setReq(null);
        req?.resolve(answer);
    };

    if (!req) return null;

    const {
        title        = 'Are you sure?',
        message      = '',
        confirmLabel = 'Confirm',
        cancelLabel  = 'Cancel',
        danger       = true,   // these prompts guard deletes by default
    } = req;

    return (
        <Modal isOpen={true} onClose={() => finish(false)} title={title}>
            {message && (
                <p style={{
                    fontSize: '0.9375rem',
                    color: 'var(--text-2)',
                    whiteSpace: 'pre-wrap',   // messages carry \n paragraphs
                    margin: 0,
                }}>{message}</p>
            )}
            <div className="modal-actions" style={{ display: 'flex', gap: '0.5rem', justifyContent: 'flex-end', marginTop: '1.25rem' }}>
                {/* Cancel takes focus on purpose — a stray Enter on a delete
                    prompt should back out, never confirm. */}
                <button type="button" className="btn btn-secondary" autoFocus onClick={() => finish(false)}>
                    {cancelLabel}
                </button>
                <button type="button" className={`btn ${danger ? 'btn-danger' : 'btn-primary'}`}
                    onClick={() => finish(true)}>
                    {confirmLabel}
                </button>
            </div>
        </Modal>
    );
};
