/* global trstempWizard */

let importProgress = 0;

/* ---------- UI DATA ---------- */
let importSteps = [
    { percentage: 10, message: 'Checking required plugin status...', step: 'plugins' },
    { percentage: 25, message: 'Connecting to template server...', step: 'template' },
    { percentage: 40, message: 'Downloading template data...', step: 'template' },
    { percentage: 60, message: 'Creating pages & content...', step: 'content' },
    { percentage: 80, message: 'Applying customization...', step: 'customization' },
    { percentage: 95, message: 'Finalizing website...', step: 'finalize' }
];

const stepMap = {
    plugins: 'status-plugins',
    template: 'status-template',
    content: 'status-content',
    customization: 'status-customization',
    finalize: 'status-finalize'
};

const tips = [
    'Your website will be fully responsive and optimized for all devices automatically.',
    'All templates include SEO-friendly markup.',
    'You can customize everything using Elementor.',
    'Turbo Addons includes 80+ premium widgets.',
    'Optimized for speed and performance.'
];

/* ---------- INIT ---------- */
document.addEventListener('DOMContentLoaded', () => {
    // Removed 800ms artificial delay - no reason to wait before starting
    trstemp_startImport();
});

/* ---------- PLUGIN INSTALL ---------- */
// NOTE: trstemp_installPluginsFromSession() is disabled.
// Step-4 no longer writes to sessionStorage('trstemp_required_plugins'),
// so this always resolved with an empty array and made a pointless AJAX call.
// function trstemp_installPluginsFromSession() {
//     const plugins = JSON.parse(sessionStorage.getItem('trstemp_required_plugins') || '[]');
//     if (!plugins.length) return Promise.resolve();
//     const fd = new FormData();
//     fd.append('action', 'trstemp_install_plugins');
//     fd.append('nonce', trstempWizard.nonce);
//     plugins.forEach(p => fd.append('plugins[]', p));
//     return fetch(trstempWizard.ajaxurl, { method: 'POST', body: fd })
//         .then(r => r.json())
//         .then(d => { if (!d.success) throw new Error(d.data || 'Plugin install failed'); });
// }

/* ---------- THEME SETUP ---------- */
function trstemp_setupTheme() {
    const fd = new FormData();
    fd.append('action', 'trstemp_setup_theme');
    fd.append('nonce', trstempWizard.nonce);
    return fetch(trstempWizard.ajaxurl, { method: 'POST', body: fd })
        .then(r => r.json())
        .then(d => { if (!d.success) throw new Error(d.data && d.data.message ? d.data.message : 'Theme setup failed'); });
}

/* ---------- MAIN FLOW ---------- */
function trstemp_startImport() {

    // Read customization saved by step-3 (key: trstemp_wizard_customizations)
    const importData = {
        template: sessionStorage.getItem('trstemp_selected_template') || '7',
        customization: JSON.parse(sessionStorage.getItem('trstemp_wizard_customizations') || '{}')
    };

    // Update content step text based on user choice
    const keepExistingData = sessionStorage.getItem("turbo_keep_existing_data") === "true";
    const contentTitle = document.getElementById('content-title');
    const contentDescription = document.getElementById('content-description');
    
    if (keepExistingData) {
        if (contentTitle) contentTitle.textContent = 'Adding Template Pages';
        if (contentDescription) contentDescription.textContent = 'Creating new pages alongside your existing content';
    } else {
        if (contentTitle) contentTitle.textContent = 'Creating Pages & Content';
        if (contentDescription) contentDescription.textContent = 'Replacing existing pages with template content';
    }

    trstemp_rotateTips();
    trstemp_updateStatus('Setting up theme...');
    trstemp_setStepActive('plugins');

    trstemp_setupTheme()
        .then(() => trstemp_runVisualSteps(importData))
        .catch(e => trstemp_showError(e.message));
}

