<?php
/**
 * Wizard Step 5: Final Details
 */
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

// ✅ STEP 1: Register and enqueue a dummy script handle
wp_register_script( 'trstemp-step5-js', '', array(), '1.0.5', true );
wp_enqueue_script( 'trstemp-step5-js' );

// ✅ STEP 2: Prepare JavaScript variables
$trstemp_vars_step5 = array(
    'ajaxurl' => admin_url('admin-ajax.php'),
    'admin_email' => get_option('admin_email'),
    'site_name' => get_bloginfo('name'),
    'site_description' => get_bloginfo('description'),

    'step_url_base' => admin_url( 'admin.php?page=turbo-starter-templates&ci=' ),
    'step3_template_base' => admin_url( 'admin.php?page=turbo-starter-templates&ci=3&template=' ),

    'step2_url' => admin_url('admin.php?page=turbo-starter-templates&ci=2'),
    'step3_url' => admin_url('admin.php?page=turbo-starter-templates&ci=3'),
    'step4_url' => admin_url('admin.php?page=turbo-starter-templates&ci=4'),
    'step6_url' => admin_url('admin.php?page=turbo-starter-templates&ci=6'),
    'nonce' => wp_create_nonce('trstemp_admin_nonce'),
    
    'strings' => array(
        'business' => esc_html__('Business', 'turbo-templates-library-for-elementor'),
        'business_pro_template' => esc_html__('Business Pro Template', 'turbo-templates-library-for-elementor'),
        'default_logo' => esc_html__('Default', 'turbo-templates-library-for-elementor'),
        'custom_logo' => esc_html__('Custom Logo', 'turbo-templates-library-for-elementor'),
        'lato_font' => esc_html__('Lato', 'turbo-templates-library-for-elementor'),
        'original_palette' => esc_html__('Original', 'turbo-templates-library-for-elementor'),
        'starting_import' => esc_html__('Starting Import...', 'turbo-templates-library-for-elementor'),
    )
);

