///////////////////////////////////////////////////////////////////////////////
// ui.js — Reusable UI components for Watch My Domains SED
//
// Namespace: SedUI
//
// SedUI.confirm(options) → Promise<boolean>
//   options: { title, message, confirmLabel, confirmClass, cancelLabel }
//
// SedUI.alert(options|string) → Promise<void>
//   options: { title, message, type }   type: 'error' | 'warning' | 'info' | 'success'
///////////////////////////////////////////////////////////////////////////////

const SedUI = (function() {
    'use strict';

    let _overlay     = null;
    let _activeDialog = null;
    let _keyHandler   = null;

    ///////////////////////////////////////////////////////////////////////////
    // Internal helpers
    ///////////////////////////////////////////////////////////////////////////

    function _ensureOverlay() {
        if (_overlay) return _overlay;
        _overlay           = document.createElement('div');
        _overlay.className = 'sui-overlay';
        document.body.appendChild(_overlay);
        return _overlay;
    }

    function _buildDialog(title, bodyContent, buttons, icon) {
        const dialog     = document.createElement('div');
        dialog.className = 'sui-dialog';

        // Header
        const header       = document.createElement('div');
        header.className   = 'sui-dialog-header';
        const titleEl      = document.createElement('span');
        titleEl.className  = 'sui-dialog-title';
        titleEl.textContent = title;
        header.appendChild(titleEl);

        // Body
        const body       = document.createElement('div');
        body.className   = 'sui-dialog-body';

        if (icon) {
            // Icon + text flex layout
            const iconWrap     = document.createElement('div');
            iconWrap.className = 'sui-dialog-body-icon-wrap';

            const mode         = document.body.classList.contains('dark-mode') ? 'dark' : 'light';
            const img          = document.createElement('img');
            img.src            = `lib/layouts/colors/${mode}/images/64/toolbar/${icon}.png`;
            img.className      = 'sui-dialog-body-icon';
            img.alt            = '';
            iconWrap.appendChild(img);

            const text         = document.createElement('div');
            text.className     = 'sui-dialog-body-text';
            if (typeof bodyContent === 'string') {
                text.textContent = bodyContent;
            } else {
                text.appendChild(bodyContent);
            }
            iconWrap.appendChild(text);
            body.appendChild(iconWrap);
        } else {
            if (typeof bodyContent === 'string') {
                body.textContent = bodyContent;
            } else {
                body.appendChild(bodyContent);
            }
        }

        // Footer
        const footer     = document.createElement('div');
        footer.className = 'sui-dialog-footer';
        buttons.forEach(function(def) {
            const btn       = document.createElement('button');
            btn.className   = 'btn btn-sm ' + (def.cls || 'btn-secondary');
            btn.textContent = def.label;
            btn.addEventListener('click', def.onClick);
            footer.appendChild(btn);
        });

        dialog.appendChild(header);
        dialog.appendChild(body);
        dialog.appendChild(footer);
        return dialog;
    }

    function _show(dialog) {
        const overlay = _ensureOverlay();
        if (_activeDialog) overlay.removeChild(_activeDialog);
        _activeDialog = dialog;
        overlay.appendChild(dialog);
        overlay.style.display = 'flex';
        // Focus the last (primary) button
        const btns = dialog.querySelectorAll('button');
        if (btns.length) setTimeout(() => btns[btns.length - 1].focus(), 30);
        // Update icon if theme changes while dialog is open
        if (!SedUI._themeObserver) {
            SedUI._themeObserver = new MutationObserver(function() {
                if (!_activeDialog) return;
                const img = _activeDialog.querySelector('.sui-dialog-body-icon');
                if (!img) return;
                const mode = document.body.classList.contains('dark-mode') ? 'dark' : 'light';
                img.src = img.src.replace(/\/(light|dark)\//, '/' + mode + '/');
            });
            SedUI._themeObserver.observe(document.body, { attributes: true, attributeFilter: ['class'] });
        }
    }

    function _hide() {
        if (_keyHandler) {
            document.removeEventListener('keydown', _keyHandler);
            _keyHandler = null;
        }
        if (_overlay) _overlay.style.display = 'none';
        if (_activeDialog && _overlay) {
            _overlay.removeChild(_activeDialog);
            _activeDialog = null;
        }
    }

    ///////////////////////////////////////////////////////////////////////////
    // Public API
    ///////////////////////////////////////////////////////////////////////////

    /**
     * Shows a confirmation dialog.
     * @returns {Promise<boolean>} — resolves true (confirm) or false (cancel/escape)
     */
    function confirm(options) {
        options = options || {};
        const title        = options.title        || 'Confirm';
        const message      = options.message      || '';
        const confirmLabel = options.confirmLabel || 'OK';
        const confirmCls   = options.confirmClass || 'btn-primary';
        const cancelLabel  = options.cancelLabel  || 'Cancel';
        const icon         = options.icon         || null;

        return new Promise(function(resolve) {
            function accept() { _hide(); resolve(true);  }
            function reject() { _hide(); resolve(false); }

            const dialog = _buildDialog(title, message, [
                { label: cancelLabel,  cls: 'btn-secondary', onClick: reject },
                { label: confirmLabel, cls: confirmCls,       onClick: accept },
            ], icon);
            _show(dialog);

            _keyHandler = function(e) {
                if (e.key === 'Escape') { e.preventDefault(); reject(); }
                if (e.key === 'Enter')  { e.preventDefault(); accept(); }
            };
            document.addEventListener('keydown', _keyHandler);
        });
    }

    /**
     * Shows an alert/notice dialog.
     * @returns {Promise<void>} — resolves when dismissed
     */
    function alert(options) {
        if (typeof options === 'string') options = { message: options };
        options = options || {};
        const type    = options.type    || 'info';
        const message = options.message || '';
        const title   = options.title   || (type === 'error' ? 'Error' : type === 'warning' ? 'Warning' : 'Notice');
        const btnCls  = type === 'error' ? 'btn-danger' : type === 'success' ? 'btn-success' : 'btn-primary';
        const icon    = options.icon !== undefined ? options.icon : (type === 'warning' ? 'warning' : null);

        return new Promise(function(resolve) {
            function dismiss() { _hide(); resolve(); }

            const dialog = _buildDialog(title, message, [
                { label: 'OK', cls: btnCls, onClick: dismiss },
            ], icon);
            dialog.classList.add('sui-dialog-' + type);
            _show(dialog);

            _keyHandler = function(e) {
                if (e.key === 'Escape' || e.key === 'Enter') {
                    e.preventDefault();
                    dismiss();
                }
            };
            document.addEventListener('keydown', _keyHandler);
        });
    }

    return { confirm, alert };

})();