import * as common from '/pages/src/common.mjs';

let userOpacity = 90;
let userZoom = 100;
let smoothing = 3;

// --- CACHE POUR LE LISSAGE DE VITESSE ---
const speedCache = new Map();

// --- REGLAGES ---
function loadSettings() {
    const sOp = localStorage.getItem('myMod_Tac_Op');
    const sZoom = localStorage.getItem('myMod_Tac_Zoom');
    const sSmooth = localStorage.getItem('myMod_Tac_Smooth');

    if(sOp) userOpacity = parseInt(sOp);
    if(sZoom) userZoom = parseInt(sZoom);
    if(sSmooth) smoothing = parseInt(sSmooth);

    document.getElementById('in-opacity').value = userOpacity;
    document.getElementById('in-zoom').value = userZoom;
    document.getElementById('in-smooth').value = smoothing;
    
    applyVisuals();
}

function saveSettings() {
    userOpacity = parseInt(document.getElementById('in-opacity').value);
    userZoom = parseInt(document.getElementById('in-zoom').value);
    smoothing = parseInt(document.getElementById('in-smooth').value);
    
    localStorage.setItem('myMod_Tac_Op', userOpacity);
    localStorage.setItem('myMod_Tac_Zoom', userZoom);
    localStorage.setItem('myMod_Tac_Smooth', smoothing);

    applyVisuals();
    document.getElementById('settings-panel').style.display = 'none';
}

function applyVisuals() {
    document.getElementById('op-label').innerText = userOpacity;
    document.getElementById('dash').style.backgroundColor = `rgba(0, 0, 0, ${userOpacity/100})`;
    document.getElementById('zoom-label').innerText = (userZoom/100).toFixed(1);
    document.getElementById('wrapper').style.transform = `scale(${userZoom/100})`;
    document.getElementById('smooth-label').innerText = smoothing;
}

// --- UTILITAIRES ---
function formatTime(sec) {
    if (sec === Infinity || isNaN(sec) || sec < 0) return '∞';
    const abs = Math.round(sec);
    if (abs < 60) return abs + 's';
    const m = Math.floor(abs / 60);
    const s = abs % 60;
    if (m > 60) {
        const h = Math.floor(m / 60);
        const rm = m % 60;
        return `${h}h ${rm}m`;
    }
    return `${m}m ${s.toString().padStart(2,'0')}s`;
}

function formatName(first, last) {
    if (!last) return first || 'Inconnu';
    return `${first.charAt(0).toUpperCase()}. ${last.toUpperCase()}`;
}

