/**
 * Dialog primitive — modal with focus trapping, Escape close, backdrop click
 * Actions: [{label, onClick, variant}]
 */
const { html } = window;
const { useEffect, useRef, useCallback } = hooks;

export function Dialog({ open, title, children, onClose, actions = [], persistent = false, className = '' }) {
    const dialogRef = useRef(null);
    const prevFocus = useRef(null);

    // Focus trap + restore
    useEffect(() => {
        if (!open) return;
        prevFocus.current = document.activeElement;
        const el = dialogRef.current;
        if (!el) return;

        // Focus first focusable element
        requestAnimationFrame(() => {
            const focusable = el.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');
            if (focusable.length) focusable[0].focus();
        });

        // Lock body scroll
        document.body.style.overflow = 'hidden';
        return () => {
            document.body.style.overflow = '';
            if (prevFocus.current) prevFocus.current.focus();
        };
    }, [open]);

    // Escape key
    useEffect(() => {
        if (!open) return;
        const handler = (e) => {
            if (e.key === 'Escape' && onClose) onClose();
        };
        document.addEventListener('keydown', handler);
        return () => document.removeEventListener('keydown', handler);
    }, [open, onClose]);

    // Focus trap: Tab cycles within dialog
    const onKeyDown = useCallback((e) => {
        if (e.key !== 'Tab') return;
        const el = dialogRef.current;
        if (!el) return;
        const focusable = el.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');
        if (!focusable.length) return;
        const first = focusable[0];
        const last = focusable[focusable.length - 1];
        if (e.shiftKey && document.activeElement === first) {
            e.preventDefault();
            last.focus();
        } else if (!e.shiftKey && document.activeElement === last) {
            e.preventDefault();
            first.focus();
        }
    }, []);

    if (!open) return null;

    const backdropClick = persistent ? undefined : onClose;

    return html`
        <div class="sw-dialog-overlay" onClick=${backdropClick}>
            <div class="sw-dialog ${className}" ref=${dialogRef}
                 role="dialog" aria-modal="true" aria-label=${title || 'Dialog'}
                 onClick=${(e) => e.stopPropagation()}
                 onKeyDown=${onKeyDown}>
                ${title && html`
                    <div class="sw-dialog__header">
                        <h2 class="sw-dialog__title">${title}</h2>
                        ${onClose && html`
                            <button class="sw-dialog__close" onClick=${onClose} aria-label="Close">\u00d7</button>
                        `}
                    </div>
                `}
                <div class="sw-dialog__body">${children}</div>
                ${actions.length > 0 && html`
                    <div class="sw-dialog__actions">
                        ${actions.map(a => html`
                            <button class="sw-btn sw-btn--${a.variant || 'secondary'} sw-btn--sm"
                                    onClick=${a.onClick}>
                                ${a.label}
                            </button>
                        `)}
                    </div>
                `}
            </div>
        </div>
    `;
}
