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


// --- 1. Hilfsfunktion für das dynamische Laden von Abhängigkeiten ---
async function loadP11Dependency(src) {
    // Falls das Script bereits im Dokument ist, nicht erneut laden
    if (document.querySelector(`script[src*="${src}"]`)) return Promise.resolve();

    return new Promise((resolve, reject) => {
        const script = document.createElement('script');
        script.src = src;
        script.async = true;
        script.onload = () => resolve();
        script.onerror = () => reject(new Error(`[p11] Failed to load dependency: ${src}`));
        document.head.appendChild(script);
    });
}

async function loadP11Style(href, id = null, disabled = false) {
    // Falls das Stylesheet bereits existiert, nicht erneut laden
    if (document.querySelector(`link[href*="${href}"]`)) return Promise.resolve();

    return new Promise((resolve, reject) => {
        const link = document.createElement('link');
        link.rel = 'stylesheet';
        link.href = href;
        if (id) link.id = id;
        if (disabled) link.disabled = true;

        link.onload = () => resolve();
        link.onerror = () => reject(new Error(`[p11] Failed to load style: ${href}`));
        document.head.appendChild(link);
    });
}

// --- 2. Modul-Imports ---
import { UtilityFunctions } from './modules/p11utility.js';
import { CarouselFunctions } from './modules/p11Carousel.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';
import { P11ChartFunctions } from './modules/p11Chart.js';

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

    // Speicher für die C#-Referenz des EventStateService
    eventStateRef: null,
    chartEventRef: 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);
        }
    },

    setChartEventRef: function (ref) {
        this.chartEventRef = ref;
        console.log("[p11] Chart-specific bridge established.");
    },

    // 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,
    Carousel: CarouselFunctions,
    ModalNative: ModalNativeFunctions,
    Modal: P11ModalFunctions,
    // Offcanvas: P11OffcanvasFunctions,
    Toast: P11ToastFunctions,
    FloatingPanel: P11FloatingPanelFunctions,
    ProgressBar: P11ProgressBarNativeFunctions,
    DrawerNative: DrawerNativeFunctions,
    PageNative: PageNativeFunctions,
    Chart: P11ChartFunctions,

    //// 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.");*/
    //            p11LibInternal.log("Auth", "Submitting LogoutForm.");
    //            form.submit();
    //        } else {
    //            console.error("[p11][Auth] ERROR: LogoutForm not found.");
    //        }
    //    }
    //}
};

window.p11Js = p11LibInternal;
window.P11 = window.p11Js;


//// --- 4. Globale Event-Listener ---
//// 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})`);
//    p11LibInternal.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', Number(x), Number(y))
//    //        .catch(err => { /* Silent catch für Performance */ });
//    //}
//    if (p11LibInternal.eventStateRef) {
//        p11LibInternal.eventStateRef.invokeMethodAsync('SetLastClickPosition', Number(x), Number(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 });

// --- 4. Globale Event-Listener ---

// Zeitstempel für die Drosselung (Throttling)
let lastCaptureTime = 0;
// 50ms ist der "Sweet Spot": Schnell genug für 20 Klicks pro Sekunde (UX), 
// aber langsam genug, um Interop-Staus in WPF/WebView2 zu verhindern.
const captureThrottleMs = 50;

const capturePointerPosition = (e) => {
    const now = Date.now();

    // 1. Zeit-Filter (Drosselung)
    // Verhindert, dass bei schnellen Touch-Gesten oder Maus-Zittern 
    // die Bridge mit identischen Koordinaten überflutet wird.
    if (now - lastCaptureTime < captureThrottleMs) return;

    // 2. Koordinaten extrahieren
    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));

    // Koordinaten-Check (Vermeidet Senden von Null-Events)
    if (x === 0 && y === 0) return;

    // Zeitstempel aktualisieren
    lastCaptureTime = now;

    // Optionales Debug Log (über interne Referenz)
    p11LibInternal.log("Utility", `Interaction captured: X=${x}, Y=${y} (${e.type})`);

    // 3. Den Wert an C# (EventStateService) senden
    // Wir senden JEDEN Klick, damit Dropdowns, Drawers und Modals 
    // in allen 50 Komponenten korrekt reagieren können.
    if (p11LibInternal.eventStateRef) {
        p11LibInternal.eventStateRef.invokeMethodAsync('SetLastClickPosition', Number(x), Number(y))
            .catch(err => {
                // Silent catch: Verhindert JS-Absturz, wenn die Bridge 
                // während eines Seitenwechsels kurzzeitig weg ist.
            });
    }
};

// Registrierung der Listener
// 'passive: true' sorgt dafür, dass das Scrollen in der App nicht blockiert wird.
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'));

//// --- 5. Initialisierung & Auto-Loading der Abhängigkeiten ---
//(async () => {
//    // Dieser Trick ermittelt den Pfad zu p11.js dynamisch.
//    // Wenn p11.js in '_content/p11/p11.js' liegt, wird basePath genau das.
//    const currentScriptUrl = import.meta.url;
//    const basePath = currentScriptUrl.substring(0, currentScriptUrl.lastIndexOf('/') + 1);
//    const libPath = `${basePath}lib/`;

//    try {
//        // --- A. CSS LADEN ---
//        const cssTask = Promise.all([
//            loadP11Style(`${libPath}bootstrap-icons/css/bootstrap-icons.min.css`),
//            loadP11Style(`${libPath}bootstrap/dist/css/bootstrap.min.css`, 'bootstrap-ltr'),
//            loadP11Style(`${libPath}bootstrap/dist/css/bootstrap.rtl.min.css`, 'bootstrap-rtl', true),
//            loadP11Style(`${basePath}p11.css`)
//        ]);
//        window.p11Js.log("Utility", "All CSS Styles loaded.");

