// file: kb_demo_app/frontend/ts/splash.ts

import { error, info, takeoverConsole } from "@fltsci/tauri-plugin-tracing";
import { listen } from '@tauri-apps/api/event';
import { SplashOrder } from './bindings/SplashOrder.ts';

// Fonction d'animation d'opacité
async function animateOpacity(
    element: HTMLElement,
    fromOpacity: number,
    toOpacity: number,
    durationMs: number
): Promise<void> {
    console.log(`Animating from ${fromOpacity} to ${toOpacity} over ${durationMs}ms`);
    //debug(`Animating from ${fromOpacity} to ${toOpacity} over ${durationMs}ms`);

    return new Promise((resolve) => {
        const startTime = performance.now();
        const startOpacity = fromOpacity;
        const changeOpacity = toOpacity - fromOpacity;

        function update(currentTime: number) {
            const elapsed = currentTime - startTime;
            if (elapsed >= durationMs) {
                element.style.opacity = toOpacity.toString();
                resolve();
                return;
            }

            const progress = elapsed / durationMs;
            element.style.opacity = (startOpacity + changeOpacity * progress).toString();
            requestAnimationFrame(update);
        }

        requestAnimationFrame(update);
    });
}

// Journalisation
function addLogMessage(message: string): void {
    console.log(`Splash: ${message}`);
    const debugInfo = document.getElementById('debug-info');
    if (debugInfo) {
        const time = new Date().toLocaleTimeString();
        let msg = `${time}: ${message}<br>`;
        debugInfo.innerHTML += msg;
    }
}

// Pour ajouter des messages directement (sans événements)
function addMessage(message: string, status: string): void {
    const messagesContainer = document.getElementById('messages-container');
    if (!messagesContainer) return;

    const messageElement = document.createElement('div');
    messageElement.className = `splash-message ${status}`;
    messageElement.textContent = message;

    messagesContainer.appendChild(messageElement);
    messagesContainer.scrollTop = messagesContainer.scrollHeight;
}
listen("splash", (event) => {
    const splashorder = event.payload as SplashOrder;
    if (splashorder.order == "fadein") {
        const container = document.getElementById('splash-container');
        if (container) {
            animateOpacity(container, 0, 1, 3000);
        } else {
            error("no container");
        }
    } else if (splashorder.order == "fadeout") {
        const container = document.getElementById('splash-container');
        if (container) {
            animateOpacity(container, 1, 0, 3000);
        } else {
            error("no container");
        }
    } else if (splashorder.order == "add_msg" && splashorder.msg && splashorder.status) {
        addMessage(splashorder.msg, splashorder.status);
    } else if (splashorder.order == "add_log" && splashorder.msg) {
        addLogMessage(splashorder.msg);
    } else {
        error("unknown order:" + splashorder.order);
    }
});


// Démarrer l'initialisation au chargement du DOM
//window.addEventListener('DOMContentLoaded', initialize);
document.addEventListener("DOMContentLoaded", () => {

    void takeoverConsole();
    info("window loaded");

});