/**
 * p11Toast.js
 * Part of the p11 UI Library.
 * Handles Bootstrap Toast specific logic and Blazor integration.
 * All comments and documentation are in English.
 */

import { UtilityFunctions } from './p11utility.js';

/* ========================================================================
   PUBLIC EXPORTED FUNCTIONS
   ======================================================================== */

export const P11ToastFunctions = {

    /**
     * Initializes a Bootstrap Toast instance and sets up the hidden event listener.
     * @param {HTMLElement} elementRef - Reference to the toast DOM element.
     * @param {object} dotNetRef - DotNetObjectReference for callbacks.
     * @param {string} toastId - The unique ID of the toast.
     * @param {object} options - Bootstrap Toast configuration options.
     */
    initializeToast: function (elementRef, dotNetRef, toastId, options) {
        if (!elementRef || !window.bootstrap?.Toast) {
            UtilityFunctions.error("initializeToast: Bootstrap Toast or ElementRef not found.");
            return null;
        }

        let instance = window.bootstrap.Toast.getInstance(elementRef);

        if (!instance) {
            // Initialize new Bootstrap Toast instance with provided options
            instance = new window.bootstrap.Toast(elementRef, options || {});

            // Setup event listener to notify Blazor when toast is hidden
            elementRef.addEventListener('hidden.bs.toast', () => {
                if (dotNetRef) {
                    UtilityFunctions.log(`Toast ${toastId} hidden. Notifying Blazor.`);
                    dotNetRef.invokeMethodAsync('JsToastHidden', toastId)
                        .catch(err => UtilityFunctions.error("Error in JsToastHidden callback", err));
                }
            });

            UtilityFunctions.log(`Toast initialized for ID: ${toastId}`);
        }

        return instance;
    },

    /**
     * Shows a toast instance.
     * @param {HTMLElement} elementRef - Reference to the toast DOM element.
     */
    showToast: function (elementRef) {
        if (!elementRef) return;
        const instance = window.bootstrap.Toast.getInstance(elementRef);
        if (instance) {
            instance.show();
            UtilityFunctions.log("showToast: Toast instance show() called.");
        } else {
            UtilityFunctions.error("showToast: No toast instance found for element.");
        }
    },

    /**
     * Hides a toast instance.
     * @param {HTMLElement} elementRef - Reference to the toast DOM element.
     */
    hideToast: function (elementRef) {
        if (!elementRef) return;
        const instance = window.bootstrap.Toast.getInstance(elementRef);
        if (instance) {
            instance.hide();
            UtilityFunctions.log("hideToast: Toast instance hide() called.");
        }
    },

    /**
     * Disposes of a toast instance.
     * @param {HTMLElement} elementRef - Reference to the toast DOM element.
     */
    disposeToast: function (elementRef) {
        if (!elementRef || !window.bootstrap?.Toast) return;
        try {
            const instance = window.bootstrap.Toast.getInstance(elementRef);
            if (instance) {
                instance.dispose();
                UtilityFunctions.log("disposeToast: Toast instance disposed.");
            }
        } catch (err) {
            UtilityFunctions.error("Error during disposeToast:", err);
        }
    },

    /**
     * Legacy Bridge Registration for Toasts.
     * Maps functions to window.TpcModalJs for compatibility with existing C# code.
     */
    registerLegacyFunctions: function () {
        if (!window.TpcModalJs) window.TpcModalJs = {};

        window.TpcModalJs.initializeToast = (el, d, id, o) => this.initializeToast(el, d, id, o);
        window.TpcModalJs.showToast = (el) => this.showToast(el);
        window.TpcModalJs.hideToast = (el) => this.hideToast(el);
        window.TpcModalJs.disposeToast = (el) => this.disposeToast(el);

        UtilityFunctions.log("Legacy Toast functions registered in p11Toast.js.");
    }
};

// Auto-register legacy support
P11ToastFunctions.registerLegacyFunctions();