// ✅ STEP 3: Create the COMPLETE inline JavaScript
$trstemp_script_step5 = '(function() {
    "use strict";
    
    // Global variables
    const trstempVarsStep5 = ' . wp_json_encode($trstemp_vars_step5) . ';
    const ajaxurl = trstempVarsStep5.ajaxurl;
    const nonce = trstempVarsStep5.nonce;
    
    // Function declarations
    function trstemp_changeStep(step) {
            step = parseInt(step, 10);

            if (step >= 1 && step <= 6) {

                if (step === 2) {
                    window.location.href = trstempVarsStep5.step2_url;
                    return;
                }

                if (step === 3) {
                    const selectedTemplate = sessionStorage.getItem("trstemp_selected_template");
                    const selectedTemplateName = sessionStorage.getItem("trstemp_selected_template_name");

                    if (selectedTemplate && selectedTemplateName) {
                        window.location.href =
                            trstempVarsStep5.step3_template_base +
                            selectedTemplate +
                            "&name=" +
                            encodeURIComponent(selectedTemplateName);
                        return;
                    }
                }

                window.location.href = trstempVarsStep5.step_url_base + step;
            }
    }
    
    function trstemp_startImport() {
        // Save all final details before starting import
        trstemp_saveFinalDetails();
        
        // Show loading state
        const btn = document.querySelector(".start-import-btn");
        if (btn) {
            btn.innerHTML = \'<span class="btn-icon">⏳</span> \' + trstempVarsStep5.strings.starting_import;
            btn.disabled = true;
        }
        
        // Redirect to import process (step 6)
        window.location.href = trstempVarsStep5.step6_url;
    }
    
    function selectImportOption(option) {
        // console.log("TRSTEMP: selectImportOption called with:", option);
        
        // Remove active class from all tabs
        document.querySelectorAll(".option-tab").forEach(tab => {
            tab.classList.remove("active");
        });
        
        // Add active class to selected tab
        // ✅ FIXED: Changed to use backticks (template literals) to avoid PHP string concatenation issues
        const selectedTab = document.querySelector(`[data-option="${option}"]`);

        if (selectedTab) {
            selectedTab.classList.add("active");
            // console.log("TRSTEMP: Added active class to tab:", option);
        } else {
            console.error("TRSTEMP: Could not find tab with data-option:", option);
        }
        
        // Update descriptions
        document.querySelectorAll(".description-content").forEach(desc => {
            desc.classList.remove("active");
        });
        const selectedDesc = document.getElementById(option + "-description");
        if (selectedDesc) {
            selectedDesc.classList.add("active");
            // console.log("TRSTEMP: Updated description for:", option);
        }
        
        const keepExisting = option === "keep";
        sessionStorage.setItem("turbo_keep_existing_data", keepExisting.toString());
        // console.log("TRSTEMP: Set turbo_keep_existing_data to:", keepExisting.toString());
    }
    
    window.selectImportOption = selectImportOption;
    
    function trstemp_saveFinalDetails() {
        const siteTitleEl = document.getElementById("site-title");
        const siteTaglineEl = document.getElementById("site-tagline");
        const adminEmailEl = document.getElementById("admin-email");
        const importCustomizerEl = document.getElementById("import-customizer");
        const importMenusEl = document.getElementById("import-menus");
        
        const finalDetails = {
            site_title: siteTitleEl ? siteTitleEl.value : "",
            site_tagline: siteTaglineEl ? siteTaglineEl.value : "",
            admin_email: adminEmailEl ? adminEmailEl.value : "",
            import_options: {
                customizer: importCustomizerEl ? importCustomizerEl.checked : true,
                menus: importMenusEl ? importMenusEl.checked : true
            },
            keep_existing_data: sessionStorage.getItem("turbo_keep_existing_data") === "true"
        };
        
        // console.log("TRSTEMP: Saving final details:", finalDetails);
        
        sessionStorage.setItem("turbo_final_details", JSON.stringify(finalDetails));
        
        // Save to wizard session
        fetch(ajaxurl, {
            method: "POST",
            headers: {"Content-Type": "application/x-www-form-urlencoded"},
            body: "action=trstemp_save_step_data&step=5&nonce=" + nonce + "&data=" + encodeURIComponent(JSON.stringify(finalDetails))
        })
        .then(response => response.json())
        .then(data => {
            // console.log("TRSTEMP: Step 5 data saved:", data);
        })
        .catch(error => {
            console.error("TRSTEMP: Error saving step 5 data:", error);
        });
    }
    
    // Load wizard session data
    function trstemp_loadWizardSessionData() {
        // console.log("TRSTEMP: Loading wizard summary...");
        
        fetch(ajaxurl, {
            method: "POST",
            headers: {"Content-Type": "application/x-www-form-urlencoded"},
            body: "action=trstemp_get_wizard_summary&nonce=" + nonce
        })
        .then(response => response.json())
        .then(data => {
            // console.log("TRSTEMP: Wizard summary response:", data);
            
            if (data.success && data.data) {
                const summary = data.data;
                // console.log("TRSTEMP: Applying wizard summary data:", summary);
                
                // Website Type
                if (summary.website_type) {
                    const websiteTypeEl = document.getElementById("selected-website-type");
                    if (websiteTypeEl) {
                        websiteTypeEl.textContent = summary.website_type;
                        // console.log("TRSTEMP: Set website type to:", summary.website_type);
                    }
                }
                
                // Template
                if (summary.template_name) {
                    const templateEl = document.getElementById("selected-template");
                    if (templateEl) {
                        templateEl.textContent = summary.template_name;
                        // console.log("TRSTEMP: Set template to:", summary.template_name);
                    }
                }
                
                // Customization details
                if (summary.logo) {
                    const logoEl = document.getElementById("logo-status");
                    if (logoEl) {
                        logoEl.textContent = trstempVarsStep5.strings.custom_logo;
                    }
                }
                
                if (summary.font_pair) {
                    const fontEl = document.getElementById("selected-font");
                    if (fontEl) {
                        const fontName = summary.font_pair.charAt(0).toUpperCase() + summary.font_pair.slice(1);
                        fontEl.textContent = fontName;
                        // console.log("TRSTEMP: Set font to:", fontName);
                    }
                }
                
                if (summary.color_palette) {
                    const paletteEl = document.getElementById("selected-palette");
                    const colorEl = document.getElementById("preview-color");
                    if (paletteEl && colorEl) {
                        const paletteName = summary.color_palette.charAt(0).toUpperCase() + summary.color_palette.slice(1);
                        paletteEl.textContent = paletteName;
                        
                        const colors = {
                            "original": "#667eea",
                            "blue": "#2196F3",
                            "green": "#4CAF50",
                            "purple": "#9C27B0",
                            "orange": "#FF9800",
                            "teal": "#009688",
                            "red": "#F44336",
                            "black": "#212121"
                        };
                        
                        const color = colors[summary.color_palette] || "#667eea";
                        colorEl.style.background = color;
                        // console.log("TRSTEMP: Set color palette to:", paletteName, color);
                    }
                }
                
                // Features from website type
                if (summary.website_type_features && summary.website_type_features.length > 0) {
                    const featuresList = document.getElementById("selected-features-list");
                    if (featuresList) {
                        featuresList.innerHTML = "";
                        summary.website_type_features.forEach(feature => {
                            const tag = document.createElement("span");
                            tag.className = "feature-tag";
                            tag.textContent = feature;
                            featuresList.appendChild(tag);
                        });
                        // console.log("TRSTEMP: Set features to:", summary.website_type_features);
                    }
                }
                
                // Auto-fill site information
                const titleInput = document.getElementById("site-title");
                const taglineInput = document.getElementById("site-tagline");
                
                if (summary.site_title && titleInput) {
                    titleInput.value = summary.site_title;
                    // console.log("TRSTEMP: Set site title to:", summary.site_title);
                } else if (titleInput && !titleInput.value) {
                    titleInput.value = trstempVarsStep5.site_name;
                }
                
                if (summary.site_tagline && taglineInput) {
                    taglineInput.value = summary.site_tagline;
                    // console.log("TRSTEMP: Set site tagline to:", summary.site_tagline);
                } else if (taglineInput && !taglineInput.value) {
                    taglineInput.value = trstempVarsStep5.site_description;
                }
            } else {
                console.log("TRSTEMP: No wizard summary data available");
            }
        })
        .catch(error => {
            console.error("TRSTEMP: Error loading wizard summary:", error);
        });
    }
    
    function trstemp_populateFromWizardData() {
        // Fallback population from sessionStorage if wizard session fails
        // console.log("TRSTEMP: Populating from sessionStorage fallback...");
        
        // Website type
        const websiteType = sessionStorage.getItem("turbo_website_type_name");
        const websiteTypeEl = document.getElementById("selected-website-type");
        if (websiteType && websiteTypeEl && websiteTypeEl.textContent === trstempVarsStep5.strings.business) {
            websiteTypeEl.textContent = websiteType;
        }
        
        // Template
        const templateName = sessionStorage.getItem("trstemp_selected_template_name");
        const templateEl = document.getElementById("selected-template");
        if (templateName && templateEl && templateEl.textContent === trstempVarsStep5.strings.business_pro_template) {
            templateEl.textContent = templateName;
        }
        
        // Customization from sessionStorage
        const currentFont = sessionStorage.getItem("turbo_font_pair");
        const currentPalette = sessionStorage.getItem("trstemp_color_palette");
        const currentLogo = sessionStorage.getItem("turbo_custom_logo");
        
        if (currentFont) {
            const fontEl = document.getElementById("selected-font");
            if (fontEl) {
                const fontName = currentFont.charAt(0).toUpperCase() + currentFont.slice(1);
                fontEl.textContent = fontName;
            }
        }
        
        if (currentPalette) {
            const paletteEl = document.getElementById("selected-palette");
            const colorEl = document.getElementById("preview-color");
            if (paletteEl && colorEl) {
                const paletteName = currentPalette.charAt(0).toUpperCase() + currentPalette.slice(1);
                paletteEl.textContent = paletteName;
                
                const colors = {
                    "original": "#667eea",
                    "blue": "#2196F3",
                    "green": "#4CAF50",
                    "purple": "#9C27B0",
                    "orange": "#FF9800",
                    "teal": "#009688",
                    "red": "#F44336",
                    "black": "#212121"
                };
                
                const color = colors[currentPalette] || "#667eea";
                colorEl.style.background = color;
            }
        }
        
        if (currentLogo) {
            const logoEl = document.getElementById("logo-status");
            if (logoEl) {
                logoEl.textContent = trstempVarsStep5.strings.custom_logo;
            }
        }
    }
    
    function trstemp_refreshDisplayData() {
        // Refresh website type
        const websiteType = sessionStorage.getItem("turbo_website_type_name");
        const websiteTypeEl = document.getElementById("selected-website-type");
        if (websiteType && websiteTypeEl && websiteTypeEl.textContent !== websiteType) {
            websiteTypeEl.textContent = websiteType;
        }
        
        // Refresh template name
        const templateName = sessionStorage.getItem("trstemp_selected_template_name");
        const templateEl = document.getElementById("selected-template");
        if (templateName && templateEl && templateEl.textContent !== templateName) {
            templateEl.textContent = templateName;
        }
        
        // Refresh customization data
        const currentFont = sessionStorage.getItem("turbo_font_pair");
        const currentPalette = sessionStorage.getItem("trstemp_color_palette");
        const currentLogo = sessionStorage.getItem("turbo_custom_logo");
        
        if (currentFont) {
            const fontEl = document.getElementById("selected-font");
            if (fontEl) {
                const fontName = currentFont.charAt(0).toUpperCase() + currentFont.slice(1);
                if (fontEl.textContent !== fontName) {
                    fontEl.textContent = fontName;
                }
            }
        }
        
        if (currentPalette) {
            const paletteEl = document.getElementById("selected-palette");
            const colorEl = document.getElementById("preview-color");
            if (paletteEl && colorEl) {
                const paletteName = currentPalette.charAt(0).toUpperCase() + currentPalette.slice(1);
                if (paletteEl.textContent !== paletteName) {
                    paletteEl.textContent = paletteName;
                    
                    const colors = {
                        "original": "#667eea",
                        "blue": "#2196F3",
                        "green": "#4CAF50",
                        "purple": "#9C27B0",
                        "orange": "#FF9800",
                        "teal": "#009688",
                        "red": "#F44336",
                        "black": "#212121"
                    };
                    
                    const color = colors[currentPalette] || "#667eea";
                    colorEl.style.background = color;
                }
            }
        }
        
        if (currentLogo) {
            const logoEl = document.getElementById("logo-status");
            if (logoEl && logoEl.textContent !== trstempVarsStep5.strings.custom_logo) {
                logoEl.textContent = trstempVarsStep5.strings.custom_logo;
            }
        }
        
        // Refresh features
        const websiteTypeFeatures = sessionStorage.getItem("turbo_website_features");
        if (websiteTypeFeatures) {
            const features = JSON.parse(websiteTypeFeatures);
            const featuresList = document.getElementById("selected-features-list");
            if (featuresList) {
                const currentFeatures = Array.from(featuresList.children).map(el => el.textContent);
                
                if (JSON.stringify(currentFeatures) !== JSON.stringify(features)) {
                    featuresList.innerHTML = "";
                    features.forEach(feature => {
                        const tag = document.createElement("span");
                        tag.className = "feature-tag";
                        tag.textContent = feature;
                        featuresList.appendChild(tag);
                    });
                }
            }
        }
    }
    
    // Initialize on DOM ready
    document.addEventListener("DOMContentLoaded", function() {
        // console.log("TRSTEMP: Step 5 loading...");
        
        // Debug: Show current sessionStorage state
        // console.log("TRSTEMP: Current turbo_keep_existing_data:", sessionStorage.getItem("turbo_keep_existing_data"));
        
        // Load wizard session data first and wait for it
        trstemp_loadWizardSessionData();
        
        // Also try to populate immediately from sessionStorage as fallback
        setTimeout(trstemp_populateFromWizardData, 500);
        
        // Debug: Log all sessionStorage data
        // console.log("TRSTEMP Step 5 - SessionStorage Data:");
        for (let i = 0; i < sessionStorage.length; i++) {
            const key = sessionStorage.key(i);
            if (key.startsWith("turbo_")) {
                // console.log(key + ":", sessionStorage.getItem(key));
            }
        }
        
        // Website type - use the correct key from step-1
        const websiteType = sessionStorage.getItem("turbo_website_type_name");
        // console.log("Website Type:", websiteType);
        const websiteTypeEl = document.getElementById("selected-website-type");
        if (websiteType && websiteTypeEl) {
            websiteTypeEl.textContent = websiteType;
        }
        
        // Template - get the actual selected template name
        const templateName = sessionStorage.getItem("trstemp_selected_template_name");
        // console.log("Template Name:", templateName);
        const templateEl = document.getElementById("selected-template");
        if (templateName && templateEl) {
            templateEl.textContent = templateName;
        }
        
        // Customization
        const customization = sessionStorage.getItem("turbo_customization");
        if (customization) {
            const custom = JSON.parse(customization);
            if (custom.colors) {
                const previewColor1 = document.getElementById("preview-color-1");
                const previewColor2 = document.getElementById("preview-color-2");
                if (previewColor1) previewColor1.style.background = custom.colors.primary;
                if (previewColor2) previewColor2.style.background = custom.colors.secondary;
            }
            if (custom.font) {
                const fontEl = document.getElementById("selected-font");
                if (fontEl) {
                    fontEl.textContent = custom.font + " Font";
                }
            }
        }
        
        // Features - Load from step 1 website type selection
        const websiteTypeFeatures = sessionStorage.getItem("turbo_website_features");
        const selectedFeatures = sessionStorage.getItem("turbo_selected_features");
        
        if (websiteTypeFeatures) {
            // Show features based on website type selection from step 1
            const features = JSON.parse(websiteTypeFeatures);
            const featuresList = document.getElementById("selected-features-list");
            if (featuresList) {
                featuresList.innerHTML = "";
                
                features.forEach(feature => {
                    const tag = document.createElement("span");
                    tag.className = "feature-tag";
                    tag.textContent = feature;
                    featuresList.appendChild(tag);
                });
            }
        } else if (selectedFeatures) {
            // Fallback to plugin-based features
            const features = JSON.parse(selectedFeatures);
            const featuresList = document.getElementById("selected-features-list");
            if (featuresList) {
                featuresList.innerHTML = "";
                
                const featureNames = {
                    "turbo_addons": "Turbo Addons",
                    "elementor": "Elementor",
                    "header_footer": "Header Footer",
                    "contact_forms": "Contact Forms",
                    "ecommerce": "WooCommerce",
                    "seo": "SEO Tools"
                };
                
                features.forEach(feature => {
                    if (featureNames[feature]) {
                        const tag = document.createElement("span");
                        tag.className = "feature-tag";
                        tag.textContent = featureNames[feature];
                        featuresList.appendChild(tag);
                    }
                });
            }
        }
        
        // Load customization details from Step 3
        const wizardCustomizations = sessionStorage.getItem("turbo_wizard_customizations");
        if (wizardCustomizations) {
            const custom = JSON.parse(wizardCustomizations);
            
            // Auto-fill site information
            const titleInput = document.getElementById("site-title");
            const taglineInput = document.getElementById("site-tagline");
            
            if (custom.site_title && titleInput) {
                titleInput.value = custom.site_title;
            }
            if (custom.site_tagline && taglineInput) {
                taglineInput.value = custom.site_tagline;
            }
            
            // Show customization details
            const logoEl = document.getElementById("logo-status");
            if (custom.logo && logoEl) {
                logoEl.textContent = trstempVarsStep5.strings.custom_logo;
            }
            
            const fontEl = document.getElementById("selected-font");
            if (custom.font_pair && fontEl) {
                const fontName = custom.font_pair.charAt(0).toUpperCase() + custom.font_pair.slice(1);
                fontEl.textContent = fontName;
            }
            
            const paletteEl = document.getElementById("selected-palette");
            const colorEl = document.getElementById("preview-color");
            if (custom.color_palette && paletteEl && colorEl) {
                const paletteName = custom.color_palette.charAt(0).toUpperCase() + custom.color_palette.slice(1);
                paletteEl.textContent = paletteName;
                
                // Set color preview based on palette
                const colors = {
                    "original": "#667eea",
                    "blue": "#2196F3",
                    "green": "#4CAF50",
                    "purple": "#9C27B0",
                    "orange": "#FF9800",
                    "teal": "#009688",
                    "red": "#F44336",
                    "black": "#212121"
                };
                
                const color = colors[custom.color_palette] || "#667eea";
                colorEl.style.background = color;
            }
        }
        
        // Check sessionStorage for current selections (priority over saved customizations)
        const currentFont = sessionStorage.getItem("turbo_font_pair");
        const currentPalette = sessionStorage.getItem("trstemp_color_palette");
        const currentLogo = sessionStorage.getItem("turbo_custom_logo");
        
        const fontEl = document.getElementById("selected-font");
        if (currentFont && fontEl) {
            const fontName = currentFont.charAt(0).toUpperCase() + currentFont.slice(1);
            fontEl.textContent = fontName;
        }
        
        const paletteEl = document.getElementById("selected-palette");
        const colorEl = document.getElementById("preview-color");
        if (currentPalette && paletteEl && colorEl) {
            const paletteName = currentPalette.charAt(0).toUpperCase() + currentPalette.slice(1);
            paletteEl.textContent = paletteName;
            
            const colors = {
                "original": "#667eea",
                "blue": "#2196F3",
                "green": "#4CAF50",
                "purple": "#9C27B0",
                "orange": "#FF9800",
                "teal": "#009688",
                "red": "#F44336",
                "black": "#212121"
            };
            
            const color = colors[currentPalette] || "#667eea";
            colorEl.style.background = color;
        }
        
        const logoEl = document.getElementById("logo-status");
        if (currentLogo && logoEl) {
            logoEl.textContent = trstempVarsStep5.strings.custom_logo;
        }
        
        // Auto-fill website information - will be overridden by wizard data if available
        const titleInput = document.getElementById("site-title");
        const taglineInput = document.getElementById("site-tagline");
        const emailInput = document.getElementById("admin-email");
        
        if (titleInput && !titleInput.value) {
            titleInput.value = trstempVarsStep5.site_name;
        }
        if (taglineInput && !taglineInput.value) {
            taglineInput.value = trstempVarsStep5.site_description;
        }
        if (emailInput && !emailInput.value) {
            emailInput.value = trstempVarsStep5.admin_email;
        }
        
        // Load saved final details if returning to this step
        const savedDetails = sessionStorage.getItem("turbo_final_details");
        if (savedDetails) {
            const details = JSON.parse(savedDetails);
            const titleInput = document.getElementById("site-title");
            const taglineInput = document.getElementById("site-tagline");
            const emailInput = document.getElementById("admin-email");
            const importCustomizer = document.getElementById("import-customizer");
            const importMenus = document.getElementById("import-menus");
            
            if (details.siteTitle && titleInput) titleInput.value = details.siteTitle;
            if (details.siteTagline && taglineInput) taglineInput.value = details.siteTagline;
            if (details.adminEmail && emailInput) emailInput.value = details.adminEmail;
            
            if (details.importOptions) {
                if (importCustomizer) importCustomizer.checked = details.importOptions.customizer;
                if (importMenus) importMenus.checked = details.importOptions.menus;
            }
        }
        
        // Set default import option
        // sessionStorage.setItem("turbo_keep_existing_data", "false");
        // ✅ Restore previously selected import option (keep / replace)
        const savedImportOption =
            sessionStorage.getItem("turbo_keep_existing_data") === "true"
                ? "keep"
                : "replace";

        // console.log("TRSTEMP: Restoring import option:", savedImportOption);
        // console.log("TRSTEMP: turbo_keep_existing_data value:", sessionStorage.getItem("turbo_keep_existing_data"));
        selectImportOption(savedImportOption);
        
        // Fix tab functionality
        document.querySelectorAll(".option-tab").forEach(tab => {
            tab.addEventListener("click", function() {
                const option = this.getAttribute("data-option");
                // console.log("TRSTEMP: Tab clicked:", option);
                selectImportOption(option);
            });
        });
        
        // Save final details
        trstemp_saveFinalDetails();
        
        // Refresh data every 2 seconds to catch any updates
        setInterval(trstemp_refreshDisplayData, 2000);
        
        // Save details when form changes
        const siteTitleEl = document.getElementById("site-title");
        const siteTaglineEl = document.getElementById("site-tagline");
        const adminEmailEl = document.getElementById("admin-email");
        
        if (siteTitleEl) siteTitleEl.addEventListener("input", trstemp_saveFinalDetails);
        if (siteTaglineEl) siteTaglineEl.addEventListener("input", trstemp_saveFinalDetails);
        if (adminEmailEl) adminEmailEl.addEventListener("input", trstemp_saveFinalDetails);
        
        document.querySelectorAll("input[type=\'checkbox\']").forEach(checkbox => {
            checkbox.addEventListener("change", trstemp_saveFinalDetails);
        });
    });
    
    // Load data immediately when script loads
    if (document.readyState === "loading") {
        document.addEventListener("DOMContentLoaded", function() {
            setTimeout(() => {
                trstemp_loadWizardSessionData();
                trstemp_populateFromWizardData();
            }, 100);
        });
    } else {
        setTimeout(() => {
            trstemp_loadWizardSessionData();
            trstemp_populateFromWizardData();
        }, 100);
    }

    // Override trstemp_nextStep to intercept Start Import on step 5
    // wizard.php defines trstemp_nextStep globally — we wrap it here
    document.addEventListener("DOMContentLoaded", function() {
        var _original = window.trstemp_nextStep;
        window.trstemp_nextStep = function() {
            var keepExisting = sessionStorage.getItem("turbo_keep_existing_data") === "true";
            if (!keepExisting) {
                var ok = confirm(
                    "\u26a0\ufe0f Warning: Replace Existing Content\n\n" +
                    "This will permanently delete all existing pages and replace them with the template content.\n\n" +
                    "Click OK to confirm you are willing to replace your existing content."
                );
                if (!ok) return;
            }
            trstemp_saveFinalDetails();
            if (_original) _original();
        };
    });

})();';

