/**
 * Prompt primitive — specialized Dialog that resolves Promise<string|null>
 * Usage: const val = await prompt('Enter name:', { defaultValue: 'foo' })
 */
const { html } = window;
const { useState, useRef, useEffect } = hooks;

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

let _setPrompt = null;
let _resolve = null;

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

function handleClose(value) {
    if (_resolve) _resolve(value);
    _resolve = null;
    if (_setPrompt) _setPrompt(null);
}

export function PromptHost() {
    const [state, setState] = useState(null);
    const [value, setValue] = useState('');
    const inputRef = useRef(null);
    _setPrompt = (s) => {
        setState(s);
        if (s) setValue(s.defaultValue || '');
    };

    useEffect(() => {
        if (state && inputRef.current) {
            inputRef.current.focus();
            inputRef.current.select();
        }
    }, [state]);

    if (!state) return null;

    const { message, placeholder = '', submitLabel = 'OK', cancelLabel = 'Cancel' } = state;
    const actions = [
        { label: cancelLabel, variant: 'secondary', onClick: () => handleClose(null) },
        { label: submitLabel, variant: 'primary', onClick: () => handleClose(value) },
    ];

    return html`
        <${Dialog} open title="Prompt" onClose=${() => handleClose(null)} actions=${actions}>
            <p style="margin-bottom: 0.75rem">${message}</p>
            <input class="sw-input" ref=${inputRef}
                   value=${value}
                   placeholder=${placeholder}
                   onInput=${(e) => setValue(e.target.value)}
                   onKeyDown=${(e) => { if (e.key === 'Enter') handleClose(value); }} />
        <//>
    `;
}
