<?php
if (!defined('ABSPATH')) die('Restricted Access');
if (!current_user_can('manage_options')) {
    wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'ai-flash-tune'));
}
$aiflt_page_title = __('Funnel Analysis', 'ai-flash-tune');


if (!function_exists('aiflt_get_metric_trend_icon_class')) {
    /**
     * Return a trend icon class with correct positive/negative color semantics.
     * For lower-is-better metrics, an upward arrow is bad and a downward arrow is good.
     */
    function aiflt_get_metric_trend_icon_class($has_activity, $trend, $lower_is_better = false) {
        if (!$has_activity) {
            return 'fa-minus ai-flash-tune-text-gray-400';
        }

        if ($lower_is_better) {
            return ($trend === 'up')
                ? 'fa-arrow-up ai-flash-tune-text-red-500'
                : 'fa-arrow-down ai-flash-tune-text-green-500';
        }

        return ($trend === 'up')
            ? 'fa-arrow-up ai-flash-tune-text-green-500'
            : 'fa-arrow-down ai-flash-tune-text-red-500';
    }
}

// Check for WooCommerce dependency and addon status at the top.
$aiflt_is_wc_active = aiflt_is_woocommerce_active();

// Check for WooCommerce dependency at the top of the view file.
if ($aiflt_is_wc_active) {
    // --- NEW LOGIC START: Determine the effective default start date ---
    $aiflt_plugin_install_time = get_option('aiflt_activation_time', time());
    $aiflt_default_start_timestamp = strtotime('-29 days'); 
    $aiflt_min_valid_start_timestamp = $aiflt_plugin_install_time;

    // Determine the earliest valid default date by taking the LATER of the two timestamps.
    $aiflt_effective_start_timestamp = max($aiflt_default_start_timestamp, $aiflt_min_valid_start_timestamp);
    $aiflt_effective_default_start_date = gmdate('Y-m-d', $aiflt_effective_start_timestamp);
    // --- NEW LOGIC END ---
    
    // Sanitize and set default date range from GET parameters
    // CRITICAL FIX: Use the calculated effective default start date.
    $aiflt_start_date = isset($_GET['start_date']) && !empty($_GET['start_date']) ? sanitize_text_field(wp_unslash($_GET['start_date'])) : $aiflt_effective_default_start_date;
    
    $aiflt_end_date = isset($_GET['end_date']) && !empty($_GET['end_date']) ? sanitize_text_field(wp_unslash($_GET['end_date'])) : gmdate('Y-m-d');
    $aiflt_current_device = isset($_GET['device']) ? sanitize_text_field(wp_unslash($_GET['device'])) : 'all';

    // Pass the date range to the logic function
    $aiflt_all_funnel_data = AIFLT_Funnel_Analyzer_Logic::get_funnel_data($aiflt_current_device, $aiflt_start_date, $aiflt_end_date);
    $aiflt_has_funnel_activity = !empty($aiflt_all_funnel_data) && empty($aiflt_all_funnel_data['is_empty']) && (int) ($aiflt_all_funnel_data['total_sessions'] ?? 0) > 0;
} else {
    $aiflt_has_funnel_activity = false;
}
?>
<div class="ai-flash-tune-admin-wrapper">
    <?php include_once('ai-flash-tune-admin-sidebar.php'); ?>
    <div class="ai-flash-tune-main-content">
        <div class="ai-flash-tune-flex ai-flash-tune-justify-between ai-flash-tune-flex-center ai-flash-tune-mb-8 ai-flash-tune-page-header">
            <span class="ai-flash-tune-main-title"><?php echo esc_html($aiflt_page_title); ?></span>
            <?php
            if (aiflt_is_woocommerce_active()) { ?>
                <div class="ai-flash-tune-header-actions-wrapper">
                    <div class="ai-flash-tune-flex ai-flash-tune-flex-center ai-flash-tune-space-x-4 ai-flash-tune-header-actions">
                        <span class="ai-flash-tune-text-gray-600 ai-flash-tune-text-sm ai-flash-tune-last-updated">
                            <?php echo esc_html(gmdate('M d, Y', strtotime($aiflt_start_date))) . ' - ' . esc_html(gmdate('M d, Y', strtotime($aiflt_end_date))); ?>
                        </span>
                        <a class="ai-flash-tune-bg-blue-500 hover:ai-flash-tune-bg-blue-600 ai-flash-tune-text-white ai-flash-tune-font-semibold ai-flash-tune-py-2 ai-flash-tune-px-4 ai-flash-tune-rounded-lg ai-flash-tune-shadow-md ai-flash-tune-date-range-toggle" href="#">
                            <i class="fas fa-calendar-alt ai-flash-tune-mr-2"></i> <?php echo esc_html(__('Date Range', 'ai-flash-tune')); ?>
                        </a>
                    </div>
                    
                    <div id="ai-flash-tune-date-range-form-wrapper" class="ai-flash-tune-card ai-flash-tune-date-range-form hidden">
                        <form method="GET" class="ai-flash-tune-flex ai-flash-tune-flex-center">
                            <input type="hidden" name="page" value="funnelanalysis" />
                            <div class="ai-flash-tune-date-range-field">
                                <label for="aift-start-date"><?php echo esc_html__('Start Date', 'ai-flash-tune'); ?></label>
                                <input type="text" id="aift-start-date" name="start_date" value="<?php echo esc_attr($aiflt_start_date); ?>" />
                            </div>
                            <div class="ai-flash-tune-date-range-field">
                                <label for="aift-end-date"><?php echo esc_html__('End Date', 'ai-flash-tune'); ?></label>
                                <input type="text" id="aift-end-date" name="end_date" value="<?php echo esc_attr($aiflt_end_date); ?>" />
                            </div>
                            <input type="submit" value="<?php echo esc_attr__('Apply', 'ai-flash-tune'); ?>" class="ai-flash-tune-btn ai-flash-tune-btn-blue" />
                        </form>
                    </div>
                </div>
                <?php
            } ?>
        </div>
        <?php
        // Check for WooCommerce dependency at the top of the view file.
        if (!aiflt_is_woocommerce_active()) {
            $aiflt_install_url = admin_url('plugin-install.php?s=woocommerce&tab=search&type=term');
            $aiflt_wc_status = aiflt_get_woocommerce_status(); // Call the helper function
            ?>
            <div class="ai-flash-tune-wc-required-notice">
                <i class="fas fa-plug ai-flash-tune-notice-icon"></i>
                <p class="ai-flash-tune-notice-title"><?php echo esc_html__('WooCommerce is Required', 'ai-flash-tune'); ?></p>
                <p class="ai-flash-tune-notice-text"><?php echo esc_html__('This page requires WooCommerce to be installed and active to display funnel data. Please install or activate WooCommerce to continue.', 'ai-flash-tune'); ?></p>
                <a href="<?php echo esc_url($aiflt_wc_status['action_url']); ?>" class="ai-flash-tune-notice-button">
                    <?php echo esc_html($aiflt_wc_status['button_text']); ?>
                </a>
            </div>
            <?php
            return; // Stop rendering the rest of the page.
        } ?>
        <!-- Session Performance Overview Section -->
        <div class="ai-flash-tune-card ai-flash-tune-mb-8">
            <span class="ai-flash-tune-text-xl ai-flash-tune-font-semibold ai-flash-tune-text-gray-800 ai-flash-tune-mb-4 ai-flash-tune-card-title"><?php echo esc_html(__('Session Performance Overview', 'ai-flash-tune')); ?></span>
            <div class="ai-flash-tune-grid ai-flash-tune-gap-6 ai-flash-tune-grid-cols-1 ai-flash-tune-grid-cols-md-2 ai-flash-tune-grid-cols-lg-3">
                <div class="ai-flash-tune-card ai-flash-tune-metric-card">
                    <p class="ai-flash-tune-text-sm ai-flash-tune-text-gray-500 ai-flash-tune-metric-label"><?php echo esc_html(__('Total Sessions', 'ai-flash-tune')); ?></p>
                    <div class="ai-flash-tune-flex ai-flash-tune-justify-between ai-flash-tune-flex-center ai-flash-tune-mt-2">
                        <p class="ai-flash-tune-text-3xl ai-flash-tune-font-bold ai-flash-tune-text-gray-900 ai-flash-tune-metric-value"><?php echo esc_html($aiflt_all_funnel_data['total_sessions']); ?></p>
                        <i class="fas <?php echo esc_attr(aiflt_get_metric_trend_icon_class($aiflt_has_funnel_activity, $aiflt_all_funnel_data['trends']['total_sessions'])); ?> ai-flash-tune-text-xl ai-flash-tune-metric-icon"></i>
                    </div>
                </div>
                <div class="ai-flash-tune-card ai-flash-tune-metric-card">
                    <p class="ai-flash-tune-text-sm ai-flash-tune-text-gray-500 ai-flash-tune-metric-label"><?php echo esc_html(__('Completed Sessions', 'ai-flash-tune')); ?></p>
                    <div class="ai-flash-tune-flex ai-flash-tune-justify-between ai-flash-tune-flex-center ai-flash-tune-mt-2">
                        <p class="ai-flash-tune-text-3xl ai-flash-tune-font-bold ai-flash-tune-text-gray-900 ai-flash-tune-metric-value"><?php echo esc_html($aiflt_all_funnel_data['completed_sessions']); ?></p>
                        <i class="fas <?php echo esc_attr(aiflt_get_metric_trend_icon_class($aiflt_has_funnel_activity, $aiflt_all_funnel_data['trends']['completed_sessions'])); ?> ai-flash-tune-text-xl ai-flash-tune-metric-icon"></i>
                    </div>
                </div>
                <div class="ai-flash-tune-card ai-flash-tune-metric-card">
                    <p class="ai-flash-tune-text-sm ai-flash-tune-text-gray-500 ai-flash-tune-metric-label"><?php echo esc_html(__('Abandoned Shopping Sessions', 'ai-flash-tune')); ?></p>
                    <div class="ai-flash-tune-flex ai-flash-tune-justify-between ai-flash-tune-flex-center ai-flash-tune-mt-2">
                        <p class="ai-flash-tune-text-3xl ai-flash-tune-font-bold ai-flash-tune-text-gray-900 ai-flash-tune-metric-value"><?php echo esc_html($aiflt_all_funnel_data['drop_off_sessions']); ?></p>
                        <i class="fas <?php echo esc_attr(aiflt_get_metric_trend_icon_class($aiflt_has_funnel_activity, $aiflt_all_funnel_data['trends']['drop_off_sessions'], true)); ?> ai-flash-tune-text-xl ai-flash-tune-metric-icon"></i>
                    </div>
                </div>
                <div class="ai-flash-tune-card ai-flash-tune-metric-card">
                    <p class="ai-flash-tune-text-sm ai-flash-tune-text-gray-500 ai-flash-tune-metric-label"><?php echo esc_html(__('Recovered Drop-Offs', 'ai-flash-tune')); ?></p>
                    <div class="ai-flash-tune-flex ai-flash-tune-justify-between ai-flash-tune-flex-center ai-flash-tune-mt-2">
                        <p class="ai-flash-tune-text-3xl ai-flash-tune-font-bold ai-flash-tune-text-gray-900 ai-flash-tune-metric-value"><?php echo esc_html($aiflt_all_funnel_data['recovered_drop_offs']); ?></p>
                        <i class="fas <?php echo esc_attr(aiflt_get_metric_trend_icon_class($aiflt_has_funnel_activity, $aiflt_all_funnel_data['trends']['recovery_rate'])); ?> ai-flash-tune-text-xl ai-flash-tune-metric-icon"></i>
                    </div>
                </div>
                <div class="ai-flash-tune-card ai-flash-tune-metric-card">
                    <p class="ai-flash-tune-text-sm ai-flash-tune-text-gray-500 ai-flash-tune-metric-label"><?php echo esc_html(__('Estimated Abandoned Cart Value', 'ai-flash-tune')); ?></p>
                    <div class="ai-flash-tune-flex ai-flash-tune-justify-between ai-flash-tune-flex-center ai-flash-tune-mt-2">
                        <p class="ai-flash-tune-text-3xl ai-flash-tune-font-bold ai-flash-tune-text-gray-900 ai-flash-tune-metric-value"><?php echo wp_kses_post($aiflt_all_funnel_data['lost_sales']); ?></p>
                        <i class="fas <?php echo esc_attr(aiflt_get_metric_trend_icon_class($aiflt_has_funnel_activity, $aiflt_all_funnel_data['trends']['lost_sales'], true)); ?> ai-flash-tune-text-xl ai-flash-tune-metric-icon"></i>
                    </div>
                </div>
                <div class="ai-flash-tune-card ai-flash-tune-metric-card">
                    <p class="ai-flash-tune-text-sm ai-flash-tune-text-gray-500 ai-flash-tune-metric-label"><?php echo esc_html(__('Conversion Rate', 'ai-flash-tune')); ?></p>
                    <div class="ai-flash-tune-flex ai-flash-tune-justify-between ai-flash-tune-flex-center ai-flash-tune-mt-2">
                        <p class="ai-flash-tune-text-3xl ai-flash-tune-font-bold ai-flash-tune-text-gray-900 ai-flash-tune-metric-value"><?php echo esc_html($aiflt_all_funnel_data['conversion_rate']); ?>%</p>
                        <i class="fas <?php echo esc_attr(aiflt_get_metric_trend_icon_class($aiflt_has_funnel_activity, $aiflt_all_funnel_data['trends']['conversion_rate'])); ?> ai-flash-tune-text-xl ai-flash-tune-metric-icon"></i>
                    </div>
                </div>
                <div class="ai-flash-tune-card ai-flash-tune-metric-card">
                    <p class="ai-flash-tune-text-sm ai-flash-tune-text-gray-500 ai-flash-tune-metric-label"><?php echo esc_html(__('Recovery Rate', 'ai-flash-tune')); ?></p>
                    <div class="ai-flash-tune-flex ai-flash-tune-justify-between ai-flash-tune-flex-center ai-flash-tune-mt-2">
                        <p class="ai-flash-tune-text-3xl ai-flash-tune-font-bold ai-flash-tune-text-gray-900 ai-flash-tune-metric-value"><?php echo esc_html($aiflt_all_funnel_data['recovery_rate']); ?>%</p>
                        <i class="fas <?php echo esc_attr(aiflt_get_metric_trend_icon_class($aiflt_has_funnel_activity, $aiflt_all_funnel_data['trends']['recovery_rate'])); ?> ai-flash-tune-text-xl ai-flash-tune-metric-icon"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- Funnel Flow Visualization Section -->
        <div class="ai-flash-tune-card ai-flash-tune-mb-8 ai-flash-tune-funnel-section ai-flash-tune-funnel-analysis">
            <div class="ai-flash-tune-flex ai-flash-tune-justify-between ai-flash-tune-flex-center ai-flash-tune-mb-4">
                <span class="ai-flash-tune-text-xl ai-flash-tune-font-semibold ai-flash-tune-text-gray-800 ai-flash-tune-card-title"><?php echo esc_html(__('WooCommerce Funnel Overview', 'ai-flash-tune')); ?></span>
                <?php if (!$aiflt_all_funnel_data['is_empty']) : ?>
                    <div class="ai-flash-tune-flex ai-flash-tune-justify-end ai-flash-tune-funnel-toggles">
                        <div class="ai-flash-tune-inline-flex ai-flash-tune-rounded-md ai-flash-tune-shadow-sm" role="group">
                            <a href="#" data-device="desktop" class="ai-flash-tune-px-4 ai-flash-tune-py-2 ai-flash-tune-text-sm ai-flash-tune-font-medium ai-flash-tune-text-blue-700 ai-flash-tune-bg-white ai-flash-tune-border ai-flash-tune-border-gray-200 ai-flash-tune-rounded-l-lg ai-flash-tune-funnel-toggle-button <?php echo ($aiflt_current_device === 'desktop' || $aiflt_current_device === 'all') ? 'active' : ''; ?>">
                                <?php echo esc_html(__('Desktop', 'ai-flash-tune')); ?>
                            </a>
                            <a href="#" data-device="mobile" class="ai-flash-tune-px-4 ai-flash-tune-py-2 ai-flash-tune-text-sm ai-flash-tune-font-medium ai-flash-tune-text-gray-900 ai-flash-tune-bg-white ai-flash-tune-border ai-flash-tune-rounded-r-lg ai-flash-tune-border-gray-200 ai-flash-tune-funnel-toggle-button <?php echo ($aiflt_current_device === 'mobile') ? 'active' : ''; ?>">
                                <?php echo esc_html(__('Mobile', 'ai-flash-tune')); ?>
                            </a>
                        </div>
                    </div>
                <?php endif; ?>
            </div>

            <!-- Funnel Flow Visualization -->
            <?php if ($aiflt_all_funnel_data['is_empty']) : ?>
                <div class="ai-flash-tune-empty-state-message">
                    <i class="fas fa-chart-line ai-flash-tune-empty-state-icon"></i>
                    <p class="ai-flash-tune-empty-state-title"><?php echo esc_html(__('No Funnel Data Found', 'ai-flash-tune')); ?></p>
                    <p class="ai-flash-tune-empty-state-text"><?php echo esc_html(__('No funnel activity is recorded for this date range yet. Visit a product page, add a product to cart, open checkout, then refresh this page to confirm tracking.', 'ai-flash-tune')); ?></p>
                </div>
            <?php else : ?>
                <div id="ai-flash-tune-funnel-flow" class="ai-flash-tune-funnel-flow-detail ai-flash-tune-flex ai-flash-tune-flex-wrap ai-flash-tune-flex-center ai-flash-tune-funnel-flow">
                    <!-- Funnel steps will be loaded here via AJAX -->
                    <div class="ai-flash-tune-funnel-step-detail ai-flash-tune-funnel-step-item">
                        <i class="fas fa-spinner fa-spin ai-flash-tune-text-indigo-600 ai-flash-tune-text-4xl ai-flash-tune-mb-2"></i>
                        <p class="ai-flash-tune-font-bold ai-flash-tune-text-lg ai-flash-tune-step-label"><?php echo esc_html(__('Loading Funnel Data...', 'ai-flash-tune')); ?></p>
                    </div>
                </div>
            <?php endif; ?>
        </div>
        <?php if ($aiflt_has_funnel_activity) : ?>
        <div class="ai-flash-tune-card ai-flash-tune-mb-8 ai-flash-tune-ask-ai-section ai-flash-tune-preset-ai-section">
            <div class="ai-flash-tune-preset-ai-header">
                <div>
                    <span class="ai-flash-tune-section-chip"><i class="fas fa-robot"></i> <?php echo esc_html__('AI Funnel Diagnosis', 'ai-flash-tune'); ?></span>
                    <span class="ai-flash-tune-text-xl ai-flash-tune-font-semibold ai-flash-tune-text-gray-800 ai-flash-tune-card-title"><?php echo esc_html(__('Diagnose a Specific Drop-Off', 'ai-flash-tune')); ?></span>
                    <p class="ai-flash-tune-text-gray-600 ai-flash-tune-section-description"><?php echo esc_html(__('Choose a preset question to get an evidence-backed explanation from your configured AI provider. Only sanitized aggregate funnel signals are used when OpenAI/Zywrap mode and consent are enabled.', 'ai-flash-tune')); ?></p>
                </div>
                <span class="ai-flash-tune-provider-note"><i class="fas fa-shield-alt"></i> <?php echo esc_html__('Uses current AI settings', 'ai-flash-tune'); ?></span>
            </div>

            <div class="ai-flash-tune-preset-ai-grid" role="group" aria-label="<?php echo esc_attr__('Preset AI diagnosis questions', 'ai-flash-tune'); ?>">
                <button type="button" class="ai-flash-tune-ai-preset-card" data-preset="checkout_dropoff" data-question="<?php echo esc_attr__('Preset: why_checkout_dropping. Explain why checkout is dropping using only the supplied aggregate funnel data. Include Summary, Evidence Used, Likely Causes To Verify, Safe Next Checks, and What Not To Change Yet. Do not recommend payment gateways, discounts, trust badges, heatmaps, surveys, A/B tests, or broad redesigns unless the supplied data proves they are needed.', 'ai-flash-tune'); ?>">
                    <span class="ai-flash-tune-ai-preset-icon"><i class="fas fa-credit-card"></i></span>
                    <span class="ai-flash-tune-ai-preset-title"><?php echo esc_html__('Why is checkout dropping?', 'ai-flash-tune'); ?></span>
                    <span class="ai-flash-tune-ai-preset-desc"><?php echo esc_html__('Explain the checkout leak and what to check first.', 'ai-flash-tune'); ?></span>
                </button>
                <button type="button" class="ai-flash-tune-ai-preset-card" data-preset="cart_abandonment" data-question="<?php echo esc_attr__('Preset: why_carts_abandoned. Explain cart abandonment using only the supplied aggregate cart and funnel data. Include Summary, Evidence Used, Evidence-Backed Pressures, Likely Reasons To Verify, Safe Recovery Checks, and What Not To Change Yet. Do not suggest discounts, free shipping, fake urgency, testimonials, retargeting ads, or payment changes unless the supplied data supports them.', 'ai-flash-tune'); ?>">
                    <span class="ai-flash-tune-ai-preset-icon"><i class="fas fa-shopping-cart"></i></span>
                    <span class="ai-flash-tune-ai-preset-title"><?php echo esc_html__('Why are carts abandoned?', 'ai-flash-tune'); ?></span>
                    <span class="ai-flash-tune-ai-preset-desc"><?php echo esc_html__('Review abandonment pressure and likely causes.', 'ai-flash-tune'); ?></span>
                </button>
                <button type="button" class="ai-flash-tune-ai-preset-card" data-preset="fix_first" data-question="<?php echo esc_attr__('Preset: what_should_i_fix_first. Prioritize the next three safe fixes for this WooCommerce funnel using only supplied aggregate data. For each fix include Evidence, Impact, Effort, Confidence, Safe Next Action, Where To Check, Rollback / Safety, and Measure. Do not recommend payment gateways, discounts, A/B tests, surveys, heatmaps, page speed fixes, or broad redesigns without supporting data.', 'ai-flash-tune'); ?>">
                    <span class="ai-flash-tune-ai-preset-icon"><i class="fas fa-list-check"></i></span>
                    <span class="ai-flash-tune-ai-preset-title"><?php echo esc_html__('What should I fix first?', 'ai-flash-tune'); ?></span>
                    <span class="ai-flash-tune-ai-preset-desc"><?php echo esc_html__('Get a short ranked action list.', 'ai-flash-tune'); ?></span>
                </button>
                <button type="button" class="ai-flash-tune-ai-preset-card" data-preset="simple_words" data-question="<?php echo esc_attr__('Preset: explain_in_simple_words. Explain this funnel in simple language for a non-technical WooCommerce store owner. Use the exact funnel numbers. Avoid jargon, blame, hype, fake certainty, discounts, A/B testing, and unsupported causes. Include What The Numbers Mean, Biggest Risk, First Safe Action, and What Not To Panic About.', 'ai-flash-tune'); ?>">
                    <span class="ai-flash-tune-ai-preset-icon"><i class="fas fa-comment-dots"></i></span>
                    <span class="ai-flash-tune-ai-preset-title"><?php echo esc_html__('Explain in simple words', 'ai-flash-tune'); ?></span>
                    <span class="ai-flash-tune-ai-preset-desc"><?php echo esc_html__('Plain-English summary for store owners.', 'ai-flash-tune'); ?></span>
                </button>
            </div>

            <div class="ai-flash-tune-preset-ai-options">
                <div class="ai-flash-tune-form-field" style="max-width: 300px;">
                    <label for="ai-flash-tune-ai-language" class="ai-flash-tune-form-label" style="font-size: 0.9em; margin-bottom: 0.25rem;">
                        <?php echo esc_html__('Response Language', 'ai-flash-tune'); ?>
                    </label>
                    <select id="ai-flash-tune-ai-language" class="ai-flash-tune-input">
                        <?php
                        // Get current WP locale (e.g. 'en_US', 'fr_FR')
                        $current_locale = get_locale();
                        // A comprehensive list of WordPress languages
                        $all_languages = [
                            'en_US' => 'English (US)',
                            'en_GB' => 'English (UK)',
                            'af'    => 'Afrikaans',
                            'ar'    => 'Arabic',
                            'az'    => 'Azerbaijani',
                            'be'    => 'Belarusian',
                            'bg_BG' => 'Bulgarian',
                            'bn_BD' => 'Bengali',
                            'bs_BA' => 'Bosnian',
                            'ca'    => 'Catalan',
                            'ceb'   => 'Cebuano',
                            'cs_CZ' => 'Czech',
                            'cy'    => 'Welsh',
                            'da_DK' => 'Danish',
                            'de_DE' => 'German',
                            'de_CH' => 'German (Switzerland)',
                            'el'    => 'Greek',
                            'es_ES' => 'Spanish (Spain)',
                            'es_MX' => 'Spanish (Mexico)',
                            'es_CO' => 'Spanish (Colombia)',
                            'es_AR' => 'Spanish (Argentina)',
                            'es_CL' => 'Spanish (Chile)',
                            'et'    => 'Estonian',
                            'eu'    => 'Basque',
                            'fa_IR' => 'Persian',
                            'fi'    => 'Finnish',
                            'fr_FR' => 'French (France)',
                            'fr_CA' => 'French (Canada)',
                            'fr_BE' => 'French (Belgium)',
                            'ga'    => 'Irish',
                            'gl_ES' => 'Galician',
                            'gu'    => 'Gujarati',
                            'he_IL' => 'Hebrew',
                            'hi_IN' => 'Hindi',
                            'hr'    => 'Croatian',
                            'hu_HU' => 'Hungarian',
                            'hy'    => 'Armenian',
                            'id_ID' => 'Indonesian',
                            'is_IS' => 'Icelandic',
                            'it_IT' => 'Italian',
                            'ja'    => 'Japanese',
                            'ka_GE' => 'Georgian',
                            'km'    => 'Khmer',
                            'kn'    => 'Kannada',
                            'ko_KR' => 'Korean',
                            'lt_LT' => 'Lithuanian',
                            'lv'    => 'Latvian',
                            'mk_MK' => 'Macedonian',
                            'ml_IN' => 'Malayalam',
                            'mn'    => 'Mongolian',
                            'mr'    => 'Marathi',
                            'ms_MY' => 'Malay',
                            'my_MM' => 'Burmese',
                            'nb_NO' => 'Norwegian (Bokmål)',
                            'nl_NL' => 'Dutch',
                            'nl_BE' => 'Dutch (Belgium)',
                            'pa_IN' => 'Punjabi',
                            'pl_PL' => 'Polish',
                            'pt_PT' => 'Portuguese (Portugal)',
                            'pt_BR' => 'Portuguese (Brazil)',
                            'ro_RO' => 'Romanian',
                            'ru_RU' => 'Russian',
                            'si_LK' => 'Sinhala',
                            'sk_SK' => 'Slovak',
                            'sl_SI' => 'Slovenian',
                            'sq'    => 'Albanian',
                            'sr_RS' => 'Serbian',
                            'sv_SE' => 'Swedish',
                            'sw'    => 'Swahili',
                            'ta_IN' => 'Tamil',
                            'te'    => 'Telugu',
                            'th'    => 'Thai',
                            'tl'    => 'Tagalog',
                            'tr_TR' => 'Turkish',
                            'uk'    => 'Ukrainian',
                            'ur'    => 'Urdu',
                            'uz_UZ' => 'Uzbek',
                            'vi'    => 'Vietnamese',
                            'zh_CN' => 'Chinese (Simplified)',
                            'zh_TW' => 'Chinese (Traditional)',
                            'zh_HK' => 'Chinese (Hong Kong)',
                        ];

                        // 1. Check if exact locale exists
                        $selected_val = '';
                        if (array_key_exists($current_locale, $all_languages)) {
                            $selected_val = $all_languages[$current_locale];
                        } 
                        // 2. If not, try matching the first 2 letters (e.g. 'fr_FR' -> 'fr')
                        else {
                            $short_code = substr($current_locale, 0, 2);
                            foreach ($all_languages as $key => $val) {
                                if (substr($key, 0, 2) === $short_code) {
                                    $selected_val = $val;
                                    break;
                                }
                            }
                        }

                        // Output options
                        foreach ($all_languages as $code => $name) {
                            // We pass the Name (e.g. "French") to the AI, as it understands names better than codes in prompts
                            $is_selected = ($name === $selected_val) ? 'selected' : '';
                            
                            // Fallback: If English US, make it selected by default if nothing else matched
                            if ($code === 'en_US' && empty($selected_val)) {
                                $is_selected = 'selected';
                            }

                            echo '<option value="' . esc_attr($name) . '" ' . esc_attr($is_selected) . '>' . esc_html($name) . '</option>';
                        }
                        ?>
                    </select>
                </div>
                <button type="button" id="ai-flash-tune-custom-question-toggle" class="ai-flash-tune-btn ai-flash-tune-btn-secondary ai-flash-tune-custom-question-toggle">
                    <i class="fas fa-pen"></i> <?php echo esc_html__('Ask custom question', 'ai-flash-tune'); ?>
                </button>
            </div>

            <div id="ai-flash-tune-custom-question-panel" class="ai-flash-tune-custom-question-panel" style="display:none;">
                <textarea id="ai-flash-tune-ai-prompt-input" rows="4" class="ai-flash-tune-w-full ai-flash-tune-p-4 ai-flash-tune-border ai-flash-tune-border-gray-300 ai-flash-tune-rounded-lg ai-flash-tune-ai-prompt-input" placeholder="<?php echo esc_attr__( 'Ask a focused question, for example: why are users reaching checkout but not completing the order?', 'ai-flash-tune' ); ?>"></textarea>
                <a id="ai-flash-tune-ask-ai-button" class="ai-flash-tune-bg-indigo-600 hover:ai-flash-tune-bg-indigo-700 ai-flash-tune-text-white ai-flash-tune-font-semibold ai-flash-tune-py-2 ai-flash-tune-px-4 ai-flash-tune-rounded-lg ai-flash-tune-shadow-md ai-flash-tune-cta-button" href="#">
                    <i class="fas fa-robot ai-flash-tune-mr-2"></i> <?php echo esc_html(__('Ask Custom Question', 'ai-flash-tune')); ?>
                </a>
            </div>
        </div>
        <div id="ai-flash-tune-ai-response-section" class="ai-flash-tune-card ai-flash-tune-mb-8 ai-flash-tune-ai-answer-card hidden">
            <div class="ai-flash-tune-ai-answer-header">
                <div>
                    <span class="aiflt-kicker"><?php echo esc_html__('AI diagnosis', 'ai-flash-tune'); ?></span>
                    <h3><?php echo esc_html__('Funnel diagnosis result', 'ai-flash-tune'); ?></h3>
                </div>
                <span class="ai-flash-tune-ai-answer-badge"><?php echo esc_html__('Review before acting', 'ai-flash-tune'); ?></span>
            </div>
            <div id="ai-flash-tune-ai-response-content" class="ai-flash-tune-ai-answer-content">
                <div class="ai-flash-tune-flex ai-flash-tune-flex-center ai-flash-tune-p-4">
                    <span class="ai-flash-tune-ml-3 ai-flash-tune-text-gray-600"><?php echo esc_html(__('Thinking...', 'ai-flash-tune')); ?></span>
                </div>
            </div>
        </div>
