<?php

if (!defined('ABSPATH')) {
    exit;
}

$current_page = isset($_GET['page']) ? sanitize_text_field(wp_unslash($_GET['page'])) : '';

$woocommerce_active = class_exists('WooCommerce');

global $wpdb;
$vitals_table = $wpdb->prefix . 'aieo_core_product_vitals';
$has_vitals_data = false;

if ($woocommerce_active) {
    
    
    $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$vitals_table'") === $vitals_table;

    if ($table_exists) {
        
        $vitals_count = $wpdb->get_var("SELECT COUNT(*) FROM $vitals_table");
        $has_vitals_data = ($vitals_count > 0);
    }
} else {
    
    $has_vitals_data = true; 
}

$main_admin_url = admin_url('admin.php?page=ai-eshop-optimizer');
$analyze_data_url = admin_url('admin.php?page=ai-eshop-optimizer#analyze-data-section');
$chat_admin_url = admin_url('admin.php?page=ai-eshop-chat');
$dmm_admin_url = admin_url('admin.php?page=ai-eshop-dmm');
?>

<style>
.aieo-top-bar-nav {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 40px;
    margin: 0 30px;
}

.aieo-nav-tab {
    text-decoration: none;
    font-weight: 600;
    font-size: 15px;
    color: #6b7280;
    padding: 8px 20px;
    border-radius: 6px;
    transition: all 0.3s ease;
    position: relative;
    white-space: nowrap;
}

.aieo-nav-tab:hover {
    color: #667eea;
    text-decoration: none;
    background: rgba(102, 126, 234, 0.1);
}

.aieo-nav-tab.active {
    color: white;
    background: #667eea;
}

.aieo-nav-tab.disabled {
    color: #d1d5db;
    cursor: not-allowed;
    opacity: 0.6;
}

.aieo-nav-tab.disabled:hover {
    background: transparent;
    color: #d1d5db;
}

.aieo-nav-tab-warning {
    position: absolute;
    top: -8px;
    right: -8px;
    background: #f59e0b;
    color: white;
    font-size: 10px;
    padding: 2px 5px;
    border-radius: 8px;
    font-weight: 700;
    line-height: 1;
}

@media (max-width: 1024px) {
    .aieo-top-bar-nav {
        gap: 15px;
        margin: 0 15px;
    }

    .aieo-nav-tab {
        font-size: 13px;
        padding: 6px 12px;
    }
}

@media (max-width: 768px) {
    .aieo-top-bar-nav {
        display: none;
    }
}

/* Warning Banner Styles */
.aieo-warning-banner {
    background: #fef3c7;
    border-left: 4px solid #f59e0b;
    padding: 20px;
    margin: 20px 0;
    border-bottom-right-radius: 8px;
    border-top-right-radius: 8px;
}

.aieo-warning-content {
    display: flex;
    align-items: flex-start;
    gap: 15px;
}

.aieo-warning-icon {
    font-size: 24px;
}

.aieo-warning-text {
    flex: 1;
}

.aieo-warning-heading {
    margin: 0 0 10px 0;
    color: #92400e;
    font-size: 18px;
}

.aieo-warning-message {
    margin: 0 0 10px 0;
    color: #78350f;
    line-height: 1.6;
}

.aieo-warning-inline-link {
    color: #92400e;
    font-weight: 600;
    text-decoration: underline;
}

.aieo-warning-inline-link:hover {
    color: #78350f;
}

.aieo-warning-button {
    display: inline-block;
    background: #f59e0b;
    color: white;
    padding: 10px 20px;
    border-radius: 6px;
    text-decoration: none;
    font-weight: 600;
    margin-top: 5px;
}

.aieo-warning-button:hover {
    background: #d97706;
    color: white;
    text-decoration: none;
}
</style>

<!--
    Top 3-tab nav (Analytics & Shop Recommendations Setup | e-shop Manager | AI
    Chat) retired 2026-06-25 — the shared e-shop Manager menu bar now handles
    all navigation across the three pages (the "Set Up" + "AI Chat" pills cover
    the two sibling pages, with the current one highlighted). The data-prep
    warning banner below is intentionally KEPT.
-->

<?php if (!$has_vitals_data && $current_page === 'ai-eshop-chat'): ?>
<div class="aieo-warning-banner">
    <div class="aieo-warning-content">
        <div class="aieo-warning-icon">⚠️</div>
        <div class="aieo-warning-text">
            <h3 class="aieo-warning-heading">
                <?php esc_html_e('Product Data Required', 'ai-eshop-optimizer'); ?>
            </h3>
            <p class="aieo-warning-message">
                <?php
                printf(
                    
                    esc_html__('To enable product-based chat capabilities, please complete the %s step in Analytics & Shop Recommendations Setup Analysis first. The AI Chat feature requires preprocessing of product and order data to function properly.', 'ai-eshop-optimizer'),
                    '<a href="' . esc_url($analyze_data_url) . '" class="aieo-warning-inline-link">' . esc_html__('Analyze Data', 'ai-eshop-optimizer') . '</a>'
                );
                ?>
            </p>
            <a href="<?php echo esc_url($analyze_data_url); ?>" class="aieo-warning-button">
                <?php esc_html_e('Go to Analyze Data', 'ai-eshop-optimizer'); ?> →
            </a>
        </div>
    </div>
</div>
<?php endif; ?>

<style>
/* Modal Styles */
.aieo-modal-overlay {
    display: none;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    z-index: 999999;
    align-items: center;
    justify-content: center;
}

.aieo-modal-overlay.active {
    display: flex;
}

