<?php
/**
 * Wizard Step 3: Template Customization
 * 
 * @package TurboStarterTemplates
 * @since 1.0.5
 * 
 * phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
 * phpcs:disable WordPress.Security.NonceVerification.Recommended
 * phpcs:disable WordPress.Security.ValidatedSanitizedInput.MissingUnslash
 * phpcs:disable WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
 * phpcs:disable WordPress.PHP.DevelopmentFunctions.error_log_error_log
 * phpcs:disable WordPress.PHP.DevelopmentFunctions.error_log_print_r
 */

// Security: Prevent direct access
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

// Check if Pro plugin active
function trstemp_is_turbo_pro_active() {
    if ( ! function_exists( 'get_plugins' ) ) {
        require_once ABSPATH . 'wp-admin/includes/plugin.php';
    }
    $all_plugins    = get_plugins();
    $active_plugins = (array) get_option( 'active_plugins', array() );
    foreach ( $all_plugins as $plugin_file => $plugin_data ) {
        if ( in_array( $plugin_file, $active_plugins, true ) ) {
            if ( isset( $plugin_data['Name'] ) && $plugin_data['Name'] === 'Turbo Addons Elementor Pro' ) {
                return true;
            }
        }
    }
    return false;
}

$turbo_pro_active = trstemp_is_turbo_pro_active();
?>
<input type="hidden" id="trstemp_pro_active" value="<?php echo esc_attr( $turbo_pro_active ? '1' : '0' ); ?>">
<?php


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

// Security: Sanitize input parameters
$selected_template = isset( $_GET['template'] ) ? absint( wp_unslash( $_GET['template'] ) ) : 2;
$template_name = isset( $_GET['name'] ) ? sanitize_text_field( wp_unslash( urldecode( $_GET['name'] ) ) ) : esc_html__( 'Template', 'turbo-templates-library-for-elementor' );

error_log('TRSTEMP STEP3: Using URL parameters - Template ID: ' . $selected_template . ', Name: ' . $template_name);

// Enqueue WordPress media scripts securely
wp_enqueue_media();
wp_enqueue_script( 'thickbox' );
wp_enqueue_style( 'thickbox' );

$api_base = 'https://templates.wp-turbo.com/api/v1';

// Get template name from API if needed
if ( $template_name === 'Template' || empty( $template_name ) ) {
    $api_response = wp_remote_get( esc_url_raw( $api_base . '/template-packs/' . $selected_template ), array(
        'timeout' => 10,
        'headers' => array( 'Accept' => 'application/json' )
    ) );
    
    if ( ! is_wp_error( $api_response ) ) {
        $body = wp_remote_retrieve_body( $api_response );
        $data = json_decode( $body, true );
        if ( isset( $data['data']['name'] ) ) {
            $template_name = sanitize_text_field( $data['data']['name'] );
        }
    }
    
    if ( $template_name === 'Template' ) {
        $api_response = wp_remote_get( esc_url_raw( $api_base . '/templates/' . $selected_template ), array(
            'timeout' => 10,
            'headers' => array( 'Accept' => 'application/json' )
        ) );
        
        if ( ! is_wp_error( $api_response ) ) {
            $body = wp_remote_retrieve_body( $api_response );
            $data = json_decode( $body, true );
            if ( isset( $data['data']['name'] ) ) {
                $template_name = sanitize_text_field( $data['data']['name'] );
            }
        }
    }
}

// All templates are now free
$is_pro_template = false;
$show_pro_button = false;

// If template name contains certain keywords, try single templates first
$is_likely_single = (strpos(strtolower($template_name), 'agro') !== false || 
                    strpos(strtolower($template_name), 'single') !== false);

error_log('TRSTEMP STEP3: All templates are now FREE');

// Get demo URL - check template name to determine if it's single or pack
$demo_url = '';
$original_demo_url = '';

