<?php
/**
 * LuxStrat International — Universal Admin Panel
 *
 * Includes: Settings, Actions, Inbound Link Scanner, Enrich Posts,
 * Emergency Controls, Recent Posts log, Theme Reference.
 *
 * @package DamalionBlogAI
 * @subpackage LuxStratIntl
 */

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

class DBA_LuxStrat_Intl_Admin {

    private static $instance = null;

    public static function get_instance() {
        if ( null === self::$instance ) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    private function __construct() {
        if ( did_action( 'admin_menu' ) ) {
            $this->register_menus();
        } else {
            add_action( 'admin_menu', array( $this, 'register_menus' ), 36 );
        }

        add_action( 'wp_ajax_dba_luxstrat_intl_save',      array( $this, 'ajax_save' ) );
        add_action( 'wp_ajax_dba_luxstrat_intl_run',        array( $this, 'ajax_run' ) );
        add_action( 'wp_ajax_dba_luxstrat_intl_progress',   array( $this, 'ajax_progress' ) );
        add_action( 'wp_ajax_dba_luxstrat_intl_reset',      array( $this, 'ajax_reset' ) );
        add_action( 'wp_ajax_dba_luxstrat_intl_scan',       array( $this, 'ajax_scan' ) );
        add_action( 'wp_ajax_dba_luxstrat_intl_strip',      array( $this, 'ajax_strip' ) );
        add_action( 'wp_ajax_dba_luxstrat_intl_strip_selected', array( $this, 'ajax_strip_selected' ) );
        add_action( 'wp_ajax_dba_luxstrat_intl_enrich',     array( $this, 'ajax_enrich' ) );
        add_action( 'wp_ajax_dba_luxstrat_intl_stop',       array( $this, 'ajax_stop' ) );
        add_action( 'wp_ajax_dba_luxstrat_intl_fullreset',  array( $this, 'ajax_full_reset' ) );
        add_action( 'wp_ajax_dba_luxstrat_intl_queue_add',  array( $this, 'ajax_queue_add' ) );
        add_action( 'wp_ajax_dba_luxstrat_intl_queue_remove', array( $this, 'ajax_queue_remove' ) );
        add_action( 'wp_ajax_dba_luxstrat_intl_queue_edit',   array( $this, 'ajax_queue_edit' ) );
        add_action( 'wp_ajax_dba_luxstrat_intl_queue_move',   array( $this, 'ajax_queue_move' ) );

        // Kaizen + Anti-Orphan (v2.17.0)
        add_action( 'wp_ajax_dba_luxstrat_intl_orphan_audit',  array( $this, 'ajax_orphan_audit' ) );
        add_action( 'wp_ajax_dba_luxstrat_intl_flush_kaizen',  array( $this, 'ajax_flush_kaizen' ) );
    }

    public function register_menus() {
        $languages = DBA_LuxStrat_Intl_Loader::get_languages();
        foreach ( $languages as $lang => $config ) {
            $flag  = ! empty( $config['flag'] )  ? $config['flag']  : "\xF0\x9F\x8C\x90";
            $label = ! empty( $config['label'] ) ? $config['label'] : strtoupper( $lang );
            add_submenu_page(
                'dba-settings',
                'LuxStrat — ' . $label,
                $flag . ' LuxStrat ' . strtoupper( $lang ),
                'manage_options',
                'dba-luxstrat-' . $lang,
                function() use ( $lang, $config ) { $this->render_page( $lang, $config ); }
            );
        }
    }

    private function render_page( $lang, $lang_config ) {
        if ( ! current_user_can( 'manage_options' ) ) wp_die( 'Access denied.' );

        $settings      = get_option( 'dba_luxstrat_' . $lang . '_settings', array() );
        $themes        = ! empty( $lang_config['themes'] ) ? $lang_config['themes'] : array();
        $active_themes = ! empty( $settings['active_themes'] ) ? $settings['active_themes'] : array_keys( $themes );
        $last_theme    = get_option( 'dba_luxstrat_' . $lang . '_last_theme', '(none)' );
        $schedule_info = DBA_LuxStrat_Intl_Scheduler::get_schedule_info( $lang, $lang_config );
        $extra_cats    = ! empty( $settings['extra_category_ids'] ) ? $settings['extra_category_ids'] : array();
        $flag          = $lang_config['flag'] ?? "\xF0\x9F\x8C\x90";
        $label         = $lang_config['label'] ?? strtoupper( $lang );
        $prefix        = DBA_LuxStrat_Intl_Dedupe::meta_prefix( $lang );

        // ══════════════════════════════════════════════════════════════
        //  WPML: Switch to target language BEFORE fetching categories
        //  and posts. Without this, get_categories() returns the
        //  default language (English) categories instead of FR/DE/ES.
        // ══════════════════════════════════════════════════════════════
        $original_lang = null;
        $wpml_switched = false;
        if ( function_exists( 'icl_get_languages' ) ) {
            global $sitepress;
            if ( $sitepress ) {
                $original_lang = $sitepress->get_current_language();
                $sitepress->switch_lang( $lang );
                $wpml_switched = true;
            }
        }

        $all_categories = get_categories( array(
            'taxonomy'   => 'category',
            'hide_empty' => false,
            'orderby'    => 'name',
            'order'      => 'ASC',
            // WPML will now filter these to the target language
        ) );

        $recent_posts = new WP_Query( array(
            'post_type' => 'post', 'post_status' => 'any', 'posts_per_page' => 20,
            'orderby' => 'date', 'order' => 'DESC',
            'suppress_filters' => false, // Let WPML filter by language
            'meta_query' => array( array( 'key' => $prefix . 'auto_created', 'compare' => 'EXISTS' ) ),
        ) );

        $all_lsi_posts = get_posts( array(
            'post_type' => 'post', 'post_status' => array('publish','draft','pending'),
            'posts_per_page' => -1, 'fields' => 'ids',
            'meta_query' => array( array( 'key' => $prefix . 'auto_created', 'compare' => 'EXISTS' ) ),
            'suppress_filters' => false, // Let WPML filter by language
        ) );

        // Recent posts (last 4 days) — for enrich/repair stats
        $recent_lsi_posts = get_posts( array(
            'post_type' => 'post', 'post_status' => array('publish','draft','pending'),
            'posts_per_page' => -1, 'fields' => 'ids',
            'meta_query' => array( array( 'key' => $prefix . 'auto_created', 'compare' => 'EXISTS' ) ),
            'date_query' => array( array( 'after' => '4 days ago' ) ),
            'suppress_filters' => false,
        ) );

        // ══════════════════════════════════════════════════════════════
        //  WPML: Restore original admin language
        // ══════════════════════════════════════════════════════════════
        if ( $wpml_switched && isset( $sitepress ) && $sitepress ) {
            $sitepress->switch_lang( $original_lang ?: 'en' );
        }

        $missing_images = 0; $missing_seo = 0;
        foreach ( $recent_lsi_posts as $pid ) {
            if ( ! has_post_thumbnail( $pid ) ) $missing_images++;
            if ( empty( get_post_meta( $pid, '_yoast_wpseo_metadesc', true ) ) && empty( get_post_meta( $pid, 'rank_math_description', true ) ) ) $missing_seo++;
        }

        // ══════════════════════════════════════════════════════════════
        //  LINK REPORT — count auto-injected links IN each LuxStrat post
        // ══════════════════════════════════════════════════════════════
        $inbound_report = array();
        $link_class = DBA_LuxStrat_Intl_Inbound::LINK_CLASS;
        foreach ( $all_lsi_posts as $pid ) {
            $post_obj = get_post( $pid );
            $count = 0;
            if ( $post_obj && ! empty( $post_obj->post_content ) ) {
                $count = substr_count( $post_obj->post_content, 'class="' . $link_class . '"' );
            }
            $inbound_report[ $pid ] = array(
                'title'    => get_the_title( $pid ),
                'url'      => get_permalink( $pid ),
                'inbound'  => $count,
                'status'   => get_post_status( $pid ),
                'date'     => get_the_date( 'Y-m-d', $pid ),
                'theme'    => get_post_meta( $pid, $prefix . 'theme_label', true ),
            );
        }

        $this->render_html( $lang, $lang_config, $settings, $themes, $active_themes, $last_theme, $schedule_info, $extra_cats, $flag, $label, $prefix, $all_categories, $recent_posts, $all_lsi_posts, $missing_images, $missing_seo, count( $recent_lsi_posts ), $inbound_report, get_option( 'dba_luxstrat_' . $lang . '_title_queue', array() ) );
    }

    private function render_html( $lang, $lang_config, $settings, $themes, $active_themes, $last_theme, $schedule_info, $extra_cats, $flag, $label, $prefix, $all_categories, $recent_posts, $all_lsi_posts, $missing_images, $missing_seo, $recent_count = 0, $inbound_report = array(), $title_queue = array() ) {
        ?>
        <div class="wrap">
            <h1 style="display:flex;align-items:center;gap:10px;">
                <span style="font-size:28px;"><?php echo $flag; ?></span>
                LuxStrat — <?php echo esc_html( $label ); ?> (<?php echo strtoupper( $lang ); ?>)
            </h1>
            <p style="font-size:14px;color:#555;max-width:800px;">
                Automated publication of Luxembourg structuring articles in <strong><?php echo esc_html( $label ); ?></strong>.
                <strong><?php echo esc_html( $schedule_info['frequency'] ); ?></strong>.
                Published to <code>damalion.com/?lang=<?php echo esc_attr( $lang ); ?></code>.
            </p>

            <!-- STATUS CARDS -->
            <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:16px;margin:20px 0;">
                <div style="background:#fff;border:1px solid #ddd;border-radius:8px;padding:20px;">
                    <h3 style="margin:0 0 8px;font-size:14px;color:#666;">Status</h3>
                    <span style="display:inline-block;padding:4px 12px;border-radius:20px;font-size:13px;font-weight:600;
                        background:<?php echo ! empty( $settings['enabled'] ) ? '#dcfce7' : '#fee2e2'; ?>;
                        color:<?php echo ! empty( $settings['enabled'] ) ? '#166534' : '#991b1b'; ?>;">
                        <?php echo ! empty( $settings['enabled'] ) ? 'ACTIVE' : 'DISABLED'; ?>
                    </span>
                </div>
                <div style="background:#fff;border:1px solid #ddd;border-radius:8px;padding:20px;">
                    <h3 style="margin:0 0 8px;font-size:14px;color:#666;">Schedule</h3>
                    <strong style="font-size:13px;"><?php echo esc_html( $schedule_info['frequency'] ); ?></strong>
                    <br><span style="font-size:12px;color:#888;">Cron: <?php echo $schedule_info['cron_active'] ? 'YES' : 'NO'; ?></span>
                </div>
                <div style="background:#fff;border:1px solid #ddd;border-radius:8px;padding:20px;">
                    <h3 style="margin:0 0 8px;font-size:14px;color:#666;">Next Run</h3>
                    <span style="font-size:13px;"><?php echo esc_html( $schedule_info['next_run'] ); ?></span>
                </div>
                <div style="background:#fff;border:1px solid #ddd;border-radius:8px;padding:20px;">
                    <h3 style="margin:0 0 8px;font-size:14px;color:#666;">Last Theme</h3>
                    <span style="font-size:13px;font-weight:600;"><?php echo esc_html( $last_theme ); ?></span>
                </div>
                <div style="background:#fff;border:1px solid #ddd;border-radius:8px;padding:20px;">
                    <h3 style="margin:0 0 8px;font-size:14px;color:#666;">Total Posts</h3>
                    <span style="font-size:18px;font-weight:700;"><?php echo count( $all_lsi_posts ); ?></span>
                </div>
            </div>

            <!-- SETTINGS -->
            <div style="background:#fff;border:1px solid #ddd;border-radius:8px;padding:24px;margin:20px 0;max-width:900px;">
                <h2 style="margin-top:0;">Settings</h2>
                <form id="dba-lsi-form">
                    <?php wp_nonce_field( 'dba_admin_nonce', 'dba_lsi_nonce' ); ?>
                    <table class="form-table">
                        <tr><th>Enable Module</th><td><label><input type="checkbox" name="lsi_enabled" value="1" <?php checked( ! empty( $settings['enabled'] ) ); ?>> Enable <?php echo esc_html( $label ); ?> article generation</label></td></tr>
                        <tr><th>Active Themes</th><td>
                            <?php foreach ( $themes as $slug => $tc ) : ?>
                            <label style="display:block;margin-bottom:8px;">
                                <input type="checkbox" name="lsi_themes[]" value="<?php echo esc_attr( $slug ); ?>" <?php checked( in_array( $slug, $active_themes, true ) ); ?>>
                                <span style="display:inline-block;width:12px;height:12px;border-radius:3px;background:<?php echo esc_attr( $tc['color'] ?? '#666' ); ?>;margin:0 6px;vertical-align:middle;"></span>
                                <?php echo esc_html( $tc['label'] ); ?>
                                <code style="font-size:10px;color:#999;margin-left:6px;"><?php echo esc_html( implode( ', ', $tc['category_slugs'] ?? array() ) ); ?></code>
                            </label>
                            <?php endforeach; ?>
                        </td></tr>
                        <tr><th>Additional Categories</th><td>
                            <div style="max-height:250px;overflow-y:auto;border:1px solid #ddd;padding:10px;border-radius:4px;">
                                <?php foreach ( $all_categories as $cat ) : ?>
                                <label style="display:block;margin-bottom:4px;font-size:12px;">
                                    <input type="checkbox" name="lsi_extra_cats[]" value="<?php echo (int) $cat->term_id; ?>" <?php checked( in_array( (int) $cat->term_id, $extra_cats, true ) ); ?>>
                                    <?php echo esc_html( $cat->name ); ?> <span style="color:#aaa;">(<?php echo esc_html( $cat->slug ); ?>)</span>
                                </label>
                                <?php endforeach; ?>
                            </div>
                        </td></tr>
                        <tr><th>Post Status</th><td>
                            <select name="lsi_post_status">
                                <option value="publish" <?php selected( ( $settings['post_status'] ?? 'publish' ), 'publish' ); ?>>Publish</option>
                                <option value="draft" <?php selected( ( $settings['post_status'] ?? '' ), 'draft' ); ?>>Draft</option>
                                <option value="pending" <?php selected( ( $settings['post_status'] ?? '' ), 'pending' ); ?>>Pending</option>
                            </select>
                        </td></tr>
                        <tr><th>Author</th><td><?php wp_dropdown_users( array( 'name' => 'lsi_author_id', 'selected' => $settings['author_id'] ?? 1, 'role__in' => array( 'administrator', 'editor', 'author' ) ) ); ?></td></tr>
                        <tr><th>Fallback Category</th><td><?php wp_dropdown_categories( array( 'name' => 'lsi_category_id', 'selected' => $settings['category_id'] ?? 0, 'show_option_none' => '-- None --', 'hide_empty' => false ) ); ?></td></tr>
                        <tr><th>Word Count</th><td>Min: <input type="number" name="lsi_word_min" value="<?php echo esc_attr( $settings['word_count_min'] ?? 1000 ); ?>" min="500" max="3000" style="width:80px;"> Max: <input type="number" name="lsi_word_max" value="<?php echo esc_attr( $settings['word_count_max'] ?? 1800 ); ?>" min="800" max="5000" style="width:80px;"></td></tr>
                        <tr><th>CTA Text</th><td><textarea name="lsi_cta_text" rows="2" class="large-text"><?php echo esc_textarea( $settings['cta_text'] ?? ( $lang_config['cta_defaults']['text'] ?? '' ) ); ?></textarea></td></tr>
                        <tr><th>CTA Link Text</th><td><input type="text" name="lsi_cta_link_text" class="regular-text" value="<?php echo esc_attr( $settings['cta_link_text'] ?? ( $lang_config['cta_defaults']['link_text'] ?? '' ) ); ?>"></td></tr>
                        <tr><th>CTA Link URL</th><td><input type="url" name="lsi_cta_link_url" class="regular-text" value="<?php echo esc_attr( $settings['cta_link_url'] ?? ( $lang_config['cta_defaults']['link_url'] ?? '' ) ); ?>"></td></tr>
                    </table>
                    <div id="dba-lsi-save-result" style="margin:10px 0;"></div>
                    <button type="submit" id="dba-lsi-save" class="button button-primary button-large">Save Settings</button>
                </form>
            </div>

            <!-- CUSTOM TITLE QUEUE -->
            <div style="background:#fff;border:1px solid #ddd;border-radius:8px;padding:24px;margin:20px 0;max-width:900px;">
                <h2 style="margin-top:0;">✏️ Custom Title Queue</h2>
                <p style="font-size:13px;color:#555;">
                    Type a title below. The next generation will use it as the post title and generate content based on it. Country/city are still selected by rotation.
                </p>
                <div style="display:flex;gap:10px;align-items:center;margin:14px 0;">
                    <input type="text" id="dba-lsi-queue-input" class="regular-text" style="flex:1;padding:8px 12px;font-size:14px;" placeholder="e.g. Créer une Sàrl ou Sàrl-S au Luxembourg" accept-charset="UTF-8">
                    <button id="dba-lsi-queue-add" class="button button-primary" style="white-space:nowrap;">
                        <span style="font-size:14px;">+</span> Add to Queue
                    </button>
                </div>
                <div id="dba-lsi-queue-result" style="margin:6px 0;"></div>
                <div id="dba-lsi-queue-list">
                    <?php if ( ! empty( $title_queue ) ) : ?>
                        <table class="widefat striped" style="font-size:13px;margin-top:10px;">
                            <thead><tr><th style="width:30px;">#</th><th>Title</th><th style="width:160px;text-align:center;">Actions</th></tr></thead>
                            <tbody id="dba-lsi-queue-tbody">
                                <?php foreach ( $title_queue as $qi => $qt ) : ?>
                                <tr data-queue-index="<?php echo (int) $qi; ?>">
                                    <td style="color:#888;font-weight:600;" class="dba-lsi-queue-num"><?php echo (int) $qi + 1; ?></td>
                                    <td>
                                        <span class="dba-lsi-queue-title-display"><?php echo esc_html( $qt ); ?></span>
                                        <input type="text" class="dba-lsi-queue-title-edit regular-text" value="<?php echo esc_attr( $qt ); ?>" style="display:none;width:100%;padding:4px 8px;font-size:13px;" />
                                    </td>
                                    <td style="text-align:center;white-space:nowrap;">
                                        <button class="button button-small dba-lsi-queue-up" data-index="<?php echo (int) $qi; ?>" title="Move up" <?php disabled( $qi === 0 ); ?> style="padding:0 6px;">▲</button>
                                        <button class="button button-small dba-lsi-queue-down" data-index="<?php echo (int) $qi; ?>" title="Move down" <?php disabled( $qi === count( $title_queue ) - 1 ); ?> style="padding:0 6px;">▼</button>
                                        <button class="button button-small dba-lsi-queue-edit-btn" data-index="<?php echo (int) $qi; ?>" title="Edit title" style="color:#2271b1;border-color:#2271b1;">✎</button>
                                        <button class="button button-small dba-lsi-queue-save-btn" data-index="<?php echo (int) $qi; ?>" title="Save edit" style="display:none;color:#166534;border-color:#166534;">✓</button>
                                        <button class="button button-small dba-lsi-queue-cancel-btn" data-index="<?php echo (int) $qi; ?>" title="Cancel edit" style="display:none;color:#666;border-color:#999;">✕</button>
                                        <button class="button button-small dba-lsi-queue-remove" data-index="<?php echo (int) $qi; ?>" style="color:#b32d2e;border-color:#b32d2e;" title="Remove from queue">🗑</button>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    <?php else : ?>
                        <p style="color:#999;font-style:italic;font-size:12px;margin:4px 0;">Queue is empty. Titles will be auto-generated by theme rotation.</p>
                    <?php endif; ?>
                </div>
            </div>

            <!-- ACTIONS + PROGRESS PIPELINE -->
            <div style="background:#fff;border:1px solid #ddd;border-radius:8px;padding:24px;margin:20px 0;max-width:900px;">
                <h2 style="margin-top:0;">Generate Article</h2>
                <div id="dba-lsi-action-result" style="margin:10px 0;"></div>
                <button id="dba-lsi-run" class="button button-primary button-hero" style="width:100%;margin-bottom:16px;">▶ Generate Now (Post + SEO + DALL-E Image)</button>
                <button id="dba-lsi-reset" class="button" style="margin-bottom:16px;">Reset Rotation</button>

                <!-- PROGRESS PIPELINE -->
                <div id="dba-lsi-pipeline" style="display:none;margin-top:12px;border:1px solid #e5e7eb;border-radius:8px;padding:20px;background:#fafafa;">
                    <h3 style="margin:0 0 16px;font-size:14px;font-weight:700;color:#1e293b;">Pipeline Progress</h3>

                    <!-- Overall progress bar -->
                    <div style="margin-bottom:20px;">
                        <div style="display:flex;justify-content:space-between;margin-bottom:6px;">
                            <span style="font-size:12px;font-weight:600;color:#64748b;text-transform:uppercase;letter-spacing:.05em;">Overall</span>
                            <span id="dba-lsi-pct-text" style="font-size:13px;font-weight:700;color:#2563eb;">0%</span>
                        </div>
                        <div style="background:#e5e7eb;border-radius:6px;height:10px;overflow:hidden;">
                            <div id="dba-lsi-pct-bar" style="background:linear-gradient(90deg,#2563eb,#7c3aed);height:100%;width:0%;transition:width .4s cubic-bezier(.4,0,.2,1);border-radius:6px;position:relative;overflow:hidden;">
                                <div style="position:absolute;top:0;left:0;right:0;bottom:0;background:linear-gradient(90deg,transparent,rgba(255,255,255,.25),transparent);animation:lsi-shimmer 1.5s infinite;"></div>
                            </div>
                        </div>
                    </div>

                    <!-- Phase steps -->
                    <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:12px;">
                        <!-- Step 1: Content -->
                        <div id="dba-lsi-step-content" class="dba-lsi-step" style="border:1px solid #e5e7eb;border-radius:8px;padding:14px;background:#fff;transition:all .3s;">
                            <div style="display:flex;align-items:center;gap:8px;margin-bottom:8px;">
                                <div id="dba-lsi-icon-content" style="width:28px;height:28px;border-radius:50%;border:2px solid #cbd5e1;display:flex;align-items:center;justify-content:center;font-size:12px;font-weight:700;color:#94a3b8;transition:all .3s;">1</div>
                                <span style="font-size:12px;font-weight:700;color:#475569;">CONTENT</span>
                            </div>
                            <div style="font-size:11px;color:#64748b;">Post Generation</div>
                            <div id="dba-lsi-detail-content" style="font-size:10px;color:#94a3b8;margin-top:4px;min-height:14px;"></div>
                            <div style="margin-top:8px;background:#e5e7eb;border-radius:3px;height:4px;overflow:hidden;">
                                <div id="dba-lsi-bar-content" style="background:#3b82f6;height:100%;width:0%;transition:width .4s;border-radius:3px;"></div>
                            </div>
                        </div>

                        <!-- Step 2: SEO -->
                        <div id="dba-lsi-step-seo" class="dba-lsi-step" style="border:1px solid #e5e7eb;border-radius:8px;padding:14px;background:#fff;transition:all .3s;">
                            <div style="display:flex;align-items:center;gap:8px;margin-bottom:8px;">
                                <div id="dba-lsi-icon-seo" style="width:28px;height:28px;border-radius:50%;border:2px solid #cbd5e1;display:flex;align-items:center;justify-content:center;font-size:12px;font-weight:700;color:#94a3b8;transition:all .3s;">2</div>
                                <span style="font-size:12px;font-weight:700;color:#475569;">SEO</span>
                            </div>
                            <div style="font-size:11px;color:#64748b;">Validation + Meta</div>
                            <div id="dba-lsi-detail-seo" style="font-size:10px;color:#94a3b8;margin-top:4px;min-height:14px;"></div>
                            <div style="margin-top:8px;background:#e5e7eb;border-radius:3px;height:4px;overflow:hidden;">
                                <div id="dba-lsi-bar-seo" style="background:#10b981;height:100%;width:0%;transition:width .4s;border-radius:3px;"></div>
                            </div>
                        </div>

                        <!-- Step 3: DALL-E -->
                        <div id="dba-lsi-step-dalle" class="dba-lsi-step" style="border:1px solid #e5e7eb;border-radius:8px;padding:14px;background:#fff;transition:all .3s;">
                            <div style="display:flex;align-items:center;gap:8px;margin-bottom:8px;">
                                <div id="dba-lsi-icon-dalle" style="width:28px;height:28px;border-radius:50%;border:2px solid #cbd5e1;display:flex;align-items:center;justify-content:center;font-size:12px;font-weight:700;color:#94a3b8;transition:all .3s;">3</div>
                                <span style="font-size:12px;font-weight:700;color:#475569;">DALL-E</span>
                            </div>
                            <div style="font-size:11px;color:#64748b;">Featured Image (landscape)</div>
                            <div id="dba-lsi-detail-dalle" style="font-size:10px;color:#94a3b8;margin-top:4px;min-height:14px;"></div>
                            <div style="margin-top:8px;background:#e5e7eb;border-radius:3px;height:4px;overflow:hidden;">
                                <div id="dba-lsi-bar-dalle" style="background:#8b5cf6;height:100%;width:0%;transition:width .4s;border-radius:3px;"></div>
                            </div>
                        </div>
                    </div>

                    <!-- Live status line -->
                    <div id="dba-lsi-live-status" style="margin-top:12px;padding:8px 12px;background:#f8fafc;border-radius:4px;font-size:11px;color:#64748b;font-family:monospace;min-height:18px;"></div>
                </div>

                <style>
                    @keyframes lsi-shimmer { 0%{transform:translateX(-100%)} 100%{transform:translateX(200%)} }
                    @keyframes lsi-pulse { 0%,100%{box-shadow:0 0 0 0 rgba(59,130,246,.3)} 50%{box-shadow:0 0 0 6px rgba(59,130,246,0)} }
                    .dba-lsi-step-active { border-color:#3b82f6 !important; background:#eff6ff !important; }
                    .dba-lsi-step-done { border-color:#10b981 !important; }
                    .dba-lsi-step-error { border-color:#ef4444 !important; background:#fef2f2 !important; }
                    .dba-lsi-icon-active { border-color:#3b82f6 !important; color:#3b82f6 !important; background:#eff6ff; animation:lsi-pulse 1.5s infinite; }
                    .dba-lsi-icon-done { border-color:#10b981 !important; color:#fff !important; background:#10b981 !important; }
                    .dba-lsi-icon-error { border-color:#ef4444 !important; color:#fff !important; background:#ef4444 !important; }
                </style>
            </div>

            <!-- DALL-E PROMPT POOL REFERENCE -->
            <div style="background:#f5f3ff;border:1px solid #c4b5fd;border-radius:8px;padding:24px;margin:20px 0;max-width:900px;">
                <h2 style="margin-top:0;">DALL-E Prompt Pool (<?php echo count( DBA_LuxStrat_Intl_Generator::get_dalle_prompt_pool() ); ?> variants)</h2>
                <p style="font-size:13px;color:#555;">One prompt is selected <strong>randomly</strong> per generation. All images: <code>1792×1024</code> (landscape) via DALL-E 3.</p>
                <div style="display:flex;flex-wrap:wrap;gap:8px;margin-top:10px;">
                    <?php foreach ( DBA_LuxStrat_Intl_Generator::get_dalle_prompt_pool() as $key => $prompt ) : ?>
                    <span style="font-size:11px;padding:4px 12px;background:#ede9fe;border:1px solid #c4b5fd;border-radius:20px;color:#6d28d9;cursor:help;" title="<?php echo esc_attr( mb_substr( $prompt, 0, 200 ) ) . '...'; ?>">
                        <?php echo esc_html( ucwords( str_replace( '_', ' ', $key ) ) ); ?>
                    </span>
                    <?php endforeach; ?>
                </div>
            </div>

            <!-- INBOUND LINK SCANNER -->
            <div style="background:#f0f7ff;border:1px solid #b3d4fc;border-radius:8px;padding:24px;margin:20px 0;max-width:900px;">
                <h2 style="margin-top:0;">Inbound Link Scanner — Internal Linking</h2>
                <p style="font-size:13px;color:#555;">
                    Injects internal links <strong>into selected posts</strong> pointing to theme pillar pages (SOPARFI, SPF, RAIF, etc.).
                    Max <?php echo DBA_LuxStrat_Intl_Inbound::MAX_LINKS_PER_POST; ?> auto-links per post. Only the selected post is modified.
                </p>

                <?php
                // Stats
                $inbound_stats  = get_option( 'dba_luxstrat_' . $lang . '_inbound_stats', array() );
                $total_orphans  = 0;
                $total_linked   = 0;
                foreach ( $inbound_report as $pid => $info ) {
                    if ( $info['inbound'] === 0 && $info['status'] === 'publish' ) $total_orphans++;
                    if ( $info['inbound'] > 0 ) $total_linked++;
                }
                ?>

                <!-- Stats bar -->
                <div style="display:flex;gap:12px;margin:14px 0;flex-wrap:wrap;">
                    <div style="padding:8px 14px;background:#dcfce7;border-radius:6px;font-size:13px;">
                        Linked: <strong style="color:#166534;"><?php echo $total_linked; ?></strong>
                    </div>
                    <div style="padding:8px 14px;background:<?php echo $total_orphans > 0 ? '#fee2e2' : '#dcfce7'; ?>;border-radius:6px;font-size:13px;">
                        Orphans: <strong style="color:<?php echo $total_orphans > 0 ? '#991b1b' : '#166534'; ?>;"><?php echo $total_orphans; ?></strong>
                    </div>
                    <div style="padding:8px 14px;background:#f0f4ff;border-radius:6px;font-size:13px;">
                        Total posts: <strong><?php echo count( $all_lsi_posts ); ?></strong>
                    </div>
                    <?php if ( ! empty( $inbound_stats['last_run'] ) ) : ?>
                    <div style="padding:8px 14px;background:#f5f5f5;border-radius:6px;font-size:12px;color:#888;">
                        Last scan: <?php echo esc_html( $inbound_stats['last_run'] ); ?>
                    </div>
                    <?php endif; ?>
                </div>

                <!-- Inbound Report Table -->
                <?php if ( ! empty( $inbound_report ) ) : ?>
                <div style="max-height:350px;overflow-y:auto;border:1px solid #ddd;border-radius:6px;margin:14px 0;">
                    <table class="widefat striped" style="font-size:12px;">
                        <thead style="position:sticky;top:0;background:#f0f7ff;z-index:1;">
                            <tr>
                                <th style="width:30px;"><input type="checkbox" id="dba-lsi-check-all" title="Select all"></th>
                                <th>Post</th>
                                <th style="width:80px;">Theme</th>
                                <th style="width:60px;text-align:center;">Links</th>
                                <th style="width:60px;">Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ( $inbound_report as $pid => $info ) :
                                $is_orphan = ( $info['inbound'] === 0 && $info['status'] === 'publish' );
                            ?>
                            <tr style="<?php echo $is_orphan ? 'background:#fff5f5;' : ''; ?>">
                                <td><input type="checkbox" class="dba-lsi-target-cb" value="<?php echo (int) $pid; ?>" <?php checked( $is_orphan ); ?>></td>
                                <td>
                                    <a href="<?php echo get_edit_post_link( $pid ); ?>" target="_blank" style="font-size:12px;"><?php echo esc_html( mb_strimwidth( $info['title'], 0, 60, '...' ) ); ?></a>
                                    <br><span style="color:#999;font-size:11px;"><?php echo esc_html( $info['date'] ); ?></span>
                                </td>
                                <td><span style="padding:2px 8px;border-radius:10px;background:#f0f4ff;font-size:11px;"><?php echo esc_html( $info['theme'] ); ?></span></td>
                                <td style="text-align:center;">
                                    <?php if ( $info['inbound'] === 0 && $info['status'] === 'publish' ) : ?>
                                        <span style="color:#991b1b;font-weight:700;">0 ⚠️</span>
                                    <?php elseif ( $info['inbound'] <= 2 ) : ?>
                                        <span style="color:#b45309;font-weight:600;"><?php echo $info['inbound']; ?></span>
                                    <?php else : ?>
                                        <span style="color:#166534;font-weight:600;"><?php echo $info['inbound']; ?></span>
                                    <?php endif; ?>
                                </td>
                                <td><span style="font-size:11px;"><?php echo esc_html( $info['status'] ); ?></span></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <p style="font-size:11px;color:#888;margin:4px 0;">
                    <strong>Red rows</strong> = posts with 0 auto-injected links (published). Pre-selected for linking.
                    Check/uncheck to control which posts get new links injected into them.
                </p>
                <?php endif; ?>

                <div id="dba-lsi-scan-result" style="margin:10px 0;"></div>
                <div id="dba-lsi-scan-progress" style="display:none;margin:10px 0;">
                    <div style="background:#e5e7eb;border-radius:4px;height:24px;overflow:hidden;">
                        <div id="dba-lsi-scan-bar" style="background:#3b82f6;height:100%;width:0%;transition:width .3s;display:flex;align-items:center;justify-content:center;color:#fff;font-size:12px;font-weight:600;">0%</div>
                    </div>
                    <p id="dba-lsi-scan-status" style="font-size:12px;color:#666;margin:4px 0;"></p>
                </div>
                <div style="display:flex;gap:10px;flex-wrap:wrap;">
                    <button id="dba-lsi-scan-selected" class="button button-primary" style="background:#16a34a;border-color:#15803d;">🎯 Scan & Link Selected Posts</button>
                    <button id="dba-lsi-scan" class="button button-primary" style="background:#3b82f6;border-color:#2563eb;">Scan & Link ALL (<?php echo strtoupper( $lang ); ?>)</button>
                    <button id="dba-lsi-strip-selected" class="button" style="color:#b45309;border-color:#b45309;">🔄 Strip Selected Inbound Links</button>
                    <button id="dba-lsi-strip" class="button" style="color:#b32d2e;border-color:#b32d2e;">Strip All Inbound Links</button>
                </div>
            </div>

            <!-- ENRICH / REPAIR RECENT POSTS -->
            <div style="background:#fff;border:1px solid #ddd;border-radius:8px;padding:24px;margin:20px 0;max-width:900px;">
                <h2 style="margin-top:0;">Enrich &amp; Repair Recent Posts</h2>
                <p style="font-size:13px;color:#555;">
                    Processes <strong>recent</strong> <?php echo strtoupper( $lang ); ?> LuxStrat posts only. Adds missing DALL-E featured images and SEO meta.
                </p>

                <!-- SCOPE SELECTOR -->
                <div style="display:flex;align-items:center;gap:12px;margin:14px 0;padding:12px 16px;background:#f0f4ff;border:1px solid #b3d4fc;border-radius:6px;">
                    <label style="font-size:13px;font-weight:600;color:#1e3a5f;">Scope:</label>
                    <select id="dba-lsi-enrich-days" style="padding:6px 12px;border:1px solid #b3d4fc;border-radius:4px;font-size:13px;font-weight:600;">
                        <option value="1">Last 24 hours</option>
                        <option value="2">Last 2 days</option>
                        <option value="4" selected>Last 4 days</option>
                        <option value="7">Last 7 days</option>
                        <option value="14">Last 14 days</option>
                        <option value="30">Last 30 days</option>
                    </select>
                    <span style="font-size:12px;color:#666;">Currently <strong><?php echo $recent_count; ?></strong> posts in last 4 days</span>
                </div>

                <div style="display:flex;gap:20px;margin:12px 0;">
                    <div style="padding:10px 16px;background:#fef3c7;border-radius:6px;font-size:13px;">Missing images (last 4d): <strong><?php echo $missing_images; ?></strong></div>
                    <div style="padding:10px 16px;background:#fef3c7;border-radius:6px;font-size:13px;">Missing SEO (last 4d): <strong><?php echo $missing_seo; ?></strong></div>
                </div>

                <div id="dba-lsi-enrich-result" style="margin:10px 0;"></div>
                <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;">
                    <button id="dba-lsi-enrich" class="button button-primary button-hero" style="background:#7c3aed;border-color:#6d28d9;width:100%;">Enrich Recent Posts (Images + SEO)</button>
                    <button id="dba-lsi-repair" class="button button-primary button-hero" style="background:#ec4899;border-color:#db2777;width:100%;">Repair Recent Posts (Images + SEO)</button>
                </div>
                <div id="dba-lsi-repair-result" style="margin:10px 0;"></div>
            </div>

            <!-- EMERGENCY CONTROLS -->
            <div style="background:#fff;border:1px solid #ddd;border-radius:8px;padding:24px;margin:20px 0;max-width:900px;">
                <h2 style="margin-top:0;">Emergency Controls</h2>
                <div id="dba-lsi-emergency-result" style="margin:10px 0;"></div>
                <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;">
                    <button id="dba-lsi-stop" class="button button-hero" style="background:#ef4444;border-color:#dc2626;color:#fff;width:100%;font-weight:700;">STOP</button>
                    <button id="dba-lsi-fullreset" class="button button-hero" style="background:#3b82f6;border-color:#2563eb;color:#fff;width:100%;font-weight:700;">RESET</button>
                </div>
                <p style="font-size:12px;color:#888;margin-top:8px;">STOP halts running operations. RESET clears rotation, daily locks, reschedules cron.</p>
            </div>

            <!-- RECENT POSTS -->
            <div style="background:#fff;border:1px solid #ddd;border-radius:8px;padding:24px;margin:20px 0;max-width:900px;">
                <h2 style="margin-top:0;">Recent Posts (<?php echo strtoupper( $lang ); ?>)</h2>
                <?php if ( $recent_posts->have_posts() ) : ?>
                <table class="widefat striped" style="font-size:13px;">
                    <thead><tr><th>Date</th><th>Title</th><th>Theme</th><th>Words</th><th>Img</th><th>SEO</th><th>Status</th></tr></thead>
                    <tbody>
                        <?php while ( $recent_posts->have_posts() ) : $recent_posts->the_post(); $pid = get_the_ID(); ?>
                        <tr>
                            <td><?php echo get_the_date( 'Y-m-d H:i' ); ?></td>
                            <td><a href="<?php echo get_edit_post_link(); ?>" target="_blank"><?php the_title(); ?></a></td>
                            <td><span style="padding:2px 8px;border-radius:10px;background:#f0f4ff;font-size:11px;"><?php echo esc_html( get_post_meta( $pid, $prefix . 'theme_label', true ) ); ?></span></td>
                            <td><?php echo esc_html( get_post_meta( $pid, $prefix . 'word_count', true ) ); ?></td>
                            <td><?php echo has_post_thumbnail( $pid ) ? 'Y' : 'N'; ?></td>
                            <td><?php echo ! empty( get_post_meta( $pid, '_yoast_wpseo_metadesc', true ) ) ? 'Y' : 'N'; ?></td>
                            <td><?php echo get_post_status(); ?></td>
                        </tr>
                        <?php endwhile; wp_reset_postdata(); ?>
                    </tbody>
                </table>
                <?php else : ?>
                    <p style="color:#888;">No posts yet.</p>
                <?php endif; ?>
            </div>

            <!-- THEME REFERENCE -->
            <!-- ══════════════════════════════════════════════════════════════ -->
            <!--  🧠 KAIZEN LEARNING ENGINE                                   -->
            <!-- ══════════════════════════════════════════════════════════════ -->
            <?php
            $kz_loaded = class_exists( 'DBA_LuxStrat_Intl_Kaizen' );
            ?>
            <div style="background:<?php echo $kz_loaded ? '#faf5ff' : '#fef2f2'; ?>;border:1px solid <?php echo $kz_loaded ? '#d8b4fe' : '#fca5a5'; ?>;border-left:4px solid <?php echo $kz_loaded ? '#9333ea' : '#dc2626'; ?>;border-radius:6px;padding:18px 22px;margin:20px 0;max-width:900px;">
                <h2 style="margin-top:0;color:<?php echo $kz_loaded ? '#6b21a8' : '#991b1b'; ?>;">🧠 Kaizen Learning — <?php echo $kz_loaded ? '<span style="color:#6b21a8;">ACTIVE ✓</span> <span style="font-size:12px;font-weight:normal;color:#888;">WPML lang: ' . strtoupper( esc_html( $lang ) ) . '</span>' : '<span style="color:#991b1b;">NOT LOADED</span>'; ?></h2>
                <?php if ( $kz_loaded ) : ?>
                <table class="widefat" style="border:none;background:transparent;">
                    <?php
                    $kz_corrections = DBA_LuxStrat_Intl_Kaizen::detect_corrections( $lang );
                    $kz_overused    = DBA_LuxStrat_Intl_Kaizen::get_overused_transitions( $lang );
                    ?>
                    <tr>
                        <td style="padding:8px 6px;width:220px;"><strong><?php echo ! empty( $kz_corrections ) ? '🔍' : '✅'; ?> Editor Corrections</strong></td>
                        <td style="padding:8px 6px;"><?php echo count( $kz_corrections ); ?> corrections (<?php echo strtoupper( $lang ); ?>, last 14d)
                            <?php foreach ( array_slice( $kz_corrections, 0, 3 ) as $co ) : ?>
                                <br><span style="font-size:11px;color:#666;">• <?php echo esc_html( strtoupper( str_replace( '_', ' ', $co['type'] ) ) . ' [' . $co['theme'] . ']: ' . $co['detail'] ); ?></span>
                            <?php endforeach; ?>
                        </td>
                    </tr>
                    <tr>
                        <td style="padding:8px 6px;"><strong><?php echo ! empty( $kz_overused ) ? '⚠️' : '✅'; ?> Overused Transitions</strong></td>
                        <td style="padding:8px 6px;"><?php echo ! empty( $kz_overused ) ? '✗ ' . esc_html( implode( ', ', $kz_overused ) ) : 'None — vocabulary is varied ✓'; ?></td>
                    </tr>
                    <tr>
                        <td style="padding:8px 6px;"><strong>🔄 Cache</strong></td>
                        <td style="padding:8px 6px;">
                            <button type="button" id="dba-lsi-flush-kaizen" class="button button-small">Flush Kaizen Cache (<?php echo strtoupper( $lang ); ?>)</button>
                            <span id="dba-lsi-kaizen-status" style="font-size:12px;margin-left:8px;"></span>
                        </td>
                    </tr>
                </table>
                <?php endif; ?>
            </div>

            <!-- ══════════════════════════════════════════════════════════════ -->
            <!--  🛡️ ANTI-ORPHAN PROTECTION                                   -->
            <!-- ══════════════════════════════════════════════════════════════ -->
            <?php
            $ao_loaded = class_exists( 'DBA_LuxStrat_Intl_Anti_Orphan' );
            $ao_stats = $ao_loaded ? DBA_LuxStrat_Intl_Anti_Orphan::get_orphan_stats( $lang ) : array( 'total' => 0, 'linked' => 0, 'auth_linked' => 0, 'orphan_count' => 0, 'orphans' => array() );
            $ao_orphan_count = $ao_stats['orphan_count'];
            ?>
            <div style="background:<?php echo $ao_orphan_count > 0 ? '#fffbeb' : '#f0fdf4'; ?>;border:1px solid <?php echo $ao_orphan_count > 0 ? '#fcd34d' : '#86efac'; ?>;border-left:4px solid <?php echo $ao_orphan_count > 0 ? '#f59e0b' : '#22c55e'; ?>;border-radius:6px;padding:18px 22px;margin:20px 0;max-width:900px;">
                <h2 style="margin-top:0;color:<?php echo $ao_orphan_count > 0 ? '#92400e' : '#166534'; ?>;">🛡️ Anti-Orphan (<?php echo strtoupper( $lang ); ?>) — <?php
                    if ( ! $ao_loaded ) {
                        echo '<span style="color:#991b1b;">NOT LOADED</span>';
                    } elseif ( $ao_orphan_count > 0 ) {
                        echo '<span style="color:#c2410c;">' . $ao_orphan_count . ' ORPHAN' . ( $ao_orphan_count > 1 ? 'S' : '' ) . '</span>';
                    } else {
                        echo '<span style="color:#166534;">ALL ' . $ao_stats['total'] . ' POSTS LINKED ✓</span>';
                    }
                ?></h2>
                <table class="widefat" style="border:none;background:transparent;">
                    <tr>
                        <td style="padding:8px 6px;width:220px;"><strong><?php echo $ao_orphan_count === 0 ? '✅' : '⚠️'; ?> Cross-Theme Links</strong></td>
                        <td style="padding:8px 6px;"><?php echo $ao_stats['linked']; ?>/<?php echo $ao_stats['total']; ?> posts cross-linked
                            <?php if ( $ao_orphan_count > 0 ) : ?> — <span style="color:#c2410c;font-weight:bold;"><?php echo $ao_orphan_count; ?> orphans</span><?php endif; ?>
                        </td>
                    </tr>
                    <tr>
                        <td style="padding:8px 6px;"><strong><?php echo $ao_stats['auth_linked'] > 0 ? '✅' : '⚠️'; ?> 🏛️ Authority Links</strong></td>
                        <td style="padding:8px 6px;"><?php echo $ao_stats['auth_linked']; ?>/<?php echo $ao_stats['total']; ?> posts → CSSF, Guichet.lu, RCS, ACD, Legilux</td>
                    </tr>
                </table>

                <?php if ( ! empty( $ao_stats['orphans'] ) ) : ?>
                <div style="background:#fff;border:1px solid #fcd34d;border-radius:4px;padding:8px 12px;margin:10px 0;max-height:150px;overflow-y:auto;font-size:12px;">
                    <?php foreach ( $ao_stats['orphans'] as $ao_item ) : ?>
                        <div style="padding:2px 0;border-bottom:1px solid #fef3c7;">❌ <a href="<?php echo admin_url( 'post.php?post=' . $ao_item['id'] . '&action=edit' ); ?>" target="_blank">#<?php echo $ao_item['id']; ?> — <?php echo esc_html( $ao_item['title'] ); ?></a></div>
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>

                <?php if ( $ao_orphan_count > 0 && $ao_loaded ) : ?>
                <div style="margin-top:10px;">
                    <button type="button" id="dba-lsi-run-audit" class="button button-primary button-small">🛡️ Fix All Orphans (<?php echo $ao_orphan_count; ?>)</button>
                    <span id="dba-lsi-audit-status" style="font-size:12px;margin-left:8px;"></span>
                </div>
                <?php endif; ?>
            </div>

            <div style="background:#fff;border:1px solid #ddd;border-radius:8px;padding:24px;margin:20px 0;max-width:900px;">
                <h2 style="margin-top:0;">Themes</h2>
                <?php foreach ( $themes as $slug => $tc ) : ?>
                <div style="margin-bottom:14px;padding:10px;border-left:4px solid <?php echo esc_attr( $tc['color'] ?? '#666' ); ?>;background:#fafafa;">
                    <strong><?php echo esc_html( $tc['label'] ); ?></strong>
                    <br><span style="font-size:12px;color:#666;"><?php echo esc_html( $tc['description'] ?? '' ); ?></span>
                    <br><code style="font-size:11px;"><?php echo esc_html( $slug ); ?></code>
                    <span style="font-size:11px;color:#999;margin-left:10px;">Categories: <?php echo esc_html( implode( ', ', $tc['category_slugs'] ?? array() ) ); ?></span>
                </div>
                <?php endforeach; ?>
            </div>
        </div>

        <script>
        jQuery(function($) {
            var nonce = '<?php echo wp_create_nonce("dba_admin_nonce"); ?>';
            var lang  = '<?php echo esc_js($lang); ?>';

            $('#dba-lsi-form').on('submit', function(e) {
                e.preventDefault();
                var $btn = $('#dba-lsi-save').prop('disabled', true).text('Saving...');
                var themes = []; $('input[name="lsi_themes[]"]:checked').each(function(){ themes.push($(this).val()); });
                var cats = []; $('input[name="lsi_extra_cats[]"]:checked').each(function(){ cats.push(parseInt($(this).val())); });
                $.post(ajaxurl, {
                    action:'dba_luxstrat_intl_save', nonce:nonce, lang:lang,
                    enabled: $('input[name="lsi_enabled"]').is(':checked') ? 1 : 0,
                    active_themes:themes, extra_category_ids:cats,
                    post_status: $('select[name="lsi_post_status"]').val(),
                    author_id: $('select[name="lsi_author_id"]').val(),
                    category_id: $('select[name="lsi_category_id"]').val(),
                    word_count_min: $('input[name="lsi_word_min"]').val(),
                    word_count_max: $('input[name="lsi_word_max"]').val(),
                    cta_text: $('textarea[name="lsi_cta_text"]').val(),
                    cta_link_text: $('input[name="lsi_cta_link_text"]').val(),
                    cta_link_url: $('input[name="lsi_cta_link_url"]').val()
                }, function(r) {
                    $btn.prop('disabled',false).text('Save Settings');
                    $('#dba-lsi-save-result').html(r.success ? '<div class="notice notice-success inline"><p>Saved.</p></div>' : '<div class="notice notice-error inline"><p>'+(r.data||'Error')+'</p></div>');
                });
            });

            $('#dba-lsi-run').on('click', function() {
                if(!confirm('Generate a '+lang.toUpperCase()+' post now? (Post + SEO + DALL-E image)')) return;
                var $btn=$(this).prop('disabled',true).text('Generating...');
                $('#dba-lsi-action-result').html('');
                $('#dba-lsi-pipeline').show();

                // Reset progress UI
                resetPipeline();

                // Start progress polling
                var pollInterval = setInterval(function(){
                    $.post(ajaxurl,{action:'dba_luxstrat_intl_progress',nonce:nonce,lang:lang},function(r){
                        if(r.success && r.data) updatePipeline(r.data);
                    });
                }, 1500);

                $.ajax({url:ajaxurl,type:'POST',timeout:180000,
                    data:{action:'dba_luxstrat_intl_run',nonce:nonce,lang:lang},
                    success:function(r){
                        clearInterval(pollInterval);
                        $btn.prop('disabled',false).text('▶ Generate Now (Post + SEO + DALL-E Image)');
                        if(r.success){
                            var d=r.data;
                            updatePipeline({phase:'done',percent:100,detail:'Post #'+d.post_id+' — '+d.title+' ('+d.words+' words)'});
                            $('#dba-lsi-action-result').html('<div class="notice notice-success inline"><p>✅ <a href="'+d.edit_url+'" target="_blank">#'+d.post_id+' — '+d.title+'</a> ('+d.words+' words)</p></div>');
                        } else {
                            updatePipeline({phase:'error',percent:0,detail:r.data||'Error'});
                            $('#dba-lsi-action-result').html('<div class="notice notice-error inline"><p>❌ '+(r.data||'Error')+'</p></div>');
                        }
                    },
                    error:function(){
                        clearInterval(pollInterval);
                        $btn.prop('disabled',false).text('▶ Generate Now (Post + SEO + DALL-E Image)');
                        updatePipeline({phase:'error',percent:0,detail:'Request timed out'});
                        $('#dba-lsi-action-result').html('<div class="notice notice-error inline"><p>Request failed / timed out</p></div>');
                    }
                });
            });

            /* ── Pipeline Progress UI Helpers ── */
            function resetPipeline(){
                $('#dba-lsi-pct-bar').css('width','0%');
                $('#dba-lsi-pct-text').text('0%').css('color','#2563eb');
                ['content','seo','dalle'].forEach(function(s){
                    $('#dba-lsi-step-'+s).removeClass('dba-lsi-step-active dba-lsi-step-done dba-lsi-step-error');
                    $('#dba-lsi-icon-'+s).removeClass('dba-lsi-icon-active dba-lsi-icon-done dba-lsi-icon-error');
                    $('#dba-lsi-bar-'+s).css('width','0%');
                    $('#dba-lsi-detail-'+s).text('');
                });
                $('#dba-lsi-live-status').text('Starting pipeline...');
            }

            function updatePipeline(d){
                var phase=d.phase, pct=d.percent, detail=d.detail||'';

                // Overall bar
                $('#dba-lsi-pct-bar').css('width',pct+'%');
                $('#dba-lsi-pct-text').text(pct+'%');

                // Phase mapping: which phases are done/active
                var phases=['content','seo','dalle'];
                var phaseIndex = phases.indexOf(phase);

                // If done or error, handle specially
                if(phase==='done'){
                    phases.forEach(function(s){
                        $('#dba-lsi-step-'+s).removeClass('dba-lsi-step-active dba-lsi-step-error').addClass('dba-lsi-step-done');
                        $('#dba-lsi-icon-'+s).removeClass('dba-lsi-icon-active dba-lsi-icon-error').addClass('dba-lsi-icon-done').html('✓');
                        $('#dba-lsi-bar-'+s).css('width','100%');
                    });
                    $('#dba-lsi-pct-text').text('100%').css('color','#10b981');
                    $('#dba-lsi-pct-bar').css('background','linear-gradient(90deg,#10b981,#059669)');
                    $('#dba-lsi-live-status').html('✅ ' + detail);
                    return;
                }
                if(phase==='error'){
                    if(phaseIndex<0) phaseIndex=0;
                    $('#dba-lsi-step-'+phases[Math.min(phaseIndex,2)]).addClass('dba-lsi-step-error');
                    $('#dba-lsi-icon-'+phases[Math.min(phaseIndex,2)]).addClass('dba-lsi-icon-error').html('✕');
                    $('#dba-lsi-live-status').html('❌ ' + detail);
                    return;
                }

                // Mark completed phases
                for(var i=0;i<phaseIndex;i++){
                    $('#dba-lsi-step-'+phases[i]).removeClass('dba-lsi-step-active').addClass('dba-lsi-step-done');
                    $('#dba-lsi-icon-'+phases[i]).removeClass('dba-lsi-icon-active').addClass('dba-lsi-icon-done').html('✓');
                    $('#dba-lsi-bar-'+phases[i]).css('width','100%');
                }

                // Mark active phase
                if(phaseIndex>=0 && phaseIndex<phases.length){
                    var activePhase=phases[phaseIndex];
                    $('#dba-lsi-step-'+activePhase).addClass('dba-lsi-step-active').removeClass('dba-lsi-step-done');
                    $('#dba-lsi-icon-'+activePhase).addClass('dba-lsi-icon-active').removeClass('dba-lsi-icon-done');

                    // Phase-local progress bars
                    var localPct=0;
                    if(phase==='content') localPct = Math.min(100, Math.round((pct/35)*100));
                    else if(phase==='seo') localPct = Math.min(100, Math.round(((pct-35)/35)*100));
                    else if(phase==='dalle') localPct = Math.min(100, Math.round(((pct-70)/30)*100));
                    $('#dba-lsi-bar-'+activePhase).css('width', Math.max(5,localPct)+'%');
                    $('#dba-lsi-detail-'+activePhase).text(detail.length>60 ? detail.substr(0,57)+'...' : detail);
                }

                // Pending phases
                for(var j=phaseIndex+1;j<phases.length;j++){
                    $('#dba-lsi-step-'+phases[j]).removeClass('dba-lsi-step-active dba-lsi-step-done');
                    $('#dba-lsi-icon-'+phases[j]).removeClass('dba-lsi-icon-active dba-lsi-icon-done');
                }

                $('#dba-lsi-live-status').text(d.time ? '['+d.time+'] '+detail : detail);
            }

            $('#dba-lsi-reset').on('click', function() {
                if(!confirm('Reset '+lang.toUpperCase()+' rotation?')) return;
                $.post(ajaxurl,{action:'dba_luxstrat_intl_reset',nonce:nonce,lang:lang},function(r){
                    if(r.success) $('#dba-lsi-action-result').html('<div class="notice notice-success inline"><p>Reset done.</p></div>');
                });
            });

            /* INBOUND SCAN — select-all checkbox */
            $('#dba-lsi-check-all').on('change', function() {
                $('.dba-lsi-target-cb').prop('checked', $(this).prop('checked'));
            });

            /* INBOUND SCAN — targeted (selected posts only) */
            $('#dba-lsi-scan-selected').on('click', function() {
                var selected = [];
                $('.dba-lsi-target-cb:checked').each(function() { selected.push($(this).val()); });
                if(selected.length === 0) {
                    $('#dba-lsi-scan-result').html('<div class="notice notice-warning inline"><p>No posts selected. Check the posts you want to add inbound links for.</p></div>');
                    return;
                }
                if(!confirm('Scan site and add inbound links for '+selected.length+' selected '+lang.toUpperCase()+' post(s)?')) return;
                var $btn=$(this).prop('disabled',true).text('Scanning...');
                var $prog=$('#dba-lsi-scan-progress').show();
                var totalLinked=0;
                function batch(offset){
                    $.post(ajaxurl,{action:'dba_luxstrat_intl_scan',nonce:nonce,lang:lang,offset:offset,target_ids:selected.join(',')},function(r){
                        if(!r.success){$btn.prop('disabled',false).text('🎯 Scan & Link Selected Posts');$prog.hide();$('#dba-lsi-scan-result').html('<div class="notice notice-error inline"><p>'+(r.data||'Error')+'</p></div>');return;}
                        var d=r.data; totalLinked+=d.linked;
                        var pct=d.total>0?Math.min(100,Math.round((d.offset/d.total)*100)):100;
                        $('#dba-lsi-scan-bar').css('width',pct+'%').text(pct+'%');
                        var status='Processed '+Math.min(d.offset,d.total)+'/'+d.total+' - Linked: '+totalLinked;
                        if(d.orphans_fixed>0) status+=' - Orphans fixed: '+d.orphans_fixed;
                        $('#dba-lsi-scan-status').text(status);
                        if(d.done){
                            $btn.prop('disabled',false).text('🎯 Scan & Link Selected Posts');
                            var msg='Done! Scanned '+d.total+' posts, linked '+totalLinked+' ('+d.keywords+' keywords)';
                            if(d.orphans_found>0) msg+='. Orphans found: '+d.orphans_found+', fixed: '+d.orphans_fixed;
                            $('#dba-lsi-scan-result').html('<div class="notice notice-success inline"><p>'+msg+'</p></div>');
                            setTimeout(function(){$prog.hide();},2000);
                            setTimeout(function(){location.reload();},2500);
                        } else {setTimeout(function(){batch(d.offset);},500);}
                    }).fail(function(){$btn.prop('disabled',false).text('🎯 Scan & Link Selected Posts');$prog.hide();});
                }
                batch(0);
            });

            /* INBOUND SCAN — full site (batch) */
            $('#dba-lsi-scan').on('click', function() {
                if(!confirm('Scan entire site and auto-link '+lang.toUpperCase()+' keywords?')) return;
                var $btn=$(this).prop('disabled',true).text('Scanning...');
                var $prog=$('#dba-lsi-scan-progress').show();
                var totalLinked=0;
                function batch(offset){
                    $.post(ajaxurl,{action:'dba_luxstrat_intl_scan',nonce:nonce,lang:lang,offset:offset},function(r){
                        if(!r.success){$btn.prop('disabled',false).text('Scan & Link ALL');$prog.hide();$('#dba-lsi-scan-result').html('<div class="notice notice-error inline"><p>'+(r.data||'Error')+'</p></div>');return;}
                        var d=r.data; totalLinked+=d.linked;
                        var pct=d.total>0?Math.min(100,Math.round((d.offset/d.total)*100)):100;
                        $('#dba-lsi-scan-bar').css('width',pct+'%').text(pct+'%');
                        $('#dba-lsi-scan-status').text('Processed '+Math.min(d.offset,d.total)+'/'+d.total+' - Linked: '+totalLinked);
                        if(d.done){$btn.prop('disabled',false).text('Scan & Link ALL');
                            var msg='Done! Scanned '+d.total+' posts, linked '+totalLinked+' ('+d.keywords+' keywords)';
                            if(d.orphans_found>0) msg+='. Orphans found: '+d.orphans_found+', fixed: '+d.orphans_fixed;
                            $('#dba-lsi-scan-result').html('<div class="notice notice-success inline"><p>'+msg+'</p></div>');setTimeout(function(){$prog.hide();},2000);
                            setTimeout(function(){location.reload();},2500);}
                        else{setTimeout(function(){batch(d.offset);},500);}
                    }).fail(function(){$btn.prop('disabled',false).text('Scan & Link ALL');$prog.hide();});
                }
                batch(0);
            });

            /* STRIP SELECTED — remove inbound links only for checked posts */
            $('#dba-lsi-strip-selected').on('click', function() {
                var selected = [];
                $('.dba-lsi-target-cb:checked').each(function() { selected.push($(this).val()); });
                if(selected.length === 0) {
                    $('#dba-lsi-scan-result').html('<div class="notice notice-warning inline"><p>No posts selected.</p></div>');
                    return;
                }
                if(!confirm('Remove all inbound links pointing to '+selected.length+' selected post(s)? This only strips links to these targets, not all links.')) return;
                var $btn=$(this).prop('disabled',true).text('Stripping...');
                $.post(ajaxurl,{action:'dba_luxstrat_intl_strip_selected',nonce:nonce,lang:lang,target_ids:selected.join(',')},function(r){
                    $btn.prop('disabled',false).text('🔄 Strip Selected Inbound Links');
                    if(r.success){
                        $('#dba-lsi-scan-result').html('<div class="notice notice-success inline"><p>Stripped inbound links from '+r.data.cleaned+' source post(s) for '+selected.length+' target(s).</p></div>');
                        setTimeout(function(){location.reload();},1500);
                    } else {
                        $('#dba-lsi-scan-result').html('<div class="notice notice-error inline"><p>'+(r.data||'Error')+'</p></div>');
                    }
                }).fail(function(){$btn.prop('disabled',false).text('🔄 Strip Selected Inbound Links');});
            });

            $('#dba-lsi-strip').on('click', function() {
                if(!confirm('Remove ALL LuxStrat '+lang.toUpperCase()+' inbound links?')) return;
                var $btn=$(this).prop('disabled',true).text('Stripping...');
                $.post(ajaxurl,{action:'dba_luxstrat_intl_strip',nonce:nonce,lang:lang},function(r){
                    $btn.prop('disabled',false).text('Strip All Inbound Links');
                    $('#dba-lsi-scan-result').html(r.success?'<div class="notice notice-success inline"><p>Stripped from '+r.data.cleaned+' posts.</p></div>':'<div class="notice notice-error inline"><p>'+(r.data||'Error')+'</p></div>');
                });
            });

            /* ENRICH / REPAIR (scoped to recent days) */
            $('#dba-lsi-enrich, #dba-lsi-repair').on('click', function() {
                var days = parseInt($('#dba-lsi-enrich-days').val()) || 4;
                var isRepair = this.id === 'dba-lsi-repair';
                if(!confirm((isRepair ? 'Repair' : 'Enrich') + ' ' + lang.toUpperCase() + ' posts from the last ' + days + ' days?')) return;
                var $btn=$(this).prop('disabled',true); var orig=$btn.text(); $btn.text('Processing...');
                var tgt=isRepair?'#dba-lsi-repair-result':'#dba-lsi-enrich-result';
                $(tgt).html('<div class="notice notice-info inline"><p>Processing posts from last '+days+' days... may take minutes.</p></div>');
                $.ajax({url:ajaxurl,type:'POST',timeout:300000,
                    data:{action:'dba_luxstrat_intl_enrich',nonce:nonce,lang:lang,days:days},
                    success:function(r){$btn.prop('disabled',false).text(orig);
                        if(r.success){var d=r.data;$(tgt).html('<div class="notice notice-success inline"><p>Processed '+d.total+' posts (last '+days+' days). Images: '+d.images_added+', SEO: '+d.seo_fixed+'</p></div>');}
                        else{$(tgt).html('<div class="notice notice-error inline"><p>'+(r.data||'Error')+'</p></div>');}
                    },
                    error:function(){$btn.prop('disabled',false).text(orig);$(tgt).html('<div class="notice notice-error inline"><p>Timeout</p></div>');}
                });
            });

            /* EMERGENCY */
            $('#dba-lsi-stop').on('click', function() {
                if(!confirm('STOP all '+lang.toUpperCase()+' operations?')) return;
                $.post(ajaxurl,{action:'dba_luxstrat_intl_stop',nonce:nonce,lang:lang},function(r){
                    $('#dba-lsi-emergency-result').html(r.success?'<div class="notice notice-warning inline"><p>Stop signal sent.</p></div>':'<div class="notice notice-error inline"><p>'+(r.data||'Error')+'</p></div>');
                });
            });

            /* CUSTOM TITLE QUEUE — ADD */
            $('#dba-lsi-queue-add').on('click', function() {
                var title = $.trim($('#dba-lsi-queue-input').val());
                if(!title) { $('#dba-lsi-queue-result').html('<div class="notice notice-warning inline"><p>Please enter a title.</p></div>'); return; }
                var $btn=$(this).prop('disabled',true).text('Adding...');
                $.ajax({url:ajaxurl,type:'POST',data:{action:'dba_luxstrat_intl_queue_add',nonce:nonce,lang:lang,title:title},contentType:'application/x-www-form-urlencoded; charset=UTF-8',
                    success:function(r){
                        $btn.prop('disabled',false).html('<span style="font-size:14px;">+</span> Add to Queue');
                        if(r.success){
                            $('#dba-lsi-queue-input').val('');
                            $('#dba-lsi-queue-result').html('<div class="notice notice-success inline"><p>Title added to queue (#'+r.data.count+').</p></div>');
                            setTimeout(function(){location.reload();},800);
                        } else {
                            $('#dba-lsi-queue-result').html('<div class="notice notice-error inline"><p>'+(r.data||'Error')+'</p></div>');
                        }
                    },
                    error:function(){$btn.prop('disabled',false).html('<span style="font-size:14px;">+</span> Add to Queue');}
                });
            });
            $('#dba-lsi-queue-input').on('keypress', function(e) { if(e.which===13){e.preventDefault();$('#dba-lsi-queue-add').click();} });

            /* CUSTOM TITLE QUEUE — REMOVE */
            $(document).on('click','.dba-lsi-queue-remove',function(){
                var idx=$(this).data('index');
                if(!confirm('Remove this title from the queue?')) return;
                var $btn=$(this).prop('disabled',true);
                $.post(ajaxurl,{action:'dba_luxstrat_intl_queue_remove',nonce:nonce,lang:lang,index:idx},function(r){
                    if(r.success){ setTimeout(function(){location.reload();},400); }
                    else { alert(r.data||'Error removing title.'); $btn.prop('disabled',false); }
                }).fail(function(){$btn.prop('disabled',false);});
            });

            /* CUSTOM TITLE QUEUE — INLINE EDIT */
            $(document).on('click','.dba-lsi-queue-edit-btn',function(){
                var $tr=$(this).closest('tr');
                $tr.find('.dba-lsi-queue-title-display').hide();
                $tr.find('.dba-lsi-queue-title-edit').show().focus().select();
                $tr.find('.dba-lsi-queue-edit-btn').hide();
                $tr.find('.dba-lsi-queue-save-btn, .dba-lsi-queue-cancel-btn').show();
            });
            $(document).on('click','.dba-lsi-queue-cancel-btn',function(){
                var $tr=$(this).closest('tr');
                var original=$tr.find('.dba-lsi-queue-title-display').text();
                $tr.find('.dba-lsi-queue-title-edit').val(original).hide();
                $tr.find('.dba-lsi-queue-title-display').show();
                $tr.find('.dba-lsi-queue-edit-btn').show();
                $tr.find('.dba-lsi-queue-save-btn, .dba-lsi-queue-cancel-btn').hide();
            });
            $(document).on('click','.dba-lsi-queue-save-btn',function(){
                var $tr=$(this).closest('tr');
                var idx=$(this).data('index');
                var newTitle=$.trim($tr.find('.dba-lsi-queue-title-edit').val());
                if(!newTitle){alert('Title cannot be empty.');return;}
                var $btn=$(this).prop('disabled',true);
                $.ajax({url:ajaxurl,type:'POST',data:{action:'dba_luxstrat_intl_queue_edit',nonce:nonce,lang:lang,index:idx,title:newTitle},contentType:'application/x-www-form-urlencoded; charset=UTF-8',
                    success:function(r){
                        $btn.prop('disabled',false);
                        if(r.success){
                            $tr.find('.dba-lsi-queue-title-display').text(r.data.title).show();
                            $tr.find('.dba-lsi-queue-title-edit').val(r.data.title).hide();
                            $tr.find('.dba-lsi-queue-edit-btn').show();
                            $tr.find('.dba-lsi-queue-save-btn, .dba-lsi-queue-cancel-btn').hide();
                            $('#dba-lsi-queue-result').html('<div class="notice notice-success inline"><p>Title updated.</p></div>');
                            setTimeout(function(){$('#dba-lsi-queue-result').html('');},2000);
                        } else { alert(r.data||'Error saving title.'); }
                    },
                    error:function(){$btn.prop('disabled',false);}
                });
            });
            $(document).on('keypress','.dba-lsi-queue-title-edit',function(e){
                if(e.which===13){e.preventDefault();$(this).closest('tr').find('.dba-lsi-queue-save-btn').click();}
            });
            $(document).on('keydown','.dba-lsi-queue-title-edit',function(e){
                if(e.which===27){$(this).closest('tr').find('.dba-lsi-queue-cancel-btn').click();}
            });

            /* CUSTOM TITLE QUEUE — MOVE UP / DOWN */
            $(document).on('click','.dba-lsi-queue-up, .dba-lsi-queue-down',function(){
                var idx=$(this).data('index');
                var dir=$(this).hasClass('dba-lsi-queue-up')?'up':'down';
                var $btn=$(this).prop('disabled',true);
                $.post(ajaxurl,{action:'dba_luxstrat_intl_queue_move',nonce:nonce,lang:lang,index:idx,direction:dir},function(r){
                    if(r.success){ location.reload(); }
                    else { alert(r.data||'Error moving title.'); $btn.prop('disabled',false); }
                }).fail(function(){$btn.prop('disabled',false);});
            });

            $('#dba-lsi-fullreset').on('click', function() {
                if(!confirm('FULL RESET '+lang.toUpperCase()+'? Clears rotation, locks, reschedules cron.')) return;
                $.post(ajaxurl,{action:'dba_luxstrat_intl_fullreset',nonce:nonce,lang:lang},function(r){
                    $('#dba-lsi-emergency-result').html(r.success?'<div class="notice notice-success inline"><p>Full reset complete.</p></div>':'<div class="notice notice-error inline"><p>'+(r.data||'Error')+'</p></div>');
                });
            });

            // ── Kaizen cache flush ──
            $('#dba-lsi-flush-kaizen').on('click', function(){
                var btn=$(this).prop('disabled',1).text('⏳ Flushing...');
                $.post(ajaxurl, {action:'dba_luxstrat_intl_flush_kaizen', nonce:nonce, lang:lang}, function(r){
                    btn.prop('disabled',0).text('Flush Kaizen Cache ('+lang.toUpperCase()+')');
                    $('#dba-lsi-kaizen-status').html(r.success ? '<span style="color:#166534;">✓ '+r.data+'</span>' : '<span style="color:#991b1b;">✕ '+r.data+'</span>');
                }).fail(function(){ btn.prop('disabled',0); $('#dba-lsi-kaizen-status').html('<span style="color:#991b1b;">✕ Request failed</span>'); });
            });

            // ── Anti-Orphan audit ──
            $('#dba-lsi-run-audit').on('click', function(){
                var btn=$(this).prop('disabled',1).text('🛡️ Fixing...');
                $.post(ajaxurl, {action:'dba_luxstrat_intl_orphan_audit', nonce:nonce, lang:lang}, function(r){
                    btn.prop('disabled',0);
                    if (r.success) {
                        var d=r.data;
                        btn.text('🛡️ Done');
                        $('#dba-lsi-audit-status').html('<span style="color:#166534;">✓ Fixed '+d.fixed+'/'+d.orphaned+' orphans ('+d.total+' total)</span>');
                        if (d.fixed > 0) setTimeout(function(){ location.reload(); }, 2000);
                    } else {
                        btn.text('🛡️ Fix All Orphans');
                        $('#dba-lsi-audit-status').html('<span style="color:#991b1b;">✕ '+(r.data||'Error')+'</span>');
                    }
                }).fail(function(){ btn.prop('disabled',0).text('🛡️ Fix All Orphans'); });
            });
        });
        </script>
        <?php
    }

    /* ══════════════════════════════════════════════════
     *  AJAX HANDLERS
     * ══════════════════════════════════════════════════ */

    public function ajax_save() {
        check_ajax_referer('dba_admin_nonce','nonce');
        if(!current_user_can('manage_options')) wp_send_json_error('Permission denied.');
        $lang=sanitize_key($_POST['lang']??'');
        if(empty($lang)) wp_send_json_error('Missing language.');
        $languages=DBA_LuxStrat_Intl_Loader::get_languages();
        if(!isset($languages[$lang])) wp_send_json_error('Unknown language.');
        $extra_cats=array();
        if(isset($_POST['extra_category_ids'])&&is_array($_POST['extra_category_ids'])){$extra_cats=array_filter(array_map('absint',$_POST['extra_category_ids']));}
        $settings=array(
            'enabled'=>!empty($_POST['enabled']),
            'active_themes'=>isset($_POST['active_themes'])&&is_array($_POST['active_themes'])?array_map('sanitize_key',$_POST['active_themes']):array(),
            'extra_category_ids'=>$extra_cats,
            'post_status'=>sanitize_key($_POST['post_status']??'publish'),
            'author_id'=>absint($_POST['author_id']??1),
            'category_id'=>absint($_POST['category_id']??0),
            'word_count_min'=>max(500,absint($_POST['word_count_min']??1000)),
            'word_count_max'=>max(800,absint($_POST['word_count_max']??1800)),
            'wpml_language'=>$lang,
            'cta_text'=>sanitize_textarea_field($_POST['cta_text']??''),
            'cta_link_text'=>sanitize_text_field($_POST['cta_link_text']??''),
            'cta_link_url'=>esc_url_raw($_POST['cta_link_url']??''),
        );
        update_option('dba_luxstrat_'.$lang.'_settings',$settings);
        if($settings['enabled']){DBA_LuxStrat_Intl_Scheduler::activate_language($lang,$languages[$lang]);}
        wp_send_json_success('Saved.');
    }

    public function ajax_run() {
        check_ajax_referer('dba_admin_nonce','nonce');
        if(!current_user_can('manage_options')) wp_send_json_error('Permission denied.');
        $lang=sanitize_key($_POST['lang']??'');
        // Clear any stale progress
        DBA_LuxStrat_Intl_Generator::clear_progress( $lang );
        DBA_LuxStrat_Intl_Generator::update_progress( $lang, 'content', 2, 'Initialising pipeline...' );
        $scheduler=DBA_LuxStrat_Intl_Scheduler::get_instance();
        $result=$scheduler->manual_run($lang);
        if(is_wp_error($result)) {
            DBA_LuxStrat_Intl_Generator::update_progress( $lang, 'error', 0, $result->get_error_message() );
            wp_send_json_error($result->get_error_message());
        }
        $result['edit_url']=get_edit_post_link($result['post_id'],'raw');
        wp_send_json_success($result);
    }

    public function ajax_progress() {
        check_ajax_referer('dba_admin_nonce','nonce');
        if(!current_user_can('manage_options')) wp_send_json_error('Permission denied.');
        $lang=sanitize_key($_POST['lang']??'');
        if(empty($lang)) wp_send_json_error('Missing language.');
        $progress = DBA_LuxStrat_Intl_Generator::get_progress( $lang );
        if ( $progress ) {
            wp_send_json_success( $progress );
        } else {
            wp_send_json_success( array( 'phase' => 'pending', 'percent' => 0, 'detail' => 'Waiting...' ) );
        }
    }

    public function ajax_reset() {
        check_ajax_referer('dba_admin_nonce','nonce');
        if(!current_user_can('manage_options')) wp_send_json_error('Permission denied.');
        $lang=sanitize_key($_POST['lang']??'');
        delete_option('dba_luxstrat_'.$lang.'_last_theme');
        wp_send_json_success('Reset.');
    }

    public function ajax_scan() {
        check_ajax_referer('dba_admin_nonce','nonce');
        if(!current_user_can('manage_options')) wp_send_json_error('Permission denied.');
        $lang=sanitize_key($_POST['lang']??'');
        $offset=absint($_POST['offset']??0);
        $languages=DBA_LuxStrat_Intl_Loader::get_languages();
        if(!isset($languages[$lang])) wp_send_json_error('Unknown language.');

        // Targeted scan: only build links for specific target post IDs
        $target_ids = array();
        if ( ! empty( $_POST['target_ids'] ) ) {
            $target_ids = array_map( 'absint', explode( ',', sanitize_text_field( $_POST['target_ids'] ) ) );
            $target_ids = array_filter( $target_ids );
        }

        $result=DBA_LuxStrat_Intl_Inbound::scan_batch($lang,$languages[$lang],$offset, $target_ids);
        wp_send_json_success($result);
    }

    public function ajax_strip() {
        check_ajax_referer('dba_admin_nonce','nonce');
        if(!current_user_can('manage_options')) wp_send_json_error('Permission denied.');
        $lang=sanitize_key($_POST['lang']??'');
        $languages=DBA_LuxStrat_Intl_Loader::get_languages();
        if(!isset($languages[$lang])) wp_send_json_error('Unknown language.');
        $cleaned=DBA_LuxStrat_Intl_Inbound::strip_all_links($lang,$languages[$lang]);
        wp_send_json_success(array('cleaned'=>$cleaned));
    }

    public function ajax_strip_selected() {
        check_ajax_referer('dba_admin_nonce','nonce');
        if(!current_user_can('manage_options')) wp_send_json_error('Permission denied.');
        $lang=sanitize_key($_POST['lang']??'');
        if(empty($lang)) wp_send_json_error('Missing language.');
        $target_ids = array();
        if ( ! empty( $_POST['target_ids'] ) ) {
            $target_ids = array_map( 'absint', explode( ',', sanitize_text_field( $_POST['target_ids'] ) ) );
            $target_ids = array_filter( $target_ids );
        }
        if(empty($target_ids)) wp_send_json_error('No posts selected.');
        $cleaned = DBA_LuxStrat_Intl_Inbound::strip_selected_links( $lang, $target_ids );
        wp_send_json_success(array('cleaned'=>$cleaned,'targets'=>count($target_ids)));
    }

    public function ajax_enrich() {
        check_ajax_referer('dba_admin_nonce','nonce');
        if(!current_user_can('manage_options')) wp_send_json_error('Permission denied.');
        $lang=sanitize_key($_POST['lang']??'');
        $days=max(1, min(30, absint($_POST['days']??4))); // 1–30 days, default 4
        $languages=DBA_LuxStrat_Intl_Loader::get_languages();
        if(!isset($languages[$lang])) wp_send_json_error('Unknown language.');

        $prefix = DBA_LuxStrat_Intl_Dedupe::meta_prefix( $lang );

        // ── Switch WPML to target language ──
        $original_lang = null;
        $wpml_switched = false;
        if ( function_exists( 'icl_get_languages' ) ) {
            global $sitepress;
            if ( $sitepress ) {
                $original_lang = $sitepress->get_current_language();
                $sitepress->switch_lang( $lang );
                $wpml_switched = true;
            }
        }

        // ── Query ONLY posts from last N days ──
        $post_ids = get_posts( array(
            'post_type'      => 'post',
            'post_status'    => array( 'publish', 'draft', 'pending' ),
            'posts_per_page' => -1,
            'fields'         => 'ids',
            'meta_query'     => array( array( 'key' => $prefix . 'auto_created', 'compare' => 'EXISTS' ) ),
            'date_query'     => array( array( 'after' => $days . ' days ago' ) ),
            'suppress_filters' => false,
        ) );

        // Restore WPML
        if ( $wpml_switched && isset( $sitepress ) && $sitepress ) {
            $sitepress->switch_lang( $original_lang ?: 'en' );
        }

        error_log( 'LuxStrat[' . $lang . ']: Enrich — ' . count( $post_ids ) . ' posts found in last ' . $days . ' days' );

        if ( empty( $post_ids ) ) {
            wp_send_json_success( array( 'total' => 0, 'images_added' => 0, 'seo_fixed' => 0 ) );
        }

        // ── Call Inbound::enrich_all with scoped post IDs ──
        // If enrich_all accepts post_ids parameter, use it; otherwise fall back to per-post enrichment
        if ( method_exists( 'DBA_LuxStrat_Intl_Inbound', 'enrich_posts' ) ) {
            // Preferred: pass specific post IDs
            $result = DBA_LuxStrat_Intl_Inbound::enrich_posts( $lang, $languages[$lang], $post_ids );
        } elseif ( method_exists( 'DBA_LuxStrat_Intl_Inbound', 'enrich_all' ) ) {
            // Fallback: call enrich_all but pass days hint via transient
            set_transient( 'dba_luxstrat_' . $lang . '_enrich_scope', array(
                'days'     => $days,
                'post_ids' => $post_ids,
            ), 600 );
            $result = DBA_LuxStrat_Intl_Inbound::enrich_all( $lang, $languages[$lang] );
            delete_transient( 'dba_luxstrat_' . $lang . '_enrich_scope' );
        } else {
            // Manual enrichment: add images + SEO for each post
            $images_added = 0;
            $seo_fixed    = 0;

            foreach ( $post_ids as $pid ) {
                // Add missing featured image
                if ( ! has_post_thumbnail( $pid ) ) {
                    $theme_slug = get_post_meta( $pid, $prefix . 'theme', true );
                    $themes     = ! empty( $languages[$lang]['themes'] ) ? $languages[$lang]['themes'] : array();
                    $tc         = isset( $themes[$theme_slug] ) ? $themes[$theme_slug] : array( 'short_label' => 'Luxembourg', 'keywords' => array() );
                    $settings   = get_option( 'dba_luxstrat_' . $lang . '_settings', array() );
                    $title      = get_the_title( $pid );
                    DBA_LuxStrat_Intl_Generator::generate_featured_image_for_post( $pid, $title, $tc, $settings, $lang );
                    if ( has_post_thumbnail( $pid ) ) $images_added++;
                }

                // Add missing SEO meta
                $has_seo = ! empty( get_post_meta( $pid, '_yoast_wpseo_metadesc', true ) ) || ! empty( get_post_meta( $pid, 'rank_math_description', true ) );
                if ( ! $has_seo ) {
                    $excerpt = get_the_excerpt( $pid );
                    if ( ! empty( $excerpt ) ) {
                        $desc = mb_strlen( $excerpt ) > 135 ? mb_substr( $excerpt, 0, 132 ) . '...' : $excerpt;
                        update_post_meta( $pid, '_yoast_wpseo_metadesc', sanitize_text_field( $desc ) );
                        update_post_meta( $pid, 'rank_math_description', sanitize_text_field( $desc ) );
                        $seo_fixed++;
                    }
                }
            }

            $result = array( 'total' => count( $post_ids ), 'images_added' => $images_added, 'seo_fixed' => $seo_fixed );
        }

        wp_send_json_success( $result );
    }

    public function ajax_stop() {
        check_ajax_referer('dba_admin_nonce','nonce');
        if(!current_user_can('manage_options')) wp_send_json_error('Permission denied.');
        $lang=sanitize_key($_POST['lang']??'');
        set_transient('dba_luxstrat_'.$lang.'_stop',1,300);
        wp_send_json_success('Stop signal sent.');
    }

    public function ajax_full_reset() {
        check_ajax_referer('dba_admin_nonce','nonce');
        if(!current_user_can('manage_options')) wp_send_json_error('Permission denied.');
        $lang=sanitize_key($_POST['lang']??'');
        $languages=DBA_LuxStrat_Intl_Loader::get_languages();
        delete_option('dba_luxstrat_'.$lang.'_last_theme');
        delete_transient('dba_luxstrat_'.$lang.'_ran_'.date('Y-m-d'));
        delete_transient('dba_luxstrat_'.$lang.'_stop');
        if(isset($languages[$lang])){DBA_LuxStrat_Intl_Scheduler::activate_language($lang,$languages[$lang]);}
        wp_send_json_success('Full reset complete.');
    }

    /* ══════════════════════════════════════════════════
     *  CUSTOM TITLE QUEUE HANDLERS
     * ══════════════════════════════════════════════════ */

    public function ajax_queue_add() {
        check_ajax_referer( 'dba_admin_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error( 'Permission denied.' );
        $lang  = sanitize_key( $_POST['lang'] ?? '' );
        $title = sanitize_text_field( wp_unslash( $_POST['title'] ?? '' ) );
        if ( empty( $lang ) ) wp_send_json_error( 'Missing language.' );
        if ( empty( $title ) ) wp_send_json_error( 'Title cannot be empty.' );
        if ( mb_strlen( $title ) > 200 ) wp_send_json_error( 'Title too long (max 200 characters).' );

        $queue = get_option( 'dba_luxstrat_' . $lang . '_title_queue', array() );
        if ( ! is_array( $queue ) ) $queue = array();
        $queue[] = $title;
        update_option( 'dba_luxstrat_' . $lang . '_title_queue', $queue, false );
        error_log( 'LuxStrat[' . $lang . ']: Title added to queue: "' . $title . '" (queue size: ' . count( $queue ) . ')' );
        wp_send_json_success( array( 'count' => count( $queue ), 'title' => $title ) );
    }

    public function ajax_queue_remove() {
        check_ajax_referer( 'dba_admin_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error( 'Permission denied.' );
        $lang  = sanitize_key( $_POST['lang'] ?? '' );
        $index = absint( $_POST['index'] ?? 0 );
        if ( empty( $lang ) ) wp_send_json_error( 'Missing language.' );

        $queue = get_option( 'dba_luxstrat_' . $lang . '_title_queue', array() );
        if ( ! is_array( $queue ) ) $queue = array();
        if ( ! isset( $queue[ $index ] ) ) wp_send_json_error( 'Invalid queue index.' );

        $removed = $queue[ $index ];
        array_splice( $queue, $index, 1 );
        update_option( 'dba_luxstrat_' . $lang . '_title_queue', array_values( $queue ), false );
        error_log( 'LuxStrat[' . $lang . ']: Title removed from queue: "' . $removed . '" (queue size: ' . count( $queue ) . ')' );
        wp_send_json_success( array( 'count' => count( $queue ), 'removed' => $removed ) );
    }

    public function ajax_queue_edit() {
        check_ajax_referer( 'dba_admin_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error( 'Permission denied.' );
        $lang  = sanitize_key( $_POST['lang'] ?? '' );
        $index = absint( $_POST['index'] ?? 0 );
        $title = sanitize_text_field( wp_unslash( $_POST['title'] ?? '' ) );
        if ( empty( $lang ) ) wp_send_json_error( 'Missing language.' );
        if ( empty( $title ) ) wp_send_json_error( 'Title cannot be empty.' );
        if ( mb_strlen( $title ) > 200 ) wp_send_json_error( 'Title too long (max 200 characters).' );

        $queue = get_option( 'dba_luxstrat_' . $lang . '_title_queue', array() );
        if ( ! is_array( $queue ) ) $queue = array();
        if ( ! isset( $queue[ $index ] ) ) wp_send_json_error( 'Invalid queue index.' );

        $old = $queue[ $index ];
        $queue[ $index ] = $title;
        update_option( 'dba_luxstrat_' . $lang . '_title_queue', $queue, false );
        error_log( 'LuxStrat[' . $lang . ']: Title edited in queue [' . $index . ']: "' . $old . '" → "' . $title . '"' );
        wp_send_json_success( array( 'index' => $index, 'title' => $title ) );
    }

    public function ajax_queue_move() {
        check_ajax_referer( 'dba_admin_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error( 'Permission denied.' );
        $lang      = sanitize_key( $_POST['lang'] ?? '' );
        $index     = absint( $_POST['index'] ?? 0 );
        $direction = sanitize_key( $_POST['direction'] ?? '' );
        if ( empty( $lang ) ) wp_send_json_error( 'Missing language.' );
        if ( ! in_array( $direction, array( 'up', 'down' ), true ) ) wp_send_json_error( 'Invalid direction.' );

        $queue = get_option( 'dba_luxstrat_' . $lang . '_title_queue', array() );
        if ( ! is_array( $queue ) ) $queue = array();
        if ( ! isset( $queue[ $index ] ) ) wp_send_json_error( 'Invalid queue index.' );

        $swap = ( $direction === 'up' ) ? $index - 1 : $index + 1;
        if ( $swap < 0 || $swap >= count( $queue ) ) wp_send_json_error( 'Cannot move further.' );

        // Swap
        $tmp           = $queue[ $index ];
        $queue[ $index ] = $queue[ $swap ];
        $queue[ $swap ]  = $tmp;

        update_option( 'dba_luxstrat_' . $lang . '_title_queue', $queue, false );
        error_log( 'LuxStrat[' . $lang . ']: Queue reordered — moved [' . $index . '] ' . $direction . ' ↔ [' . $swap . ']' );
        wp_send_json_success( array( 'moved' => $direction, 'from' => $index, 'to' => $swap ) );
    }

    /* ══════════════════════════════════════════════════════════════
     *  AJAX: ORPHAN AUDIT (per language)
     * ══════════════════════════════════════════════════════════════ */
    public function ajax_orphan_audit() {
        check_ajax_referer( 'dba_admin_nonce', 'nonce' );
        $lang = sanitize_key( $_POST['lang'] ?? '' );
        if ( empty( $lang ) ) wp_send_json_error( 'Missing language.' );
        if ( ! class_exists( 'DBA_LuxStrat_Intl_Anti_Orphan' ) ) wp_send_json_error( 'Anti-Orphan class not loaded.' );
        $result = DBA_LuxStrat_Intl_Anti_Orphan::audit_language( $lang );
        wp_send_json_success( $result );
    }

    /* ══════════════════════════════════════════════════════════════
     *  AJAX: FLUSH KAIZEN CACHE (per language)
     * ══════════════════════════════════════════════════════════════ */
    public function ajax_flush_kaizen() {
        check_ajax_referer( 'dba_admin_nonce', 'nonce' );
        $lang = sanitize_key( $_POST['lang'] ?? '' );
        if ( ! class_exists( 'DBA_LuxStrat_Intl_Kaizen' ) ) wp_send_json_error( 'Kaizen class not loaded.' );
        DBA_LuxStrat_Intl_Kaizen::invalidate_cache( $lang );
        wp_send_json_success( 'Cache flushed' . ( $lang ? " for {$lang}" : ' (all)' ) . '.' );
    }
}