.aieo-modal-content {
    background: white;
    border-radius: 8px;
    max-width: 500px;
    width: 90%;
    box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3);
    animation: modalSlideIn 0.3s ease;
}

@keyframes modalSlideIn {
    from {
        opacity: 0;
        transform: translateY(-50px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.aieo-modal-header {
    padding: 20px;
    border-bottom: 1px solid #e5e7eb;
    display: flex;
    align-items: center;
    gap: 15px;
}

.aieo-modal-body {
    padding: 20px;
}

.aieo-modal-footer {
    padding: 15px 20px;
    border-top: 1px solid #e5e7eb;
    display: flex;
    gap: 10px;
    justify-content: flex-end;
}

.aieo-modal-btn {
    padding: 10px 20px;
    border-radius: 6px;
    font-weight: 600;
    text-decoration: none;
    cursor: pointer;
    border: none;
    font-size: 14px;
    transition: all 0.3s ease;
}

.aieo-modal-btn-primary {
    background: #f59e0b;
    color: white;
}

.aieo-modal-btn-primary:hover {
    background: #d97706;
}

.aieo-modal-btn-secondary {
    background: #e5e7eb;
    color: #374151;
}

.aieo-modal-btn-secondary:hover {
    background: #d1d5db;
}

/* Highlight animation for anchor target */
#analyze-data-section:target {
    animation: highlightPulse 2s ease-in-out;
}

@keyframes highlightPulse {
    0%, 100% {
        background-color: transparent;
    }
    50% {
        background-color: rgba(245, 158, 11, 0.2);
        border-radius: 8px;
    }
}
</style>

<!-- Modal HTML -->
<div id="aieo-data-warning-modal" class="aieo-modal-overlay">
    <div class="aieo-modal-content">
        <div class="aieo-modal-header">
            <div style="font-size: 24px;">⚠️</div>
            <h3 style="margin: 0; color: #92400e; font-size: 18px;">
                <?php esc_html_e('Product Data Required', 'ai-eshop-optimizer'); ?>
            </h3>
        </div>
        <div class="aieo-modal-body">
            <p style="margin: 0; color: #78350f; line-height: 1.6;">
                <?php esc_html_e('To enable product-based chat capabilities, please complete the "Analyze Data" step in Analytics & Shop Recommendations Setup Analysis first. The AI Chat feature requires preprocessing of product and order data to function properly.', 'ai-eshop-optimizer'); ?>
            </p>
        </div>
        <div class="aieo-modal-footer">
            <button class="aieo-modal-btn aieo-modal-btn-secondary" onclick="aieoCloseModal()">
                <?php esc_html_e('Continue Anyway', 'ai-eshop-optimizer'); ?>
            </button>
            <a href="<?php echo esc_url($analyze_data_url); ?>" class="aieo-modal-btn aieo-modal-btn-primary">
                <?php esc_html_e('Go to Analyze Data', 'ai-eshop-optimizer'); ?> →
            </a>
        </div>
    </div>
</div>

<script>
(function() {
    const warningTab = document.getElementById('aieo-chat-tab-warning');
    const modal = document.getElementById('aieo-data-warning-modal');

    // Check if data has been analyzed (set by export-progress.js after completion)
    const dataAnalyzed = sessionStorage.getItem('aieo_data_analyzed');

    // If data was analyzed, remove the warning immediately
    if (dataAnalyzed === '1' && warningTab) {
        // TODO: Uncomment for debugging
        // console.log('Data analyzed flag found - removing warning on page load');

        // CRITICAL: Remove modal from DOM completely (prevents ALL interactions)
        if (modal) {
            modal.remove();
            // TODO: Uncomment for debugging
            // console.log('Modal removed from DOM');
        }

        // Remove warning span
        const warningSpan = warningTab.querySelector('.aieo-nav-tab-warning');
        if (warningSpan) {
            warningSpan.remove();
        }

        // Remove ID to prevent any future modal attachment
        warningTab.removeAttribute('id');

        return; // Exit - don't attach event listeners
    }

    // Only show modal if NOT already on chat page AND data hasn't been analyzed
    if (warningTab && '<?php echo esc_js($current_page); ?>' !== 'ai-eshop-chat') {
        // Show modal on click
        warningTab.addEventListener('click', function(e) {
            e.preventDefault();
            modal.classList.add('active');
        });

        // Show modal on hover
        warningTab.addEventListener('mouseenter', function(e) {
            modal.classList.add('active');
        });

        // Keep modal open when hovering over it
        modal.addEventListener('mouseenter', function() {
            modal.classList.add('active');
        });

        // Close modal when mouse leaves both the tab and modal
        let hoverTimeout;
        warningTab.addEventListener('mouseleave', function() {
            hoverTimeout = setTimeout(function() {
                if (!modal.matches(':hover')) {
                    modal.classList.remove('active');
                }
            }, 200);
        });

        modal.addEventListener('mouseleave', function() {
            hoverTimeout = setTimeout(function() {
                if (!warningTab.matches(':hover')) {
                    modal.classList.remove('active');
                }
            }, 200);
        });
    }

    // Close modal when clicking overlay
    if (modal) {
        modal.addEventListener('click', function(e) {
            if (e.target === modal) {
                modal.classList.remove('active');
            }
        });
    }
})();

function aieoCloseModal() {
    const modal = document.getElementById('aieo-data-warning-modal');
    if (modal) {
        modal.classList.remove('active');
        // Navigate to chat page
        window.location.href = '<?php echo esc_url($chat_admin_url); ?>';
    }
}
</script>