if ($is_likely_single) {
    // Try single templates first for AGRO and similar
    $single_url = $api_base . '/templates/' . $selected_template;
    error_log('TRSTEMP: Fetching single template demo URL from: ' . $single_url);
    $response = wp_remote_get( esc_url_raw( $single_url ), array(
        'timeout' => 10,
        'headers' => array( 'Accept' => 'application/json' )
    ) );
    
    if ( ! is_wp_error( $response ) ) {
        $body = wp_remote_retrieve_body( $response );
        $data = json_decode( $body, true );
        error_log('TRSTEMP: Single template response: ' . print_r($data, true));
        if ( isset( $data['data']['demo_url'] ) && ! empty( $data['data']['demo_url'] ) ) {
            $demo_url = esc_url_raw( $data['data']['demo_url'] );
            $original_demo_url = $demo_url;
            error_log('TRSTEMP: Found single template demo URL: ' . $demo_url);
        }
    }
    
    // If not found, try template packs
    if ( empty( $demo_url ) ) {
        $pack_url = $api_base . '/template-packs/' . $selected_template;
        $response = wp_remote_get( esc_url_raw( $pack_url ), array(
            'timeout' => 10,
            'headers' => array( 'Accept' => 'application/json' )
        ) );
        
        if ( ! is_wp_error( $response ) ) {
            $body = wp_remote_retrieve_body( $response );
            $data = json_decode( $body, true );
            if ( isset( $data['data']['demo_url'] ) && ! empty( $data['data']['demo_url'] ) ) {
                $demo_url = esc_url_raw( $data['data']['demo_url'] );
                $original_demo_url = $demo_url;
            }
        }
    }
} else {
    // Try template packs first
    $pack_url = $api_base . '/template-packs/' . $selected_template;
    error_log('TRSTEMP: Fetching template pack demo URL from: ' . $pack_url);
    $response = wp_remote_get( esc_url_raw( $pack_url ), array(
        'timeout' => 10,
        'headers' => array( 'Accept' => 'application/json' )
    ) );
    
    if ( ! is_wp_error( $response ) ) {
        $body = wp_remote_retrieve_body( $response );
        $data = json_decode( $body, true );
        error_log('TRSTEMP: Template pack response: ' . print_r($data, true));
        if ( isset( $data['data']['demo_url'] ) && ! empty( $data['data']['demo_url'] ) ) {
            $demo_url = esc_url_raw( $data['data']['demo_url'] );
            $original_demo_url = $demo_url;
            error_log('TRSTEMP: Found template pack demo URL: ' . $demo_url);
        }
    }
    
    // If not found in packs, try single templates
    if ( empty( $demo_url ) ) {
        $single_url = $api_base . '/templates/' . $selected_template;
        error_log('TRSTEMP: Fetching single template demo URL from: ' . $single_url);
        $response = wp_remote_get( esc_url_raw( $single_url ), array(
            'timeout' => 10,
            'headers' => array( 'Accept' => 'application/json' )
        ) );
        
        if ( ! is_wp_error( $response ) ) {
            $body = wp_remote_retrieve_body( $response );
            $data = json_decode( $body, true );
            error_log('TRSTEMP: Single template response: ' . print_r($data, true));
            if ( isset( $data['data']['demo_url'] ) && ! empty( $data['data']['demo_url'] ) ) {
                $demo_url = esc_url_raw( $data['data']['demo_url'] );
                $original_demo_url = $demo_url;
                error_log('TRSTEMP: Found single template demo URL: ' . $demo_url);
            }
        }
    }
}

error_log('TRSTEMP: Final demo URL for template ' . $selected_template . ' (' . $template_name . '): ' . $demo_url);

// Use proxy for iframe with cache busting
if ( ! empty( $demo_url ) ) {

    $original_demo_url = $demo_url;

    $proxy_url = wp_nonce_url(
        add_query_arg(
            array(
                'action'   => 'trstemp_admin_proxy_demo', // ✅ MUST match registered action
                'demo_url' => $demo_url,                  // ❌ NO urlencode
                't'        => time(),
            ),
            admin_url( 'admin-ajax.php' )
        ),
        'trstemp_proxy_demo'
    );

    error_log( 'TRSTEMP: Proxy URL (FINAL): ' . $proxy_url );

    $demo_url = $proxy_url;
} else {
    error_log('TRSTEMP: No demo URL found, using fallback');
    $demo_url = 'data:text/html,<div style="display:flex;align-items:center;justify-content:center;height:100vh;font-family:Arial;text-align:center;background:#f8f9fa;"><div><h2>' . esc_html__( 'Template Preview', 'turbo-templates-library-for-elementor' ) . '</h2><p>' . esc_html__( 'Demo URL not available', 'turbo-templates-library-for-elementor' ) . '</p></div></div>';
}

// ✅ STEP 2: Prepare JavaScript variables
$js_vars = array(
    'selected_template' => $selected_template,
    'template_name' => $template_name,
    'original_demo_url' => $original_demo_url,
    'import_url' => admin_url( 'admin.php?page=turbo-starter-templates&ci=4' ),
    'nonce' => wp_create_nonce('trstemp_admin_nonce'),
    'ajaxurl' => admin_url('admin-ajax.php'),
    'strings' => array(
        'demo_not_available' => esc_html__( 'Demo URL not available', 'turbo-templates-library-for-elementor' ),
        'lato_font' => esc_html__( 'Lato & Lato', 'turbo-templates-library-for-elementor' ),
        'start_building' => esc_html__( 'Start Building', 'turbo-templates-library-for-elementor' ),
    )
);