// ✅ STEP 4: Add the inline script properly using wp_add_inline_script()
wp_add_inline_script( 'trstemp-step5-js', $trstemp_script_step5 );
?>

<div class="trstemp-final-step">
    <div class="step-header">
        <h2>Final Details</h2>
        <p>Review your selections and add final touches before we build your website.</p>
    </div>
    
    <div class="review-sections">
        <div class="review-section">
            <h3>Theme</h3>
            <div class="review-item">
                <span id="selected-website-type">Recommended: Hello Elementor</span>
            </div>
        </div>
        
        <div class="review-section">
            <h3>Template</h3>
            <div class="review-item">
                <span id="selected-template">Business Pro Template</span>
            </div>
        </div>  
    
    </div>
    
    <div class="import-options">
        <h3>⚙️ Import Options</h3>
        <p>Choose how you want to handle your existing content:</p>
        <div class="content-options">
            <div class="option-tabs">
                <button class="option-tab" data-option="replace">
                    <div class="tab-icon">🔄</div>
                    <div class="trstemp-tab-content">
                        <h4>Replace Existing Content</h4>
                        <p>Delete current pages and create fresh template pages</p>
                    </div>
                </button>
                <button class="option-tab" data-option="keep">
                    <div class="tab-icon">➕</div>
                    <div class="trstemp-tab-content">
                        <h4>Keep Existing Content</h4>
                        <p>Add template pages alongside your current content</p>
                    </div>
                </button>
            </div>
            <div class="option-description">
                <div id="replace-description" class="description-content">
                    <strong>Recommended for new sites:</strong> This will delete all existing pages and create a complete website from the template.
                </div>
                <div id="keep-description" class="description-content">
                    <strong>Recommended for existing sites:</strong> This will add template pages without affecting your current content.
                </div>
            </div>
        </div>

        <div class="additional-options">
            <h4>Additional Import Settings</h4>
            <div class="options-grid">
                <div class="option-card">
                    <input type="checkbox" id="import-customizer" checked>
                    <label for="import-customizer">
                        <h4><?php echo esc_html__('🎨 Import Theme Settings', 'turbo-templates-library-for-elementor'); ?></h4>
                        <p><?php echo esc_html__('Apply template colors, fonts, and layout settings', 'turbo-templates-library-for-elementor'); ?></p>
                    </label>
                </div>
                
                <div class="option-card">
                    <input type="checkbox" id="import-menus" checked>
                    <label for="import-menus">
                        <h4><?php echo esc_html__('📋 Import Navigation Menus', 'turbo-templates-library-for-elementor'); ?></h4>
                        <p><?php echo esc_html__('Create header and footer navigation menus', 'turbo-templates-library-for-elementor'); ?></p>
                    </label>
                </div>
            </div>
        </div>
        
    </div>
    
    <div class="ready-section">
        <div class="ready-content">
            <h3>🚀 Ready to Build Your Website?</h3>
            <p>We'll create your professional website in just a few minutes. You can always customize everything later.</p>
            
            <div class="estimated-time">
                <span class="time-icon">⏱️</span>
                <span>Estimated time: 1-5 minutes</span>
            </div>
            
            <div class="what-happens">
                <h4>What happens next:</h4>
                <ul>
                    <li>Install and activate required plugins</li>
                    <li>Download and import your selected template</li>
                    <li>Apply your customization settings</li>
                    <li>Set up your website content and structure</li>
                    <li>Configure SEO and performance settings</li>
                </ul>
            </div>
            
            <!-- <button class="start-import-btn" onclick="trstemp_startImport()">
                <span class="btn-icon">🚀</span>
                Start Import
            </button> -->
        </div>
    </div>
</div>