/**
 * Free Templates Tab — fetches and displays only free (free_pro === 'Free') templates.
 * All element IDs are prefixed with "free-" to avoid conflicts with the main Templates tab.
 */
document.addEventListener('DOMContentLoaded', function () {
    let currentPage = 1;
    let totalPages = 1;
    let currentCategoryId = null;
    let currentCategorySlug = null;
    let currentSearchQuery = null;
    const templatesApiEndpoint = fleximp_template_ajax_object.apiEndpoint;
    let isFetchingTemplates = false;
    let isFetchingCategories = false;

    // -------------------------------------------------------------------------
    // Loader helpers
    // -------------------------------------------------------------------------
    function showLoader(num = 6) {
        const loader = document.getElementById('free-templates-skeleton-loader');
        const list = document.getElementById('free-templates-list');
        if (list) list.innerHTML = '';
        if (loader) {
            const grid = loader.querySelector('.skeleton-grid');
            if (grid) {
                grid.innerHTML = '';
                for (let i = 0; i < num; i++) {
                    const item = document.createElement('div');
                    item.className = 'skeleton-item';
                    item.innerHTML = `
                        <div class="skeleton-image"></div>
                        <div class="skeleton-content">
                            <div class="skeleton-title"></div>
                            <div class="skeleton-buttons">
                                <div class="skeleton-button"></div>
                                <div class="skeleton-button"></div>
                            </div>
                        </div>`;
                    grid.appendChild(item);
                }
            }
            loader.style.display = 'block';
        }
    }

    function hideLoader() {
        const loader = document.getElementById('free-templates-skeleton-loader');
        if (loader) loader.style.display = 'none';
    }

    // -------------------------------------------------------------------------
    // Template data helpers
    // -------------------------------------------------------------------------
    function getTemplateData(template) {
        let pluginsData = template.metafields?.selected_plugins || {};
        if (Array.isArray(pluginsData)) pluginsData = {};
        return {
            textDomain: template.template_domain,
            jsonPath: template.metafields?.json_path || '',
            contentPath: template.metafields?.content_path || '',
            templateCss: template.metafields?.template_css_path || '',
            templateJs: template.metafields?.template_js_path || '',
            templatePhp: template.metafields?.template_php_path || '',
            plugins: JSON.stringify(pluginsData),
            templateMobileImage: template.metafields?.template_screenshot || '',
            templateResponsiveImage: template.metafields?.template_responsive_image || '',
            title: template.title || '',
        };
    }

    function setButtonDataAttributes(button, template) {
        const data = getTemplateData(template);
        button.setAttribute('data-text-domain', data.textDomain);
        button.setAttribute('data-json-path', data.jsonPath);
        button.setAttribute('data-content-path', data.contentPath);
        button.setAttribute('data-template-php', data.templatePhp);
        button.setAttribute('data-template-css', data.templateCss);
        button.setAttribute('data-template-js', data.templateJs);
        button.setAttribute('data-plugins', data.plugins);
        button.setAttribute('data-template-mobile-image', data.templateMobileImage);
        button.setAttribute('data-template-responsive-image', data.templateResponsiveImage);
        button.setAttribute('data-title', data.title);
    }

    // -------------------------------------------------------------------------
    // Import process UI
    // -------------------------------------------------------------------------
    function ensureElementor() {
        if (fleximp_template_ajax_object.isElementorActive === '1') {
            return Promise.resolve();
        }
        return fetch(fleximp_template_ajax_object.ajax_url, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: new URLSearchParams({
                action: 'fleximp_checked_install_plugin',
                plugin_slug: 'elementor',
                plugin_name: 'Elementor',
                plugin_main_file: 'elementor.php',
            }),
        })
            .then(r => r.json())
            .then(resp => {
                if (!resp.success) {
                    throw new Error(resp.data?.message || 'Failed to install Elementor.');
                }
            });
    }

    function handleConfirmClick() {
        const textDomain = this.getAttribute('data-text-domain');
        const jsonPath = this.getAttribute('data-json-path');
        const contentPath = this.getAttribute('data-content-path');
        const templateCss = this.getAttribute('data-template-css');
        const templateJs = this.getAttribute('data-template-js');
        const templatePhp = this.getAttribute('data-template-php');
        const plugins = this.getAttribute('data-plugins');
        const templateResponsiveImage = this.getAttribute('data-template-responsive-image');
        const templateMobileImage = this.getAttribute('data-template-mobile-image');
        const templateTitle = this.getAttribute('data-title');

        sessionStorage.setItem('fleximp_import_data', JSON.stringify({
            textDomain, jsonPath, contentPath, templateCss, templateJs,
            templatePhp, plugins, templateResponsiveImage, templateMobileImage, title: templateTitle,
        }));

        if (!textDomain) { alert('Text domain not found.'); return; }

        ensureElementor()
            .then(() => fetch(fleximp_ajax_object.ajax_url, {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: new URLSearchParams({
                    action: 'fleximp_set_text_domain',
                    text_domain: textDomain,
                    template_php: templatePhp,
                    template_mobile_image: templateMobileImage,
                    template_title: templateTitle,
                })
            }))
            .then(res => res.json())
            .then(response => {
                if (response.success) {
                    sessionStorage.setItem('fleximp_auto_continue_free', '1');
                    location.reload();
                } else {
                    alert('Failed to update text domain.');
                }
            })
            .catch(error => {
                console.error('Import error:', error);
                alert('Error: ' + error.message);
            });
    }

    function showImportProcess(template) {
        const importSection = document.querySelector('.flex-free-import-process');
        const importTitle = document.getElementById('free-import-process-title');
        const importDescription = document.getElementById('free-import-process-description');
        const importMobileTitle = document.getElementById('free-import-process-mobile-title');
        const importMobileImage = document.getElementById('free-import-process-mobile-image');
        const importScreenshot = document.getElementById('free-import-process-mid-image');
        const importResponsive = document.getElementById('free-import-process-responsive-image');

        if (importSection && importScreenshot && importTitle && importMobileTitle && importMobileImage && importResponsive) {
            importTitle.textContent = template.title;
            importDescription.textContent = template.metafields?.template_desc || '';
            importMobileTitle.textContent = template.title;
            importMobileImage.src = template.metafields?.template_screenshot || '';
            importScreenshot.src = template.metafields?.template_screenshot || '';
            importResponsive.src = template.metafields?.template_responsive_image || '';
            importSection.style.display = 'block';
            importSection.scrollIntoView({ behavior: 'smooth' });

            const confirmBtn = document.getElementById('free-import-process-confirm-btn');
            if (confirmBtn) {
                setButtonDataAttributes(confirmBtn, template);
                sessionStorage.setItem('fleximp_import_data', JSON.stringify(getTemplateData(template)));
                confirmBtn.addEventListener('click', handleConfirmClick, { once: true });
            }

            const cancelBtn = document.getElementById('free-import-process-cancel-btn');
            if (cancelBtn) {
                cancelBtn.addEventListener('click', () => { importSection.style.display = 'none'; });
            }

            const demoUrl = template.metafields?.demo_url || '#';
            const docUrl = template.metafields?.documentation_url || '';
            const buyUrl = template.metafields?.buy_now_url || '#';

            const upgradeBtn = document.getElementById('free-upgrade-pro-btn');
            if (upgradeBtn) upgradeBtn.href = buyUrl;

            const doneUpgradeBtn = document.getElementById('free-done-upgrade-pro-btn');
            if (doneUpgradeBtn) doneUpgradeBtn.href = buyUrl;

            const liveDemoBtn = document.getElementById('free-live-demo-btn');
            if (liveDemoBtn) liveDemoBtn.href = demoUrl;

            const liveDocBtn = document.getElementById('free-document-url-btn');
            if (liveDocBtn) {
                liveDocBtn.href = docUrl;
                liveDocBtn.style.display = docUrl ? 'inline-block' : 'none';
            }

            hideLoader();
        }
    }

    function showDoneProcess() {
        const importSection = document.querySelector('.flex-free-import-process');
        const uninstallBtn = document.getElementById('free-import-process-uninstall-btn');
        if (importSection && uninstallBtn) {
            importSection.style.display = 'block';
            importSection.scrollIntoView({ behavior: 'smooth' });
            document.getElementById('free-import-process-confirm').style.display = 'none';
            document.getElementById('free-import-process-plugins').style.display = 'none';
            document.getElementById('free-import-process-done').style.display = 'block';
            uninstallBtn.style.display = 'inline-block';
            hideLoader();
        }
    }

    // -------------------------------------------------------------------------
    // Fetch & display templates (free only)
    // -------------------------------------------------------------------------
    function fetchTemplates(categoryId = null, categorySlug = null, page = 1, searchQuery = null) {
        if (isFetchingTemplates) return;
        isFetchingTemplates = true;
        showLoader();

        if (categoryId && categorySlug) {
            currentCategoryId = categoryId;
            currentCategorySlug = categorySlug;
        }
        currentPage = page;
        currentSearchQuery = searchQuery;

        const themeAuthor = fleximp_template_ajax_object.active_theme_author?.toLowerCase() || '';
        const isFlexTheme = themeAuthor === 'flextheme';
        const currentTextDomain = fleximp_template_ajax_object.fleximp_current_text_domain;

        const requestBody = {
            action: 'getTemplates',
            per_page: 6,
            page: currentPage,
            free_pro: 'Free',
        };

        requestBody.free_theme_domain = isFlexTheme ? currentTextDomain : '';

        if (currentCategoryId && currentCategorySlug) {
            requestBody.product_cat = currentCategoryId;
        } else {
            requestBody.product_cat = 15;
        }

        if (searchQuery) requestBody.search = searchQuery;

        fetch(templatesApiEndpoint, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(requestBody),
        })
            .then(response => response.json())
            .then(async data => {
                if (data.success && data.data) {
                    let templates = data.data.posts || data.data.data?.posts;
                    const freeTemplate = data?.data?.data?.free_template || data?.data?.free_template || data?.free_template || null;

                    if (Array.isArray(templates)) {
                        // Keep only free templates as a safety client-side guard
                        templates = templates.filter(t => t.metafields?.free_pro !== 'Pro');

                        // If there's a free_template, show the import process for it
                        if (freeTemplate) {
                            showImportProcess(freeTemplate);
                        }

                        await displayTemplates(templates, freeTemplate);
                        totalPages = data.data.total_pages || (data.data.data ? data.data.data.total_pages : 1);
                        updatePaginationControls();
                    } else {
                        await displayTemplates([]);
                    }
                } else {
                    await displayTemplates([]);
                }
                isFetchingTemplates = false;
            })
            .catch(async error => {
                console.error('Free Templates Network Error:', error);
                await displayTemplates([]);
                isFetchingTemplates = false;
            });
    }

    // -------------------------------------------------------------------------
    // Pagination
    // -------------------------------------------------------------------------
    function updatePaginationControls() {
        const container = document.getElementById('free-pagination-controls');
        if (!container) return;
        container.innerHTML = '';

        const prevLi = document.createElement('li');
        prevLi.className = `page-item ${currentPage === 1 ? 'disabled' : ''}`;
        prevLi.innerHTML = `<a class="page-link" href="#" aria-label="Previous"><span aria-hidden="true"><i class="fa-solid fa-angle-left" style="color:hsl(0,0%,100%);"></i></span></a>`;
        prevLi.addEventListener('click', e => {
            e.preventDefault();
            if (currentPage > 1) fetchTemplates(currentCategoryId, currentCategorySlug, currentPage - 1, currentSearchQuery);
        });
        container.appendChild(prevLi);

        const maxVisible = 6;
        let startPage = Math.max(1, currentPage - Math.floor(maxVisible / 2));
        let endPage = Math.min(totalPages, startPage + maxVisible - 1);
        if (endPage - startPage + 1 < maxVisible) startPage = Math.max(1, endPage - maxVisible + 1);

        if (startPage > 1) {
            const firstLi = document.createElement('li');
            firstLi.className = 'page-item';
            firstLi.innerHTML = `<a class="page-link" href="#">1</a>`;
            firstLi.addEventListener('click', e => { e.preventDefault(); fetchTemplates(currentCategoryId, currentCategorySlug, 1, currentSearchQuery); });
            container.appendChild(firstLi);
            if (startPage > 2) {
                const el = document.createElement('li');
                el.className = 'page-item disabled';
                el.innerHTML = `<span class="page-link">...</span>`;
                container.appendChild(el);
            }
        }

        for (let i = startPage; i <= endPage; i++) {
            const li = document.createElement('li');
            li.className = `page-item ${i === currentPage ? 'active' : ''}`;
            li.innerHTML = `<a class="page-link" href="#">${i}</a>`;
            li.addEventListener('click', (e => {
                const pg = i;
                return ev => { ev.preventDefault(); fetchTemplates(currentCategoryId, currentCategorySlug, pg, currentSearchQuery); };
            })());
            container.appendChild(li);
        }

        if (endPage < totalPages) {
            if (endPage < totalPages - 1) {
                const el = document.createElement('li');
                el.className = 'page-item disabled';
                el.innerHTML = `<span class="page-link">...</span>`;
                container.appendChild(el);
            }
            const lastLi = document.createElement('li');
            lastLi.className = 'page-item';
            lastLi.innerHTML = `<a class="page-link" href="#">${totalPages}</a>`;
            lastLi.addEventListener('click', e => { e.preventDefault(); fetchTemplates(currentCategoryId, currentCategorySlug, totalPages); });
            container.appendChild(lastLi);
        }

        const nextLi = document.createElement('li');
        nextLi.className = `page-item ${currentPage === totalPages ? 'disabled' : ''}`;
        nextLi.innerHTML = `<a class="page-link" href="#" aria-label="Next"><span aria-hidden="true"><i class="fa-solid fa-angle-right" style="color:hsl(0,0%,100%);"></i></span></a>`;
        nextLi.addEventListener('click', e => {
            e.preventDefault();
            if (currentPage < totalPages) fetchTemplates(currentCategoryId, currentCategorySlug, currentPage + 1);
        });
        container.appendChild(nextLi);
    }

    // -------------------------------------------------------------------------
    // Fetch & populate categories
    // -------------------------------------------------------------------------
    function fetchCategories() {
        if (isFetchingCategories) return;
        isFetchingCategories = true;

        fetch(templatesApiEndpoint, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ action: 'getCategories' }),
        })
            .then(r => r.json())
            .then(data => {
                if (data.success && Array.isArray(data.data.data)) {
                    displayCategories(data.data.data);
                }
            })
            .catch(err => console.error('Free Templates category error:', err))
            .finally(() => { isFetchingCategories = false; });
    }

    function displayCategories(categories) {
        const select = document.getElementById('free-categories-list');
        if (!select) return;
        select.innerHTML = '';
        categories.forEach((cat, index) => {
            const opt = document.createElement('option');
            opt.value = cat.id;
            opt.setAttribute('data-slug', cat.slug);
            opt.textContent = cat.name;
            if (index === 0) opt.selected = true;
            select.appendChild(opt);
        });
        if (categories.length > 0) {
            fetchTemplates(categories[0].id, categories[0].slug);
        }
    }

    // -------------------------------------------------------------------------
    // Display templates
    // -------------------------------------------------------------------------
    async function displayTemplates(templates, freeTemplate = null) {
        const list = document.getElementById('free-templates-list');
        if (!list) { hideLoader(); return; }
        list.innerHTML = '';

        const activeImportedTemplate = fleximp_template_ajax_object.imported_template;
        const activeThemeTextDomain = fleximp_template_ajax_object.fleximp_current_text_domain;

        const filtered = templates.filter(t =>
            t.template_domain !== activeImportedTemplate &&
            t.template_domain !== activeThemeTextDomain
        );

        if (!filtered.length) {
            list.innerHTML = `<div class="no-templates-message">No free templates found</div>`;
            hideLoader();
            const isImportedFree = templates.some(t => t.template_domain === activeImportedTemplate) ||
                (freeTemplate !== null && freeTemplate.template_domain === activeImportedTemplate);
            if (activeImportedTemplate && isImportedFree && activeImportedTemplate === activeThemeTextDomain) {
                showDoneProcess();
            }
            return;
        }

        filtered.forEach(template => {
            const templateSlug = template.title.toLowerCase().replace(/ /g, '-');
            const demoUrl = template.metafields?.demo_url || '#';
            const selectedPlugins = template.metafields?.selected_plugins || [];
            const jsonPath = template.metafields?.json_path || '';
            const templateMainImage = template.metafields?.template_main_image || '';
            const templateDesc = template.metafields?.template_desc || '';
            const templateDocument = template.metafields?.documentation_url || '';
            const templateMobileImage = template.metafields?.template_screenshot || '';
            const templateResponsiveImage = template.metafields?.template_responsive_image || '';
            const contentPath = template.metafields?.content_path || '';
            const textDomain = template.template_domain || '';
            const templateCss = template.metafields?.template_css_path || '';
            const templateJs = template.metafields?.template_js_path || '';
            const templatePhp = template.metafields?.template_php_path || '';
            const buyNowUrl = template.metafields?.buy_now_url || '#';
            const isImported = fleximp_template_ajax_object.imported_template;
            const fleximpCurrentTextDomain = fleximp_template_ajax_object.fleximp_dynamic_text_domain;

            let buttonHTML = '';

            if (isImported === textDomain) {
                buttonHTML = `
                <button class="btn flex-template-buttons uninstall-btn"
                    data-template="${templateSlug}"
                    data-title="${template.title}"
                    data-plugins='${JSON.stringify(selectedPlugins)}'
                    data-json-path="${jsonPath}"
                    data-template-main-image="${templateMainImage}"
                    data-template-mobile-image="${templateMobileImage}"
                    data-template-responsive-image="${templateResponsiveImage}"
                    data-template-description="${templateDesc}"
                    data-template-doc-url="${templateDocument}"
                    data-content-path="${contentPath}"
                    data-text-domain="${textDomain}"
                    data-template-css="${templateCss}"
                    data-template-js="${templateJs}"
                    data-template-php="${templatePhp}">
                    Uninstall
                </button>`;
            } else {
                if (activeThemeTextDomain !== textDomain) {
                    const installedSlugs = fleximp_template_ajax_object.installed_theme_slugs || [];
                    const isInstalled = installedSlugs.includes(textDomain);
                    const themeLabel = isInstalled ? 'ACTIVATE THEME' : 'INSTALL THEME';
                    buttonHTML = `
                <button class="btn flex-unique-free-activate-theme-btn flex-template-buttons"
                    data-theme-slug="${textDomain}">
                    ${themeLabel}
                </button>`;
                } else {
                    buttonHTML = `
                    <button class="btn flex-unique-free-import-button flex-template-buttons import-btn"
                        data-template="${templateSlug}"
                        data-title="${template.title}"
                        data-plugins='${JSON.stringify(selectedPlugins)}'
                        data-json-path="${jsonPath}"
                        data-template-main-image="${templateMainImage}"
                        data-template-mobile-image="${templateMobileImage}"
                        data-template-responsive-image="${templateResponsiveImage}"
                        data-template-description="${templateDesc}"
                        data-template-doc-url="${templateDocument}"
                        data-content-path="${contentPath}"
                        data-text-domain="${textDomain}"
                        data-template-css="${templateCss}"
                        data-template-js="${templateJs}"
                        data-template-php="${templatePhp}"
                        data-buy-url="${buyNowUrl}"
                        data-demo-url="${demoUrl}">
                        IMPORT DEMO
                    </button>`;
                }
            }

            list.innerHTML += `
                <div class="template-item grid-item" style="position: relative;">
                    <div class="flex-imp-temp-inner-box"><img src="${templateMainImage}" alt="${template.title}" style=""></div>
                    <div class="fleximp-temp-buttons widgets-btn">
                        <div class="buttons widgets-btn pb-3">
                            <div class="btn-title">
                                <p class="template-title">${template.title}</p>
                            </div>
                            <div class="premium-badge">Free</div>
                        </div>
                        <div class="d-md-flex d-sm-block d-flex flex-gap-div">
                            <a href="${demoUrl}" target="_blank" class="btn flex-template-buttons">LIVE DEMO</a>
                            ${buttonHTML}
                        </div>
                    </div>
                </div>`;
        });

        hideLoader();

        const isImportedFree = templates.some(t => t.template_domain === activeImportedTemplate) ||
            (freeTemplate !== null && freeTemplate.template_domain === activeImportedTemplate);
        if (activeImportedTemplate && isImportedFree && activeImportedTemplate === activeThemeTextDomain) {
            showDoneProcess();
        }
    }

    // -------------------------------------------------------------------------
    // Import button click (delegated)
    // -------------------------------------------------------------------------
    document.addEventListener('click', function (event) {
        if (!event.target.classList.contains('flex-unique-free-import-button')) return;

        const btn = event.target;
        const templateTitle = btn.getAttribute('data-title');
        const templateDesc = btn.getAttribute('data-template-description');
        const templateMobileImage = btn.getAttribute('data-template-mobile-image');
        const textDomain = btn.getAttribute('data-text-domain');
        const jsonPath = btn.getAttribute('data-json-path');
        const contentPath = btn.getAttribute('data-content-path');
        const templateCss = btn.getAttribute('data-template-css');
        const templateJs = btn.getAttribute('data-template-js');
        const templatePhp = btn.getAttribute('data-template-php');
        const plugins = btn.getAttribute('data-plugins');
        const templateResponsiveImage = btn.getAttribute('data-template-responsive-image');
        const demoUrl = btn.getAttribute('data-demo-url');
        const docUrl = btn.getAttribute('data-template-doc-url') || '';

        const importSection = document.querySelector('.flex-free-import-process');
        const importTitle = document.getElementById('free-import-process-title');
        const importDescription = document.getElementById('free-import-process-description');
        const importMobileTitle = document.getElementById('free-import-process-mobile-title');
        const importMobileImage = document.getElementById('free-import-process-mobile-image');
        const importResponsive = document.getElementById('free-import-process-responsive-image');

        if (importSection && importTitle && importMobileTitle && importMobileImage && importResponsive) {
            importTitle.textContent = templateTitle;
            importDescription.textContent = templateDesc;
            importMobileTitle.textContent = templateTitle;
            importMobileImage.src = templateMobileImage;
            importResponsive.src = templateResponsiveImage;
            importSection.style.display = 'block';
            importSection.scrollIntoView({ behavior: 'smooth' });

            const liveDemoBtn = document.getElementById('free-live-demo-btn');
            if (liveDemoBtn) liveDemoBtn.href = demoUrl;

            const upgradeProBtn = document.getElementById('free-upgrade-pro-btn');
            if (upgradeProBtn) upgradeProBtn.href = btn.getAttribute('data-buy-url') || '#';

            const liveDocBtn = document.getElementById('free-document-url-btn');
            if (liveDocBtn) {
                liveDocBtn.href = docUrl;
                liveDocBtn.style.display = docUrl ? 'inline-block' : 'none';
            }

            const confirmBtn = document.getElementById('free-import-process-confirm-btn');
            if (confirmBtn) {
                confirmBtn.addEventListener('click', function () {
                    sessionStorage.setItem('fleximp_import_data', JSON.stringify({
                        textDomain, jsonPath, contentPath, templateCss, templateJs,
                        templatePhp, plugins, templateResponsiveImage, templateMobileImage,
                        title: templateTitle,
                    }));

                    if (!textDomain) { alert('Text domain not found.'); return; }

                    fetch(fleximp_ajax_object.ajax_url, {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                        body: new URLSearchParams({
                            action: 'fleximp_set_text_domain',
                            text_domain: textDomain,
                            template_php: templatePhp,
                            template_mobile_image: templateMobileImage,
                            template_title: templateTitle,
                        })
                    })
                        .then(r => r.json())
                        .then(resp => {
                            if (resp.success) {
                                sessionStorage.setItem('fleximp_auto_continue_free', '1');
                                location.reload();
                            } else {
                                alert('Failed to update text domain.');
                            }
                        })
                        .catch(err => {
                            console.error('Text domain AJAX error:', err);
                            alert('Error updating text domain.');
                        });
                }, { once: true });
            }

            const cancelBtn = document.getElementById('free-import-process-cancel-btn');
            if (cancelBtn) {
                cancelBtn.addEventListener('click', () => { importSection.style.display = 'none'; }, { once: true });
            }
        }
    });

    // -------------------------------------------------------------------------
    // Activate-theme button click (delegated)
    // -------------------------------------------------------------------------
    document.addEventListener('click', function (event) {
        if (!event.target.classList.contains('flex-unique-free-activate-theme-btn')) return;

        const btn = event.target;
        const themeSlug = btn.getAttribute('data-theme-slug');
        if (!themeSlug) return;

        const originalLabel = btn.textContent.trim();
        btn.disabled = true;
        btn.textContent = originalLabel === 'ACTIVATE THEME' ? 'Activating...' : 'Installing...';

        fetch(fleximp_template_ajax_object.ajax_url, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: new URLSearchParams({
                action: 'fleximp_install_activate_theme',
                security: fleximp_template_ajax_object.fleximp_nonce,
                theme_slug: themeSlug,
            }),
        })
            .then(r => r.json())
            .then(resp => {
                if (resp.success) {
                    btn.textContent = 'Activated! Reloading...';
                    window.location.reload();
                } else {
                    const msg = resp.data?.message || 'Theme installation failed.';
                    alert(msg);
                    btn.disabled = false;
                    btn.textContent = originalLabel;
                }
            })
            .catch(err => {
                console.error('Theme install error:', err);
                alert('An error occurred while installing the theme.');
                btn.disabled = false;
                btn.textContent = originalLabel;
            });
    });

    // -------------------------------------------------------------------------
    // Initialise — only fetch when the Free Templates tab becomes active
    // -------------------------------------------------------------------------
    let initialised = false;

    function initFreeTemplates() {
        if (initialised) return;
        initialised = true;
        showLoader();
        fetchCategories();
    }

    // Check if Free Templates tab is already active on page load
    if (jQuery('#free-templates').hasClass('active') || jQuery('#free-templates').hasClass('show')) {
        initFreeTemplates();
    }

    // Bootstrap 3/4 tab shown event
    jQuery(document).on('shown.bs.tab', 'a[href="#free-templates"]', function () {
        initFreeTemplates();
    });

    // Category select
    jQuery(document).on('change', '#free-categories-list', function () {
        const selected = jQuery(this).find('option:selected');
        fetchTemplates(selected.val(), selected.attr('data-slug'), 1, currentSearchQuery);
    });

    // Search
    jQuery(document).on('input', '#free-flex-templates-search', debounce(function () {
        const selected = jQuery('#free-categories-list option:selected');
        fetchTemplates(selected.val(), selected.attr('data-slug'), 1, jQuery(this).val());
    }, 300));
});