// ✅ STEP 3: Create the COMPLETE inline JavaScript
$inline_script = '(function() {

    "use strict";
    
    // Global variables
    const trstempVars = ' . wp_json_encode($js_vars) . ';
    const ajaxurl = trstempVars.ajaxurl;
    const nonce   = trstempVars.nonce;
    
    // Store template info securely
    sessionStorage.setItem("trstemp_selected_template", ' . wp_json_encode($selected_template) . ');
    sessionStorage.setItem("trstemp_selected_template_name", ' . wp_json_encode($template_name) . ');
    
    // Function declarations
    function trstemp_openMediaLibrary() {
        document.getElementById("logo-file-input").click();
    }

    function trstemp_handleFileSelect(event) {
        const file = event.target.files[0];
        if (file && file.type.startsWith("image/")) {
            const reader = new FileReader();
            reader.onload = function(e) {
                const preview = document.getElementById("logo-preview");
                preview.innerHTML = \'<img src="\' + e.target.result + \'" alt="Logo" onclick="trstemp_openMediaLibrary()" style="cursor:pointer; max-width: 100%; max-height: 100%; object-fit: contain;">\';
                sessionStorage.setItem("trstemp_custom_logo", e.target.result);
                trstemp_showToast("Logo uploaded successfully!");
            };
            reader.readAsDataURL(file);
        }
    }

    // Expose functions to global scope
    window.trstemp_openMediaLibrary = trstemp_openMediaLibrary;
    window.trstemp_handleFileSelect = trstemp_handleFileSelect;
    window.trstemp_showToast = trstemp_showToast;

    // Define other functions that need global scope
    window.trstemp_continueToImport = function() {
        trstemp_continueToImport();
    };

    window.trstemp_resetToOriginal = function() {
        trstemp_resetToOriginal();
    };

    window.trstemp_openExternalPreview = function() {
        trstemp_openExternalPreview();
    };

    window.trstemp_applyFontChanges = function(font) {
        trstemp_applyFontChanges(font);
    };

    window.trstemp_applyColorChanges = function(palette) {
        trstemp_applyColorChanges(palette);
    };

    window.trstemp_handleIframeLoad = function() {
        trstemp_handleIframeLoad();
    };

    window.trstemp_handleIframeError = function() {
        trstemp_handleIframeError();
    };
    
    function trstemp_continueToImport() {
        const customizations = {
            template_id: ' . wp_json_encode($selected_template) . ',
            template_name: ' . wp_json_encode($template_name) . ',
            logo: sessionStorage.getItem("trstemp_custom_logo"),
            font_pair: document.querySelector(".font-option.active")?.dataset.font || "lato",
            color_palette: document.querySelector(".palette.active")?.dataset.palette || "original",
            site_title: document.getElementById("site-title").value,
            site_tagline: document.getElementById("site-tagline").value
        };
        
        console.log("TRSTEMP: Saving step 3 customizations:", customizations);
        
        sessionStorage.setItem("trstemp_wizard_customizations", JSON.stringify(customizations));
        
        // Save to wizard session
        fetch(ajaxurl, {
            method: "POST",
            headers: {"Content-Type": "application/x-www-form-urlencoded"},
            body: "action=trstemp_save_step_data&step=3&nonce=" + nonce + "&data=" + encodeURIComponent(JSON.stringify(customizations))
        })
        .then(response => response.json())
        .then(data => {
            console.log("TRSTEMP: Step 3 data saved:", data);
            window.location.href = trstempVars.import_url;
        })
        .catch(error => {
            console.error("TRSTEMP: Error saving step 3 data:", error);
            // Continue anyway
            window.location.href = trstempVars.import_url;
        });
    }
    
    function trstemp_openExternalPreview() {
        const demoUrl = ' . wp_json_encode($original_demo_url) . ';
        if (demoUrl && demoUrl !== "") {
            window.open(demoUrl, "_blank");
        } else {
            alert(trstempVars.strings.demo_not_available);
        }
    }
    
    function trstemp_resetToOriginal() {
        // Reset font selection
        document.querySelectorAll(".font-option").forEach(o => o.classList.remove("active"));
        const latoOption = document.querySelector(\'.font-option[data-font="lato"]\');
        if (latoOption) {
            latoOption.classList.add("active");
            document.getElementById("current-font-name").textContent = trstempVars.strings.lato_font;
        }
        
        // Reset color selection
        document.querySelectorAll(".palette").forEach(p => p.classList.remove("active"));
        const originalPalette = document.querySelector(\'.palette[data-palette="original"]\');
        if (originalPalette) {
            originalPalette.classList.add("active");
        }
        
        // Force reload iframe with cache busting
        const iframe = document.getElementById("template-preview");
        if (iframe) {
            const currentSrc = iframe.src;
            const separator = currentSrc.includes("?") ? "&" : "?";
            iframe.src = currentSrc + separator + "reset=" + Date.now();
            console.log("TRSTEMP: Iframe reloaded for reset");
        }
    }
    
    // Font change function
    function trstemp_applyFontChanges(fontFamily) {
        const fontMap = {
            "lato": "Lato, sans-serif",
            "inter": "Inter, sans-serif", 
            "roboto": "Roboto, sans-serif",
            "poppins": "Poppins, sans-serif"
        };
        
        const selectedFont = fontMap[fontFamily] || "Lato, sans-serif";
        
        // Load Google Font if needed
        const googleFonts = {
            "lato": "Lato:300,400,700",
            "inter": "Inter:300,400,700",
            "roboto": "Roboto:300,400,700", 
            "poppins": "Poppins:300,400,700"
        };
        
        const css = `
            @import url("https://fonts.googleapis.com/css2?family=${googleFonts[fontFamily]}&display=swap");
            
            *, *::before, *::after {
                font-family: ${selectedFont} !important;
            }
            body, html {
                font-family: ${selectedFont} !important;
            }
            h1, h2, h3, h4, h5, h6 {
                font-family: ${selectedFont} !important;
            }
            p, span, div, a, li, ul, ol {
                font-family: ${selectedFont} !important;
            }
            button, .btn, .button, input, textarea, select {
                font-family: ${selectedFont} !important;
            }
            .elementor-heading-title, .elementor-widget-heading, .elementor-button {
                font-family: ${selectedFont} !important;
            }
            nav, .menu, .navigation, .navbar {
                font-family: ${selectedFont} !important;
            }
        `;
        
        console.log("TRSTEMP: Applying font changes:", fontFamily, selectedFont);
        
        const iframe = document.getElementById("template-preview");
        if (iframe && iframe.contentWindow) {
            iframe.contentWindow.postMessage({
                type: "INJECT_CSS",
                css: css
            }, "*");
            console.log("TRSTEMP: Font postMessage sent");
        } else {
            console.error("TRSTEMP: Iframe not accessible");
        }
    }
    
    // Color change function
    function trstemp_applyColorChanges(palette) {
        const colorMap = {
            "original": {
                primary: "#667eea",
                secondary: "#764ba2",
                accent: "#f093fb",
                highlight: "#43e97b"
            },
            "blue": {
                primary: "#2196F3",
                secondary: "#1976D2", 
                accent: "#03DAC6",
                highlight: "#00BCD4"
            },
            "green": {
                primary: "#4CAF50",
                secondary: "#388E3C",
                accent: "#8BC34A", 
                highlight: "#CDDC39"
            },
            "red": {
                primary: "#F44336",
                secondary: "#D32F2F",
                accent: "#FF5722",
                highlight: "#FF9800"
            },
            "orange": {
                primary: "#FF9800",
                secondary: "#F57C00",
                accent: "#FF6F00",
                highlight: "#FFB74D"
            },
            "purple": {
                primary: "#9C27B0",
                secondary: "#7B1FA2",
                accent: "#E91E63",
                highlight: "#AD1457"
            },
            "black": {
                primary: "#212121",
                secondary: "#424242",
                accent: "#616161",
                highlight: "#757575"
            }
        };
        
        const colors = colorMap[palette] || colorMap["original"];
        const css = `
            /* Buttons - All types with maximum specificity */
            button, .btn, .button, input[type="submit"], input[type="button"], .elementor-button, [role="button"],
            .elementor-widget-button .elementor-button, .wp-block-button__link, .woocommerce-button,
            .elementor-button-wrapper .elementor-button, .btn-primary, .btn-secondary {
                background-color: ${colors.primary} !important;
                background: ${colors.primary} !important;
                border-color: ${colors.primary} !important;
                color: white !important;
            }
            button:hover, .btn:hover, .button:hover, input[type="submit"]:hover, .elementor-button:hover,
            .elementor-widget-button .elementor-button:hover, .wp-block-button__link:hover {
                background-color: ${colors.secondary} !important;
                background: ${colors.secondary} !important;
                border-color: ${colors.secondary} !important;
            }
            
            /* Headings - More comprehensive */
            h1, h2, h3, h4, h5, h6, .elementor-heading-title, 
            .elementor-widget-heading h1, .elementor-widget-heading h2, .elementor-widget-heading h3,
            .elementor-widget-heading h4, .elementor-widget-heading h5, .elementor-widget-heading h6,
            .wp-block-heading, .entry-title, .page-title, .post-title {
                color: ${colors.secondary} !important;
            }
            
            /* Text elements - Force override inline styles */
            p, span, div, .elementor-text-editor p, .elementor-widget-text-editor p,
            .elementor-widget-text-editor span, .wp-block-paragraph {
                color: ${colors.accent} !important;
            }
            
            /* Override ALL inline color styles */
            *[style*="color:"] {
                color: ${colors.accent} !important;
            }
            
            /* Links - Comprehensive coverage */
            a, .elementor-widget-container a, .menu a, .navigation a, nav a,
            .elementor-nav-menu a, .wp-block-navigation a, .site-navigation a {
                color: ${colors.accent} !important;
            }
            a:hover, .elementor-widget-container a:hover, .menu a:hover, nav a:hover,
            .elementor-nav-menu a:hover, .wp-block-navigation a:hover {
                color: ${colors.primary} !important;
            }
            
            /* Icons - All possible selectors */
            .elementor-widget-icon, .elementor-icon, i, .fa, [class*="icon-"],
            .elementor-icon-wrapper, .elementor-widget-icon .elementor-icon {
                color: ${colors.primary} !important;
            }
            
            /* Lists */
            ul li::marker, ol li::marker, .elementor-widget-icon-list .elementor-icon-list-item {
                color: ${colors.primary} !important;
            }
            
            /* Sections and backgrounds - Force gradients */
            .elementor-section, .hero-section, .banner-section, .elementor-top-section,
            .elementor-section[data_element_type="section"], .wp-block-cover {
                background: linear-gradient(135deg, ${colors.primary} 0%, ${colors.secondary} 100%) !important;
            }
            
            /* Override background colors */
            .elementor-widget-container, .elementor-column, .elementor-row {
                background-color: transparent !important;
            }
            
            /* Force text color in containers */
            .elementor-widget-container *, .elementor-column *, .elementor-row * {
                color: inherit !important;
            }
            
            /* Special elements */
            .elementor-widget-divider .elementor-divider-separator {
                border-color: ${colors.primary} !important;
            }
            
            /* Form elements */
            input, textarea, select {
                border-color: ${colors.primary} !important;
            }
            input:focus, textarea:focus, select:focus {
                border-color: ${colors.secondary} !important;
                box-shadow: 0 0 0 2px ${colors.primary}33 !important;
            }
        `;
        
        console.log("TRSTEMP: Applying color changes:", palette, colors);
        
        const iframe = document.getElementById("template-preview");
        if (iframe && iframe.contentWindow) {
            iframe.contentWindow.postMessage({
                type: "INJECT_CSS",
                css: css
            }, "*");
            console.log("TRSTEMP: Color postMessage sent");
        } else {
            console.error("TRSTEMP: Iframe not accessible");
        }
    }
    
    function trstemp_handleIframeLoad() {
        console.log("TRSTEMP: Iframe loaded successfully");
        const fallback = document.getElementById("preview-fallback");
        const iframe = document.getElementById("template-preview");
        
        if (fallback) fallback.style.display = "none";
        if (iframe) iframe.style.display = "block";
        
        // Try to detect navigation attempts using a click interceptor
        if (iframe && iframe.contentWindow) {
            try {
                // This only works for same-origin iframes
                const iframeLinks = iframe.contentDocument?.querySelectorAll("a") || [];
                iframeLinks.forEach(link => {
                    link.addEventListener("click", function(e) {
                        const href = this.getAttribute("href");
                        // Only intercept if clicking internal navigation links
                        if (href && (href.startsWith("/") || href.includes(new URL(iframe.src).hostname))) {
                            console.log("TRSTEMP: Navigation attempt to:", href);
                            const modal = document.getElementById("trstemp-navigation-modal");
                            if (modal) {
                                modal.style.display = "flex";
                                setTimeout(() => {
                                    modal.style.opacity = "1";
                                }, 10);
                            }
                            e.preventDefault();
                            return false;
                        }
                    });
                });
            } catch (err) {
                console.log("TRSTEMP: Cannot intercept iframe links (cross-origin):", err.message);
            }
        }
        
        // Test iframe accessibility after it loads
        setTimeout(() => {
            console.log("TRSTEMP: Testing iframe accessibility...");
            if (iframe) {
                try {
                    const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
                    if (iframeDoc) {
                        console.log("TRSTEMP: Same origin - can access iframe document directly");
                    } else {
                        console.log("TRSTEMP: Cross origin - must use postMessage");
                    }
                } catch (e) {
                    console.log("TRSTEMP: Cross origin detected:", e.message);
                }
                
                if (iframe.contentWindow) {
                    iframe.contentWindow.postMessage({
                        type: "INJECT_CSS",
                        css: "/* TRSTEMP Test CSS */"
                    }, "*");
                    console.log("TRSTEMP: Test postMessage sent");
                }
            }
        }, 2000);
    }
    
    function trstemp_handleIframeError() {
        console.log("TRSTEMP: Iframe failed to load, showing fallback");
        const fallback = document.getElementById("preview-fallback");
        const iframe = document.getElementById("template-preview");

        if (fallback) fallback.style.display = "flex";
        if (iframe) iframe.style.display = "none";
    }
    
    function trstemp_showToast(message) {
        // Remove existing toast
        const existingToast = document.getElementById("trstemp-toast");
        if (existingToast) {
            existingToast.remove();
        }
        
        // Create toast element
        const toast = document.createElement("div");
        toast.id = "trstemp-toast";
        toast.innerHTML = `
            <div style="
                position: fixed;
                top: 20px;
                right: 20px;
                background: #28a745;
                color: white;
                padding: 15px 20px;
                border-radius: 8px;
                box-shadow: 0 4px 20px rgba(0,0,0,0.2);
                z-index: 999999;
                font-size: 14px;
                font-weight: 600;
                animation: slideIn 0.3s ease;
            ">
                ✓ ${message}
            </div>
        `;
        
        // Add CSS animation
        const style = document.createElement("style");
        style.textContent = `
            @keyframes slideIn {
                from { transform: translateX(100%); opacity: 0; }
                to { transform: translateX(0); opacity: 1; }
            }
            @keyframes slideOut {
                from { transform: translateX(0); opacity: 1; }
                to { transform: translateX(100%); opacity: 0; }
            }
        `;
        document.head.appendChild(style);
        
        document.body.appendChild(toast);
        
        // Auto remove after 3 seconds
        setTimeout(() => {
            if (toast) {
                toast.firstElementChild.style.animation = "slideOut 0.3s ease";
                setTimeout(() => toast.remove(), 300);
            }
        }, 3000);
    }
    
    // Initialize on DOM ready
    document.addEventListener("DOMContentLoaded", function() {
        // Footer button
        const footer = document.querySelector(".turbo-wizard-footer-right");
        if (footer) {
           footer.innerHTML =
            "<button class=\"turbo-btn-primary\" onclick=\"window.trstemp_continueToImport()\">🚀 " +
            trstempVars.strings.start_building +
            "</button>";
        }

        // ✅ Add Free/Pro/Buy Now buttons here
        const turboProActive = document.getElementById("trstemp_pro_active").value == "1";
        const accessType = sessionStorage.getItem("trstemp_template_access_type") || "free";
        const container = document.getElementById("trstemp-action-buttons");
        container.innerHTML = "";
        if (accessType == "free") {
            container.innerHTML = `<button class="btn-continue-float" onclick="window.trstemp_continueToImport()">🚀 Start Building</button>`;
        } else if (accessType == "pro" && turboProActive) {
            container.innerHTML = `<button class="btn-continue-float" onclick="window.trstemp_continueToImport()">🚀 Start Building</button>`;
        } else {
            container.innerHTML = `<a href="https://turbo-addons.com/pricing/" class="btn-continue-float" target="_blank" style="display:inline-flex;text-decoration:none;text-align:center;">🌟 Upgrade to Pro </a>`;
        }
                
        // Initialize font and color options
        document.querySelectorAll(".font-option").forEach(option => {
            option.addEventListener("click", function() {
                document.querySelectorAll(".font-option").forEach(o => o.classList.remove("active"));
                this.classList.add("active");
                
                const fontName = this.dataset.name;
                document.getElementById("current-font-name").textContent = fontName;
                sessionStorage.setItem("turbo_font_pair", this.dataset.font);
                
                // Apply font changes to preview
                trstemp_applyFontChanges(this.dataset.font);
                
                // Show toast notification
                trstemp_showToast("Font updated successfully!");
            });
        });

        document.querySelectorAll(".palette").forEach(palette => {
            palette.addEventListener("click", function() {
                document.querySelectorAll(".palette").forEach(p => p.classList.remove("active"));
                this.classList.add("active");
                sessionStorage.setItem("trstemp_color_palette", this.dataset.palette);
                
                // Apply color changes to preview
                trstemp_applyColorChanges(this.dataset.palette);
                
                // Show toast notification
                trstemp_showToast("Color palette updated successfully!");
            });
        });

        // Event listeners for site info
        document.getElementById("site-title")?.addEventListener("input", function() {
            sessionStorage.setItem("turbo_site_title", this.value);
        });

        document.getElementById("site-tagline")?.addEventListener("input", function() {
            sessionStorage.setItem("turbo_site_tagline", this.value);
        });

        // Load previous customizations on page load
        fetch(ajaxurl, {
            method: "POST",
            headers: {"Content-Type": "application/x-www-form-urlencoded"},
            body: "action=trstemp_get_step_data&step=3&nonce=" + nonce
        })
        .then(response => response.json())
        .then(data => {
            if (data.success && data.data) {
                console.log("TRSTEMP: Loaded step 3 data from session:", data.data);
                const customizations = data.data;
                
                // Restore font selection
                if (customizations.font_pair) {
                    const fontOption = document.querySelector(\'[data-font="\' + customizations.font_pair + \'"]\');
                    if (fontOption) {
                        document.querySelectorAll(".font-option").forEach(o => o.classList.remove("active"));
                        fontOption.classList.add("active");
                        document.getElementById("current-font-name").textContent = fontOption.dataset.name;
                    }
                }
                
                // Restore color palette
                if (customizations.color_palette) {
                    const paletteOption = document.querySelector(\'[data-palette="\' + customizations.color_palette + \'"]\');
                    if (paletteOption) {
                        document.querySelectorAll(".palette").forEach(p => p.classList.remove("active"));
                        paletteOption.classList.add("active");
                    }
                }
                
                // Restore site info
                if (customizations.site_title) {
                    document.getElementById("site-title").value = customizations.site_title;
                }
                if (customizations.site_tagline) {
                    document.getElementById("site-tagline").value = customizations.site_tagline;
                }
                
                // Restore logo
                if (customizations.logo) {
                    const preview = document.getElementById("logo-preview");
                    preview.innerHTML = \'<img src="\' + customizations.logo + \'" alt="Logo" onclick="trstemp_openMediaLibrary()" style="cursor:pointer;">\';
                    sessionStorage.setItem("trstemp_custom_logo", customizations.logo);
                }
            }
        })
        .catch(error => {
            console.error("TRSTEMP: Error loading step 3 data:", error);
        });

        // Check iframe loading after a timeout
        setTimeout(function() {
            const iframe = document.getElementById("template-preview");
            const fallback = document.getElementById("preview-fallback");
            
            try {
                if (iframe && (iframe.contentDocument || iframe.contentWindow)) {
                    console.log("TRSTEMP: Iframe appears to be loaded");
                    if (fallback) fallback.style.display = "none";
                    iframe.style.display = "block";
                } else {
                    console.log("TRSTEMP: Iframe not accessible, showing fallback");
                    if (fallback) fallback.style.display = "flex";
                    iframe.style.display = "none";
                }
            } catch (e) {
                console.log("TRSTEMP: Iframe access error, showing fallback:", e);
                if (fallback) fallback.style.display = "flex";
                iframe.style.display = "none";
            }
        }, 3000);
    });
})();';

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

<div class="trstemp-customization-page">
    <div class="customization-sidebar">
        <div class="template-info">
            <h2><?php echo esc_html( $template_name ); ?></h2>
            <p><?php echo esc_html__( 'Customize your template before importing', 'turbo-templates-library-for-elementor' ); ?></p>
        </div>

        <div class="customization-sections">
            <div class="customization-section">
                <h3><?php echo esc_html__( '🏢 Site Logo', 'turbo-templates-library-for-elementor' ); ?></h3>
                <div class="logo-upload">
                    <div class="logo-preview" id="logo-preview" onclick="trstemp_openMediaLibrary()">
                        <span><?php echo esc_html__( 'Click to upload logo', 'turbo-templates-library-for-elementor' ); ?></span>
                    </div>
                    <input type="file" id="logo-file-input" accept="image/*" style="display:none;" onchange="trstemp_handleFileSelect(event)">
                    <button class="btn-upload" onclick="trstemp_openMediaLibrary()">
                        <?php echo esc_html__( 'Upload Logo', 'turbo-templates-library-for-elementor' ); ?>
                    </button>
                </div>
            </div>

            <div class="customization-section">
                <h3><?php echo esc_html__( '📝 Font Pair:', 'turbo-templates-library-for-elementor' ); ?> <span id="current-font-name"><?php echo esc_html__( 'Lato & Lato', 'turbo-templates-library-for-elementor' ); ?></span></h3>
                <div class="font-samples" id="font-preview-area">
                    <div class="font-row" id="font-sample-1" style="font-weight: 300;">Ag Ag Ag Ag Ag Ag</div>
                    <div class="font-row" id="font-sample-2" style="font-weight: 600;">Ag Ag Ag Ag Ag</div>
                </div>
                <div class="font-options">
                    <div class="font-option active" data-font="lato" data-name="<?php echo esc_attr__( 'Lato & Lato', 'turbo-templates-library-for-elementor' ); ?>">
                        <span><?php echo esc_html__( 'Lato', 'turbo-templates-library-for-elementor' ); ?></span>
                    </div>
                    <div class="font-option" data-font="inter" data-name="<?php echo esc_attr__( 'Inter & Inter', 'turbo-templates-library-for-elementor' ); ?>">
                        <span><?php echo esc_html__( 'Inter', 'turbo-templates-library-for-elementor' ); ?></span>
                    </div>
                    <div class="font-option" data-font="roboto" data-name="<?php echo esc_attr__( 'Roboto & Roboto', 'turbo-templates-library-for-elementor' ); ?>">
                        <span><?php echo esc_html__( 'Roboto', 'turbo-templates-library-for-elementor' ); ?></span>
                    </div>
                    <div class="font-option" data-font="poppins" data-name="<?php echo esc_attr__( 'Poppins & Poppins', 'turbo-templates-library-for-elementor' ); ?>">
                        <span><?php echo esc_html__( 'Poppins', 'turbo-templates-library-for-elementor' ); ?></span>
                    </div>
                </div>
            </div>

            <div class="customization-section">
                <h3><?php echo esc_html__( '🎨 Color Palette', 'turbo-templates-library-for-elementor' ); ?></h3>
                <div class="color-palettes">
                    <div class="palette active" data-palette="original">
                        <div class="palette-colors">
                            <span style="background: #667eea;"></span>
                            <span style="background: #764ba2;"></span>
                            <span style="background: #f093fb;"></span>
                            <span style="background: #43e97b;"></span>
                        </div>
                        <span><?php echo esc_html__( 'Original', 'turbo-templates-library-for-elementor' ); ?></span>
                    </div>
                    <div class="palette" data-palette="blue">
                        <div class="palette-colors">
                            <span style="background: #2196F3;"></span>
                            <span style="background: #1976D2;"></span>
                            <span style="background: #03DAC6;"></span>
                            <span style="background: #00BCD4;"></span>
                        </div>
                        <span><?php echo esc_html__( 'Blue', 'turbo-templates-library-for-elementor' ); ?></span>
                    </div>
                    <div class="palette" data-palette="green">
                        <div class="palette-colors">
                            <span style="background: #4CAF50;"></span>
                            <span style="background: #388E3C;"></span>
                            <span style="background: #8BC34A;"></span>
                            <span style="background: #CDDC39;"></span>
                        </div>
                        <span><?php echo esc_html__( 'Green', 'turbo-templates-library-for-elementor' ); ?></span>
                    </div>
                    <div class="palette" data-palette="red">
                        <div class="palette-colors">
                            <span style="background: #F44336;"></span>
                            <span style="background: #D32F2F;"></span>
                            <span style="background: #FF5722;"></span>
                            <span style="background: #FF9800;"></span>
                        </div>
                        <span><?php echo esc_html__( 'Red', 'turbo-templates-library-for-elementor' ); ?></span>
                    </div>
                    <div class="palette" data-palette="orange">
                        <div class="palette-colors">
                            <span style="background: #FF9800;"></span>
                            <span style="background: #F57C00;"></span>
                            <span style="background: #FF6F00;"></span>
                            <span style="background: #FFB74D;"></span>
                        </div>
                        <span><?php echo esc_html__( 'Orange', 'turbo-templates-library-for-elementor' ); ?></span>
                    </div>
                    <div class="palette" data-palette="purple">
                        <div class="palette-colors">
                            <span style="background: #9C27B0;"></span>
                            <span style="background: #7B1FA2;"></span>
                            <span style="background: #E91E63;"></span>
                            <span style="background: #AD1457;"></span>
                        </div>
                        <span><?php echo esc_html__( 'Purple', 'turbo-templates-library-for-elementor' ); ?></span>
                    </div>
                    <div class="palette" data-palette="black">
                        <div class="palette-colors">
                            <span style="background: #212121;"></span>
                            <span style="background: #424242;"></span>
                            <span style="background: #616161;"></span>
                            <span style="background: #757575;"></span>
                        </div>
                        <span><?php echo esc_html__( 'Black', 'turbo-templates-library-for-elementor' ); ?></span>
                    </div>
                </div>
            </div>

            <div class="customization-section">
                <h3><?php echo esc_html__( '📄 Site Information', 'turbo-templates-library-for-elementor' ); ?></h3>
                <div class="form-group">
                    <label><?php echo esc_html__( 'Site Title', 'turbo-templates-library-for-elementor' ); ?></label>
                    <input type="text" id="site-title" value="<?php echo esc_attr( get_bloginfo( 'name' ) ); ?>" placeholder="<?php echo esc_attr__( 'Your Site Title', 'turbo-templates-library-for-elementor' ); ?>">
                </div>
                <div class="form-group">
                    <label><?php echo esc_html__( 'Tagline', 'turbo-templates-library-for-elementor' ); ?></label>
                    <input type="text" id="site-tagline" value="<?php echo esc_attr( get_bloginfo( 'description' ) ); ?>" placeholder="<?php echo esc_attr__( 'Your site description', 'turbo-templates-library-for-elementor' ); ?>">
                </div>
            </div>
        </div>
    </div>

    <div class="preview-area">
        <div class="preview-header">
            <h3><?php echo esc_html__( 'Live Preview -', 'turbo-templates-library-for-elementor' ); ?> <?php echo esc_html( $template_name ); ?></h3>
            <div class="preview-actions">
                <button class="btn-close" onclick="window.location.href='<?php echo esc_url( admin_url( 'admin.php?page=turbo-starter-templates&ci=2' ) ); ?>'" title="<?php echo esc_attr__( 'Back to Templates', 'turbo-templates-library-for-elementor' ); ?>">✕</button>
                <button class="btn-external" onclick="trstemp_openExternalPreview()"><?php echo esc_html__( '🌐 Open in New Tab', 'turbo-templates-library-for-elementor' ); ?></button>
                <button class="btn-refresh" onclick="trstemp_resetToOriginal()" title="<?php echo esc_attr__( 'Reset to Original', 'turbo-templates-library-for-elementor' ); ?>">🔄</button>
            </div>
        </div>
        <div class="preview-container">
            <div id="preview-fallback" style="display:flex;text-align:center;padding:40px;background:white;border-radius:8px;align-items:center;justify-content:center;flex-direction:column;">
                <h3><?php echo esc_html__( 'Template Pack Preview', 'turbo-templates-library-for-elementor' ); ?></h3>
                <p><?php echo esc_html__( 'This template pack includes multiple pages: Home, About Us, Services, Contact', 'turbo-templates-library-for-elementor' ); ?></p>
                <button onclick="trstemp_openExternalPreview()" class="btn-external" style="margin-top:15px;padding:12px 24px;background:#667eea;color:white;border:none;border-radius:6px;cursor:pointer;">
                    <?php echo esc_html__( '🌐 Open Demo in New Tab', 'turbo-templates-library-for-elementor' ); ?>
                </button>
            </div>
            <iframe id="template-preview" src="<?php echo esc_url( $demo_url ); ?>" frameborder="0" style="border-radius:8px;width:100%;height:100%;" onload="trstemp_handleIframeLoad()" onerror="trstemp_handleIframeError()" sandbox="allow-same-origin allow-scripts allow-forms allow-popups allow-top-navigation allow-popups-to-escape-sandbox"></iframe>
        </div>
    </div>

    <!-- Step 3 Footer with Action Buttons -->
    <div class="step-3-footer">
        <button class="trstemp-btn-secondary" onclick="window.location.href='<?php echo esc_url( admin_url( 'admin.php?page=turbo-starter-templates&ci=2' ) ); ?>'" id="step3-back-btn">
            <?php echo esc_html__( '← Back', 'turbo-templates-library-for-elementor' ); ?>
        </button>
        
        <div class="step-3-footer-right">
            <div id="trstemp-action-buttons"></div>
        </div>
    </div>

    <!-- Navigation Modal -->
    <div id="trstemp-navigation-modal" style="display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.6);z-index:9999999;align-items:center;justify-content:center;opacity:0;transition:opacity 0.3s ease;">
        <div style="background:white;border-radius:12px;padding:40px;max-width:450px;text-align:center;box-shadow:0 10px 40px rgba(0,0,0,0.3);">
            <div style="font-size:48px;margin-bottom:20px;">🔗</div>
            <h2 style="margin:0 0 15px 0;font-size:24px;font-weight:700;color:#333;"><?php echo esc_html__( 'View Full Template', 'turbo-templates-library-for-elementor' ); ?></h2>
            <p style="margin:0 0 30px 0;font-size:16px;color:#666;line-height:1.6;"><?php echo esc_html__( 'To explore all template pages (About, Services, Contact, etc.), click the button below to open the demo in a new tab.', 'turbo-templates-library-for-elementor' ); ?></p>
            <div style="display:flex;gap:12px;justify-content:center;">
                <button onclick="document.getElementById('trstemp-navigation-modal').style.display='none';document.getElementById('trstemp-navigation-modal').style.opacity='0';" style="padding:12px 24px;background:#f0f0f0;color:#333;border:none;border-radius:8px;font-size:14px;font-weight:600;cursor:pointer;transition:all 0.3s ease;" onmouseover="this.style.background='#e0e0e0'" onmouseout="this.style.background='#f0f0f0'">
                    <?php echo esc_html__( 'Close', 'turbo-templates-library-for-elementor' ); ?>
                </button>
                <button onclick="trstemp_openExternalPreview();document.getElementById('trstemp-navigation-modal').style.display='none';document.getElementById('trstemp-navigation-modal').style.opacity='0';" style="padding:12px 24px;background:#667eea;color:white;border:none;border-radius:8px;font-size:14px;font-weight:600;cursor:pointer;transition:all 0.3s ease;" onmouseover="this.style.background='#5a6fd8'" onmouseout="this.style.background='#667eea'">
                    <?php echo esc_html__( '🌐 Open Demo', 'turbo-templates-library-for-elementor' ); ?>
                </button>
            </div>
        </div>
    </div>
</div>