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

// --- CONFIG ---
const START_WATTS = 150; 
let userWeight = 75; // Valeur par défaut
let userOpacity = 90;
let userZoom = 100;

// Variables Manuelles (Override)
let manualWeight = null;
let targetCP5 = null;  // Si null, mode auto. Sinon, valeur en W/kg
let targetCP20 = null; // Si null, mode auto. Sinon, valeur en W/kg

// --- ETAT COURSE ---
let raceStarted = false;
let raceStartTime = 0;
let currentWatts = 0; 

// --- MEMOIRE (Buffers) ---
let buffer5m = [];
let buffer20m = [];

const TIME_5M = 300; 
const TIME_20M = 1200;

let sessionMax5m = 0;
let sessionMax20m = 0;

// Echelles par défaut (W/kg) - Ces échelles restent fixes maintenant
const SCALE_WKG_5M = 6.0; 
const SCALE_WKG_20M = 5.5; 

// --- FONCTIONS GLOBALES ---
window.resetRace = function() {
    raceStarted = false;
    buffer5m = [];
    buffer20m = [];
    sessionMax5m = 0;
    sessionMax20m = 0;
    
    document.getElementById('race-timer').innerText = "PRÊT...";
    document.getElementById('race-timer').style.color = "#888";
    
    // On passe 0 pour reset
    updateEnduranceBar('bar-5m', 'txt-5m', 'mark-5m', 'mark-val-5m', 0, 0, '5m');
    updateEnduranceBar('bar-20m', 'txt-20m', 'mark-20m', 'mark-val-20m', 0, 0, '20m');
    updateCountDown('max-5m', TIME_5M);
    updateCountDown('max-20m', TIME_20M);
};

// --- REGLAGES ---
function loadSettings() {
    // Visuel
    const sOp = localStorage.getItem('myMod_Endu_Op');
    const sZoom = localStorage.getItem('myMod_Endu_Zoom');
    if(sOp) userOpacity = parseInt(sOp);
    if(sZoom) userZoom = parseInt(sZoom);

    // Valeurs Manuelles
    const sW = localStorage.getItem('myMod_Endu_Weight');
    const sCP5 = localStorage.getItem('myMod_Endu_TargetCP5');
    const sCP20 = localStorage.getItem('myMod_Endu_TargetCP20');

    if (sW) manualWeight = parseFloat(sW);
    if (sCP5) targetCP5 = parseFloat(sCP5);
    if (sCP20) targetCP20 = parseFloat(sCP20);

    // Mise à jour Inputs UI
    document.getElementById('in-opacity').value = userOpacity;
    document.getElementById('in-zoom').value = userZoom;
    if (manualWeight) document.getElementById('in-weight').value = manualWeight;
    if (targetCP5) document.getElementById('in-cp5').value = targetCP5;
    if (targetCP20) document.getElementById('in-cp20').value = targetCP20;

    applyVisuals();
}

function saveSettings() {
    // Sauvegarde Visuel
    localStorage.setItem('myMod_Endu_Op', userOpacity);
    localStorage.setItem('myMod_Endu_Zoom', userZoom);

    // Sauvegarde Valeurs Manuelles
    const wVal = document.getElementById('in-weight').value;
    const cp5Val = document.getElementById('in-cp5').value;
    const cp20Val = document.getElementById('in-cp20').value;

    if (wVal) {
        manualWeight = parseFloat(wVal);
        localStorage.setItem('myMod_Endu_Weight', manualWeight);
        userWeight = manualWeight; // Application immédiate
    } else {
        manualWeight = null;
        localStorage.removeItem('myMod_Endu_Weight');
    }

    if (cp5Val) {
        targetCP5 = parseFloat(cp5Val);
        localStorage.setItem('myMod_Endu_TargetCP5', targetCP5);
    } else {
        targetCP5 = null;
        localStorage.removeItem('myMod_Endu_TargetCP5');
    }

    if (cp20Val) {
        targetCP20 = parseFloat(cp20Val);
        localStorage.setItem('myMod_Endu_TargetCP20', targetCP20);
    } else {
        targetCP20 = null;
        localStorage.removeItem('myMod_Endu_TargetCP20');
    }

    document.getElementById('settings-panel').style.display = 'none';
    
    // Force un refresh des données pour voir les changements
    processData();
}

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

