/**
 * Updates the progress bar and text during the import process.
 * @param {number} percent - The percentage of progress (0-100).
 * @param {string} message - The message to display with the progress.
 */
function updateProgress(percent, message) {
    const progressBar = document.getElementById('import-process-progress-bar');
    const progressText = document.getElementById('import-process-progress-text');
    if (progressBar && progressText) {
        progressBar.style.width = `${percent}%`;
        progressText.textContent = `${message} (${percent}%)`;
    }
}

function getTemplateData(template) {

    let pluginsData = template.metafields?.selected_plugins || {};

    // If pluginsData is array (wrong structure), try to recover
    if (Array.isArray(pluginsData)) {
        console.warn('selected_plugins is array, expected object');
        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 || '',
    };
}

/**
 * Sets data attributes on a button element for template import.
 * @param {HTMLElement} button - The button element.
 * @param {Object} template - The template object.
 */
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);
}

/**
 * Initializes the template admin functionality on DOM content loaded.
 * Handles template fetching, display, pagination, search, and import processes.
 */
document.addEventListener('DOMContentLoaded', function () {
    let currentPage = 1;
    let totalPages = 1;
    let currentCategoryId = null;
    let currentCategorySlug = null;
    let currentSearchQuery = null;
    let overflowTemplate = null;
    const templatesApiEndpoint = fleximp_template_ajax_object.apiEndpoint;
    let isFetchingTemplates = false;
    let isFetchingCategories = false;
    let hideLoaderTimeout = null;

    function showLoader(num = 6) {
        const loader = document.getElementById('templates-skeleton-loader');
        const templatesListContainer = document.getElementById('templates-list');
        if (templatesListContainer) {
            templatesListContainer.innerHTML = '';
        }
        if (loader) {
            const skeletonGrid = loader.querySelector('.skeleton-grid');
            if (skeletonGrid) {
                skeletonGrid.innerHTML = '';
                for (let i = 0; i < num; i++) {
                    const skeletonItem = document.createElement('div');
                    skeletonItem.className = 'skeleton-item';
                    skeletonItem.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>
                    `;
                    skeletonGrid.appendChild(skeletonItem);
                }
            }
            loader.style.display = 'block';
        }
    }

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

    /**
     * Checks if the loader is currently visible.
     * @returns {boolean} True if loader is visible, false otherwise.
     */
    function isLoaderVisible() {
        const loader = document.getElementById('templates-skeleton-loader');
        return loader && loader.style.display === 'block';
    }

    /**
     * Handles the confirm button click to set the text domain and initiate import.
     * Stores import data in sessionStorage and reloads the page for auto-continue.
     */
    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');

        const data = {
            textDomain,
            jsonPath,
            contentPath,
            templateCss,
            templateJs,
            templatePhp,
            plugins,
            templateResponsiveImage,
            templateMobileImage,
            title: templateTitle,
        };

        sessionStorage.setItem('fleximp_import_data', JSON.stringify(data));

        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_pro', '1');
                    location.reload();
                } else {
                    alert('Failed to update text domain.');
                }
            })
            .catch(error => {
                console.error('Import error:', error);
                alert('Error: ' + error.message);
            });
    }

    /**
     * Displays the import process UI for a matching template.
     * Sets up the import section, buttons, and data attributes.
     * @param {Object} matchingTemplate - The template object to import.
     */
    function showImportProcess(matchingTemplate) {
        // if (!isLoaderVisible()) {
        //     showLoader();
        // }

        const importSection = document.querySelector('#templates .flex-templates-import-process');
        const importTitle = document.getElementById('import-process-title');
        const importDescription = document.getElementById('import-process-description');
        const importMobileTitle = document.getElementById('import-process-mobile-title');
        const importMobileImage = document.getElementById('import-process-mobile-image');
        const importScreenshot = document.getElementById('import-process-mid-image');
        const importResponsiveImage = document.getElementById('import-process-responsive-image');

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

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

            const cancelBtn = document.getElementById('import-process-cancel-btn');
            if (cancelBtn) {
                cancelBtn.addEventListener('click', () => {
                    importSection.style.display = 'none';
                });
            }
            const demoUrl = matchingTemplate.metafields?.demo_url || '#';
            const docUrl = matchingTemplate.metafields?.documentation_url || '';
            const buyNow = matchingTemplate.metafields?.buy_now_url || '#';
            const isUserPremium = fleximp_template_ajax_object.isPremiumUser;
            const upgradeBtn = document.getElementById('upgrade-pro-btn');
            if (isUserPremium) {
                upgradeBtn.style.display = 'none';
            } else {
                upgradeBtn.style.display = 'inline-block';
            }
            upgradeBtn.href = buyNow;
            if (docUrl) {
                const liveDocBtn = document.getElementById('document-url-btn');
                liveDocBtn.style.display = 'inline-block';
            }
            else {
                const liveDocBtn = document.getElementById('document-url-btn');
                liveDocBtn.style.display = 'none';
            }
            const liveDemoBtn = document.getElementById('live-demo-btn');
            liveDemoBtn.href = demoUrl;
            const liveDocBtn = document.getElementById('document-url-btn');
            liveDocBtn.href = docUrl;
            setTimeout(() => {
                if (isLoaderVisible()) {
                    hideLoader();
                }
            }, 300);
        }
    }

    /**
     * Displays the done process UI after a successful import.
     * Shows the uninstall button with necessary data attributes.
     * @param {Object} importedTemplateObj - The imported template object.
     */
    function showDoneProcess() {
        const importSection = document.querySelector('#templates .flex-templates-import-process');
        const uninstallBtn = document.getElementById('import-process-uninstall-btn');
        if (importSection && uninstallBtn) {
            importSection.style.display = 'block';
            importSection.scrollIntoView({ behavior: 'smooth' });
            document.getElementById('import-process-confirm').style.display = 'none';
            document.getElementById('import-process-plugins').style.display = 'none';
            document.getElementById('import-process-done').style.display = 'block';
            uninstallBtn.style.display = 'inline-block';
            setTimeout(() => {
                if (isLoaderVisible()) {
                    hideLoader();
                }
            }, 400);
        }
    }

    /**
     * Fetches templates from the API based on category, page, and search query.
     * Updates the UI with fetched templates and pagination controls.
     * @param {number|null} categoryId - The category ID to filter by.
     * @param {string|null} categorySlug - The category slug.
     * @param {number} page - The page number to fetch.
     * @param {string|null} searchQuery - The search query string.
     */
    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_dynamic_text_domain || fleximp_template_ajax_object.fleximp_current_text_domain;
        const currentTextDomain = fleximp_template_ajax_object.fleximp_current_text_domain;

        const requestBody = {
            action: "getTemplates",
            per_page: 6,
            page: currentPage,
            free_pro: "Pro"
        };

        if (isFlexTheme) {
            requestBody.free_theme_domain = currentTextDomain;
        } else {
            requestBody.free_theme_domain = "";
        }

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

        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;
                    if (Array.isArray(templates)) {
                        // hideLoader();
                        // Keep only Pro templates as a client-side safety guard
                        templates = templates.filter(t => t.metafields?.free_pro === 'Pro');
                        const freeTemplate = data?.data?.data?.free_template || data?.data?.free_template || data?.free_template || null;
                        await displayTemplates(templates, freeTemplate);
                        totalPages = data.data.total_pages || (data.data.data ? data.data.data.total_pages : 1);
                        updatePaginationControls();
                    } else {
                        console.error('Invalid templates data format:', data);
                        await displayTemplates([], null);
                    }
                } else {
                    console.error('API Error:', data.message || 'Unknown error');
                    await displayTemplates([], null);
                }
                isFetchingTemplates = false;
            })
            .catch(async error => {
                console.error('Network Error:', error);
                await displayTemplates([], null);
                isFetchingTemplates = false;
            });
    }

    /**
     * Updates the pagination controls based on current page and total pages.
     * Creates previous, page number, and next buttons with ellipsis for large page counts.
     */
    function updatePaginationControls() {
        const paginationContainer = document.getElementById('pagination-controls');
        if (!paginationContainer) {
            console.error('Pagination container not found!');
            return;
        }

        paginationContainer.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);
            }
        });
        paginationContainer.appendChild(prevLi);

        // Page numbers with ellipsis logic
        const maxVisiblePages = 6;
        let startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2));
        let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);

        if (endPage - startPage + 1 < maxVisiblePages) {
            startPage = Math.max(1, endPage - maxVisiblePages + 1);
        }

        // First page and ellipsis if needed
        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);
            });
            paginationContainer.appendChild(firstLi);

            if (startPage > 2) {
                const ellipsisLi = document.createElement('li');
                ellipsisLi.className = 'page-item disabled';
                ellipsisLi.innerHTML = `<span class="page-link">...</span>`;
                paginationContainer.appendChild(ellipsisLi);
            }
        }

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

        // Last page and ellipsis if needed
        if (endPage < totalPages) {
            if (endPage < totalPages - 1) {
                const ellipsisLi = document.createElement('li');
                ellipsisLi.className = 'page-item disabled';
                ellipsisLi.innerHTML = `<span class="page-link">...</span>`;
                paginationContainer.appendChild(ellipsisLi);
            }

            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);
            });
            paginationContainer.appendChild(lastLi);
        }

        // Next button
        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);
            }
        });
        paginationContainer.appendChild(nextLi);
    }
    // end

    /**
     * Fetches categories from the API and displays them in the UI.
     */
    function fetchCategories() {
        if (isFetchingCategories) return;
        isFetchingCategories = true;

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


    /**
     * Displays the list of templates in the UI.
     * Handles premium/free badges, import/uninstall buttons, and auto-shows import process if needed.
     * @param {Array} templates - Array of template objects to display.
     * @param {Object|null} freeTemplate - Free template object from API response.
     */
    async function displayTemplates(templates, freeTemplate = null) {

        if (typeof freeTemplate === 'undefined') freeTemplate = null;

        const templatesListContainer = document.getElementById('templates-list');
        templatesListContainer.innerHTML = '';

        const activeImportedTemplate = fleximp_template_ajax_object.imported_template;
        const activeThemeTextDomain = fleximp_template_ajax_object.fleximp_current_text_domain;
        // let filteredTemplates = templates.filter(template => {
        //     return template.template_domain !== activeImportedTemplate;
        // });

        let filteredTemplates = templates.filter(template => {
            return (
                template.template_domain !== activeImportedTemplate &&
                template.template_domain !== activeThemeTextDomain
            );
        });


        if (!filteredTemplates.length) {
            templatesListContainer.innerHTML = `
        <div class="no-templates-message">
            No templates found
        </div>`;
            hideLoader();
            if (activeImportedTemplate && activeImportedTemplate === activeThemeTextDomain) {
                showDoneProcess();
            } else if (freeTemplate) {
                showImportProcess(freeTemplate);
            }
            return;
        }
        // end

        filteredTemplates.forEach(template => {
            const templateSlug = template.title.toLowerCase().replace(/ /g, '-');
            const demoUrl = template.metafields?.demo_url || '#';
            const buyUrl = template.metafields?.buy_now_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 flexthemebuynow = template.metafields?.buy_now_url || '';
            const flexthemeprice = template.metafields?.template_price || '';
            const fleximpCurrentTextDomain = fleximp_template_ajax_object.fleximp_dynamic_text_domain;
            const isBundleUser = fleximp_template_ajax_object.is_Bundle === true || fleximp_template_ajax_object.is_Bundle === 'true';
            let buttonHTML = '';

            const isPremium = template.metafields?.free_pro === 'Pro';
            const isUserPremium = fleximp_template_ajax_object.isPremiumUser;
            const isImported = fleximp_template_ajax_object.imported_template;
            const fleximpCurrentThemeDomain = fleximp_template_ajax_object.fleximp_current_text_domain;

            if (isPremium && textDomain !== fleximpCurrentThemeDomain) {

                if (isBundleUser) {
                    buttonHTML = `
                       <a href="${fleximp_template_ajax_object.themes_redirect_page_url}"
                          class="btn flex-template-buttons flex-temp-btn try-now-btn" target="_blank" 
                          rel="noopener noreferrer">
                           TRY NOW
                       </a>`;
                } else {
                    buttonHTML = `
                       <a href="${flexthemebuynow}" 
                          class="btn flex-template-buttons flex-temp-btn buy-now-btn" 
                          target="_blank" 
                          rel="noopener noreferrer">
                           BUY NOW
                       </a>`;
                }
            }

            else {

                if (isPremium && !isUserPremium) {

                    buttonHTML = `
                      <a href="https://www.flextheme.net/products/flex-pro-wordpress-theme"
                         target="_blank"
                         class="btn flex-template-buttons flex-temp-btn get-pro-btn">
                          UPGRADE TO FLEX PRO
                      </a>`;

                } else {

                    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 {

                        const isDisabled =
                            fleximpCurrentTextDomain !== textDomain && fleximpCurrentTextDomain !== ''
                                ? 'disabled title="first uninstall imported template"'
                                : '';

                        buttonHTML = `
                <button class="btn flex-unique-import-button flex-template-buttons import-btn"
                    ${isDisabled}
                    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-demo-url="${demoUrl}"
                    data-template-buy-url="${buyUrl}">
                    IMPORT DEMO
                </button>`;

                    }
                }
            }


            // end 
            const templateHTML = `
                <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>
                            ${isPremium
                    ? `<div class="premium-badge">${flexthemeprice ? `$${flexthemeprice}` : 'Pro'}</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>`;

            templatesListContainer.innerHTML += templateHTML;
        });

        // Auto-show import process
        const importedTemplate = fleximp_template_ajax_object.imported_template;

        hideLoader();

        if (importedTemplate && importedTemplate === activeThemeTextDomain) {

            showDoneProcess();

        } else if (freeTemplate) {

            showImportProcess(freeTemplate);
        }
    }

    /**
     * Displays the categories in the select dropdown and loads templates for the first category.
     * @param {Array} categories - Array of category objects.
     */
    function displayCategories(categories) {
        const categoriesListContainer = document.getElementById('categories-list');
        categoriesListContainer.innerHTML = '';

        categories.forEach((category, index) => {
            const option = document.createElement('option');
            option.value = category.id;
            option.setAttribute('data-slug', category.slug);
            option.textContent = category.name;
            if (index === 0) {
                option.selected = true;
            }
            categoriesListContainer.appendChild(option);
        });

        // Auto-load templates for the first category
        if (categories.length > 0) {
            fetchTemplates(categories[0].id, categories[0].slug);
        }
    }

    document.addEventListener('click', function (event) {
        if (event.target.classList.contains('flex-unique-import-button')) {
            const templateTitle = event.target.getAttribute('data-title');
            const templateDesc = event.target.getAttribute('data-template-description');
            const templateMobileImage = event.target.getAttribute('data-template-mobile-image');
            const textDomain = event.target.getAttribute('data-text-domain');
            const jsonPath = event.target.getAttribute('data-json-path');
            const contentPath = event.target.getAttribute('data-content-path');
            const templateCss = event.target.getAttribute('data-template-css');
            const templateJs = event.target.getAttribute('data-template-js');
            const templatePhp = event.target.getAttribute('data-template-php');
            const plugins = event.target.getAttribute('data-plugins');
            const templateResponsiveImage = event.target.getAttribute('data-template-responsive-image');
            const importSection = document.querySelector('#templates .flex-templates-import-process');
            const importTitle = document.getElementById('import-process-title');
            const importDescription = document.getElementById('import-process-description');
            const importMobileTitle = document.getElementById('import-process-mobile-title');
            const importMobileImage = document.getElementById('import-process-mobile-image');
            const importResponsiveImage = document.getElementById('import-process-responsive-image');

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

                const demoUrl = event.target.getAttribute('data-demo-url');
                const buyNow = event.target.getAttribute('data-template-buy-url');
                const docUrl = event.target.getAttribute('data-template-doc-url') || '';
                const isUserPremium = fleximp_template_ajax_object.isPremiumUser;
                const upgradeBtn = document.getElementById('upgrade-pro-btn');



                if (docUrl) {
                    const liveDocBtn = document.getElementById('document-url-btn');
                    liveDocBtn.style.display = 'inline-block';
                } else {
                    const liveDocBtn = document.getElementById('document-url-btn');
                    liveDocBtn.style.display = 'none';
                }
                if (isUserPremium) {
                    upgradeBtn.style.display = 'none';
                } else {
                    upgradeBtn.style.display = 'inline-block';
                }
                const liveDemoBtn = document.getElementById('live-demo-btn');
                liveDemoBtn.href = demoUrl;
                const liveDocBtn = document.getElementById('document-url-btn');
                liveDocBtn.href = docUrl;
                const buynowBtn = document.getElementById('upgrade-pro-btn');
                buynowBtn.href = buyNow;
            } else {
                console.error('Import section or elements are missing in the DOM.');
            }

            const confirmBtn = document.getElementById('import-process-confirm-btn');
            if (confirmBtn) {
                confirmBtn.addEventListener('click', function () {
                    const data = {
                        textDomain,
                        jsonPath,
                        contentPath,
                        templateCss,
                        templateJs,
                        templatePhp,
                        plugins,
                        templateResponsiveImage,
                    };

                    sessionStorage.setItem('fleximp_import_data', JSON.stringify(data));

                    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(res => res.json())
                        .then(response => {
                            if (response.success) {
                                sessionStorage.setItem('fleximp_auto_continue_pro', '1');
                                location.reload();
                            } else {
                                alert('Failed to update text domain.');
                            }
                        })
                        .catch(error => {
                            console.error('Text domain AJAX error:', error);
                            alert('Error updating text domain.');
                        });
                }, { once: true });
            }

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

    // Initialization function for templates tab
    let initialised = false;

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

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

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

    document.getElementById('categories-list').addEventListener('change', function (event) {
        const selectedOption = event.target.options[event.target.selectedIndex];
        const categoryId = selectedOption.value;
        const categorySlug = selectedOption.getAttribute('data-slug');

        fetchTemplates(categoryId, categorySlug, 1, currentSearchQuery);
    });

    jQuery('body').on('input', '#flex-templates-search', debounce(function (event) {
        const categoryId = jQuery('#categories-list option:selected').val();
        const categorySlug = jQuery('#categories-list option:selected').attr('data-slug');
        const searchQuery = jQuery(this).val();
        fetchTemplates(categoryId, categorySlug, 1, searchQuery);
    }, 300));

});


/**
 * 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 uninstall button clicks for templates.
 */
document.addEventListener('DOMContentLoaded', function () {
    jQuery(document).on('click', '.uninstall-btn', function () {
        const button = jQuery(this);
        const templateSlug = button.data('template');
        const textDomain = button.data('text-domain');

        if (!confirm('Are you sure you want to uninstall this template and remove all related data?')) {
            return;
        }

        jQuery.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'fleximp_uninstall_template',
                template_slug: templateSlug,
                text_domain: textDomain,
            },
            success: function (response) {
                if (response.success) {
                    alert(response.data.message);
                    location.reload();
                } else {
                    alert('Error: ' + response.data.message);
                }
            },
        });
    });
});

/**
 * Handles auto-continue import process after page reload.
 */
window.addEventListener('DOMContentLoaded', function () {
    if (sessionStorage.getItem('fleximp_auto_continue_pro') === '1') {
        // Activate templates tab (Pro templates)
        const templatesTab = document.querySelector('.nav-link[href="#templates"]');
        if (templatesTab) templatesTab.classList.add('active');
        const templatesPane = document.querySelector('#templates');
        if (templatesPane) templatesPane.classList.add('active', 'show');

        // Deactivate other tabs
        const freeTemplatesTab = document.querySelector('.nav-link[href="#free-templates"]');
        if (freeTemplatesTab) freeTemplatesTab.classList.remove('active');
        const freeTemplatesPane = document.querySelector('#free-templates');
        if (freeTemplatesPane) freeTemplatesPane.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_pro');
        const importData = sessionStorage.getItem('fleximp_import_data');
        if (!importData) {
            console.error('No import data found in sessionStorage');
            return;
        }

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

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

        const importButton = document.createElement('button');
        importButton.classList.add('flex-unique-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);
        runImportProcess(); // Continue import
    }
});


/**
 * Runs the asynchronous import process for templates, including plugin installation, inner pages, and demo content.
 */
async function runImportProcess() {
    document.getElementById('import-process-confirm').style.display = 'none';
    document.getElementById('import-process-plugins').style.display = 'block';
    const importSection = document.querySelector('#templates .flex-templates-import-process');
    importSection.style.display = 'block';
    importSection.scrollIntoView({ behavior: 'smooth' });

    const importBtn = document.querySelector('.flex-unique-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
    updateStepStatus('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) {
                    updateProgress(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);

    // Install plugins one by one
    for (const plugin of selectedPluginsObj) {
        await installPlugin(plugin);
    }
    updateStepStatus('step-plugins', 'Done');

    // Step 2: Import Inner Pages
    updateStepStatus('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) {
                updateProgress(75, 'Importing inner pages success');
                updateStepStatus('step-inner-pages', 'Done');
            },
            error: function (xhr, status, error) {
                console.error('Error importing inner pages data:', error);
                updateStepStatus('step-inner-pages', 'Error');
            },
            complete: function () {
                resolve();
            }
        });
    });

    // Step 3: Import Demo Content
    updateStepStatus('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) {
                updateProgress(100, 'Import success');
                updateStepStatus('step-content', 'Done');
            },
            error: function (xhr, status, error) {
                console.error('Error importing content:', error);
                updateStepStatus('step-content', 'Error');
            },
            complete: function () {
                resolve();
            }
        });
    });

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

    document.getElementById('import-process-plugins').style.display = 'none';
    document.getElementById('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 updateStepStatus(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);
    }
}