/**
 * Updates the free-templates progress bar and label during the import process.
 * @param {number} percent - Progress percentage (0–100).
 * @param {string} message - Status message to display alongside the percentage.
 */
function updateFreeProgress(percent, message) {
    const bar = document.getElementById('free-import-process-progress-bar');
    const text = document.getElementById('free-import-process-progress-text');
    if (bar && text) {
        bar.style.width = `${percent}%`;
        text.textContent = `${message} (${percent}%)`;
    }
}

/**
 * Debounces a function to limit how often it can be called.
 * @param {Function} func - The function to debounce.
 * @param {number} delay - The delay in milliseconds.
 * @returns {Function} The debounced function.
 */
function debounce(func, delay) {
    let timeoutId;
    return function (...args) {
        clearTimeout(timeoutId);
        timeoutId = setTimeout(() => func.apply(this, args), delay);
    };
}

/**
 * Handles auto-continue import process after page reload for free templates.
 */
window.addEventListener('DOMContentLoaded', function () {
    if (sessionStorage.getItem('fleximp_auto_continue_free') === '1') {
        // Check if this is a free template import
        const importData = sessionStorage.getItem('fleximp_import_data');
        if (!importData) return;

        // Activate free-templates tab
        const freeTemplatesTab = document.querySelector('.nav-link[href="#free-templates"]');
        if (freeTemplatesTab) freeTemplatesTab.classList.add('active');
        const freeTemplatesPane = document.querySelector('#free-templates');
        if (freeTemplatesPane) freeTemplatesPane.classList.add('active', 'show');

        // Deactivate other tabs
        const templatesTab = document.querySelector('.nav-link[href="#templates"]');
        if (templatesTab) templatesTab.classList.remove('active');
        const templatesPane = document.querySelector('#templates');
        if (templatesPane) templatesPane.classList.remove('active', 'show');

        const dashboardTab = document.querySelector('.nav-link[href="#dashboard"]');
        if (dashboardTab) dashboardTab.classList.remove('active');
        const dashboardPane = document.querySelector('#dashboard');
        if (dashboardPane) dashboardPane.classList.remove('active', 'show');

        sessionStorage.removeItem('fleximp_auto_continue_free');

        const {
            textDomain,
            jsonPath,
            contentPath,
            templateCss,
            templateJs,
            templatePhp,
            plugins,
            templateResponsiveImage,
            title: templateTitle
        } = JSON.parse(importData);

        const importResponsiveImage = document.getElementById('free-import-process-responsive-image');
        if (importResponsiveImage) importResponsiveImage.src = templateResponsiveImage;

        const importButton = document.createElement('button');
        importButton.classList.add('flex-unique-free-import-button');
        importButton.setAttribute('data-text-domain', textDomain);
        importButton.setAttribute('data-json-path', jsonPath);
        importButton.setAttribute('data-content-path', contentPath);
        importButton.setAttribute('data-template-css', templateCss);
        importButton.setAttribute('data-template-js', templateJs);
        importButton.setAttribute('data-template-php', templatePhp);
        importButton.setAttribute('data-plugins', plugins);
        importButton.setAttribute('data-title', templateTitle);

        document.body.appendChild(importButton);
        runFreeImportProcess(); // Continue import
    }
});