//        // --- B. JS LADEN ---
//        const jsTask = Promise.all([
//            loadP11Dependency(`${libPath}bootstrap/dist/js/bootstrap.bundle.min.js`),
//            loadP11Dependency(`${libPath}chartjs/chart.umd.min.js`)
//        ]);

//        // Jetzt warten wir, bis beide Gruppen fertig sind
//        await Promise.all([cssTask, jsTask]);

//        window.p11Js.log("Utility", "External dependencies (Bootstrap & Chart.js) loaded automatically from library path.");

//        // Erst wenn die Scripte geladen sind, markieren wir die Library als fertig
//        console.log("[p11] UI Library initialized. Dependencies resolved via " + libPath);

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

//    } catch (err) {
//        // Falls der Pfad falsch wäre oder die Dateien fehlen:
//        console.error("[p11] Critical error during dependency loading. Check if 'lib' folder exists at: " + libPath, err);
//    }
//})();

// --- 5. Initialisierung & Auto-Loading der Abhängigkeiten ---
(async () => {
    // Sofort-Sichtbarkeit (Test-Modus aktiv)
    document.documentElement.classList.add('p11-ready');

    console.log("[p11] >>> Async Initialization started.");

    // Pfad-Ermittlung
    const currentScriptUrl = import.meta.url;
    const basePath = currentScriptUrl.substring(0, currentScriptUrl.lastIndexOf('/') + 1);
    const libPath = `${basePath}lib/`;

    try {
        console.log("[p11] Base Path identified:", basePath);
        console.log("[p11] Starting Parallel Asset Load...");

        // --- A. CSS & JS Tasks definieren mit Einzel-Logs ---
        //const cssTask = Promise.all([
        //    loadP11Style(`${libPath}bootstrap-icons/css/bootstrap-icons.min.css`).then(() => console.log("[p11] CSS: Icons loaded.")),
        //    loadP11Style(`${libPath}bootstrap/dist/css/bootstrap.min.css`, 'bootstrap-ltr').then(() => console.log("[p11] CSS: Bootstrap LTR loaded.")),
        //    loadP11Style(`${libPath}bootstrap/dist/css/bootstrap.rtl.min.css`, 'bootstrap-rtl', true).then(() => console.log("[p11] CSS: Bootstrap RTL (disabled) registered.")),
        //    loadP11Style(`${basePath}p11.css`).then(() => console.log("[p11] CSS: p11.css loaded."))
        //]);
        const cssTask = Promise.all([
            loadP11Style(`${libPath}bootstrap-icons/css/bootstrap-icons.min.css`).then(() => console.log("[p11] CSS: Icons loaded.")),
            loadP11Style(`${libPath}bootstrap/dist/css/bootstrap.min.css`, 'bootstrap-ltr').then(() => console.log("[p11] CSS: Bootstrap LTR loaded.")),

            // FIX: Wir laden es normal, damit onload feuert, und deaktivieren es im .then()
            loadP11Style(`${libPath}bootstrap/dist/css/bootstrap.rtl.min.css`, 'bootstrap-rtl')
                .then(() => {
                    document.getElementById('bootstrap-rtl').disabled = true;
                    console.log("[p11] CSS: Bootstrap RTL loaded and disabled.");
                }),

            loadP11Style(`${basePath}p11.css`).then(() => console.log("[p11] CSS: p11.css loaded."))
        ]);

        const jsTask = Promise.all([
            loadP11Dependency(`${libPath}bootstrap/dist/js/bootstrap.bundle.min.js`).then(() => console.log("[p11] JS: Bootstrap Bundle loaded.")),
            loadP11Dependency(`${libPath}chartjs/chart.umd.min.js`).then(() => console.log("[p11] JS: Chart.js loaded."))
        ]);

        // --- B. WARTEN BIS ALLES GELADEN IST ---
        console.log("[p11] Waiting for all Promises to resolve...");
        await Promise.all([cssTask, jsTask]);
        console.log("[p11] SUCCESS: All assets are in place.");

        // --- C. GLOBAL PUBLIZIEREN (Optional / Legacy) ---
        // window.p11Js = p11LibInternal;
        // window.P11 = window.p11Js;

        // Legacy Bridge für Auth
        window.TpcModalJs = window.TpcModalJs || {};

        // Finaler Log über das interne Objekt
        p11LibInternal.log("Utility", "External dependencies loaded and P11 initialized.");
        console.log("[p11] UI Library fully initialized. Resolved via: " + libPath);

        // --- D. READY SIGNAL ---
        window.p11Ready = true;
        window.dispatchEvent(new CustomEvent('p11-js-ready'));
        console.log("[p11] >>> Event 'p11-js-ready' dispatched.");

    } catch (err) {
        console.error("[p11] !!! CRITICAL ERROR during dependency loading:", err);

        // FAILSAFE: Auch bei Fehlern (z.B. 404 bei einer Datei) 
        // setzen wir Ready, damit Blazor nicht in einer weißen Seite hängen bleibt.
        window.p11Ready = true;
        window.dispatchEvent(new CustomEvent('p11-js-ready'));

        // Wir erzwingen die Sichtbarkeit im Fehlerfall
        document.documentElement.classList.add('p11-ready');
    }
})();