/**
 * p11.js – Central Entry Point
 * Orchestrates all sub-modules and provides a global access point.
 */

import { UtilityFunctions } from './modules/p11utility.js';
import { ModalNativeFunctions } from './modules/p11ModalNative.js';
import { P11ModalFunctions } from './modules/p11Modal.js';
//import { P11OffcanvasFunctions } from './modules/p11Offcanvas.js';
import { P11ToastFunctions } from './modules/p11Toast.js';
import { P11FloatingPanelFunctions } from './modules/p11FloatingPanel.js';
import { P11ProgressBarNativeFunctions } from './modules/p11ProgressBarNative.js';
import { DrawerNativeFunctions } from './modules/p11DrawerNative.js';
import { PageNativeFunctions } from './modules/p11PageNative.js';

// Zentrales p11Js Objekt
window.p11Js = {
    // Zentraler Debug-Schalter (Controlled by EventStateService.cs)
    isDebug: true,

    // Speicher für die C#-Referenz des EventStateService
    eventStateRef: null,

    //// Funktion wird vom EventStateService.InitializeAsync aufgerufen
    //setEventStateRef: function (dotNetRef) {
    //    this.eventStateRef = dotNetRef;
    //    this.log("Utility", "EventStateService-Ref registriert.");
    //},
    // In window.p11Js innerhalb von p11.js
    setEventStateRef: function (dotNetRef) {
        this.eventStateRef = dotNetRef;
        this.log("Utility", "EventStateService-Ref registriert.");

        // NEU: Sofortige Bestätigung an C# (EventStateService.cs) senden
        // Wir nutzen einen Try-Catch, falls die Bridge im Moment des App-Starts kurz zuckt
        try {
            dotNetRef.invokeMethodAsync('NotifyJsReady')
                .then(() => this.log("Utility", "C# über JS-Bereitschaft informiert."))
                .catch(err => console.error("[p11][Utility] NotifyJsReady failed:", err));
        } catch (e) {
            console.error("[p11][Utility] Invoke NotifyJsReady critical error:", e);
        }
    },

    // Zentrale Log-Funktion
    log: function (module, message, data) {
        if (this.isDebug) {
            const timestamp = new Date().toLocaleTimeString();
            const logMsg = `[p11][${module}] ${message}`;
            if (data) {
                console.log(logMsg, data);
            } else {
                console.log(logMsg);
            }
        }
    },

    // Module zuweisen
    Utility: UtilityFunctions,
    ModalNative: ModalNativeFunctions,
    Modal: P11ModalFunctions,
    // Offcanvas: P11OffcanvasFunctions,
    Toast: P11ToastFunctions,
    FloatingPanel: P11FloatingPanelFunctions,
    ProgressBar: P11ProgressBarNativeFunctions,
    DrawerNative: DrawerNativeFunctions,
    PageNative: PageNativeFunctions,

    // AUTH / LOGOUT (Last remaining piece from old p11.js)
    Auth: {
        submitLogoutForm: function () {
            const form = document.getElementById('LogoutForm');
            if (form) {
                window.p11Js.log("Auth", "Submitting LogoutForm.");
                form.submit();
            } else {
                console.error("[p11][Auth] ERROR: LogoutForm not found.");
            }
        }
    }
};

// --- GLOBAL POINTER LISTENER (Desktop & Mobile) ---
// Funktion, die Koordinaten sowohl von Maus als auch Touch extrahiert
const capturePointerPosition = (e) => {
    // pageX/Y für Maus, touches[0] für Touch-Events
    const x = Math.round(e.pageX || (e.touches ? e.touches[0].pageX : 0));
    const y = Math.round(e.pageY || (e.touches ? e.touches[0].pageY : 0));

    // Falls keine sinnvollen Koordinaten (z.B. x=0, y=0), abbrechen
    if (x === 0 && y === 0) return;

    // Optionales Debug Log
    window.p11Js.log("Utility", `Global interaction captured: X=${x}, Y=${y} (${e.type})`);

    // Den Wert an C# (EventStateService) senden
    if (window.p11Js.eventStateRef) {
        window.p11Js.eventStateRef.invokeMethodAsync('SetLastClickPosition', x, y)
            .catch(err => { /* Silent catch für Performance */ });
    }
};

// Registrierung für beide Welten am Ende der Datei
// 'passive: true' ist wichtig für die Scroll-Performance auf Mobilgeräten!
window.addEventListener('mousedown', capturePointerPosition, { passive: true });
window.addEventListener('touchstart', capturePointerPosition, { passive: true });

// Alias for global access
window.P11 = window.p11Js;

// Legacy Bridge for Auth (to keep existing C# calls working)
window.TpcModalJs = window.TpcModalJs || {};
window.TpcModalJs.submitLogoutForm = () => window.p11Js.Auth.submitLogoutForm();

console.log("[p11] UI Library initialized. Modules loaded: Utility, ModalNative, PageNative, Modal, Offcanvas, Toast, FloatingPanel, ProgressBar, DrawerNative, Auth.");

window.p11Ready = true;
window.dispatchEvent(new CustomEvent('p11-js-ready'));