/**
 * Runs the asynchronous import process for free templates.
 */
async function runFreeImportProcess() {
    document.getElementById('free-import-process-confirm').style.display = 'none';
    document.getElementById('free-import-process-plugins').style.display = 'block';
    const importSection = document.querySelector('.flex-free-import-process');
    importSection.style.display = 'block';
    importSection.scrollIntoView({ behavior: 'smooth' });

    const importBtn = document.querySelector('.flex-unique-free-import-button');
    const selectedPlugins = JSON.parse(importBtn.getAttribute('data-plugins'));
    const jsonPath = importBtn.getAttribute('data-json-path');
    const contentPath = importBtn.getAttribute('data-content-path');
    const templateCss = importBtn.getAttribute('data-template-css');
    const templateJs = importBtn.getAttribute('data-template-js');
    const textDomain = importBtn.getAttribute('data-text-domain');
    const templatePhp = importBtn.getAttribute('data-template-php');

    // Step 1: Install Plugins
    updateFreeStepStatus('free-step-plugins', 'In Process');
    const installPlugin = (plugin) => {
        return new Promise((resolve) => {
            jQuery.ajax({
                url: fleximp_ajax_object.ajax_url,
                method: 'POST',
                data: {
                    action: 'fleximp_checked_install_plugin',
                    plugin_slug: plugin.text_domain,
                    plugin_name: plugin.name,
                    plugin_main_file: plugin.main_file
                },
                success: function (response) {
                    updateFreeProgress(33, `Installed plugin: ${plugin.name}`);
                },
                error: function (xhr, status, error) {
                    console.error(`Error installing plugin ${plugin.name}:`, error);
                },
                complete: function () {
                    resolve();
                }
            });
        });
    };

    const selectedPluginsObj = Object.values(selectedPlugins);
    for (const plugin of selectedPluginsObj) {
        await installPlugin(plugin);
    }
    updateFreeStepStatus('free-step-plugins', 'Done');

    // Step 2: Import Inner Pages
    updateFreeStepStatus('free-step-inner-pages', 'In Process');
    await new Promise((resolve) => {
        jQuery.ajax({
            url: fleximp_ajax_object.ajax_url,
            method: 'POST',
            data: {
                action: 'fleximp_import_inner_pages_data',
                nonce: fleximp_ajax_object.nonce,
                content_path: contentPath,
                text_domain: textDomain,
                template_css: templateCss,
                template_js: templateJs,
                template_php: templatePhp
            },
            success: function (response) {
                updateFreeProgress(75, 'Importing inner pages success');
                updateFreeStepStatus('free-step-inner-pages', 'Done');
            },
            error: function (xhr, status, error) {
                console.error('Error importing inner pages data:', error);
                updateFreeStepStatus('free-step-inner-pages', 'Error');
            },
            complete: function () {
                resolve();
            }
        });
    });

    // Step 3: Import Demo Content
    updateFreeStepStatus('free-step-content', 'In Process');
    await new Promise((resolve) => {
        jQuery.ajax({
            url: fleximp_ajax_object.ajax_url,
            method: 'POST',
            data: {
                action: 'fleximp_import_demo_content',
                text_domain: textDomain,
                json_path: jsonPath
            },
            success: function (response) {
                updateFreeProgress(100, 'Import success');
                updateFreeStepStatus('free-step-content', 'Done');
            },
            error: function (xhr, status, error) {
                console.error('Error importing content:', error);
                updateFreeStepStatus('free-step-content', 'Error');
            },
            complete: function () {
                resolve();
            }
        });
    });

    const continueButton = document.getElementById('free-import-process-continue-btn');
    if (continueButton) continueButton.style.display = 'inline-block';

    document.getElementById('free-import-process-plugins').style.display = 'none';
    document.getElementById('free-import-process-done').style.display = 'block';

    setTimeout(() => location.reload(), 5000);
}

