/**
 * Confirm primitive — specialized Dialog that resolves a Promise<boolean>
 * Usage: const ok = await confirm('Delete this?', { destructive: true })
 */
const { html } = window;
const { useState } = hooks;
const { h, render } = preact;

import { Dialog } from './dialog.js';

let _setConfirm = null;
let _resolve = null;

export function confirm(message, opts = {}) {
    return new Promise((resolve) => {
        _resolve = resolve;
        if (_setConfirm) _setConfirm({ message, ...opts });
    });
}

function handleClose(result) {
    if (_resolve) _resolve(result);
    _resolve = null;
    if (_setConfirm) _setConfirm(null);
}

export function ConfirmHost() {
    const [state, setState] = useState(null);
    _setConfirm = setState;

    if (!state) return null;

    const { message, destructive, confirmLabel = 'Confirm', cancelLabel = 'Cancel' } = state;
    const actions = [
        { label: cancelLabel, variant: 'secondary', onClick: () => handleClose(false) },
        { label: confirmLabel, variant: destructive ? 'danger' : 'primary', onClick: () => handleClose(true) },
    ];

    return html`
        <${Dialog} open title="Confirm" onClose=${() => handleClose(false)} actions=${actions}>
            <p>${message}</p>
        <//>
    `;
}