// --- CALCULS & UI ---
function getAverage(buffer) {
    if (buffer.length === 0) return 0;
    const sum = buffer.reduce((a, b) => a + b, 0);
    return sum / buffer.length;
}

// Règles Couleurs (Basées sur W/kg standard)
function getCatInfo5m(wkg) {
    if (wkg < 3.2) return { class: 'cat-jaune', txtClass: 'txt-cat-jaune', nextLimit: 3.2, nextColor: '#33ccff' }; 
    if (wkg < 4.1) return { class: 'cat-bleu', txtClass: 'txt-cat-bleu', nextLimit: 4.1, nextColor: '#33ff33' };  
    if (wkg < 5.1) return { class: 'cat-vert', txtClass: 'txt-cat-vert', nextLimit: 5.1, nextColor: '#d32f2f' };  
    return { class: 'cat-rouge', txtClass: 'txt-cat-rouge', nextLimit: null, nextColor: null };                    
}
function getCatInfo20m(wkg) {
    if (wkg < 2.63) return { class: 'cat-jaune', txtClass: 'txt-cat-jaune', nextLimit: 2.63, nextColor: '#33ccff' }; 
    if (wkg < 3.36) return { class: 'cat-bleu', txtClass: 'txt-cat-bleu', nextLimit: 3.36, nextColor: '#33ff33' };  
    if (wkg < 4.2) return { class: 'cat-vert', txtClass: 'txt-cat-vert', nextLimit: 4.2, nextColor: '#d32f2f' };  
    return { class: 'cat-rouge', txtClass: 'txt-cat-rouge', nextLimit: null, nextColor: null };                    
}

function updateEnduranceBar(idBar, idTxt, idMark, idMarkVal, valWatts, valWkg, type, customTarget) {
    const bar = document.getElementById(idBar);
    const txt = document.getElementById(idTxt);
    const mark = document.getElementById(idMark);
    const markVal = document.getElementById(idMarkVal);
    
    // Valeur affichée : TOUJOURS W/KG
    let displayVal = valWkg.toFixed(2);
    
    // L'échelle est MAINTENANT FIXE dans les deux modes
    const scaleMax = (type === '5m') ? SCALE_WKG_5M : SCALE_WKG_20M;
    
    // Calcul du remplissage
    let widthPct = (valWkg / scaleMax) * 100;

    if (customTarget && customTarget > 0) {
        // MODE MANUEL
        // On affiche le marqueur à la position de la limite souhaitée
        mark.style.display = 'block';
        
        let targetPos = (customTarget / scaleMax) * 100;
        mark.style.left = Math.min(100, targetPos) + '%';
        
        // Style du marqueur limite (Blanc pour bien ressortir)
        mark.style.backgroundColor = 'white';
        mark.style.boxShadow = '0 0 6px white';
        
        // Affiche la valeur de la limite au dessus du trait
        markVal.innerText = customTarget.toFixed(2);
        markVal.style.color = 'white';
        
    } else {
        // MODE AUTO (W/kg)
        // Gestion Marqueur Auto (Prochaine catégorie)
        const info = (type === '5m') ? getCatInfo5m(valWkg) : getCatInfo20m(valWkg);
        
        if (valWkg > 0 && info.nextLimit && info.nextLimit <= scaleMax) {
            mark.style.display = 'block';
            mark.style.left = (info.nextLimit / scaleMax * 100) + '%';
            mark.style.backgroundColor = info.nextColor;
            mark.style.boxShadow = `0 0 6px ${info.nextColor}`;
            markVal.innerText = info.nextLimit;
            markVal.style.color = info.nextColor;
        } else {
            mark.style.display = 'none';
        }
    }

    txt.innerText = (valWatts > 0) ? displayVal : "--";
    
    // Couleur de la barre (reste standard pour garder l'info de zone physiologique)
    const infoColor = (type === '5m') ? getCatInfo5m(valWkg) : getCatInfo20m(valWkg);
    bar.className = 'bar-fill ' + (valWatts > 0 ? infoColor.class : '');
    
    bar.style.width = Math.min(100, widthPct) + '%';
}

