<?php
if ( ! defined( 'ABSPATH' ) ) exit;

/**
 * Hiển thị giao diện chính: EONSR AEO Agent Article Studio
 * 
 * Bao gồm:
 * 1. Logic xử lý Form Submit (Publish/Schedule/Translation).
 * 2. Giao diện cấu hình bài viết (Left Sidebar).
 * 3. Giao diện Preview & Tab chức năng (Right Sidebar).
 * 4. Wizard Setup (Popup cấu hình ban đầu).
 */
function eonsr_aeo_agent_article_studio_page() {
    
    // =========================================================================
    // [SECTION 1] CONFIGURATION & DATA RETRIEVAL
    // =========================================================================
    
    // 1.1 Lấy thông tin License & Features (Updated prefixes)
    $license_info   = get_option('eonsr_aeo_agent_license_details', []);
    $features       = get_option('eonsr_aeo_agent_license_features', []);
    $license_status = get_option('eonsr_aeo_agent_license_status', 'unsubmitted');
    
    // 1.2 Trạng thái Setup
    $setup_completed = get_option('eonsr_aeo_agent_setup_completed', false);

    // 1.3 Lấy dữ liệu đã lưu (User Preferences)
    $saved_langs     = get_option('eonsr_aeo_agent_selected_languages', ['Vietnamese', 'English']);
    $saved_countries = get_option('eonsr_aeo_agent_selected_countries', ['VN', 'US']);
    $saved_styles    = get_option('eonsr_aeo_agent_selected_styles', ['Mac dinh']); 

    // 1.4 Thiết lập giới hạn tính năng (Feature Flags)
    // $f_min_words   = $features['minWordCount'] ?? 800;
    // $f_max_words   = $features['maxWordCount'] ?? 3500;
    // $f_ai_model    = $features['aiModel'] ?? 'EONSR Lite';
    // $f_allow_yt    = $features['allowYoutube'] ?? false;
    // $f_langs       = $features['allowedLanguageCount'] ?? 1;
    // $f_langs_limit = $features['allowedLanguageCount'] ?? 2;
    // $f_style_limit = $features['styleLimit'] ?? 1;

    // 1.4 Thiết lập giới hạn tính năng (Feature Flags)
    $f_min_words   = 800;
    $f_max_words   = 3500;
    $f_ai_model    = 'EONSR Pro';
    $f_langs       = $features['allowedLanguageCount'] ?? 24;
    $f_langs_limit = $features['allowedLanguageCount'] ?? 24;
    $f_style_limit = $features['styleLimit'] ?? 4;

    // 1.5 Định nghĩa dữ liệu tĩnh (Styles, Countries, Languages)
    // --- Styles Data ---
    $all_styles = [
        'Mac dinh' => [
            'name' => 'EONSR Style (Chuẩn SEO)', 
            'url'  => 'https://eonsr.com/vi/cach-tan-dung-kien-thuc-aws-certified-cloud-practitioner-cho-chuyen-doi-so-va-toi-uu-chi-phi/',
            'desc' => 'Phong cách cân bằng, chuyên nghiệp, tối ưu cho SEO.'
        ],
        'Sleek Blog' => [
            'name' => 'Sleek Blog (Hiện đại)', 
            'url'  => '#',
            'desc' => 'Văn phong trẻ trung, hiện đại, thích hợp cho blog cá nhân.'
        ],
        'Urban Polished' => [
            'name' => 'Urban Polished (Chuyên nghiệp)', 
            'url'  => '#',
            'desc' => 'Trang trọng, gãy gọn, phù hợp cho doanh nghiệp.'
        ],
        'Universe' => [
            'name' => 'Universe (Sáng tạo)', 
            'url'  => '#',
            'desc' => 'Bay bổng, dùng nhiều từ ngữ hình tượng.'
        ],
    ];

    // --- Countries Data ---
    $all_countries = [
        'VN' => ['name' => 'Vietnam', 'flag' => '🇻🇳'],
        'US' => ['name' => 'United States', 'flag' => '🇺🇸'],
        'GB' => ['name' => 'United Kingdom', 'flag' => '🇬🇧'],
        'FR' => ['name' => 'France', 'flag' => '🇫🇷'],
        'DE' => ['name' => 'Germany', 'flag' => '🇩🇪'],
        'JP' => ['name' => 'Japan', 'flag' => '🇯🇵'],
        'KR' => ['name' => 'South Korea', 'flag' => '🇰🇷'],
        'CN' => ['name' => 'China', 'flag' => '🇨🇳'],
        'RU' => ['name' => 'Russia', 'flag' => '🇷🇺'],
        'ES' => ['name' => 'Spain', 'flag' => '🇪🇸'],
        'IT' => ['name' => 'Italy', 'flag' => '🇮🇹'],
        'CA' => ['name' => 'Canada', 'flag' => '🇨🇦'],
        'AU' => ['name' => 'Australia', 'flag' => '🇦🇺'],
        'IN' => ['name' => 'India', 'flag' => '🇮🇳'],
        'BR' => ['name' => 'Brazil', 'flag' => '🇧🇷'],
        'TH' => ['name' => 'Thailand', 'flag' => '🇹🇭'],
        'ID' => ['name' => 'Indonesia', 'flag' => '🇮🇩'],
        'SG' => ['name' => 'Singapore', 'flag' => '🇸🇬'],
        'MY' => ['name' => 'Malaysia', 'flag' => '🇲🇾'],
        'PH' => ['name' => 'Philippines', 'flag' => '🇵🇭'],
        'TR' => ['name' => 'Turkey', 'flag' => '🇹🇷'],
        'SA' => ['name' => 'Saudi Arabia', 'flag' => '🇸🇦'],
        'AE' => ['name' => 'UAE', 'flag' => '🇦🇪'],
        'ZA' => ['name' => 'South Africa', 'flag' => '🇿🇦'],
        'NG' => ['name' => 'Nigeria', 'flag' => '🇳🇬'],
        'EG' => ['name' => 'Egypt', 'flag' => '🇪🇬'],
        'AR' => ['name' => 'Argentina', 'flag' => '🇦🇷'],
        'MX' => ['name' => 'Mexico', 'flag' => '🇲🇽'],
        'NL' => ['name' => 'Netherlands', 'flag' => '🇳🇱'],
        'SE' => ['name' => 'Sweden', 'flag' => '🇸🇪'],
        'NO' => ['name' => 'Norway', 'flag' => '🇳🇴'],
        'DK' => ['name' => 'Denmark', 'flag' => '🇩🇰'],
        'FI' => ['name' => 'Finland', 'flag' => '🇫🇮'],
        'PL' => ['name' => 'Poland', 'flag' => '🇵🇱'],
        'UA' => ['name' => 'Ukraine', 'flag' => '🇺🇦'],
        'PT' => ['name' => 'Portugal', 'flag' => '🇵🇹'],
        'IL' => ['name' => 'Israel', 'flag' => '🇮🇱']
    ];

    // --- Languages Data ---
    $all_languages = [
        'Vietnamese' => ['name' => 'Tiếng Việt', 'flag' => '🇻🇳'],
        'English'    => ['name' => 'English', 'flag' => '🇺🇸'],
        'French'     => ['name' => 'Français', 'flag' => '🇫🇷'],
        'German'     => ['name' => 'Deutsch', 'flag' => '🇩🇪'],
        'Japanese'   => ['name' => '日本語', 'flag' => '🇯🇵'],
        'Korean'     => ['name' => '한국어', 'flag' => '🇰🇷'],
        'Chinese'    => ['name' => '中文', 'flag' => '🇨🇳'],
        'Russian'    => ['name' => 'Русский', 'flag' => '🇷🇺'],
        'Spanish'    => ['name' => 'Español', 'flag' => '🇪🇸'],
        'Italian'    => ['name' => 'Italiano', 'flag' => '🇮🇹'],
        'Thai'       => ['name' => 'ไทย', 'flag' => '🇹🇭'],
        'Indonesian' => ['name' => 'Bahasa Indonesia', 'flag' => '🇮🇩'],
        'Portuguese' => ['name' => 'Português', 'flag' => '🇵🇹'],
        'Hindi'      => ['name' => 'हिन्दी', 'flag' => '🇮🇳'],
        'Arabic'     => ['name' => 'العربية', 'flag' => '🇸🇦'],
        'Turkish'    => ['name' => 'Türkçe', 'flag' => '🇹🇷'],
        'Dutch'      => ['name' => 'Nederlands', 'flag' => '🇳🇱'],
        'Swedish'    => ['name' => 'Svenska', 'flag' => '🇸🇪'],
        'Norwegian'  => ['name' => 'Norsk', 'flag' => '🇳🇴'],
        'Danish'     => ['name' => 'Dansk', 'flag' => '🇩🇰'],
        'Finnish'    => ['name' => 'Suomi', 'flag' => '🇫🇮'],
        'Polish'     => ['name' => 'Polski', 'flag' => '🇵🇱'],
        'Ukrainian'  => ['name' => 'Українська', 'flag' => '🇺🇦'],
        'Hebrew'     => ['name' => 'עברית', 'flag' => '🇮🇱']
    ];

    // =========================================================================
    // [SECTION 2] FORM SUBMISSION LOGIC
    // =========================================================================
    
    // Handle Publish / Schedule / Translation Trigger
    if ( isset($_POST['eonsr_aeo_agent_publish_nonce']) && 
         wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['eonsr_aeo_agent_publish_nonce'])),'eonsr_aeo_agent_publish') && 
         current_user_can('publish_posts') ) {
        
        // 2.1 Sanitize Inputs
        $post_id     = isset($_POST['post_id']) ? absint(wp_unslash($_POST['post_id'])) : 0;
        $meta_desc   = isset($_POST['preview_meta_desc']) ? sanitize_text_field(wp_unslash($_POST['preview_meta_desc'])) : '';
        $choice      = isset($_POST['post_status_choice']) ? sanitize_text_field(wp_unslash($_POST['post_status_choice'])) : 'draft';
        $title       = isset($_POST['preview_title']) ? sanitize_text_field(wp_unslash($_POST['preview_title'])) : '';
        $tags        = isset($_POST['preview_tags']) ? sanitize_text_field(wp_unslash($_POST['preview_tags'])) : '';
        $focus_kw    = isset($_POST['preview_focus_kw']) ? sanitize_text_field(wp_unslash($_POST['preview_focus_kw'])) : '';
        $post_categories = isset($_POST['post_categories']) && is_array($_POST['post_categories']) ? array_map('absint', wp_unslash($_POST['post_categories'])) : [];
        
        // 2.2 Translation Logic Check
        $enable_trans  = isset($_POST['eonsr_aeo_agent_enable_translation']); 
        $target_langs = isset($_POST['eonsr_aeo_target_langs']) && is_array($_POST['eonsr_aeo_target_langs']) ? array_map('sanitize_text_field', wp_unslash($_POST['eonsr_aeo_target_langs'])) : [];
        $can_translate = ($f_langs > 1);

        if ( $post_id && get_post($post_id) && $title ) {
            $post_data = [
                'ID'         => $post_id,
                'post_title' => $title,
            ];
            
            $message_status = '';
            
            // 2.3 Handle Post Status
            if ($choice === 'schedule') {
                $schedule_date = isset($_POST['schedule_date']) ? sanitize_text_field(wp_unslash($_POST['schedule_date'])) : '';
                $schedule_time = isset($_POST['schedule_time']) ? sanitize_text_field(wp_unslash($_POST['schedule_time'])) : '';
                
                if ($schedule_date && $schedule_time) {
                    $schedule_datetime_str      = $schedule_date . ' ' . $schedule_time;
                    $post_data['post_status']   = 'future';
                    $post_data['post_date']     = $schedule_datetime_str;
                    $post_data['post_date_gmt'] = get_gmt_from_date($schedule_datetime_str);
                    $post_data['edit_date']     = true;
                    $message_status             = 'đã được lên lịch vào ' . gmdate( 'Y-m-d H:i', strtotime( $schedule_datetime_str ) );
                } else {
                    $post_data['post_status'] = 'draft'; 
                    $message_status           = 'đã lưu nháp (lỗi hẹn giờ)';
                }
            } else {
                $post_data['post_status'] = 'publish';
                $post_data['edit_date']   = true; 
                $message_status           = 'đã đăng thành công';
            }

            // 2.4 Update Post
            $updated_post_id = wp_update_post($post_data, true);

            if (!is_wp_error($updated_post_id)) {
                // Update Categories
                if (!empty($post_categories)) {
                    $sanitized_categories = array_map('absint', $post_categories);
                    wp_set_post_categories($updated_post_id, $sanitized_categories);
                }

                // Update SEO Meta & Tags
                if ( ! empty( $meta_desc ) ) { 
                    update_post_meta($updated_post_id, '_yoast_wpseo_metadesc', $meta_desc); 
                    update_post_meta($updated_post_id, 'rank_math_description', $meta_desc); 
                }
                if ( ! empty( $focus_kw ) ) { 
                    update_post_meta($updated_post_id, '_yoast_wpseo_focuskw', $focus_kw); 
                    update_post_meta($updated_post_id, 'rank_math_focus_keyword', $focus_kw); 
                }
                if ($tags) {
                    wp_set_post_tags( $updated_post_id, $tags, false );
                }
                
                // 2.5 Trigger Translation API
                $trans_notice = '';
                if ( $can_translate && $enable_trans && !empty($target_langs) ) {
                    $triggered_langs = [];
                    
                    foreach ($target_langs as $t_lang) {
                        // Updated function name
                        if (function_exists('eonsr_aeo_agent_trigger_translation_job_no_polylang')) {
                            // Call external Node.js handler
                            $result = eonsr_aeo_agent_trigger_translation_job_no_polylang($updated_post_id, $t_lang);
                            if ($result) {
                                $triggered_langs[] = $t_lang;
                            }
                        }
                    }

                    if (!empty($triggered_langs)) {
                        $lang_list_str = implode(', ', $triggered_langs);
                        $trans_notice .= '<div style="margin-top: 10px; padding-top: 10px; border-top: 1px solid #c3c4c7;">';
                        $trans_notice .= '<p style="margin: 0; color: #2271b1;">';
                        $trans_notice .= '<span class="dashicons dashicons-translation" style="vertical-align: text-bottom;"></span> ';
                        $trans_notice .= '<strong>Hệ thống đang chạy ngầm tạo bài viết cho: ' . esc_html($lang_list_str) . '</strong>';
                        $trans_notice .= '</p></div>';
                    }
                }

                // 2.6 Render Success Notice
                $view_url = ('future' === $post_data['post_status']) ? get_preview_post_link($updated_post_id) : get_permalink($updated_post_id);
                $view_btn = $view_url ? ' <a class="button button-secondary" href="'.esc_url($view_url).'" target="_blank" rel="noopener">Xem bài viết</a>' : '';

                // Added prefix to ID
                $final_message = '<div id="aeo-agent-post-publish-success" class="notice notice-success is-dismissible" data-post-id="' . esc_attr($updated_post_id) . '">';
                $final_message .= '<p>Bài viết chính <strong>' . esc_html($message_status) . '</strong>.' . $view_btn . '</p>';
                $final_message .= $trans_notice;
                $final_message .= '</div>';
                
                echo wp_kses_post($final_message);
            }
        }
    }
    ?>
    
    <div class="wrap">
        <h1><span class="dashicons-before dashicons-media-text"></span> EONSR AEO Agent</h1>
        
        <!-- ===================================================================
             [SECTION 3] LICENSE & QUOTA NOTIFICATIONS
        =================================================================== -->
        <?php 
        if ( $license_status === 'activated' && isset($license_info['expiryDate']) ) : 
            // Calculate Expiry
            $expires_date = new DateTime($license_info['expiryDate']);
            $now          = new DateTime();
            $calc_now     = clone $now; $calc_now->setTime(0,0,0);
            $calc_expires = clone $expires_date; $calc_expires->setTime(0,0,0);
            $diff         = $calc_now->diff($calc_expires);
            $days_left    = $diff->days;
            $is_expired   = ($diff->invert === 1);

            // Get Usage Stats
            $usage            = isset($license_info['usage']) ? $license_info['usage'] : [];
            $postsToday       = isset($usage['postsToday']) ? $usage['postsToday'] : 0;            
            $dailyPostLimit   = isset($features['dailyPostLimit']) ? $features['dailyPostLimit'] : 100;
            $imagesToday      = isset($usage['imagesToday']) ? $usage['imagesToday'] : 0;
            $dailyImageLimit  = isset($features['dailyImageLimit']) ? $features['dailyImageLimit'] : 0;
            $used_tokens      = isset($usage['tokenUsage']) ? $usage['tokenUsage'] : 0;
            
            // Reset Time Calculation
            $reset_msg = '';
            if (isset($usage['lastDailyReset'])) {
                try {
                    $last_reset = new DateTime($usage['lastDailyReset']);
                    $next_reset = clone $last_reset;
                    $next_reset->modify('+1 day');
                    $diff_reset = $now->diff($next_reset);
                    if ($diff_reset->invert === 0) {
                        $reset_msg = "(Reset sau {$diff_reset->h}h {$diff_reset->i}p)";
                    }
                } catch (Exception $e) { }
            }
        ?>
            <!-- Info Banner -->
            <!-- <div class="notice notice-info is-dismissible" style="display:flex; justify-content:space-between; align-items:center;"> -->
                <!-- License Status -->
                <!-- <div>
                    <span class="dashicons dashicons-shield"></span>
                    Gói: <strong><?php echo esc_html($license_info['planType'] ?? 'FREE'); ?></strong>
                    <span style="margin: 0 10px; color:#ccc">|</span>
                    Hết hạn: <strong><?php echo esc_html(gmdate('d/m/Y', $expires_date->getTimestamp())); ?></strong>
                    <?php if ($is_expired): ?>
                        <strong style="color: #d63638;">(Đã hết hạn)</strong>
                    <?php else: ?>
                        <strong style="color: #f59e0b;">(Còn <?php echo esc_html($days_left); ?> ngày)</strong>
                    <?php endif; ?>
                </div> -->
                
                <!-- Quota Counters -->
                <!-- <div style="background: rgba(255,255,255,0.6); padding: 6px 15px; border-radius: 4px; min-width: 240px;">
                    <div style="font-size: 13px; display: flex; align-items: center; margin-bottom: 3px;">
                        <span class="dashicons dashicons-chart-pie" style="font-size:16px; width:20px; height:16px; color:#2271b1; margin-right: 2px;"></span>
                        <span>Bài viết: <strong id="aeo-live-usage" style="font-size:14px; color:#2271b1"><?php echo esc_html($postsToday); ?></strong><span style="color: #666;">/<?php echo esc_html($dailyPostLimit); ?></span> <span style="font-size: 11px; color: #666; margin-left:5px; font-weight: normal;"><?php echo esc_html($reset_msg); ?></span></span>
                    </div>
                    <div style="font-size: 13px; display: flex; align-items: center; margin-bottom: 3px;">
                        <span class="dashicons dashicons-format-image" style="font-size:16px; width:20px; height:16px; color:#2271b1; margin-right: 2px;"></span>
                        <span>Ảnh đã tạo: <strong id="aeo-live-images" style="font-size:14px; color:#2271b1"><?php echo esc_html($imagesToday); ?></strong><span style="color: #666;">/<?php echo esc_html($dailyImageLimit); ?></span></span>
                    </div>
                    <div style="font-size: 12px; color: #444; display: flex; align-items: center;">
                        <span class="dashicons dashicons-database" style="font-size:14px; width:20px; height:14px; color:#555; margin-right: 2px;"></span>
                        <span>Tokens: <strong id="aeo-live-tokens"><?php echo esc_html(number_format($used_tokens)); ?></strong></span>
                    </div>
                </div> -->
            <!-- </div> -->
        <?php endif; ?>

        <!-- ===================================================================
             [SECTION 4] MAIN GRID LAYOUT
        =================================================================== -->
        <!-- Updated class name with prefix -->
        <div class="eonsr-aeo-agent-grid aeo-agent-grid">
            
            <!-- ========== LEFT SIDEBAR: CONFIG FORM ========== -->
            <div class="eonsr-aeo-agent-card aeo-agent-card">
                <h2>Tham số bài viết</h2>
                <form method="post" id="aeo-agent-generate-form">
                    <?php wp_nonce_field('eonsr_aeo_agent_generate_ajax','eonsr_aeo_agent_generate_nonce'); ?>
                    
                    <!-- AI Model -->
                    <div class="form-group">
                        <label class="aeo-agent-label" for="model_name">Mô hình</label>
                        <select class="aeo-agent-select" name="model_name" id="model_name" required>
                            <option value="gemini-3-flash-preview" selected>EONSR Lite</option>
                            <?php if ( stripos($f_ai_model, 'Lite') === false ): ?>
                                <option value="gemini-3-flash-preview">EONSR Pro</option>
                            <?php endif; ?>
                        </select>
                        <?php if (stripos($f_ai_model, 'Lite') !== false): ?>
                        <?php endif; ?>
                    </div>

                    <!-- Topic -->
                    <div class="form-group">
                        <label class="aeo-agent-label" for="primary_term">Chủ đề / Từ khóa chính <span class="required-mark">*</span></label>
                        <input class="aeo-agent-input" type="text" required name="primary_term" id="primary_term" placeholder="Điền thông tin (2-4 chữ cho kết quả tốt nhất)">
                    </div>

                    <!-- Audience -->
                    <div class="form-group">
                        <label class="aeo-agent-label" for="audience_select">Đối tượng</label>
                        <select id="audience_select" class="aeo-agent-select" onchange="updateAudienceInput(this)">
                            <option value="General Audience" selected>General Audience (Đại chúng)</option>
                            <option value="Beginners & Novices">Beginners (Người mới bắt đầu)</option>
                            <option value="Professionals & Experts">Professionals (Chuyên gia)</option>
                            <option value="Business Owners">Business Owners (Chủ doanh nghiệp)</option>
                            <option value="Potential Customers">Potential Customers (Khách hàng tiềm năng)</option>
                            <option value="Investors">Investors (Nhà đầu tư)</option>
                            <option value="Tech Enthusiasts">Tech Enthusiasts (Người yêu công nghệ)</option>
                            <option value="Students & Researchers">Students (Học sinh/Sinh viên)</option>
                            <option value="custom" class="custom-option">-- Tự nhập (Khác) --</option>
                        </select>
                        <input type="text" id="audience_real_input" name="audience" value="General Audience" class="aeo-agent-input" style="display: none; margin-top: 8px;" placeholder="Nhập đối tượng cụ thể">
                    </div>

                    <!-- Country & Language -->
                    <div class="form-row">
                        <div class="form-group half">
                            <label class="aeo-agent-label" for="country">Quốc gia</label>
                            <select class="aeo-agent-select" name="country" id="country">
                                <?php 
                                foreach ($saved_countries as $c_code) {
                                    $c_data = $all_countries[$c_code] ?? null;
                                    $c_label = is_array($c_data) ? $c_data['flag'] . ' ' . $c_data['name'] : $c_code;
                                    echo "<option value='".esc_attr($c_code)."'>".esc_html($c_label)."</option>";
                                }
                                ?>
                            </select>
                        </div>
                        <div class="form-group half">
                            <label class="aeo-agent-label" for="language">Ngôn ngữ</label>
                            <select class="aeo-agent-select" name="language" id="language">
                                <?php 
                                foreach ($saved_langs as $l_code) {
                                    $l_data = $all_languages[$l_code] ?? null;
                                    $l_label = is_array($l_data) ? $l_data['flag'] . ' ' . $l_data['name'] : $l_code;
                                    echo "<option value='".esc_attr($l_code)."'>".esc_html($l_label)."</option>";
                                }
                                ?>
                            </select>
                        </div>
                    </div>

                    <!-- Word Count -->
                    <div class="form-group">
                        <label class="aeo-agent-label" for="min_words">Số từ tối thiểu</label>
                        <select class="aeo-agent-select" name="min_words" id="min_words">
                            <?php
                            $word_options = [
                                800  => '800 từ',
                                1200 => '1200 từ (Chuẩn SEO)',
                                1600 => '1600 từ',
                                2000 => '2000 từ',
                                3000 => '3000 từ',
                                3500 => '3500+ từ'
                            ];
                            $has_valid_option = false;
                            foreach ($word_options as $val => $label) {
                                if ($val >= $f_min_words && $val <= $f_max_words) {
                                    $selected = ($val == 1200) ? 'selected' : '';
                                    echo '<option value="' . esc_attr($val) . '" ' . esc_attr($selected) . '>' . esc_html($label) . '</option>';
                                    $has_valid_option = true;
                                }
                            }
                            if (!$has_valid_option) {
                                echo '<option value="' . esc_attr($f_max_words) . '" selected>' . esc_html($f_max_words) . ' từ (Max Plan)</option>';
                            }
                            ?>
                        </select>
                        <?php if ($f_max_words < 3500): ?>
                            <!-- <small class="help-text">Giới hạn gói hiện tại: <?php echo esc_html($f_min_words) . ' - ' . esc_html($f_max_words); ?> từ.</small> -->
                        <?php endif; ?>
                    </div>

                    <!-- Writing Style -->
                    <div class="form-group">
                        <label class="aeo-agent-label" for="output_style">Phong cách viết</label>
                       <select class="aeo-agent-select" name="output_style" id="output_style">
                            <?php 
                            foreach ($saved_styles as $s_code) {
                                $s_name = isset($all_styles[$s_code]) ? $all_styles[$s_code]['name'] : $s_code;
                                echo "<option value='".esc_attr($s_code)."'>".esc_html($s_name)."</option>";
                            }
                            ?>
                        </select>
                    </div>

                    <!-- Tone (Disabled / Coming Soon) -->
                    <!-- <div class="form-group form-group-disabled">
                        <label class="aeo-agent-label" for="tone_style">Giọng văn <span class="badge-coming-soon">Coming Soon</span></label>
                        <select class="aeo-agent-select" name="tone_style" id="tone_style" disabled>
                            <option value="Journalistic" selected>Journalistic (Báo chí)</option>
                        </select>
                        <small class="help-text">🔒 Tính năng này sẽ được phát triển trong phiên bản tiếp theo.</small>
                    </div> -->

                    <!-- Toggles -->
                    <div class="form-group">
                        <label class="checkbox-label">
                            <input type="checkbox" id="gen_keywords" name="gen_keywords" checked>
                            <span class="checkbox-text">Tự động tạo tags (bao gồm từ khóa chính)</span>
                        </label>
                    </div>

                    <!-- <div class="form-group">
                        <label class="checkbox-label">
                            <input type="checkbox" id="gen_youtube" name="gen_youtube" <?php echo $f_allow_yt ? '' : 'disabled'; ?>>
                            <span class="checkbox-text" <?php echo $f_allow_yt ? '' : 'style="color:#999"'; ?>>
                                Tự động tìm và nhúng video YouTube <?php if (!$f_allow_yt) echo ' (🔒 Basic Plan)'; ?>
                            </span>
                        </label>
                    </div> -->

                    <!-- Custom Logo Toggle -->
                    <?php
                    // $allow_logo = isset($features['allowCustomLogo']) ? $features['allowCustomLogo'] : false;
                    // $use_logo = get_option('eonsr_aeo_agent_use_custom_logo', false);
                    // if (!$allow_logo) $use_logo = false;
                    // $current_logo_url = get_option('eonsr_aeo_agent_custom_logo_url');

                    $allow_logo = true;
                    $use_logo = get_option('eonsr_aeo_agent_use_custom_logo', false);
                    $current_logo_url = get_option('eonsr_aeo_agent_custom_logo_url');
                    
                    ?>
                    <!-- <div class="form-group">
                        <label class="checkbox-label">
                            <input type="checkbox" id="use_custom_logo" name="use_custom_logo" <?php echo $use_logo ? 'checked' : ''; ?> <?php echo $allow_logo ? '' : 'disabled'; ?>>
                            <span class="checkbox-text" <?php echo $allow_logo ? '' : 'style="color:#999"'; ?>>
                                Thêm Logo vào ảnh <?php if (!$allow_logo) echo ' (🔒 Tính năng mở rộng)'; ?>
                            </span>
                        </label>
                        
                        <?php if ($allow_logo): ?>
                        <div id="aeo-logo-upload-area" style="margin-top:10px; margin-left:25px; <?php echo $use_logo ? '' : 'display:none;'; ?>">
                            <div style="display:flex; align-items:center; gap:10px;">
                                <div id="aeo-logo-preview" style="width:50px; height:50px; border:1px dashed #ccc; display:flex; align-items:center; justify-content:center; background:#f9f9f9; overflow:hidden; border-radius:4px;">
                                    <?php if ($current_logo_url): ?>
                                        <img src="<?php echo esc_url($current_logo_url); ?>" style="max-width:100%; max-height:100%;">
                                    <?php else: ?>
                                        <span class="dashicons dashicons-format-image" style="color:#ccc"></span>
                                    <?php endif; ?>
                                </div>
                                <div>
                                    <button type="button" class="button button-small" id="btn-upload-logo">Tải logo lên (PNG)</button>
                                    <button type="button" class="button button-small button-link-delete" id="btn-remove-logo" <?php echo $current_logo_url ? '' : 'style="display:none"'; ?>>Xóa</button>
                                    <input type="file" id="aeo-logo-file" accept="image/png" style="display:none;">
                                </div>
                            </div>
                            <small class="help-text">Logo sẽ được chèn vào góc dưới bên trái ảnh.</small>
                        </div>
                        <?php endif; ?>
                    </div> -->

                    <!-- Submit Button -->
                    <div class="aeo-agent-actions">
                        <button class="button button-primary button-hero button-generate" type="submit">
                            <span class="dashicons dashicons-star-filled button-icon-sparkle"></span> Tạo bài viết & Câu lệnh ảnh
                        </button>
                    </div>
                </form>


            </div>

            <!-- ========== RIGHT SIDEBAR: PREVIEW & PUBLISH ========== -->
            <div class="eonsr-aeo-agent-card aeo-agent-card" id="aeo-agent-preview-card">
                <form method="post" id="aeo-agent-publish-form">
                    
                    <div class="aeo-agent-card-header">
                        <h2>Xem trước & Hoàn tất</h2>
                        <div class="aeo-agent-header-actions">
                            <?php wp_nonce_field('eonsr_aeo_agent_publish','eonsr_aeo_agent_publish_nonce'); ?>
                            
                            <?php
                            // Check Translation Rights
                            if ( count($saved_langs) > 1 ) :
                                $can_translate = ($f_langs_limit > 1);
                            ?>
                            <div class="aeo-agent-translation-wrapper" style="position: relative; margin-right: 15px;">
                                <!-- Translation Toggle -->
                                <!-- <label class="checkbox-label" title="<?php echo $can_translate ? 'Tạo thêm bài viết cho ngôn ngữ khác' : 'Nâng cấp gói để mở khóa tính năng này'; ?>">
                                    <input type="checkbox" id="aeo_toggle_translate" name="eonsr_aeo_agent_enable_translation" value="1" <?php echo $can_translate ? '' : 'disabled'; ?>>
                                    <span class="checkbox-text" <?php echo $can_translate ? '' : 'style="color:#999"'; ?>>
                                        <span class="dashicons dashicons-translation"></span> Dịch đa ngữ <?php if (!$can_translate) echo ' (🔒)'; ?>
                                    </span>
                                </label> -->

                                <!-- Dropdown Languages -->
                                <div id="aeo_translation_dropdown" style="display:none; position: absolute; top: 30px; right: 0; background: #fff; border: 1px solid #c3c4c7; border-radius: 4px; padding: 10px; box-shadow: 0 3px 10px rgba(0,0,0,0.1); z-index: 100; min-width: 220px;">
                                    <p style="margin: 0 0 8px; font-size: 12px; font-weight: 600; color: #50575e; border-bottom: 1px solid #f0f0f1; padding-bottom: 5px;">Chọn ngôn ngữ đích:</p>
                                    <div style="max-height: 200px; overflow-y: auto;">
                                        <?php 
                                        foreach ($saved_langs as $lang_code) {
                                            $l_data = isset($all_languages[$lang_code]) ? $all_languages[$lang_code] : null;
                                            $l_label = is_array($l_data) ? $l_data['flag'] . ' ' . $l_data['name'] : $lang_code;
                                            ?>
                                            <label class="checkbox-label" style="display: flex; align-items: center; margin-bottom: 6px;">
                                                <input type="checkbox" name="eonsr_aeo_target_langs[]" value="<?php echo esc_attr($lang_code); ?>">
                                                <span class="checkbox-text" style="margin-left: 5px;"><?php echo esc_html($l_label); ?></span>
                                            </label>
                                            <?php
                                        }
                                        ?>
                                    </div>
                                </div>
                            </div>
                            <?php endif; ?>

                            <!-- Status & Schedule Options -->
                            <div class="aeo-agent-publish-status-options">
                                <label class="radio-label">
                                    <input type="radio" name="post_status_choice" value="publish" checked>
                                    <span>Nháp</span>
                                </label>
                                <label class="radio-label">
                                    <input type="radio" name="post_status_choice" value="schedule">
                                    <span>Hẹn giờ</span>
                                </label>
                            </div>
                            
                            <div id="aeo-agent-schedule-options">
                                <input type="date" name="schedule_date" value="<?php echo esc_attr( current_time('Y-m-d') ); ?>">
                                <input type="time" name="schedule_time" value="<?php echo esc_attr( current_time('H:i') ); ?>">
                            </div>
                            
                            <button id="aeo-agent-publish-btn" class="button button-primary" type="submit" disabled>
                                <span class="dashicons dashicons-upload"></span> Đăng bài
                            </button>
                        </div>
                    </div>



                    <!-- Category Selector -->
                    <div class="aeo-agent-category-selector">
                        <label class="aeo-agent-label">Chuyên mục <span id="aeo-agent-category-status"></span></label>
                        <div class="aeo-agent-category-list">
                            <?php
                            // Logic: Detect categories based on Polylang or Default
                            if ( function_exists( 'pll_current_language' ) && function_exists('pll_get_term_translations') ) {
                                $current_admin_lang = pll_current_language('slug');
                                if ( $current_admin_lang ) {
                                    $categories = get_categories( ['hide_empty' => false, 'lang' => $current_admin_lang] );
                                    foreach ($categories as $category) {
                                        echo '<label class="checkbox-label"><input type="checkbox" name="post_categories[]" value="' . esc_attr($category->term_id) . '"><span class="checkbox-text">' . esc_html($category->name) . '</span></label>';
                                    }
                                } else { 
                                    $processed_term_ids = [];
                                    $all_categories = get_categories( ['hide_empty' => false, 'lang' => ''] );
                                    $default_lang = pll_default_language();
                                    foreach ($all_categories as $category) {
                                        if ( in_array( $category->term_id, $processed_term_ids ) ) continue;
                                        $translations = pll_get_term_translations( $category->term_id );
                                        $display_names = [];
                                        $term_ids_in_group = [];
                                        foreach ( $translations as $term_id ) {
                                            $term = get_term( $term_id );
                                            if ( $term && ! is_wp_error( $term ) ) {
                                                $display_names[] = $term->name;
                                                $term_ids_in_group[] = $term_id;
                                            }
                                        }
                                        $processed_term_ids = array_merge($processed_term_ids, $term_ids_in_group);
                                        $label = implode( ' / ', array_unique($display_names) );
                                        $value_id = $translations[$default_lang] ?? $category->term_id;
                                        echo '<label class="checkbox-label"><input type="checkbox" name="post_categories[]" value="' . esc_attr( $value_id ) . '"><span class="checkbox-text">' . esc_html( $label ) . '</span></label>';
                                    }
                                }
                            } else {
                                $categories = get_categories( ['hide_empty' => false] );
                                foreach ($categories as $category) {
                                    echo '<label class="checkbox-label"><input type="checkbox" name="post_categories[]" value="' . esc_attr($category->term_id) . '"><span class="checkbox-text">' . esc_html($category->name) . '</span></label>';
                                }
                            }
                            ?>
                        </div>
                    </div>

                    <!-- Hidden Fields -->
                    <input type="hidden" name="post_id" id="post_id" value="">
                    <input type="hidden" name="preview_title" value="">
                    <input type="hidden" name="preview_content" value="">
                    <input type="hidden" name="preview_slug" value="">
                    <input type="hidden" name="preview_tags" value="">
                    <input type="hidden" name="preview_meta_desc" value="">
                    <input type="hidden" name="preview_focus_kw" value="">
                    <input type="hidden" name="featured_image_base64" id="featured_image_base64" value="">
                    <input type="hidden" name="figcaption_image_base64" id="figcaption_image_base64" value="">
                </form>

                <!-- Preview Area -->
                <h3 id="aeo-agent-preview-title">(Chưa có nội dung)</h3>
                <div id="aeo-agent-preview-keywords" class="aeo-agent-badge-wrap"></div>

                <div id="aeo-agent-initial-placeholder">
                    <div id="aeo-agent-preview-body-placeholder">
                        <p>Điền thông tin và bấm <strong>Tạo bài viết & Câu lệnh ảnh</strong> để xem trước.</p>
                    </div>
                </div>

                <!-- Tabs Container -->
                <div id="aeo-agent-tabs-wrapper" style="display:none; margin-top: 15px;">
                    <div class="aeo-agent-tabs-header">
                        <div class="aeo-agent-tabs-nav">
                            <a href="#" class="aeo-agent-tab-link active" data-tab="content">Nội dung bài viết</a>
                            <a href="#" class="aeo-agent-tab-link" data-tab="summary">Tóm tắt</a>
                            <a href="#" class="aeo-agent-tab-link" data-tab="images">Tùy chỉnh ảnh</a>
                            <a href="#" class="aeo-agent-tab-link disabled" data-tab="review">Xem tổng quan</a>
                        </div>
                        <div class="aeo-agent-tabs-actions">
                            <span id="aeo-agent-update-status"></span>
                            <button id="aeo-agent-update-content-btn" class="button" type="button" disabled>
                                <span class="dashicons dashicons-update"></span> Cập nhật
                            </button>
                        </div>
                    </div>

                    <div class="aeo-agent-tabs-content">
                        <!-- Tab Content -->
                        <div id="aeo-agent-tab-content" class="aeo-agent-tab-panel active">
                            <div id="aeo-agent-preview-body" contenteditable="true"></div>
                        </div>

                        <!-- Tab Summary -->
                        <div id="aeo-agent-tab-summary" class="aeo-agent-tab-panel">
                            <div class="summary-container">
                                <div class="summary-section">
                                    <h3><span class="dashicons dashicons-align-left"></span> Tóm tắt dạng đoạn văn (3-4 câu)</h3>
                                    <div id="aeo-agent-summary-paragraph" class="summary-box">
                                        <p>Tóm tắt sẽ được tạo tự động sau khi bài viết hoàn thành...</p>
                                    </div>
                                </div>
                                <div class="summary-section">
                                    <h3><span class="dashicons dashicons-editor-ul"></span> Tóm tắt dạng bullet points</h3>
                                    <div id="aeo-agent-summary-bullets" class="summary-box">
                                        <ul><li>Tóm tắt sẽ được tạo tự động sau khi bài viết hoàn thành...</li></ul>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Tab Images -->
                        <div id="aeo-agent-tab-images" class="aeo-agent-tab-panel">
                            <div class="images-container">
                                <div class="image-prompt-grid">
                                    <div class="form-group">
                                        <label class="aeo-agent-label" for="aeo-agent-featured-prompt">
                                            <span class="dashicons dashicons-format-image"></span>
                                            Tạo ảnh Thumbnail
                                        </label>
                                        <textarea id="aeo-agent-featured-prompt" class="aeo-agent-input" rows="6"></textarea>
                                    </div>
                                    <div class="form-group">
                                        <label class="aeo-agent-label" for="aeo-agent-incontent-prompt">
                                            <span class="dashicons dashicons-images-alt2"></span>
                                            Tạo ảnh trong bài
                                        </label>
                                        <textarea id="aeo-agent-incontent-prompt" class="aeo-agent-input" rows="4"></textarea>
                                    </div>
                                </div>
                                
                                <div id="aeo-agent-image-results"></div>

                                <div id="aeo-agent-image-actions" style="margin-top: 20px; text-align: center;">
                                    <button id="btn-gen-all" class="button button-primary button-large" type="button" style="display: inline-flex; align-items: center; min-width: 200px; justify-content: center;">
                                        <span class="dashicons dashicons-camera" style="margin-right: 5px;"></span>
                                        Tạo tất cả hình ảnh (2 ảnh)
                                    </button>

                                    <div id="aeo-regen-buttons" style="display: none; gap: 10px; justify-content: center; margin-top: 10px;">
                                        <button type="button" class="button btn-gen-single" data-target="featured">
                                            <span class="dashicons dashicons-refresh"></span> Tạo lại Thumbnail
                                        </button>
                                        <button type="button" class="button btn-gen-single" data-target="in_content">
                                            <span class="dashicons dashicons-refresh"></span> Tạo lại Ảnh trong bài
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Tab Review -->
                        <div id="aeo-agent-tab-review" class="aeo-agent-tab-panel">
                            <div id="aeo-agent-full-preview-body" contenteditable="true">
                                <p class="placeholder-text">Hình ảnh sẽ được ghép vào đây sau khi tạo thành công.</p>
                            </div>
                        </div>
                    </div>
                    <a href="#" id="aeo-agent-preview-btn" class="preview-link" target="_blank" rel="noopener" style="display: none;"><span class="dashicons dashicons-visibility"></span> Xem trước</a>
                </div>
            </div>
        </div>
    </div>

    <!-- ===================================================================
         [SECTION 5] WIZARD SETUP (MODAL)
    =================================================================== -->
    <?php if ( !$setup_completed && $license_status === 'activated' ): ?>


    <?php
    ?>
    <?php endif; ?>

<?php
}
?>