/**
 * Flexia — pantalla de formateo: progreso visual + llamada prepareInstallWizard.
 */
(function (global) {
    'use strict';

    var cfg = global.FLEXIA_FORMAT_LOAD || {};
    var lang = (cfg.lang === 'en') ? 'en' : 'es';
    var strings = {
        es: {
            brand: 'Flexia',
            title: 'Formateando instancia',
            subtitle: 'Estamos preparando Flexia para empezar de nuevo. No cierres esta ventana.',
            pctLabel: 'progreso',
            elapsed: 'Transcurrido',
            eta: 'Estimado',
            phase0: 'Preparando reinicio del asistente…',
            phaseBackup: 'Guardando documentos en la carpeta flexia disk…',
            phase1: 'Eliminando usuarios y accesos…',
            phase2: 'Restableciendo ajustes del escritorio…',
            phase3: 'Eliminando logos e imágenes…',
            phase4: 'Limpiando fondos y archivos multimedia…',
            phase5: 'Abriendo el asistente de configuración…',
            phaseDone: 'Formateo completado. Abriendo instalador…',
            errorDefault: 'No se pudo completar el formateo.',
            back: 'Volver al escritorio',
        },
        en: {
            brand: 'Flexia',
            title: 'Formatting instance',
            subtitle: 'Flexia is being reset. Do not close this window.',
            pctLabel: 'progress',
            elapsed: 'Elapsed',
            eta: 'Estimated',
            phase0: 'Preparing wizard reset…',
            phaseBackup: 'Saving documents to the flexia disk folder…',
            phase1: 'Removing users and sign-in data…',
            phase2: 'Resetting desktop settings…',
            phase3: 'Removing logos and images…',
            phase4: 'Cleaning wallpapers and media files…',
            phase5: 'Opening the setup wizard…',
            phaseDone: 'Format complete. Opening installer…',
            errorDefault: 'Could not complete the format.',
            back: 'Back to desktop',
        },
    };
    var L = strings[lang] || strings.es;

    var pctEl = document.getElementById('fmtPctValue');
    var ringEl = document.getElementById('fmtRingProgress');
    var barEl = document.getElementById('fmtBarFill');
    var phaseEl = document.getElementById('fmtPhase');
    var elapsedEl = document.getElementById('fmtElapsed');
    var etaEl = document.getElementById('fmtEta');
    var errEl = document.getElementById('fmtError');
    var backBtn = document.getElementById('fmtBackBtn');
    var panelEl = document.querySelector('.flexia-format-load__panel');
    var rootEl = document.body;

    var RING_LEN = 283;
    var startMs = Date.now();
    var displayPct = 0;
    var apiDone = false;
    var apiOk = false;
    var installUrl = '';
    var phaseIndex = 0;
    var keepDocs = !!cfg.keepExplorerFiles;
    var phases = keepDocs
        ? [L.phase0, L.phaseBackup, L.phase1, L.phase2, L.phase3, L.phase4, L.phase5]
        : [L.phase0, L.phase1, L.phase2, L.phase3, L.phase4, L.phase5];
    var estimateMs = keepDocs ? 45000 : 38000;

    function tr(key) {
        return L[key] || strings.es[key] || key;
    }

    function formatTime(ms) {
        var s = Math.max(0, Math.floor(ms / 1000));
        var m = Math.floor(s / 60);
        s = s % 60;
        return (m > 0 ? m + ':' : '') + (s < 10 && m > 0 ? '0' : '') + s + ' s';
    }

    function setPct(p) {
        var v = Math.max(0, Math.min(100, Math.round(p)));
        if (pctEl) pctEl.textContent = String(v) + '%';
        if (ringEl) {
            ringEl.style.strokeDashoffset = String(RING_LEN - (RING_LEN * v) / 100);
        }
        if (barEl) barEl.style.width = v + '%';
    }

    function setPhase(text, fade) {
        if (!phaseEl) return;
        if (fade) phaseEl.classList.add('is-fading');
        setTimeout(function () {
            phaseEl.textContent = text;
            phaseEl.classList.remove('is-fading');
        }, fade ? 180 : 0);
    }

    function showError(msg) {
        if (errEl) {
            errEl.textContent = msg || tr('errorDefault');
            errEl.classList.add('is-visible');
        }
        if (backBtn) backBtn.classList.add('is-visible');
    }

    function tick() {
        var elapsed = Date.now() - startMs;
        var timePct = Math.min(92, (elapsed / estimateMs) * 92);
        if (!apiDone) {
            displayPct += (timePct - displayPct) * 0.06;
            var nextPhase = Math.min(phases.length - 1, Math.floor((elapsed / estimateMs) * phases.length));
            if (nextPhase !== phaseIndex) {
                phaseIndex = nextPhase;
                setPhase(phases[phaseIndex], true);
            }
        } else if (apiOk) {
            displayPct += (100 - displayPct) * 0.12;
            if (displayPct >= 99) {
                displayPct = 100;
                setPhase(L.phaseDone, false);
                rootEl.classList.add('is-complete');
                setTimeout(function () {
                    global.location.replace(installUrl || cfg.installFallback || '../install/');
                }, 650);
                setPct(100);
                return;
            }
        }
        setPct(displayPct);
        if (elapsedEl) elapsedEl.textContent = formatTime(elapsed);
        if (etaEl && !apiDone) {
            var remain = Math.max(0, estimateMs - elapsed);
            etaEl.textContent = formatTime(remain);
        } else if (etaEl && apiOk) {
            etaEl.textContent = '—';
        }
        requestAnimationFrame(tick);
    }

    function runFormat() {
        var apiUrl = cfg.apiUrl || '../index.php?action=prepareInstallWizard';
        var keep = !!cfg.keepExplorerFiles;
        fetch(apiUrl, {
            method: 'POST',
            credentials: 'same-origin',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ keepExplorerFiles: keep }),
        })
            .then(function (res) {
                return res.json().catch(function () {
                    return {};
                });
            })
            .then(function (data) {
                apiDone = true;
                if (data && data.success) {
                    apiOk = true;
                    try {
                        if (global.FlexiaInstanceGuard && typeof global.FlexiaInstanceGuard.markPendingWipe === 'function') {
                            global.FlexiaInstanceGuard.markPendingWipe();
                        } else {
                            sessionStorage.setItem('flexia_pending_client_wipe', '1');
                        }
                    } catch (_) {}
                    installUrl = data.installUrl || cfg.installFallback || '../install/?fresh=1';
                    var took = Date.now() - startMs;
                    if (took > 8000) estimateMs = took * 1.05;
                } else {
                    apiOk = false;
                    showError((data && data.error) ? data.error : tr('errorDefault'));
                }
            })
            .catch(function () {
                apiDone = true;
                apiOk = false;
                showError(tr('errorDefault'));
            });
    }

    if (backBtn && cfg.appUrl) {
        backBtn.addEventListener('click', function () {
            global.location.href = cfg.appUrl;
        });
    }

    if (panelEl) {
        global.addEventListener('mousemove', function (ev) {
            var cx = global.innerWidth / 2;
            var cy = global.innerHeight / 2;
            var dx = (ev.clientX - cx) / cx;
            var dy = (ev.clientY - cy) / cy;
            panelEl.style.setProperty('--fmt-tilt-x', (-dy * 4).toFixed(2) + 'deg');
            panelEl.style.setProperty('--fmt-tilt-y', (dx * 5).toFixed(2) + 'deg');
        });
    }

    document.documentElement.setAttribute('lang', lang);
    var titleEl = document.getElementById('fmtTitle');
    if (titleEl) titleEl.textContent = tr('title');
    var subEl = document.getElementById('fmtSubtitle');
    if (subEl) subEl.textContent = tr('subtitle');
    var brandEl = document.getElementById('fmtBrand');
    if (brandEl) brandEl.textContent = tr('brand');
    var pctLabelEl = document.getElementById('fmtPctLabel');
    if (pctLabelEl) pctLabelEl.textContent = tr('pctLabel');
    var elapsedLabel = document.getElementById('fmtElapsedLabel');
    if (elapsedLabel) elapsedLabel.textContent = tr('elapsed');
    var etaLabel = document.getElementById('fmtEtaLabel');
    if (etaLabel) etaLabel.textContent = tr('eta');
    if (backBtn) backBtn.textContent = tr('back');

    setPhase(L.phase0, false);
    requestAnimationFrame(tick);
    runFormat();
})(typeof window !== 'undefined' ? window : this);