function updateMaxBox(idBox, valWkg, type, customTarget) {
    const el = document.getElementById(idBox);
    let cssClass = '';

    // --- LOGIQUE DE COULEUR ---
    if (customTarget && customTarget > 0) {
        // Mode PLAFOND en W/KG :
        // < Cible = Vert (OK)
        // > Cible = Rouge (Trop fort)
        if (valWkg <= customTarget) {
            cssClass = 'txt-cat-vert'; // Vert
        } else {
            cssClass = 'txt-cat-rouge'; // Rouge
        }
    } else {
        // Mode AUTO (Zones classiques)
        const info = (type === '5m') ? getCatInfo5m(valWkg) : getCatInfo20m(valWkg);
        cssClass = info.txtClass;
    }
    
    el.className = 'box-max ' + cssClass;
    el.style.color = ""; // Clear inline style
    
    // TOUJOURS W/KG
    el.innerText = valWkg.toFixed(2);
}

function updateCountDown(idBox, secondsLeft) {
    const mins = Math.floor(secondsLeft / 60);
    const secs = Math.floor(secondsLeft % 60);
    const el = document.getElementById(idBox);
    el.innerText = `${mins}:${secs.toString().padStart(2, '0')}`;
    el.className = 'box-max'; 
    el.style.color = '#777';
}

function updateTimer() {
    if (!raceStarted) return;
    const diff = Math.floor((Date.now() - raceStartTime) / 1000);
    const m = Math.floor(diff / 60);
    const s = diff % 60;
    const h = Math.floor(m / 60);
    
    let txt = `${m % 60}:${s.toString().padStart(2, '0')}`;
    if(h > 0) txt = `${h}:${txt}`;
    
    const el = document.getElementById('race-timer');
    el.innerText = txt;
}

function processData() {
    // 1. Start Auto
    if (!raceStarted) {
        if (currentWatts > START_WATTS) {
            raceStarted = true;
            raceStartTime = Date.now();
        } else {
            return; 
        }
    }

    // 2. Buffers
    buffer5m.push(currentWatts);
    if (buffer5m.length > TIME_5M) buffer5m.shift();

    buffer20m.push(currentWatts);
    if (buffer20m.length > TIME_20M) buffer20m.shift();

    // 3. Calculs
    // Priorité au poids manuel, sinon localStorage auto, sinon 75
    if (manualWeight) {
        userWeight = manualWeight;
    } else {
        const sWeight = localStorage.getItem('myMod_Weight');
        if(sWeight) userWeight = parseFloat(sWeight);
    }

    const avg5mWatts = getAverage(buffer5m);
    const avg20mWatts = getAverage(buffer20m);
    
    const wkg5 = (avg5mWatts / userWeight);
    const wkg20 = (avg20mWatts / userWeight);

    // 4. UI Updates
    updateEnduranceBar('bar-5m', 'txt-5m', 'mark-5m', 'mark-val-5m', avg5mWatts, wkg5, '5m', targetCP5);
    updateEnduranceBar('bar-20m', 'txt-20m', 'mark-20m', 'mark-val-20m', avg20mWatts, wkg20, '20m', targetCP20);

    // CP5 Max
    if (buffer5m.length < TIME_5M) updateCountDown('max-5m', TIME_5M - buffer5m.length);
    else {
        // On compare toujours en W/kg pour déterminer le "Max" de la session
        if (wkg5 > sessionMax5m) sessionMax5m = wkg5; 
        updateMaxBox('max-5m', sessionMax5m, '5m', targetCP5);
    }

    // CP20 Max
    if (buffer20m.length < TIME_20M) updateCountDown('max-20m', TIME_20M - buffer20m.length);
    else {
        if (wkg20 > sessionMax20m) sessionMax20m = wkg20;
        updateMaxBox('max-20m', sessionMax20m, '20m', targetCP20);
    }
    
    updateTimer();
}

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

    // UI Listeners
    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();
    });

    setInterval(() => {
        processData();
    }, 1000);

    if (common && common.initInteractionListeners) {
        common.initInteractionListeners();
        common.subscribe('athlete/watching', (packet) => {
            if(packet) {
                const w = (packet.power !== undefined) ? packet.power : (packet.state ? packet.state.power : undefined);
                if (w !== undefined) currentWatts = w;
            }
        });
    }
}