// --- LOGIQUE METIER (TTC) ---
function updateTactics(data) {
    let riders = [];
    if (Array.isArray(data)) riders = data;
    else if (data && data.riders) riders = data.riders;
    else if (data && data.nearby) riders = data.nearby;

    if (!riders || riders.length === 0) return;

    // Trier par Gap
    riders.sort((a, b) => (a.gap || 0) - (b.gap || 0));

    const me = riders.find(r => r.watching);
    if (!me || !me.state) return;

    const myId = me.id || (me.athlete && me.athlete.id) || 'me';
    
    // Facteur de lissage (Moyenne Mobile Exponentielle)
    const alpha = 1 / Math.max(1, smoothing);

    // Lissage de la vitesse du joueur (Sauce donne la vitesse en km/h)
    let mySpeedKmh = me.state.speed || 0;
    if (speedCache.has(myId)) {
        mySpeedKmh = speedCache.get(myId) + alpha * (mySpeedKmh - speedCache.get(myId));
    }
    speedCache.set(myId, mySpeedKmh);

    // Filtrer les cibles
    const aheadRiders = riders.filter(r => (r.gap || 0) < -0.5);
    const targetAhead = aheadRiders.length > 0 ? aheadRiders[aheadRiders.length - 1] : null;

    const behindRiders = riders.filter(r => (r.gap || 0) > 0.5);
    const targetBehind = behindRiders.length > 0 ? behindRiders[0] : null;

    // --- MISE A JOUR UI DEVANT ---
    if (targetAhead && targetAhead.state) {
        document.getElementById('name-ahead').innerText = formatName(targetAhead.athlete.firstName, targetAhead.athlete.lastName);
        const gapSec = Math.abs(targetAhead.gap);
        document.getElementById('gap-ahead').innerText = Math.round(gapSec) + 's';
        
        const tId = targetAhead.id || (targetAhead.athlete && targetAhead.athlete.id) || 'ahead';
        let tSpeedKmh = targetAhead.state.speed || 0;
        
        // Lissage vitesse cible
        if (speedCache.has(tId)) {
            tSpeedKmh = speedCache.get(tId) + alpha * (tSpeedKmh - speedCache.get(tId));
        }
        speedCache.set(tId, tSpeedKmh);

        // Vitesse Relative (km/h) : Positif = Je vais plus vite que lui
        const vRelKmh = mySpeedKmh - tSpeedKmh;
        
        const elVrel = document.getElementById('vrel-ahead');
        elVrel.innerText = (vRelKmh > 0 ? '+' : '') + vRelKmh.toFixed(1) + ' km/h';
        elVrel.className = 's-val ' + (vRelKmh > 0.5 ? 'good' : (vRelKmh < -0.5 ? 'bad' : 'neutral'));

        // Calcul de la distance réelle sur la route (Ecart en sec * vitesse de la cible en m/s)
        const distMeters = gapSec * (tSpeedKmh / 3.6);
        const elTtc = document.getElementById('ttc-ahead');

        if (vRelKmh > 0.5) { // Je le rattrape (vitesse relative > 0.5 km/h)
            const vRelMs = vRelKmh / 3.6;
            const ttc = distMeters / vRelMs;
            elTtc.innerText = `Jonction estimée : ${formatTime(ttc)}`;
            elTtc.className = 't-ttc bg-good';
        } else if (vRelKmh < -0.5) { // Il s'éloigne
            elTtc.innerText = `L'écart se creuse...`;
            elTtc.className = 't-ttc bg-bad';
        } else {
            elTtc.innerText = `Allure identique`;
            elTtc.className = 't-ttc';
            elTtc.style.backgroundColor = 'rgba(0,0,0,0.5)';
            elTtc.style.color = 'white';
        }
    } else {
        document.getElementById('name-ahead').innerText = "Personne devant";
        document.getElementById('gap-ahead').innerText = "--";
        document.getElementById('vrel-ahead').innerText = "--";
        document.getElementById('vrel-ahead').className = 's-val neutral';
        const elTtcA = document.getElementById('ttc-ahead');
        elTtcA.innerText = "-";
        elTtcA.className = 't-ttc';
        elTtcA.style.backgroundColor = 'rgba(0,0,0,0.5)';
        elTtcA.style.color = 'white';
    }

    // --- MISE A JOUR UI DERRIERE ---
    if (targetBehind && targetBehind.state) {
        document.getElementById('name-behind').innerText = formatName(targetBehind.athlete.firstName, targetBehind.athlete.lastName);
        const gapSec = Math.abs(targetBehind.gap);
        document.getElementById('gap-behind').innerText = Math.round(gapSec) + 's';
        
        const tId = targetBehind.id || (targetBehind.athlete && targetBehind.athlete.id) || 'behind';
        let tSpeedKmh = targetBehind.state.speed || 0;

        // Lissage
        if (speedCache.has(tId)) {
            tSpeedKmh = speedCache.get(tId) + alpha * (tSpeedKmh - speedCache.get(tId));
        }
        speedCache.set(tId, tSpeedKmh);

        // Vitesse Relative (km/h) : Positif = Il va plus vite que moi
        const vRelKmh = tSpeedKmh - mySpeedKmh;
        
        const elVrel = document.getElementById('vrel-behind');
        elVrel.innerText = (vRelKmh > 0 ? '+' : '') + vRelKmh.toFixed(1) + ' km/h';
        elVrel.className = 's-val ' + (vRelKmh > 0.5 ? 'bad' : (vRelKmh < -0.5 ? 'good' : 'neutral'));

        // Calcul de la distance qui nous sépare (Ecart * ma vitesse en m/s)
        const distMeters = gapSec * (mySpeedKmh / 3.6);
        const elTtc = document.getElementById('ttc-behind');

        if (vRelKmh > 0.5) { // Il me rattrape
            const vRelMs = vRelKmh / 3.6;
            const ttc = distMeters / vRelMs;
            elTtc.innerText = `Vous êtes repris dans : ${formatTime(ttc)}`;
            elTtc.className = 't-ttc bg-bad'; // ROUGE DANGER
        } else if (vRelKmh < -0.5) { // Je le distance
            elTtc.innerText = `Vous le distancez !`;
            elTtc.className = 't-ttc bg-good'; // VERT OK
        } else {
            elTtc.innerText = `Allure identique`;
            elTtc.className = 't-ttc';
            elTtc.style.backgroundColor = 'rgba(0,0,0,0.5)';
            elTtc.style.color = 'white';
        }
    } else {
        document.getElementById('name-behind').innerText = "Personne derrière";
        document.getElementById('gap-behind').innerText = "--";
        document.getElementById('vrel-behind').innerText = "--";
        document.getElementById('vrel-behind').className = 's-val neutral';
        const elTtcB = document.getElementById('ttc-behind');
        elTtcB.innerText = "-";
        elTtcB.className = 't-ttc';
        elTtcB.style.backgroundColor = 'rgba(0,0,0,0.5)';
        elTtcB.style.color = 'white';
    }
}

// --- MAIN ---
export async function main() {
    loadSettings();

    document.getElementById('btn-settings').addEventListener('click', () => {
        const p = document.getElementById('settings-panel');
        p.style.display = p.style.display === 'block' ? 'none' : 'block';
    });
    document.getElementById('btn-save').addEventListener('click', saveSettings);
    
    document.getElementById('in-opacity').addEventListener('input', (e) => {
        userOpacity = e.target.value; applyVisuals();
    });
    document.getElementById('in-zoom').addEventListener('input', (e) => {
        userZoom = e.target.value; applyVisuals();
    });
    document.getElementById('in-smooth').addEventListener('input', (e) => {
        smoothing = e.target.value; applyVisuals();
    });

    if (common && common.initInteractionListeners) {
        common.initInteractionListeners();
        
        // Vider le cache des vitesses en cas de déconnexion pour éviter les données fantômes
        common.subscribe('status', (data) => {
            if (data && !data.connected) speedCache.clear();
        });

        common.subscribe('nearby', updateTactics);
    }
}