/* ---------- VISUAL STEP ANIMATION (OLD VIBE) ---------- */
function trstemp_runVisualSteps(importData) {
    let i = 0;

    function next() {
        if (i >= importSteps.length) {
            trstemp_doRealImport(importData);
            return;
        }

        const s = importSteps[i];
        trstemp_updateProgress(s.percentage);
        trstemp_updateStatus(s.message);
        trstemp_setStepActive(s.step);

        i++;
        setTimeout(next, 1500);
    }

    next();
}

/* ---------- REAL IMPORT ---------- */
function trstemp_doRealImport(importData) {

    trstemp_updateStatus('Importing your selected template...');

    // Get the keep_existing_data setting from sessionStorage
    const keepExistingData = sessionStorage.getItem("turbo_keep_existing_data") === "true";
    
    // console.log("TRSTEMP Step 6: keep_existing_data from sessionStorage:", sessionStorage.getItem("turbo_keep_existing_data"));
    // console.log("TRSTEMP Step 6: keepExistingData boolean:", keepExistingData);
    
    const fd = new FormData();
    fd.append('action', 'trstemp_import_template');
    fd.append('template_id', importData.template);
    fd.append('customization', JSON.stringify(importData.customization));
    fd.append('keep_existing_data', keepExistingData ? '1' : '0');
    fd.append('nonce', trstempWizard.nonce);

    fetch(trstempWizard.ajaxurl, { method: 'POST', body: fd })
        .then(r => r.json())
        .then(d => {
            if (!d.success) {
                trstemp_showError(d.data || 'Import failed');
                return;
            }

            trstemp_updateProgress(100);
            trstemp_updateStatus('Website created successfully!');
            setTimeout(trstemp_completeImport, 900);
        })
        .catch(() => trstemp_showError('Network error'));
}

/* ---------- UI HELPERS ---------- */
function trstemp_updateProgress(percent) {
    const circle = document.getElementById('progress-bar');
    const text = document.getElementById('progress-text');
    if (!circle || !text) return;

    const circumference = 314;
    const offset = circumference - (percent / 100) * circumference;
    circle.style.strokeDashoffset = offset;
    text.textContent = percent + '%';
}

function trstemp_updateStatus(text) {
    const el = document.getElementById('import-subtitle');
    if (el) el.textContent = text;
}

function trstemp_setStepActive(stepKey) {
    Object.values(stepMap).forEach(id => {
        const el = document.getElementById(id);
        if (!el) return;

        if (id === stepMap[stepKey]) {
            el.classList.add('active');
        } else if (el.classList.contains('active')) {
            el.classList.remove('active');
            el.classList.add('completed');
            el.querySelector('.status-icon').textContent = '✅';
        }
    });
}

function trstemp_rotateTips() {
    let i = 0;
    const el = document.getElementById('tip-content');
    if (!el) return;

    setInterval(() => {
        el.style.opacity = '0';
        setTimeout(() => {
            el.innerHTML = `<p>${tips[i]}</p>`;
            el.style.opacity = '1';
            i = (i + 1) % tips.length;
        }, 300);
    }, 4000);
}

/* ---------- SUCCESS (OLD STYLE) ---------- */
function trstemp_completeImport() {
    document.querySelector('.import-header').style.display = 'none';
    document.querySelector('.import-progress-container').style.display = 'none';
    document.querySelector('.import-status').style.display = 'none';
    document.querySelector('.import-tips').style.display = 'none';

    document.getElementById('import-success').style.display = 'block';

    sessionStorage.clear();
}

/* ---------- ERROR ---------- */
function trstemp_showError(msg) {
    document.querySelector('.import-header').style.display = 'none';
    document.querySelector('.import-progress-container').style.display = 'none';
    document.querySelector('.import-status').style.display = 'none';
    document.querySelector('.import-tips').style.display = 'none';

    document.getElementById('error-message').textContent = msg;
    document.getElementById('import-error').style.display = 'block';
}