<?php else : ?>
        <div class="ai-flash-tune-card ai-flash-tune-mb-8 ai-flash-tune-empty-guidance-card">
            <span class="ai-flash-tune-text-xl ai-flash-tune-font-semibold ai-flash-tune-text-gray-800 ai-flash-tune-mb-4 ai-flash-tune-card-title">
                <i class="fas fa-robot ai-flash-tune-text-indigo-600 ai-flash-tune-mr-2"></i><?php echo esc_html__('Ask AI after funnel data is recorded', 'ai-flash-tune'); ?>
            </span>
            <p class="ai-flash-tune-text-gray-700 ai-flash-tune-section-description">
                <?php echo esc_html__('Store-specific AI answers need real funnel activity. Visit a product page, add a product to cart, open checkout, then refresh this page to unlock useful drop-off questions.', 'ai-flash-tune'); ?>
            </p>
            <a class="ai-flash-tune-btn ai-flash-tune-btn-blue ai-flash-tune-mt-4" href="<?php echo esc_url(admin_url('admin.php?page=products')); ?>">
                <?php echo esc_html__('Open Products to Test Tracking', 'ai-flash-tune'); ?>
            </a>
        </div>
        <?php endif; ?>
        <div class="ai-flash-tune-card ai-flash-tune-mb-8 ai-flash-tune-empty-guidance-card">
            <div class="ai-flash-tune-free-card-header">
                <span class="ai-flash-tune-text-xl ai-flash-tune-font-semibold ai-flash-tune-text-gray-800 ai-flash-tune-card-title">
                    <i class="fas fa-filter ai-flash-tune-text-purple-500 ai-flash-tune-mr-2"></i><?php echo esc_html__('Need deeper segment comparison?', 'ai-flash-tune'); ?>
                </span>
                <span class="ai-flash-tune-free-badge"><?php echo esc_html__('Advanced', 'ai-flash-tune'); ?></span>
            </div>
            <p class="ai-flash-tune-text-gray-700 ai-flash-tune-section-description">
                <?php echo esc_html__('Use the Segmentation page to compare desktop vs mobile, guests vs customers, and other behavior groups once enough traffic is recorded.', 'ai-flash-tune'); ?>
            </p>
            <a class="ai-flash-tune-btn ai-flash-tune-btn-blue ai-flash-tune-mt-4" href="<?php echo esc_url(admin_url(class_exists('AIFTAS_Logic') ? 'admin.php?page=aiftas-segmentation' : 'admin.php?page=addon-manager&addon=ai-flash-tune-advanced-segmentation')); ?>">
                <?php echo class_exists('AIFTAS_Logic') ? esc_html__('Open Segmentation', 'ai-flash-tune') : esc_html__('Review Segmentation module', 'ai-flash-tune'); ?>
            </a>
        </div>
    </div>
</div>