/**
 * Updates the status icon and text for a given import step.
 * @param {string} stepId - The ID of the step element.
 * @param {string} status - The status to set ('In Process', 'Done', 'Error').
 */
function updateFreeStepStatus(stepId, status) {
    const statusElement = document.getElementById(`${stepId}-status`);
    if (statusElement) {
        const statusIcon = statusElement.querySelector('.status-icon');
        if (statusIcon) {
            if (status === 'In Process') {
                statusIcon.innerHTML = '<span class="loader"></span>';
            } else if (status === 'Done') {
                statusIcon.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M256 512A256 256 0 1 0 256 0a256 256 0 1 0 0 512zM369 209L241 337c-9.4 9.4-24.6 9.4-33.9 0l-64-64c-9.4-9.4-9.4-24.6 0-33.9s24.6-9.4 33.9 0l47 47L335 175c9.4-9.4 24.6-9.4 33.9 0s9.4 24.6 0 33.9z"/></svg>';
            } else if (status === 'Error') {
                statusIcon.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M256 512A256 256 0 1 0 256 0a256 256 0 1 0 0 512zM175 175c9.4-9.4 24.6-9.4 33.9 0l47 47 47-47c9.4-9.4 24.6-9.4 33.9 0s9.4 24.6 0 33.9L289 241l47 47c9.4 9.4 9.4 24.6 0 33.9s-24.6 9.4-33.9 0l-47-47-47 47c-9.4 9.4-24.6 9.4-33.9 0s-9.4 24.6 0-33.9l47-47-47-47c-9.4-9.4-9.4-24.6 0-33.9z"/></svg>';
            } else {
                statusIcon.innerHTML = '';
            }
        }
        statusElement.innerHTML = statusElement.innerHTML.replace(/Not Started|In Process|Done|Error/g, status);
    }
}
