/**
 * p11Modal.js
 * Part of the p11 UI Library.
 * Handles standard Web/Desktop Modals without swipe gestures.
 * Uses local listeners and integrates with EventStateService via p11utility.
 */

export const P11ModalFunctions = {
    _activeModals: new Map(),
    _dotNetHelper: null,

    /* ========================================================================
       C# BRIDGE INTERFACE
       ======================================================================== */

    registerEventStateService: function (dotNetRef) {
        this._dotNetHelper = dotNetRef;
        window.p11Js.log("Modal", "EventStateService-Ref registriert.");
    },

    /* ========================================================================
       MODAL CORE LOGIC
       ======================================================================== */

    /**
     * Initialisiert ein Standard-Modal.
     * @param {HTMLElement} element - Das Modal-Element.
     * @param {string} elementId - Eindeutige ID (Guid).
     * @param {string} restoreFocusId - ID des Elements, das nach Schließen Fokus erhält.
     * @param {boolean} preventScroll - Ob der Body-Scroll gesperrt werden soll.
     * @param {boolean} closeOnOutsideClick - Ob Klick auf Backdrop schließt.
     */
    focusModalAndTrap: function (element, elementId, restoreFocusId, preventScroll, closeOnOutsideClick = true) {
        if (!element || !elementId) return;

        window.p11Js.log("Modal", `Initializing Standard Modal: ${elementId}`);

        // 1. Z-Index Management via Utility (Typ: StandardModal)
        const stackDepth = this._activeModals.size;
        const newZIndex = window.p11Js.Utility.getNextZIndex(stackDepth, 'P11Modal');
        element.style.zIndex = newZIndex;

        // Backdrop finden und Z-Index setzen (direkt unter dem Modal)
        const backdrop = document.querySelector('.modal-backdrop.show:not([style*="z-index"])')
            || document.querySelector('.modal-backdrop.show');
        if (backdrop) {
            backdrop.style.zIndex = (newZIndex - 1);
        }

        // 2. Scroll Lock via Utility
        if (preventScroll) {
            window.p11Js.Utility.requestScrollLock(elementId);
        }

        // 3. Lokale Listener einrichten (Kein Swipe!)

        // A: Escape-Taste
        const escapeHandler = (e) => {
            if (e.key === 'Escape') {
                window.p11Js.log("Modal", "Escape pressed.");
                this._triggerClose(elementId);
            }
        };

        // B: Outside Click (Backdrop)
        const outsideClickHandler = (e) => {
            if (closeOnOutsideClick && e.target === backdrop) {
                window.p11Js.log("Modal", "Backdrop click detected.");
                this._triggerClose(elementId);
            }
        };

        // C: Tab-Focus Trapping (lokal)
        const focusHandler = (e) => {
            if (e.key !== 'Tab') return;
            const focusable = window.p11Js.Utility.getFocusableElements(element);
            if (focusable.length === 0) { e.preventDefault(); return; }

            const first = focusable[0];
            const last = focusable[focusable.length - 1];

            if (e.shiftKey && document.activeElement === first) {
                last.focus();
                e.preventDefault();
            } else if (!e.shiftKey && document.activeElement === last) {
                first.focus();
                e.preventDefault();
            }
        };

        element.addEventListener('keydown', escapeHandler);
        element.addEventListener('keydown', focusHandler);
        if (backdrop) backdrop.addEventListener('click', outsideClickHandler);

        // 4. Registrierung für Cleanup
        this._activeModals.set(elementId, {
            element,
            backdrop,
            restoreFocusId,
            cleanup: () => {
                element.removeEventListener('keydown', escapeHandler);
                element.removeEventListener('keydown', focusHandler);
                if (backdrop) backdrop.removeEventListener('click', outsideClickHandler);
            }
        });

        // 5. Initialer Fokus
        setTimeout(() => {
            if (document.contains(element)) {
                const firstInput = window.p11Js.Utility.getFocusableElements(element)[0];
                (firstInput || element).focus();
            }
        }, 50);
    },

    /**
     * Gibt das Modal frei und stellt den Zustand wieder her.
     */
    releaseModal: function (elementId) {
        const state = this._activeModals.get(elementId);
        if (!state) return;

        window.p11Js.log("Modal", `Release Modal: ${elementId}`);

        // Cleanup der Listener
        if (state.cleanup) state.cleanup();

        // Scroll Lock lösen
        window.p11Js.Utility.releaseScrollLock(elementId);

        this._activeModals.delete(elementId);

        // Fokus-Wiederherstellung
        if (this._activeModals.size > 0) {
            const modalArray = Array.from(this._activeModals.values());
            const topModal = modalArray[modalArray.length - 1];
            topModal.element?.focus();
        } else if (state.restoreFocusId) {
            const el = document.getElementById(state.restoreFocusId);
            if (el) setTimeout(() => el.focus(), 50);
        }
    },

    /* ========================================================================
       INTERNAL HELPERS
       ======================================================================== */

    _triggerClose: function (elementId) {
        if (this._dotNetHelper) {
            // Wir nutzen die gleiche Methode wie ModalNative, 
            // der Service entscheidet anhand des Typs, was zu tun ist.
            this._dotNetHelper.invokeMethodAsync('HandleNativeBack', false, elementId);
        }
    },

    forceReset: function () {
        this._activeModals.forEach((v, key) => this.releaseModal(key));
        window.p11Js.Utility.clearBodyStyles();
    }
};