<?php
/**
 * DBA GeoBot Admin — Tabbed settings page for country investment blogs
 *
 * Adds submenu pages under the main Damalion Blog AI menu:
 *   Damalion Blog AI → 🇫🇷 France GeoBot
 *   Damalion Blog AI → 🇮🇹 Italy GeoBot
 *   Damalion Blog AI → 🇪🇸 Spain GeoBot
 *   Damalion Blog AI → 🇵🇹 Portugal GeoBot
 *
 * ═══════════════════════════════════════════════════════════════════════
 *  FULLY SCALABLE: Adding a new country in DBA_GeoBot_Registry
 *  auto-registers a new submenu page here. Zero code changes needed.
 * ═══════════════════════════════════════════════════════════════════════
 *
 * @since 2.8.0
 * @updated 2.17.0 — Added Kaizen panel, Anti-Orphan panel, Gates F/G/H display
 */

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

class DBA_GeoBot_Admin {

    private static $instance = null;

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

    private function __construct() {
        add_action( 'admin_menu',            array( $this, 'add_submenus' ), 25 );
        add_action( 'admin_init',            array( $this, 'register_settings' ) );
        add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ) );

        // AJAX: Import cities from paste
        add_action( 'wp_ajax_dba_geo_import_cities',  array( $this, 'ajax_import_cities' ) );
        add_action( 'wp_ajax_dba_geo_reset_history',  array( $this, 'ajax_reset_history' ) );

        // AJAX: Kaizen + Anti-Orphan
        add_action( 'wp_ajax_dba_geo_run_orphan_audit',    array( $this, 'ajax_run_orphan_audit' ) );
        add_action( 'wp_ajax_dba_geo_flush_kaizen_cache',  array( $this, 'ajax_flush_kaizen_cache' ) );
    }

    /* =================================================================
     *  MENU REGISTRATION — Auto-registers one page per country
     * ================================================================= */

    public function add_submenus() {
        foreach ( DBA_GeoBot_Registry::get_countries() as $key => $config ) {
            add_submenu_page(
                'dba-settings',
                $config['label'],
                $config['menu_label'],
                'manage_options',
                $config['admin_slug'],
                function() use ( $key ) {
                    $this->render_page( $key );
                }
            );
        }
    }

    public function register_settings() {
        foreach ( DBA_GeoBot_Registry::get_countries() as $key => $config ) {
            register_setting(
                $config['settings_option'] . '_group',
                $config['settings_option'],
                array( $this, 'sanitize_settings' )
            );
        }
    }

    /**
     * Sanitize settings (works for any country).
     */
    public function sanitize_settings( $input ) {
        $clean = array();
        $clean['enabled']       = ! empty( $input['enabled'] );
        $clean['posts_per_run'] = max( 1, min( 20, intval( $input['posts_per_run'] ?? 3 ) ) );
        $clean['post_status']   = in_array( $input['post_status'] ?? '', array( 'publish', 'draft', 'pending' ), true )
                                    ? $input['post_status'] : 'publish';
        $clean['author_id']     = max( 1, intval( $input['author_id'] ?? 1 ) );

        // Posting days
        $valid_days = array( 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday' );
        $days = array();
        if ( ! empty( $input['posting_days'] ) && is_array( $input['posting_days'] ) ) {
            foreach ( $input['posting_days'] as $d ) {
                $d = strtolower( sanitize_text_field( $d ) );
                if ( in_array( $d, $valid_days, true ) ) $days[] = $d;
            }
        }
        $clean['posting_days'] = ! empty( $days ) ? $days : array( 'saturday', 'sunday' );

        // Active communes (array of commune names)
        if ( ! empty( $input['active_communes'] ) && is_array( $input['active_communes'] ) ) {
            $clean['active_communes'] = array_map( 'sanitize_text_field', $input['active_communes'] );
        } else {
            $clean['active_communes'] = array(); // empty = all
        }

        // CTA overrides
        $clean['cta_text']      = sanitize_textarea_field( $input['cta_text'] ?? '' );
        $clean['cta_link_text'] = sanitize_text_field( $input['cta_link_text'] ?? '' );
        $clean['cta_link_url']  = esc_url_raw( $input['cta_link_url'] ?? '' );
        $clean['cta_disabled']  = ! empty( $input['cta_disabled'] );

        // Word count
        $clean['word_count_min'] = max( 300, min( 3000, intval( $input['word_count_min'] ?? 800 ) ) );
        $clean['word_count_max'] = max( 500, min( 5000, intval( $input['word_count_max'] ?? 1200 ) ) );
        if ( $clean['word_count_max'] <= $clean['word_count_min'] ) {
            $clean['word_count_max'] = $clean['word_count_min'] + 200;
        }

        return $clean;
    }

    /* =================================================================
     *  AJAX: Import/Paste Cities
     * ================================================================= */

    /**
     * Parse pasted city list and save to wp_options.
     *
     * Accepted line formats:
     *   City
     *   City, Department, Region
     *   City, Department, Region, Population
     *   City | Department | Region | Population
     *   Tab-separated (Excel paste)
     *   Rank, City, Department, Region, Population  (auto-detects numeric rank column)
     */
    public function ajax_import_cities() {
        check_ajax_referer( 'dba_admin_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error( 'Unauthorized' );

        $country_key = sanitize_key( $_POST['country_key'] ?? '' );
        $config = DBA_GeoBot_Registry::get_country( $country_key );
        if ( ! $config ) wp_send_json_error( 'Invalid country' );

        $raw_text = wp_unslash( $_POST['cities_text'] ?? '' );
        $mode     = sanitize_key( $_POST['import_mode'] ?? 'replace' ); // 'replace' or 'append'

        if ( trim( $raw_text ) === '' ) {
            wp_send_json_error( 'No cities provided. Paste your list and try again.' );
        }

        // Split into lines
        $lines = preg_split( '/\r?\n/', trim( $raw_text ) );
        $lines = array_filter( array_map( 'trim', $lines ) );

        if ( empty( $lines ) ) {
            wp_send_json_error( 'No valid lines found.' );
        }

        $parsed = array();
        $skipped = 0;
        $rang_counter = 1;

        foreach ( $lines as $line ) {
            // Skip obvious header rows
            if ( preg_match( '/^(rang|rank|city|commune|città|ciudad|cidade|name)/i', $line ) ) {
                $skipped++;
                continue;
            }

            // Detect separator: tab first, then pipe, then comma
            if ( strpos( $line, "\t" ) !== false ) {
                $parts = explode( "\t", $line );
            } elseif ( strpos( $line, '|' ) !== false ) {
                $parts = array_map( 'trim', explode( '|', $line ) );
            } elseif ( strpos( $line, ';' ) !== false ) {
                $parts = array_map( 'trim', explode( ';', $line ) );
            } else {
                $parts = array_map( 'trim', explode( ',', $line ) );
            }

            // Remove empty parts
            $parts = array_values( array_filter( $parts, function( $p ) { return trim( $p ) !== ''; } ) );

            if ( empty( $parts ) ) {
                $skipped++;
                continue;
            }

            // Auto-detect if first column is a numeric rank (skip it)
            $offset = 0;
            if ( count( $parts ) >= 2 && is_numeric( trim( $parts[0] ) ) ) {
                $offset = 1;
            }

            $commune     = sanitize_text_field( trim( $parts[ $offset ] ?? '' ) );
            $departement = sanitize_text_field( trim( $parts[ $offset + 1 ] ?? '' ) );
            $region      = sanitize_text_field( trim( $parts[ $offset + 2 ] ?? '' ) );
            $population  = sanitize_text_field( trim( $parts[ $offset + 3 ] ?? '' ) );

            // Also check for a 5th field (status) that might be between dept and region
            // Format: Rank, Code, City, Department, Status, Region, Population
            if ( count( $parts ) - $offset >= 6 ) {
                // Likely: Code, City, Dept, Status, Region, Pop
                $commune     = sanitize_text_field( trim( $parts[ $offset + 1 ] ?? $commune ) );
                $departement = sanitize_text_field( trim( $parts[ $offset + 2 ] ?? '' ) );
                $region      = sanitize_text_field( trim( $parts[ $offset + 4 ] ?? '' ) );
                $population  = sanitize_text_field( trim( $parts[ $offset + 5 ] ?? '' ) );
            }

            if ( $commune === '' ) {
                $skipped++;
                continue;
            }

            // Clean footnotes like [c], [1], [a]
            $commune     = preg_replace( '/\[[^\]]*\]/', '', $commune );
            $departement = preg_replace( '/\[[^\]]*\]/', '', $departement );
            $region      = preg_replace( '/\[[^\]]*\]/', '', $region );
            $population  = preg_replace( '/\[[^\]]*\]/', '', $population );

            // Clean non-breaking spaces in population
            $population = preg_replace( '/[\x{00A0}\x{202F}]/u', ' ', $population );

            $parsed[] = array(
                'rang'        => $rang_counter++,
                'code'        => '',
                'commune'     => trim( $commune ),
                'departement' => trim( $departement ),
                'region'      => trim( $region ),
                'population'  => trim( $population ),
            );
        }

        if ( empty( $parsed ) ) {
            wp_send_json_error( "Could not parse any cities from the input ({$skipped} lines skipped)." );
        }

        // Handle append mode: merge with existing, skip duplicates
        if ( $mode === 'append' ) {
            $existing = get_option( $config['communes_option_key'], array() );
            $existing_names = array_map( function( $c ) {
                return DBA_GeoBot_Registry::normalize_commune( $c['commune'] );
            }, $existing );

            $added = 0;
            foreach ( $parsed as $new_city ) {
                $slug = DBA_GeoBot_Registry::normalize_commune( $new_city['commune'] );
                if ( ! in_array( $slug, $existing_names, true ) ) {
                    $new_city['rang'] = count( $existing ) + 1;
                    $existing[] = $new_city;
                    $existing_names[] = $slug;
                    $added++;
                }
            }
            $parsed = $existing;
            $message = "Appended {$added} new cities (skipped " . ( count( $parsed ) - count( $existing ) + $added ) . " duplicates). Total: " . count( $parsed ) . " cities.";
            if ( $added === 0 ) {
                $message = "All " . count( $parsed ) . " cities already exist. No changes made.";
            }
        } else {
            $message = "Imported " . count( $parsed ) . " cities (replaced previous list).";
        }

        // Save
        update_option( $config['communes_option_key'], $parsed, false );

        error_log( "DBA GeoBot [{$country_key}]: {$message}" );

        wp_send_json_success( array(
            'message' => $message,
            'count'   => count( $parsed ),
            'skipped' => $skipped,
            'sample'  => array_slice( array_column( $parsed, 'commune' ), 0, 10 ),
        ) );
    }

    /**
     * Reset dedupe history for a country.
     */
    public function ajax_reset_history() {
        check_ajax_referer( 'dba_admin_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error( 'Unauthorized' );

        $country_key = sanitize_key( $_POST['country_key'] ?? '' );
        if ( ! DBA_GeoBot_Registry::get_country( $country_key ) ) {
            wp_send_json_error( 'Invalid country' );
        }

        DBA_GeoBot_Dedupe::reset_history( $country_key );
        wp_send_json_success( array( 'message' => 'Dedupe history cleared. All communes are available for writing.' ) );
    }

    /* =================================================================
     *  SCRIPTS
     * ================================================================= */

    public function enqueue_scripts( $hook ) {
        // Check if we're on any GeoBot admin page
        $is_geobot_page = false;
        foreach ( DBA_GeoBot_Registry::get_countries() as $config ) {
            if ( strpos( $hook, $config['admin_slug'] ) !== false ) {
                $is_geobot_page = true;
                break;
            }
        }
        if ( ! $is_geobot_page ) return;

        wp_enqueue_script(
            'dba-geobot-admin',
            DBA_PLUGIN_URL . 'assets/js/geobot-admin.js',
            array( 'jquery' ),
            DBA_VERSION,
            true
        );

        wp_localize_script( 'dba-geobot-admin', 'dba_geo', array(
            'ajaxurl' => admin_url( 'admin-ajax.php' ),
            'nonce'   => wp_create_nonce( 'dba_admin_nonce' ),
        ) );
    }

    /* =================================================================
     *  AJAX: Run Anti-Orphan Audit
     * ================================================================= */

    public function ajax_run_orphan_audit() {
        check_ajax_referer( 'dba_admin_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error( 'Unauthorized' );

        $country_key = sanitize_key( $_POST['country_key'] ?? '' );

        if ( ! class_exists( 'DBA_GeoBot_Anti_Orphan' ) ) {
            wp_send_json_error( 'Anti-Orphan class not loaded. Check that class-geobot-anti-orphan.php is included.' );
        }

        $anti_orphan = DBA_GeoBot_Anti_Orphan::get_instance();
        $result = $anti_orphan->audit_country( $country_key );

        wp_send_json_success( $result );
    }

    /* =================================================================
     *  AJAX: Flush Kaizen Cache
     * ================================================================= */

    public function ajax_flush_kaizen_cache() {
        check_ajax_referer( 'dba_admin_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error( 'Unauthorized' );

        if ( ! class_exists( 'DBA_GeoBot_Kaizen' ) ) {
            wp_send_json_error( 'Kaizen class not loaded. Check that class-geobot-kaizen.php is included.' );
        }

        DBA_GeoBot_Kaizen::invalidate_cache();
        wp_send_json_success( array( 'message' => 'Kaizen cache flushed. Next generation will build fresh learning context.' ) );
    }

    /* =================================================================
     *  PAGE RENDER — One universal template, parameterized by country
     * ================================================================= */

    public function render_page( string $country_key ) {

        $config   = DBA_GeoBot_Registry::get_country( $country_key );
        if ( ! $config ) { echo '<p>Unknown country.</p>'; return; }

        $settings = get_option( $config['settings_option'], array() );
        $enabled  = ! empty( $settings['enabled'] );
        $last_run = DBA_GeoBot_Scheduler::get_last_run_info( $country_key );
        $next_run = DBA_GeoBot_Scheduler::get_next_run_info( $country_key );
        $post_days = DBA_GeoBot_Scheduler::get_posting_days_string( $country_key );
        $stats    = DBA_GeoBot_Dedupe::get_stats( $country_key );
        $communes = DBA_GeoBot_Registry::get_communes( $country_key );
        $authors  = get_users( array( 'role__in' => array( 'administrator', 'editor', 'author' ), 'number' => 50 ) );

        ?>
        <div class="wrap">
            <h1><?php echo esc_html( $config['label'] ); ?></h1>
            <p style="font-size:14px;color:#555;">
                Automated investment blog posts for <?php echo esc_html( ucfirst( $country_key ) ); ?> cities.
                Language: <strong><?php echo strtoupper( $config['language'] ); ?></strong>
                &nbsp;|&nbsp; Category: <strong><?php echo esc_html( $config['wp_category'] ); ?></strong>
                &nbsp;|&nbsp; Communes loaded: <strong><?php echo count( $communes ); ?></strong>
            </p>

            <!-- STATUS BAR -->
            <div style="background:<?php echo $enabled ? '#d4edda' : '#fff3cd'; ?>;border:1px solid <?php echo $enabled ? '#c3e6cb' : '#ffc107'; ?>;padding:12px 20px;border-radius:6px;margin:15px 0;display:flex;justify-content:space-between;align-items:center;">
                <div>
                    <strong>Status:</strong> <?php echo $enabled ? '🟢 ENABLED' : '🟡 DISABLED'; ?>
                    &nbsp;|&nbsp;
                    <strong>Schedule:</strong> <?php echo esc_html( $post_days ); ?>
                    &nbsp;|&nbsp;
                    <strong>Next run:</strong> <?php echo esc_html( $next_run ); ?>
                </div>
                <div>
                    <button class="button button-primary dba-geo-run-batch" data-country="<?php echo esc_attr( $country_key ); ?>" style="background:#28a745;border-color:#28a745;">
                        🚀 Run <?php echo esc_html( $config['flag'] ); ?> Batch Now
                    </button>
                </div>
            </div>

            <!-- COVERAGE STATS -->
            <div style="background:#e8f4fd;border:1px solid #b8d4e3;padding:12px 20px;border-radius:6px;margin-bottom:15px;">
                <strong>Coverage:</strong>
                <?php echo intval( $stats['communes_covered'] ); ?>/<?php echo intval( $stats['communes_total'] ); ?> communes written
                (<?php echo esc_html( $stats['coverage_pct'] ); ?>%)
                &nbsp;|&nbsp;
                <strong>Last 30 days:</strong> <?php echo intval( $stats['last_30_days'] ); ?> posts
                &nbsp;|&nbsp;
                <strong>Total published:</strong> <?php echo intval( $stats['total_published'] ); ?>
                &nbsp;|&nbsp;
                <button type="button" class="button button-small dba-geo-reset-history" data-country="<?php echo esc_attr( $country_key ); ?>" style="color:#dc3545;vertical-align:middle;">🔄 Reset Rotation</button>
            </div>

            <!-- ═══════════════════════════════════════════════════════════ -->
            <!--  PLAGIARISM & GOOGLE COMPLIANCE PANEL                      -->
            <!-- ═══════════════════════════════════════════════════════════ -->
            <?php
            $dba_settings = get_option( 'dba_settings', array() );
            $has_copyscape = ! empty( $dba_settings['copyscape_user'] ) && ! empty( $dba_settings['copyscape_key'] );
            ?>
            <div style="background:#e8f5e9;border:1px solid #a5d6a7;padding:15px 20px;border-radius:6px;margin-bottom:15px;">
                <h3 style="margin:0 0 10px;font-size:15px;">🛡️ Plagiarism Detection & Google Penalty Compliance — <span style="color:#2e7d32;font-weight:bold;">ACTIVE</span></h3>
                <table style="width:100%;border-collapse:collapse;font-size:13px;">
                    <tr>
                        <td style="padding:4px 8px;width:30px;">✅</td>
                        <td style="padding:4px 8px;"><strong>Gate A — Internal Duplicate Detection</strong></td>
                        <td style="padding:4px 8px;color:#555;">Jaccard 3-gram shingling against ALL existing Damalion posts. Threshold: 35% overlap = REJECT. <span style="color:#2e7d32;font-weight:bold;">ENABLED</span></td>
                    </tr>
                    <tr>
                        <td style="padding:4px 8px;">✅</td>
                        <td style="padding:4px 8px;"><strong>Gate B — Sentence-Level Uniqueness</strong></td>
                        <td style="padding:4px 8px;color:#555;">Compares every sentence (>30 chars) against last 30 GeoBot posts. 90% similarity = flagged. Max 15% duplicate sentences allowed. <span style="color:#2e7d32;font-weight:bold;">ENABLED</span></td>
                    </tr>
                    <tr>
                        <td style="padding:4px 8px;"><?php echo $has_copyscape ? '✅' : '⚠️'; ?></td>
                        <td style="padding:4px 8px;"><strong>Gate C — Copyscape API</strong></td>
                        <td style="padding:4px 8px;color:#555;">
                            <?php if ( $has_copyscape ) : ?>
                                Premium web-wide plagiarism check via Copyscape API. <span style="color:#2e7d32;font-weight:bold;">ENABLED</span>
                            <?php else : ?>
                                <span style="color:#e65100;">Not configured.</span> Add Copyscape credentials in <a href="<?php echo admin_url( 'admin.php?page=dba-settings' ); ?>">Settings</a> for web-wide plagiarism detection. Fallback: web sentence sampling.
                            <?php endif; ?>
                        </td>
                    </tr>
                    <tr>
                        <td style="padding:4px 8px;">✅</td>
                        <td style="padding:4px 8px;"><strong>Gate D — Web Sentence Sampling</strong></td>
                        <td style="padding:4px 8px;color:#555;">5 random sentences searched via Google to detect web-wide matches. Active when Copyscape is not configured. <span style="color:#2e7d32;font-weight:bold;">ENABLED (fallback)</span></td>
                    </tr>
                    <tr>
                        <td style="padding:4px 8px;">✅</td>
                        <td style="padding:4px 8px;"><strong>Gate E — AI Prompt Anti-Template</strong></td>
                        <td style="padding:4px 8px;color:#555;">System prompt instructs AI to vary sentence structure, vocabulary, and narrative angle per city. Retry on validation failure. <span style="color:#2e7d32;font-weight:bold;">ENABLED</span></td>
                    </tr>
                    <tr>
                        <td style="padding:4px 8px;">✅</td>
                        <td style="padding:4px 8px;"><strong>Gate F — Structural Clone Detection</strong></td>
                        <td style="padding:4px 8px;color:#555;">Compares paragraph structure hash (H2 count, paragraphs per section, avg length) against last 10 posts. 4+ identical = REJECT. <span style="color:#2e7d32;font-weight:bold;">ENABLED</span></td>
                    </tr>
                    <tr>
                        <td style="padding:4px 8px;">✅</td>
                        <td style="padding:4px 8px;"><strong>Gate G — Opener &amp; Transition Repetition</strong></td>
                        <td style="padding:4px 8px;color:#555;">Section openers (first 3 words) compared across last 10 posts. Same transition word 3+ times in one article = REJECT. <span style="color:#2e7d32;font-weight:bold;">ENABLED</span></td>
                    </tr>
                    <tr>
                        <td style="padding:4px 8px;">✅</td>
                        <td style="padding:4px 8px;"><strong>Gate H — Title Deduplication</strong></td>
                        <td style="padding:4px 8px;color:#555;">Title skeleton (minus city name) compared at 85% similarity against all posts in last 90 days. Match = REJECT. <span style="color:#2e7d32;font-weight:bold;">ENABLED</span></td>
                    </tr>
                </table>
                <p style="margin:10px 0 0;font-size:12px;color:#555;">
                    <strong>Pipeline:</strong> Every article passes through Gates A → B → (C or D) → E → F → G → H before publishing. Any gate failure = article REJECTED and regenerated (up to 2 retries). Failed articles are logged with full error trace.
                </p>
            </div>

            <!-- ═══════════════════════════════════════════════════════════ -->
            <!--  INTERNAL LINKING & HUB PAGE — Google Indexing              -->
            <!-- ═══════════════════════════════════════════════════════════ -->
            <?php
            $hub_page_id = DBA_GeoBot_Linker::get_instance()->get_hub_page_id( $country_key );
            $hub_permalink = $hub_page_id ? get_permalink( $hub_page_id ) : '';
            $hub_updated   = $hub_page_id ? get_post_meta( $hub_page_id, '_dba_geo_hub_updated', true ) : '';
            $hub_city_count = $hub_page_id ? (int) get_post_meta( $hub_page_id, '_dba_geo_hub_city_count', true ) : 0;
            $all_country_posts = DBA_GeoBot_Linker::get_instance()->get_country_posts( $country_key );
            $linked_count = 0;
            foreach ( $all_country_posts as $cp ) {
                $pc = get_post_field( 'post_content', $cp['post_id'] );
                if ( strpos( $pc, '<!-- GeoBot Internal Linking Block -->' ) !== false ) $linked_count++;
            }
            $total_posts_count = count( $all_country_posts );
            $orphan_count = $total_posts_count - $linked_count;
            ?>
            <div style="background:<?php echo $orphan_count > 0 ? '#fff3e0' : '#e8f5e9'; ?>;border:1px solid <?php echo $orphan_count > 0 ? '#ffcc80' : '#a5d6a7'; ?>;padding:15px 20px;border-radius:6px;margin-bottom:15px;">
                <h3 style="margin:0 0 10px;font-size:15px;">🔗 Internal Linking & Hub Post — <?php echo $orphan_count > 0
                    ? '<span style="color:#e65100;font-weight:bold;">' . $orphan_count . ' ORPHAN POST' . ( $orphan_count > 1 ? 'S' : '' ) . '</span>'
                    : '<span style="color:#2e7d32;font-weight:bold;">ALL POSTS LINKED</span>'; ?></h3>

                <table style="width:100%;border-collapse:collapse;font-size:13px;margin-bottom:12px;">
                    <tr>
                        <td style="padding:4px 8px;width:30px;"><?php echo $hub_page_id ? '✅' : '❌'; ?></td>
                        <td style="padding:4px 8px;"><strong>Hub/Pillar Post</strong></td>
                        <td style="padding:4px 8px;color:#555;">
                            <?php if ( $hub_page_id && $hub_permalink ) : ?>
                                <a href="<?php echo esc_url( $hub_permalink ); ?>" target="_blank"><?php echo esc_html( get_the_title( $hub_page_id ) ); ?></a>
                                — <?php echo $hub_city_count; ?> cities indexed
                                <?php if ( $hub_updated ) : ?> | Updated: <?php echo esc_html( $hub_updated ); ?><?php endif; ?>
                                | Categories: <?php echo esc_html( implode( ', ', wp_get_post_categories( $hub_page_id, array( 'fields' => 'names' ) ) ) ); ?>
                            <?php else : ?>
                                <span style="color:#e65100;">Not created yet.</span> Select categories below and click "Generate Hub Post".
                            <?php endif; ?>
                        </td>
                    </tr>
                    <tr>
                        <td style="padding:4px 8px;"><?php echo $linked_count > 0 ? '✅' : '⚠️'; ?></td>
                        <td style="padding:4px 8px;"><strong>Cross-City Links</strong></td>
                        <td style="padding:4px 8px;color:#555;">
                            <?php echo $linked_count; ?>/<?php echo $total_posts_count; ?> posts have "Related Cities" block
                            <?php if ( $orphan_count > 0 ) : ?>
                                — <span style="color:#e65100;font-weight:bold;"><?php echo $orphan_count; ?> orphan posts need linking</span>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <tr>
                        <td style="padding:4px 8px;">✅</td>
                        <td style="padding:4px 8px;"><strong>Breadcrumb Schema</strong></td>
                        <td style="padding:4px 8px;color:#555;">JSON-LD BreadcrumbList auto-injected: Home → <?php echo esc_html( $config['wp_category'] ); ?> → Region → City</td>
                    </tr>
                    <tr>
                        <td style="padding:4px 8px;">✅</td>
                        <td style="padding:4px 8px;"><strong>Auto Back-Links</strong></td>
                        <td style="padding:4px 8px;color:#555;">When a new city post is published, related existing posts are automatically updated with back-links to the new post.</td>
                    </tr>
                </table>

                <!-- Category multi-select for hub post -->
                <div style="margin-bottom:12px;">
                    <label style="font-size:13px;font-weight:600;display:block;margin-bottom:4px;">📂 Additional categories for Hub Post:</label>
                    <div style="display:flex;gap:8px;align-items:flex-start;">
                        <div style="position:relative;flex:1;max-width:500px;">
                            <input type="text" id="dba-geo-cat-search-<?php echo esc_attr( $country_key ); ?>"
                                   placeholder="🔍 Search categories…"
                                   style="width:100%;padding:4px 8px;margin-bottom:4px;border:1px solid #ccc;border-radius:3px;">
                            <div id="dba-geo-cat-list-<?php echo esc_attr( $country_key ); ?>"
                                 style="max-height:160px;overflow-y:auto;border:1px solid #ddd;padding:6px 8px;background:#fff;border-radius:3px;font-size:12px;">
                                <?php
                                // Get all categories in the relevant WPML language
                                $all_cats = get_categories( array(
                                    'hide_empty' => false,
                                    'orderby'    => 'name',
                                    'order'      => 'ASC',
                                    'number'     => 200,
                                ) );
                                // Pre-select: current hub categories (minus the auto default one)
                                $default_cat_name = $config['wp_category'];
                                $hub_current_cats = $hub_page_id ? wp_get_post_categories( $hub_page_id ) : array();
                                $default_term = term_exists( $default_cat_name, 'category' );
                                $default_tid = 0;
                                if ( $default_term ) {
                                    $default_tid = is_array( $default_term ) ? (int) $default_term['term_id'] : (int) $default_term;
                                }

                                foreach ( $all_cats as $cat ) :
                                    // Skip the auto-assigned default category — it's always added
                                    if ( (int) $cat->term_id === $default_tid ) continue;
                                    $checked = in_array( (int) $cat->term_id, $hub_current_cats ) ? ' checked' : '';
                                ?>
                                    <label class="dba-geo-cat-item-<?php echo esc_attr( $country_key ); ?>"
                                           data-name="<?php echo esc_attr( mb_strtolower( $cat->name ) ); ?>"
                                           style="display:block;padding:2px 0;cursor:pointer;white-space:nowrap;">
                                        <input type="checkbox" name="dba_hub_cat_<?php echo esc_attr( $country_key ); ?>[]"
                                               value="<?php echo (int) $cat->term_id; ?>"<?php echo $checked; ?>
                                               style="margin-right:4px;">
                                        <?php echo esc_html( $cat->name ); ?>
                                        <span style="color:#999;">(<?php echo (int) $cat->count; ?>)</span>
                                    </label>
                                <?php endforeach; ?>
                            </div>
                            <div style="font-size:11px;color:#888;margin-top:2px;">
                                "<?php echo esc_html( $default_cat_name ); ?>" is always assigned automatically.
                            </div>
                        </div>
                    </div>
                </div>

                <div style="display:flex;gap:10px;align-items:center;flex-wrap:wrap;">
                    <?php if ( $hub_page_id ) : ?>
                        <button type="button" class="button button-primary dba-geo-generate-hub" data-country="<?php echo esc_attr( $country_key ); ?>">
                            🔄 Update Hub Post
                        </button>
                    <?php else : ?>
                        <button type="button" class="button button-primary dba-geo-generate-hub" data-country="<?php echo esc_attr( $country_key ); ?>">
                            ✨ Generate Hub Post
                        </button>
                    <?php endif; ?>
                    <button type="button" class="button dba-geo-retroactive-link" data-country="<?php echo esc_attr( $country_key ); ?>" <?php echo $orphan_count === 0 ? 'disabled' : ''; ?>>
                        🔗 Fix All Orphan Posts (<?php echo $orphan_count; ?>)
                    </button>
                    <span class="dba-geo-hub-result-<?php echo esc_attr( $country_key ); ?>" style="font-size:13px;"></span>
                </div>

                <?php if ( $orphan_count > 0 && $total_posts_count > 0 ) : ?>
                <p style="margin:10px 0 0;font-size:12px;color:#e65100;">
                    ⚠️ <strong>Google won't index orphan posts.</strong> Click "Fix All Orphan Posts" to inject cross-links into all existing posts and update the hub post.
                </p>
                <?php endif; ?>
            </div>

            <!-- ═══════════════════════════════════════════════════════════ -->
            <!--  INBOUND LINK SCANNER — Site-wide links TO city posts       -->
            <!-- ═══════════════════════════════════════════════════════════ -->
            <div style="background:#e3f2fd;border:1px solid #90caf9;padding:15px 20px;border-radius:6px;margin-bottom:15px;">
                <h3 style="margin:0 0 10px;font-size:15px;">📥 Inbound Link Scanner — PageRank from rest of blog</h3>
                <p style="font-size:13px;color:#555;margin:0 0 8px;">
                    Scans the <strong>entire site</strong> — all posts, all pages, all WPML languages — and auto-links city name mentions and investment keywords to <?php echo esc_html( ucfirst( $country_key ) ); ?> GeoBot articles.
                </p>
                <p style="font-size:12px;color:#666;margin:0 0 12px;">
                    <strong>Tier 1</strong> — WPML <?php echo esc_html( strtoupper( $config['wpml_code'] ) ); ?> language posts/pages
                    &nbsp;→&nbsp; <strong>Tier 2</strong> — URLs containing "<?php echo esc_html( implode( '", "', array_slice( DBA_GeoBot_Inbound::get_url_patterns( $country_key ), 0, 4 ) ) ); ?>"…
                    &nbsp;→&nbsp; <strong>Tier 3</strong> — Everything else on the site.
                    Max <?php echo DBA_GeoBot_Inbound::MAX_LINKS_PER_POST; ?> links per post. City names &lt; <?php echo DBA_GeoBot_Inbound::MIN_CITY_NAME_LENGTH; ?> chars skipped. Hub post keywords also matched.
                </p>

                <div style="display:flex;gap:10px;align-items:center;flex-wrap:wrap;">
                    <button type="button" class="button button-primary dba-geo-inbound-scan" data-country="<?php echo esc_attr( $country_key ); ?>">
                        🔍 Scan &amp; Link (<?php echo esc_html( ucfirst( $country_key ) ); ?> only)
                    </button>
                    <button type="button" class="button dba-geo-inbound-scan-all" data-country="all">
                        🌍 Scan &amp; Link (All Countries)
                    </button>
                    <button type="button" class="button dba-geo-inbound-rescan" data-country="<?php echo esc_attr( $country_key ); ?>" title="Strip existing inbound links and re-scan everything">
                        🔄 Force Re-scan
                    </button>
                    <button type="button" class="button dba-geo-inbound-strip" style="color:#c62828;" title="Remove ALL GeoBot inbound links from ALL posts (full undo)">
                        🗑️ Strip All Inbound Links
                    </button>
                    <span class="dba-geo-inbound-result-<?php echo esc_attr( $country_key ); ?>" style="font-size:13px;"></span>
                </div>

                <div class="dba-geo-inbound-details-<?php echo esc_attr( $country_key ); ?>" style="display:none;margin-top:12px;max-height:200px;overflow-y:auto;font-size:12px;background:#fff;border:1px solid #e0e0e0;padding:10px;border-radius:4px;">
                </div>
            </div>

            <!-- PROGRESS BAR -->
            <div class="dba-geo-progress" data-country="<?php echo esc_attr( $country_key ); ?>" style="display:none;background:#f8f9fa;border:1px solid #ddd;padding:15px 20px;border-radius:6px;margin-bottom:20px;">
                <div style="display:flex;justify-content:space-between;margin-bottom:8px;">
                    <strong class="dba-geo-progress-label">Generating…</strong>
                    <span class="dba-geo-progress-detail" style="color:#666;"></span>
                </div>
                <div style="background:#e9ecef;border-radius:4px;height:24px;overflow:hidden;">
                    <div class="dba-geo-progress-bar" style="background:#28a745;height:100%;width:0%;transition:width 0.5s;border-radius:4px;"></div>
                </div>
            </div>

            <!-- LAST RUN -->
            <?php if ( ! empty( $last_run['time'] ) ) : ?>
            <div style="background:#f8f9fa;border:1px solid #ddd;padding:12px 20px;border-radius:6px;margin-bottom:20px;">
                <strong>Last run:</strong> <?php echo esc_html( $last_run['time'] ); ?>
                &nbsp;|&nbsp;
                <strong>Created:</strong> <?php echo intval( $last_run['results']['created'] ?? 0 ); ?>
                &nbsp;|&nbsp;
                <strong>Failed:</strong> <?php echo intval( $last_run['results']['failed'] ?? 0 ); ?>
            </div>
            <?php endif; ?>

            <!-- SETTINGS FORM -->
            <form method="post" action="options.php">
                <?php settings_fields( $config['settings_option'] . '_group' ); ?>

                <table class="form-table">
                    <tr>
                        <th>Enable <?php echo esc_html( $config['flag'] ); ?> GeoBot</th>
                        <td>
                            <label>
                                <input type="checkbox" name="<?php echo esc_attr( $config['settings_option'] ); ?>[enabled]" value="1" <?php checked( $enabled ); ?> />
                                Activate automated <?php echo esc_html( ucfirst( $country_key ) ); ?> investment blog publishing
                            </label>
                        </td>
                    </tr>
                    <tr>
                        <th>Publishing Days</th>
                        <td>
                            <?php
                            $all_days     = array( 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday' );
                            $current_days = $settings['posting_days'] ?? $config['default_posting_days'];
                            foreach ( $all_days as $day ) : ?>
                                <label style="margin-right:15px;">
                                    <input type="checkbox" name="<?php echo esc_attr( $config['settings_option'] ); ?>[posting_days][]" value="<?php echo $day; ?>"
                                        <?php checked( in_array( $day, $current_days, true ) ); ?> />
                                    <?php echo ucfirst( $day ); ?>
                                </label>
                            <?php endforeach; ?>
                            <p class="description">Default: Saturday, Sunday (per specification).</p>
                        </td>
                    </tr>
                    <tr>
                        <th>Posts per Run</th>
                        <td>
                            <input type="number" name="<?php echo esc_attr( $config['settings_option'] ); ?>[posts_per_run]" value="<?php echo intval( $settings['posts_per_run'] ?? $config['default_posts_per_run'] ); ?>" min="1" max="20" style="width:80px;" />
                            <p class="description">Number of commune articles to generate per scheduled run.</p>
                        </td>
                    </tr>
                    <tr>
                        <th>Post Status</th>
                        <td>
                            <select name="<?php echo esc_attr( $config['settings_option'] ); ?>[post_status]">
                                <?php foreach ( array( 'publish', 'draft', 'pending' ) as $st ) : ?>
                                <option value="<?php echo $st; ?>" <?php selected( $settings['post_status'] ?? 'publish', $st ); ?>><?php echo ucfirst( $st ); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <th>Author</th>
                        <td>
                            <select name="<?php echo esc_attr( $config['settings_option'] ); ?>[author_id]">
                                <?php foreach ( $authors as $author ) : ?>
                                <option value="<?php echo $author->ID; ?>" <?php selected( $settings['author_id'] ?? 1, $author->ID ); ?>><?php echo esc_html( $author->display_name ); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <th>Word Count Range</th>
                        <td>
                            <input type="number" name="<?php echo esc_attr( $config['settings_option'] ); ?>[word_count_min]" value="<?php echo intval( $settings['word_count_min'] ?? $config['word_count_min'] ); ?>" min="300" max="3000" style="width:80px;" /> –
                            <input type="number" name="<?php echo esc_attr( $config['settings_option'] ); ?>[word_count_max]" value="<?php echo intval( $settings['word_count_max'] ?? $config['word_count_max'] ); ?>" min="500" max="5000" style="width:80px;" /> words
                        </td>
                    </tr>
                </table>

                <!-- ════════════════════════════════════════════════════════ -->
                <!--  COMMUNE SELECTOR                                       -->
                <!-- ════════════════════════════════════════════════════════ -->
                <h2 style="margin-top:30px;">🏙️ Active Communes (<?php echo count( $communes ); ?> available)</h2>
                <p class="description" style="margin-bottom:10px;">
                    Select which communes to cover. Leave all unchecked = cover ALL communes. The bot will automatically rotate through selected communes, prioritizing those not written about recently.
                </p>
                <div style="background:#f8f9fa;border:1px solid #ddd;padding:15px 20px;border-radius:6px;margin-bottom:20px;">
                    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;">
                        <div>
                            <input type="text" id="dba-geo-commune-search-<?php echo esc_attr( $country_key ); ?>" placeholder="🔍 Search communes…" style="width:250px;padding:4px 8px;" />
                        </div>
                        <span>
                            <button type="button" onclick="document.querySelectorAll('.dba-geo-commune-cb-<?php echo esc_attr( $country_key ); ?>').forEach(c=>c.checked=true)" class="button button-small">Select All</button>
                            <button type="button" onclick="document.querySelectorAll('.dba-geo-commune-cb-<?php echo esc_attr( $country_key ); ?>').forEach(c=>c.checked=false)" class="button button-small">Deselect All</button>
                        </span>
                    </div>
                    <div style="max-height:400px;overflow-y:auto;column-count:3;column-gap:20px;">
                    <?php
                    $active = $settings['active_communes'] ?? array();
                    foreach ( $communes as $c ) :
                        $name = $c['commune'];
                        $pop  = $c['population'] ?? '';
                        $region_short = $c['region'] ?? '';
                    ?>
                        <label class="dba-geo-commune-item-<?php echo esc_attr( $country_key ); ?>" style="display:block;margin-bottom:3px;font-size:12px;white-space:nowrap;" data-name="<?php echo esc_attr( mb_strtolower( $name ) ); ?>">
                            <input type="checkbox" class="dba-geo-commune-cb-<?php echo esc_attr( $country_key ); ?>" name="<?php echo esc_attr( $config['settings_option'] ); ?>[active_communes][]" value="<?php echo esc_attr( $name ); ?>"
                                <?php checked( empty( $active ) || in_array( $name, $active, true ) ); ?> />
                            <?php echo esc_html( $name ); ?>
                            <span style="color:#999;font-size:10px;">(<?php echo esc_html( $pop ); ?>)</span>
                        </label>
                    <?php endforeach; ?>
                    </div>
                </div>

                <!-- ════════════════════════════════════════════════════════ -->
                <!--  PASTE / IMPORT CITIES                                  -->
                <!-- ════════════════════════════════════════════════════════ -->
                <h2 style="margin-top:30px;">📋 Import Cities (Paste List)</h2>
                <p class="description" style="margin-bottom:10px;">
                    Paste your city list below. Accepted formats (one city per line):
                </p>
                <div style="background:#fff8e1;border:1px solid #ffe082;padding:10px 15px;border-radius:4px;margin-bottom:12px;font-size:12px;">
                    <strong>Supported formats:</strong><br>
                    <code>City</code> &nbsp;|&nbsp;
                    <code>City, Department, Region</code> &nbsp;|&nbsp;
                    <code>City, Department, Region, Population</code><br>
                    <code>City | Department | Region</code> &nbsp;|&nbsp;
                    Tab-separated (copy from Excel) &nbsp;|&nbsp;
                    <code>Rank, City, Department, Region, Population</code> (rank column auto-skipped)
                </div>
                <div style="background:#f8f9fa;border:1px solid #ddd;padding:15px 20px;border-radius:6px;margin-bottom:20px;">
                    <textarea id="dba-geo-paste-cities-<?php echo esc_attr( $country_key ); ?>" rows="10" class="large-text" placeholder="Paris, Paris, Île-de-France, 2 103 778&#10;Marseille, Bouches-du-Rhône, Provence-Alpes-Côte d'Azur, 886 040&#10;Lyon, Métropole de Lyon, Auvergne-Rhône-Alpes, 519 127&#10;..."></textarea>
                    <div style="margin-top:10px;display:flex;align-items:center;gap:15px;">
                        <label style="font-size:13px;">
                            <input type="radio" name="dba_geo_import_mode_<?php echo esc_attr( $country_key ); ?>" value="replace" checked /> <strong>Replace</strong> all existing cities
                        </label>
                        <label style="font-size:13px;">
                            <input type="radio" name="dba_geo_import_mode_<?php echo esc_attr( $country_key ); ?>" value="append" /> <strong>Append</strong> to existing list (skip duplicates)
                        </label>
                        <button type="button" class="button button-primary dba-geo-import-cities" data-country="<?php echo esc_attr( $country_key ); ?>" style="margin-left:auto;">
                            📥 Import Cities
                        </button>
                    </div>
                    <div class="dba-geo-import-result-<?php echo esc_attr( $country_key ); ?>" style="display:none;margin-top:10px;padding:8px 12px;border-radius:4px;font-size:13px;"></div>
                </div>

                <!-- ════════════════════════════════════════════════════════ -->
                <!--  CTA SETTINGS                                           -->
                <!-- ════════════════════════════════════════════════════════ -->
                <h2 style="margin-top:30px;">📢 Call to Action</h2>
                <table class="form-table">
                    <tr>
                        <th>CTA Text</th>
                        <td>
                            <textarea name="<?php echo esc_attr( $config['settings_option'] ); ?>[cta_text]" rows="3" class="large-text"><?php echo esc_textarea( $settings['cta_text'] ?? $config['cta_text'] ); ?></textarea>
                        </td>
                    </tr>
                    <tr>
                        <th>CTA Link Text</th>
                        <td>
                            <input type="text" name="<?php echo esc_attr( $config['settings_option'] ); ?>[cta_link_text]" value="<?php echo esc_attr( $settings['cta_link_text'] ?? $config['cta_link_text'] ); ?>" class="regular-text" />
                        </td>
                    </tr>
                    <tr>
                        <th>CTA Link URL</th>
                        <td>
                            <input type="url" name="<?php echo esc_attr( $config['settings_option'] ); ?>[cta_link_url]" value="<?php echo esc_attr( $settings['cta_link_url'] ?? $config['cta_link_url'] ); ?>" class="regular-text" />
                        </td>
                    </tr>
                    <tr>
                        <th>Disable CTA</th>
                        <td>
                            <label>
                                <input type="checkbox" name="<?php echo esc_attr( $config['settings_option'] ); ?>[cta_disabled]" value="1" <?php checked( ! empty( $settings['cta_disabled'] ) ); ?> />
                                Don't append CTA block to posts
                            </label>
                        </td>
                    </tr>
                </table>

                <?php submit_button( 'Save ' . $config['flag'] . ' Settings' ); ?>
            </form>

            <!-- ════════════════════════════════════════════════════════ -->
            <!--  PLAGIARISM & GOOGLE COMPLIANCE STATUS                  -->
            <!-- ════════════════════════════════════════════════════════ -->
            <h2 style="margin-top:30px;">🛡️ Plagiarism Detection & Google Compliance</h2>
            <div style="background:#d4edda;border:1px solid #c3e6cb;padding:15px 20px;border-radius:6px;margin-bottom:20px;">
                <table style="width:100%;border-collapse:collapse;font-size:13px;">
                    <?php
                    $dba_settings = get_option( 'dba_settings', array() );
                    $has_copyscape = ! empty( $dba_settings['copyscape_user'] ) && ! empty( $dba_settings['copyscape_key'] );
                    $has_google_search = ! empty( $dba_settings['google_search_key'] ) && ! empty( $dba_settings['google_search_cx'] );
                    ?>
                    <tr>
                        <td style="padding:4px 8px;width:300px;">🟢 <strong>Internal duplicate detection</strong></td>
                        <td style="padding:4px 8px;">ACTIVE — Jaccard shingling (3-gram) against all existing posts. Threshold: 35% overlap = REJECT.</td>
                    </tr>
                    <tr>
                        <td style="padding:4px 8px;"><?php echo $has_copyscape ? '🟢' : '🟡'; ?> <strong>Copyscape API</strong></td>
                        <td style="padding:4px 8px;">
                            <?php echo $has_copyscape
                                ? 'ACTIVE — Premium API checking against global web index.'
                                : 'NOT CONFIGURED — Add Copyscape credentials in main DBA Settings for web-wide checking.'; ?>
                        </td>
                    </tr>
                    <tr>
                        <td style="padding:4px 8px;"><?php echo $has_google_search ? '🟢' : '🟡'; ?> <strong>Web sentence sampling</strong></td>
                        <td style="padding:4px 8px;">
                            <?php echo $has_google_search
                                ? 'ACTIVE — Random sentences verified via Google Custom Search. 40% match = REJECT.'
                                : 'NOT CONFIGURED — Add Google Custom Search API key in main DBA Settings. Falls back to internal-only.'; ?>
                        </td>
                    </tr>
                    <tr>
                        <td style="padding:4px 8px;">🟢 <strong>Sentence uniqueness gate</strong></td>
                        <td style="padding:4px 8px;">ACTIVE — Sentences compared at 90% similarity against existing GeoBot posts. Max 15% reuse allowed.</td>
                    </tr>
                    <tr>
                        <td style="padding:4px 8px;">🟢 <strong>Anti-template penalty</strong></td>
                        <td style="padding:4px 8px;">ACTIVE — AI prompted to use unique sentence structures per city. No boilerplate paragraphs.</td>
                    </tr>
                    <tr>
                        <td style="padding:4px 8px;">🟢 <strong>Google penalty rules</strong></td>
                        <td style="padding:4px 8px;">
                            ACTIVE — No <code>&lt;hr&gt;</code>, no <code>&lt;strong&gt;</code>, no city link in title, no "Last updated" text, no media source references. CTA excluded from plagiarism scoring.
                        </td>
                    </tr>
                </table>
                <p style="margin-top:12px;font-size:12px;color:#155724;">
                    <strong>Pipeline:</strong> Research → Generate → Validate (11 gates) → <strong>Plagiarism check (HARD GATE)</strong> → Structural clone check → Create post → Kaizen store → Yoast SEO → DALL-E image → Anti-Orphan linking → Publish.
                    <br>If any gate fails, the post is <strong>REJECTED</strong> — it never reaches WordPress.
                </p>
            </div>

            <!-- ════════════════════════════════════════════════════════ -->
            <!--  KAIZEN LEARNING ENGINE — Visible corrections + status    -->
            <!-- ════════════════════════════════════════════════════════ -->
            <?php
            $kaizen_loaded = class_exists( 'DBA_GeoBot_Kaizen' );
            $kaizen_corrections = array();
            $kaizen_overused    = array();
            if ( $kaizen_loaded ) {
                // Get raw learning context to display
                $kz_config   = DBA_GeoBot_Registry::get_country( $country_key );
                $kz_meta_key = $kz_config['meta_prefix'] . 'auto_created';
                $kz_recent   = get_posts( array(
                    'post_type'      => 'post',
                    'post_status'    => array( 'publish', 'draft' ),
                    'meta_key'       => $kz_meta_key,
                    'meta_compare'   => 'EXISTS',
                    'posts_per_page' => 15,
                    'fields'         => 'ids',
                    'date_query'     => array( array( 'after' => '5 days ago' ) ),
                    'orderby'        => 'date',
                    'order'          => 'DESC',
                ) );
                $kz_with_originals = 0;
                $kz_edited = 0;
                foreach ( $kz_recent as $kz_pid ) {
                    $orig = get_post_meta( $kz_pid, DBA_GeoBot_Kaizen::META_ORIGINAL_CONTENT, true );
                    if ( ! empty( $orig ) ) {
                        $kz_with_originals++;
                        $curr = get_post_field( 'post_content', $kz_pid );
                        $orig_wc = str_word_count( strip_tags( $orig ) );
                        $curr_wc = str_word_count( strip_tags( $curr ) );
                        if ( $orig_wc > 0 && abs( $curr_wc - $orig_wc ) / $orig_wc * 100 > 5 ) {
                            $kz_edited++;
                            $commune_name = get_post_meta( $kz_pid, $kz_config['meta_prefix'] . 'commune', true ) ?: "#{$kz_pid}";
                            $direction = $curr_wc > $orig_wc ? 'expanded' : 'trimmed';
                            $kaizen_corrections[] = array(
                                'post_id' => $kz_pid,
                                'commune' => $commune_name,
                                'type'    => "Content {$direction}: {$orig_wc} → {$curr_wc} words",
                            );
                        }
                        // Title check
                        $orig_title = get_post_meta( $kz_pid, DBA_GeoBot_Kaizen::META_ORIGINAL_TITLE, true );
                        $curr_title = get_the_title( $kz_pid );
                        if ( ! empty( $orig_title ) && $orig_title !== $curr_title ) {
                            $commune_name = get_post_meta( $kz_pid, $kz_config['meta_prefix'] . 'commune', true ) ?: "#{$kz_pid}";
                            $kaizen_corrections[] = array(
                                'post_id' => $kz_pid,
                                'commune' => $commune_name,
                                'type'    => "Title rewritten",
                            );
                        }
                    }
                }
                $kaizen_overused = DBA_GeoBot_Kaizen::get_overused_transitions( $country_key );
            }
            ?>
            <div style="background:<?php echo $kaizen_loaded ? '#ede7f6' : '#fce4ec'; ?>;border:1px solid <?php echo $kaizen_loaded ? '#b39ddb' : '#ef9a9a'; ?>;padding:15px 20px;border-radius:6px;margin-bottom:15px;">
                <h3 style="margin:0 0 10px;font-size:15px;">🧠 Kaizen Learning Engine — <?php echo $kaizen_loaded
                    ? '<span style="color:#4a148c;font-weight:bold;">ACTIVE</span>'
                    : '<span style="color:#c62828;font-weight:bold;">NOT LOADED — Upload class-geobot-kaizen.php</span>'; ?></h3>

                <?php if ( $kaizen_loaded ) : ?>
                <table style="width:100%;border-collapse:collapse;font-size:13px;margin-bottom:10px;">
                    <tr>
                        <td style="padding:4px 8px;width:30px;">📊</td>
                        <td style="padding:4px 8px;"><strong>Tracked Posts (last 5 days)</strong></td>
                        <td style="padding:4px 8px;"><?php echo $kz_with_originals; ?> posts have originals stored for diff tracking</td>
                    </tr>
                    <tr>
                        <td style="padding:4px 8px;">✏️</td>
                        <td style="padding:4px 8px;"><strong>Editor Corrections Detected</strong></td>
                        <td style="padding:4px 8px;">
                            <?php if ( ! empty( $kaizen_corrections ) ) : ?>
                                <span style="color:#e65100;font-weight:bold;"><?php echo count( $kaizen_corrections ); ?> corrections found</span> — AI will learn from these on next generation
                            <?php else : ?>
                                <span style="color:#2e7d32;">No corrections detected — AI output matches published content</span>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php if ( ! empty( $kaizen_overused ) ) : ?>
                    <tr>
                        <td style="padding:4px 8px;">⚠️</td>
                        <td style="padding:4px 8px;"><strong>Overused Transitions</strong></td>
                        <td style="padding:4px 8px;color:#e65100;"><?php echo count( $kaizen_overused ); ?> transitions blacklisted for next generation</td>
                    </tr>
                    <?php endif; ?>
                </table>

                <?php if ( ! empty( $kaizen_corrections ) ) : ?>
                <div style="background:#fff;border:1px solid #d1c4e9;border-radius:4px;padding:10px 15px;margin-bottom:10px;max-height:200px;overflow-y:auto;font-size:12px;">
                    <strong>Recent corrections (injected into AI prompt):</strong><br>
                    <?php foreach ( array_slice( $kaizen_corrections, 0, 10 ) as $kc ) : ?>
                        <div style="padding:3px 0;border-bottom:1px solid #f0f0f0;">
                            📝 <a href="<?php echo admin_url( 'post.php?post=' . $kc['post_id'] . '&action=edit' ); ?>" target="_blank"><?php echo esc_html( $kc['commune'] ); ?></a>
                            — <?php echo esc_html( $kc['type'] ); ?>
                        </div>
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>

                <?php if ( ! empty( $kaizen_overused ) ) : ?>
                <div style="background:#fff3e0;border:1px solid #ffcc80;border-radius:4px;padding:10px 15px;margin-bottom:10px;font-size:12px;">
                    <strong>Blacklisted transitions (AI told to avoid these):</strong><br>
                    <?php foreach ( array_slice( $kaizen_overused, 0, 8 ) as $ot ) : ?>
                        <span style="display:inline-block;background:#fff;border:1px solid #e0e0e0;border-radius:3px;padding:2px 8px;margin:2px 4px;font-size:11px;">✗ <?php echo esc_html( $ot ); ?></span>
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>

                <div style="display:flex;gap:10px;align-items:center;">
                    <button type="button" class="button dba-geo-flush-kaizen" data-country="<?php echo esc_attr( $country_key ); ?>">
                        🔄 Flush Kaizen Cache
                    </button>
                    <span class="dba-geo-kaizen-result-<?php echo esc_attr( $country_key ); ?>" style="font-size:13px;"></span>
                </div>
                <?php endif; ?>
            </div>

            <!-- ════════════════════════════════════════════════════════ -->
            <!--  ANTI-ORPHAN PROTECTION — Audit panel                    -->
            <!-- ════════════════════════════════════════════════════════ -->
            <?php
            $ao_loaded = class_exists( 'DBA_GeoBot_Anti_Orphan' );
            $ao_hub_id = intval( get_option( 'dba_geo_' . $country_key . '_hub_page_id', 0 ) );
            $ao_hub_ok = $ao_hub_id && get_post_status( $ao_hub_id ) && get_post_status( $ao_hub_id ) !== 'trash';
            $ao_hub_content = $ao_hub_ok ? get_post_field( 'post_content', $ao_hub_id ) : '';

            // Count orphans by checking hub content for permalinks
            $ao_all_posts = array();
            $ao_orphan_count = 0;
            $ao_orphan_list = array();
            if ( $ao_hub_ok ) {
                $ao_meta_key = $config['meta_prefix'] . 'auto_created';
                $ao_all_posts = get_posts( array(
                    'post_type'      => 'post',
                    'post_status'    => 'publish',
                    'posts_per_page' => -1,
                    'meta_query'     => array(
                        array( 'key' => $ao_meta_key, 'compare' => 'EXISTS' ),
                    ),
                    'fields' => 'ids',
                ) );
                foreach ( $ao_all_posts as $ao_pid ) {
                    if ( $ao_pid == $ao_hub_id ) continue;
                    $plink = get_permalink( $ao_pid );
                    if ( $plink && strpos( $ao_hub_content, $plink ) === false ) {
                        $ao_orphan_count++;
                        if ( count( $ao_orphan_list ) < 10 ) {
                            $ao_orphan_list[] = array(
                                'id'      => $ao_pid,
                                'title'   => get_the_title( $ao_pid ),
                                'commune' => get_post_meta( $ao_pid, $config['meta_prefix'] . 'commune', true ),
                            );
                        }
                    }
                }
            }
            $ao_total = count( $ao_all_posts );

            // Cross-link stats
            $ao_with_related = 0;
            foreach ( array_slice( $ao_all_posts, 0, 50 ) as $ao_pid ) {
                $pc = get_post_field( 'post_content', $ao_pid );
                if ( strpos( $pc, 'geobot-related-cities' ) !== false || strpos( $pc, 'GeoBot Internal Linking Block' ) !== false ) {
                    $ao_with_related++;
                }
            }

            // Verification cron
            $ao_next_audit = wp_next_scheduled( 'dba_geobot_weekly_orphan_audit' );
            ?>
            <div style="background:<?php echo $ao_orphan_count > 0 ? '#fff3e0' : '#e8f5e9'; ?>;border:1px solid <?php echo $ao_orphan_count > 0 ? '#ffcc80' : '#a5d6a7'; ?>;padding:15px 20px;border-radius:6px;margin-bottom:15px;">
                <h3 style="margin:0 0 10px;font-size:15px;">🛡️ Anti-Orphan Protection — <?php
                    if ( ! $ao_loaded ) {
                        echo '<span style="color:#c62828;font-weight:bold;">NOT LOADED — Upload class-geobot-anti-orphan.php</span>';
                    } elseif ( $ao_orphan_count > 0 ) {
                        echo '<span style="color:#e65100;font-weight:bold;">' . $ao_orphan_count . ' ORPHAN' . ( $ao_orphan_count > 1 ? 'S' : '' ) . ' DETECTED</span>';
                    } else {
                        echo '<span style="color:#2e7d32;font-weight:bold;">ALL POSTS LINKED ✓</span>';
                    }
                ?></h3>

                <table style="width:100%;border-collapse:collapse;font-size:13px;margin-bottom:10px;">
                    <tr>
                        <td style="padding:4px 8px;width:30px;"><?php echo $ao_hub_ok ? '✅' : '❌'; ?></td>
                        <td style="padding:4px 8px;width:220px;"><strong>Hub Page</strong></td>
                        <td style="padding:4px 8px;">
                            <?php if ( $ao_hub_ok ) : ?>
                                <a href="<?php echo esc_url( get_permalink( $ao_hub_id ) ); ?>" target="_blank">#<?php echo $ao_hub_id; ?></a> — active
                            <?php else : ?>
                                <span style="color:#c62828;">Not created. Use "Generate Hub Post" above.</span>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <tr>
                        <td style="padding:4px 8px;"><?php echo $ao_orphan_count === 0 ? '✅' : '⚠️'; ?></td>
                        <td style="padding:4px 8px;"><strong>Hub → Post Links</strong></td>
                        <td style="padding:4px 8px;">
                            <?php echo ( $ao_total - $ao_orphan_count ); ?>/<?php echo $ao_total; ?> posts linked from hub
                            <?php if ( $ao_orphan_count > 0 ) : ?>
                                — <span style="color:#e65100;font-weight:bold;"><?php echo $ao_orphan_count; ?> orphans not in hub page</span>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <tr>
                        <td style="padding:4px 8px;"><?php echo $ao_with_related > 0 ? '✅' : '⚠️'; ?></td>
                        <td style="padding:4px 8px;"><strong>Cross-City Links</strong></td>
                        <td style="padding:4px 8px;"><?php echo $ao_with_related; ?>/<?php echo min( $ao_total, 50 ); ?> checked posts have "Related Cities" block</td>
                    </tr>
                    <tr>
                        <td style="padding:4px 8px;"><?php echo $ao_loaded ? '✅' : '❌'; ?></td>
                        <td style="padding:4px 8px;"><strong>Auto-Link on Publish</strong></td>
                        <td style="padding:4px 8px;"><?php echo $ao_loaded ? 'New posts are auto-linked to hub + cross-linked to related cities' : 'NOT ACTIVE — class not loaded'; ?></td>
                    </tr>
                    <tr>
                        <td style="padding:4px 8px;"><?php echo $ao_next_audit ? '✅' : '⚠️'; ?></td>
                        <td style="padding:4px 8px;"><strong>Weekly Audit Cron</strong></td>
                        <td style="padding:4px 8px;">
                            <?php echo $ao_next_audit
                                ? 'Next: ' . esc_html( date( 'Y-m-d H:i', $ao_next_audit ) )
                                : 'Not scheduled'; ?>
                        </td>
                    </tr>
                </table>

                <?php if ( $ao_orphan_count > 0 && ! empty( $ao_orphan_list ) ) : ?>
                <div style="background:#fff;border:1px solid #ffcc80;border-radius:4px;padding:10px 15px;margin-bottom:10px;max-height:180px;overflow-y:auto;font-size:12px;">
                    <strong>Orphaned posts (not linked from hub):</strong><br>
                    <?php foreach ( $ao_orphan_list as $ao_item ) : ?>
                        <div style="padding:3px 0;border-bottom:1px solid #f0f0f0;">
                            ❌ <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['commune'] ?: $ao_item['title'] ); ?></a>
                        </div>
                    <?php endforeach; ?>
                    <?php if ( $ao_orphan_count > 10 ) : ?>
                        <div style="padding:3px 0;color:#999;">… and <?php echo $ao_orphan_count - 10; ?> more</div>
                    <?php endif; ?>
                </div>
                <?php endif; ?>

                <?php if ( $ao_loaded ) : ?>
                <div style="display:flex;gap:10px;align-items:center;">
                    <button type="button" class="button button-primary dba-geo-run-audit" data-country="<?php echo esc_attr( $country_key ); ?>" <?php echo $ao_orphan_count === 0 ? 'disabled' : ''; ?>>
                        🔧 Fix All Orphans Now (<?php echo $ao_orphan_count; ?>)
                    </button>
                    <span class="dba-geo-audit-result-<?php echo esc_attr( $country_key ); ?>" style="font-size:13px;"></span>
                </div>
                <?php endif; ?>
            </div>

            <!-- ════════════════════════════════════════════════════════ -->
            <!--  ZERO CONFLICT INFO                                     -->
            <!-- ════════════════════════════════════════════════════════ -->
            <h2 style="margin-top:30px;">🔒 Isolation Keys</h2>
            <div style="background:#f0f8ff;border:1px solid #b8d4e3;padding:15px 20px;border-radius:6px;margin-bottom:20px;">
                <table style="width:100%;border-collapse:collapse;font-size:13px;">
                    <tr><td style="padding:3px 8px;font-weight:bold;">Cron hook</td><td style="padding:3px 8px;"><code><?php echo esc_html( $config['cron_hook'] ); ?></code></td></tr>
                    <tr><td style="padding:3px 8px;font-weight:bold;">Settings option</td><td style="padding:3px 8px;"><code><?php echo esc_html( $config['settings_option'] ); ?></code></td></tr>
                    <tr><td style="padding:3px 8px;font-weight:bold;">Post meta prefix</td><td style="padding:3px 8px;"><code><?php echo esc_html( $config['meta_prefix'] ); ?>*</code></td></tr>
                    <tr><td style="padding:3px 8px;font-weight:bold;">Progress transient</td><td style="padding:3px 8px;"><code><?php echo esc_html( $config['progress_transient'] ); ?></code></td></tr>
                    <tr><td style="padding:3px 8px;font-weight:bold;">History option</td><td style="padding:3px 8px;"><code><?php echo esc_html( $config['history_option'] ); ?></code></td></tr>
                    <tr><td style="padding:3px 8px;font-weight:bold;">WPML code</td><td style="padding:3px 8px;"><code><?php echo esc_html( $config['wpml_code'] ); ?></code></td></tr>
                    <tr><td style="padding:3px 8px;font-weight:bold;">Timezone</td><td style="padding:3px 8px;"><code><?php echo esc_html( $config['timezone'] ); ?></code></td></tr>
                </table>
            </div>

        </div>

        <script>
        // Commune search filter
        (function() {
            var key = '<?php echo esc_js( $country_key ); ?>';
            var input = document.getElementById('dba-geo-commune-search-' + key);
            if (input) {
                input.addEventListener('input', function() {
                    var q = this.value.toLowerCase();
                    document.querySelectorAll('.dba-geo-commune-item-' + key).forEach(function(el) {
                        el.style.display = el.dataset.name.indexOf(q) >= 0 ? '' : 'none';
                    });
                });
            }
        })();

        // ═══════════════════════════════════════════════════════════
        //  Hub Post & Retroactive Link handlers
        // ═══════════════════════════════════════════════════════════
        (function() {
            var key = '<?php echo esc_js( $country_key ); ?>';
            var nonce = '<?php echo wp_create_nonce( 'dba_admin_nonce' ); ?>';

            // Safe JSON parser — catches PHP errors/warnings in response
            function safeJson(r) {
                return r.text().then(function(txt) {
                    try { return JSON.parse(txt); }
                    catch(e) {
                        var clean = txt.replace(/^[\s\S]*?(\{)/,'$1');
                        try { return JSON.parse(clean); }
                        catch(e2) { return {success:false, data:'Server returned invalid response (PHP error). Check error_log.'}; }
                    }
                });
            }

            // Category search filter
            var catSearch = document.getElementById('dba-geo-cat-search-' + key);
            if (catSearch) {
                catSearch.addEventListener('input', function() {
                    var q = this.value.toLowerCase();
                    document.querySelectorAll('.dba-geo-cat-item-' + key).forEach(function(el) {
                        el.style.display = el.dataset.name.indexOf(q) >= 0 ? '' : 'none';
                    });
                });
            }

            function showHubResult(msg, isError) {
                var el = document.querySelector('.dba-geo-hub-result-' + key);
                if (el) {
                    el.innerHTML = msg;
                    el.style.color = isError ? '#c62828' : '#2e7d32';
                }
            }

            // Generate / Update Hub Post
            document.querySelectorAll('.dba-geo-generate-hub[data-country="' + key + '"]').forEach(function(btn) {
                btn.addEventListener('click', function() {
                    // Collect selected category IDs
                    var catIds = [];
                    document.querySelectorAll('input[name="dba_hub_cat_' + key + '[]"]:checked').forEach(function(cb) {
                        catIds.push(cb.value);
                    });

                    btn.disabled = true;
                    showHubResult('⏳ Generating hub post…', false);

                    var data = new FormData();
                    data.append('action', 'dba_geo_update_hub');
                    data.append('nonce', nonce);
                    data.append('country_key', key);
                    catIds.forEach(function(id) {
                        data.append('category_ids[]', id);
                    });

                    fetch(ajaxurl, { method: 'POST', body: data })
                        .then(safeJson)
                        .then(function(r) {
                            btn.disabled = false;
                            if (r.success) {
                                var d = r.data;
                                var cats = d.categories ? d.categories.join(', ') : '';
                                showHubResult('✅ ' + d.message + (cats ? ' | Categories: ' + cats : ''), false);
                                // Update button text
                                btn.innerHTML = '🔄 Update Hub Post';
                            } else {
                                showHubResult('❌ ' + (r.data || 'Unknown error'), true);
                            }
                        })
                        .catch(function(e) {
                            btn.disabled = false;
                            showHubResult('❌ ' + e.message, true);
                        });
                });
            });

            // Fix All Orphan Posts (retroactive linking)
            document.querySelectorAll('.dba-geo-retroactive-link[data-country="' + key + '"]').forEach(function(btn) {
                btn.addEventListener('click', function() {
                    btn.disabled = true;
                    showHubResult('⏳ Linking orphan posts…', false);

                    var data = new FormData();
                    data.append('action', 'dba_geo_retroactive_link');
                    data.append('nonce', nonce);
                    data.append('country_key', key);

                    fetch(ajaxurl, { method: 'POST', body: data })
                        .then(safeJson)
                        .then(function(r) {
                            btn.disabled = false;
                            if (r.success) {
                                var d = r.data;
                                var msg = d.message || ('Linked ' + (d.updated||0) + '/' + (d.total_posts||0) + ' posts, hub: ' + (d.hub_page||'n/a'));
                                showHubResult('✅ ' + msg, false);
                            } else {
                                showHubResult('❌ ' + (r.data || 'Unknown error'), true);
                            }
                        })
                        .catch(function(e) {
                            btn.disabled = false;
                            showHubResult('❌ ' + e.message, true);
                        });
                });
            });
        })();

        // ═══════════════════════════════════════════════════════════
        //  Inbound Link Scanner AJAX handlers
        // ═══════════════════════════════════════════════════════════
        (function() {
            var key = '<?php echo esc_js( $country_key ); ?>';
            var nonce = '<?php echo wp_create_nonce( 'dba_admin_nonce' ); ?>';

            function showResult(msg, isError) {
                var el = document.querySelector('.dba-geo-inbound-result-' + key);
                if (el) {
                    el.innerHTML = msg;
                    el.style.color = isError ? '#c62828' : '#2e7d32';
                }
            }

            function showDetails(details) {
                var el = document.querySelector('.dba-geo-inbound-details-' + key);
                if (!el || !details || !details.length) return;
                var html = '<strong>Posts updated:</strong><br>';
                details.forEach(function(d) {
                    var tierLabel = d.tier === 1 ? '🟢T1' : d.tier === 2 ? '🟡T2' : '⚪T3';
                    html += '• ' + tierLabel + ' <a href="post.php?post=' + d.post_id + '&action=edit" target="_blank">' + d.title + '</a> → linked: ' + d.links.join(', ') + '<br>';
                });
                el.innerHTML = html;
                el.style.display = 'block';
            }

            function runScan(countryKey, forceRescan) {
                showResult('⏳ Scanning posts…', false);
                var data = new FormData();
                data.append('action', 'dba_geo_inbound_scan');
                data.append('nonce', nonce);
                data.append('country_key', countryKey);
                if (forceRescan) data.append('force_rescan', '1');

                fetch(ajaxurl, { method: 'POST', body: data })
                    .then(safeJson)
                    .then(function(r) {
                        if (r.success) {
                            var d = r.data;
                            if (d.error) {
                                showResult('⚠️ ' + d.error, true);
                            } else {
                                var msg = '✅ Targets: ' + (d.targets_count || 0)
                                    + ' | Scanned: ' + d.scanned
                                    + ' (T1:' + (d.tier1_scanned||0) + ' T2:' + (d.tier2_scanned||0) + ' T3:' + (d.tier3_scanned||0) + ')'
                                    + ' | ' + d.links_injected + ' links added to ' + d.linked + ' posts';
                                showResult(msg, false);
                                showDetails(d.details);
                            }
                        } else {
                            showResult('❌ ' + (r.data || 'Unknown error'), true);
                        }
                    })
                    .catch(function(e) { showResult('❌ ' + e.message, true); });
            }

            // Scan (single country)
            document.querySelectorAll('.dba-geo-inbound-scan[data-country="' + key + '"]').forEach(function(btn) {
                btn.addEventListener('click', function() { runScan(key, false); });
            });

            // Scan (all countries)
            document.querySelectorAll('.dba-geo-inbound-scan-all').forEach(function(btn) {
                btn.addEventListener('click', function() { runScan('all', false); });
            });

            // Force re-scan
            document.querySelectorAll('.dba-geo-inbound-rescan[data-country="' + key + '"]').forEach(function(btn) {
                btn.addEventListener('click', function() {
                    if (confirm('This will strip existing GeoBot inbound links from all posts and re-scan. Continue?')) {
                        runScan(key, true);
                    }
                });
            });

            // Strip all
            document.querySelectorAll('.dba-geo-inbound-strip').forEach(function(btn) {
                btn.addEventListener('click', function() {
                    if (!confirm('This will REMOVE all GeoBot inbound links from every post on the site. This cannot be undone. Are you sure?')) return;
                    showResult('⏳ Stripping links…', false);
                    var data = new FormData();
                    data.append('action', 'dba_geo_inbound_strip');
                    data.append('nonce', nonce);
                    fetch(ajaxurl, { method: 'POST', body: data })
                        .then(safeJson)
                        .then(function(r) {
                            if (r.success) {
                                showResult('✅ Stripped links from ' + r.data.posts_cleaned + ' posts. Meta removed from ' + r.data.meta_removed + ' posts.', false);
                            } else {
                                showResult('❌ ' + (r.data || 'Unknown error'), true);
                            }
                        })
                        .catch(function(e) { showResult('❌ ' + e.message, true); });
                });
            });
        })();
        // ═══════════════════════════════════════════════════════════
        //  Kaizen Flush Cache handler
        // ═══════════════════════════════════════════════════════════
        (function() {
            var key = '<?php echo esc_js( $country_key ); ?>';
            var nonce = '<?php echo wp_create_nonce( 'dba_admin_nonce' ); ?>';

            document.querySelectorAll('.dba-geo-flush-kaizen[data-country="' + key + '"]').forEach(function(btn) {
                btn.addEventListener('click', function() {
                    btn.disabled = true;
                    var el = document.querySelector('.dba-geo-kaizen-result-' + key);
                    if (el) { el.innerHTML = '⏳ Flushing…'; el.style.color = '#555'; }

                    var data = new FormData();
                    data.append('action', 'dba_geo_flush_kaizen_cache');
                    data.append('nonce', nonce);
                    data.append('country_key', key);

                    fetch(ajaxurl, { method: 'POST', body: data })
                        .then(safeJson)
                        .then(function(r) {
                            btn.disabled = false;
                            if (el) {
                                if (r.success) {
                                    el.innerHTML = '✅ ' + r.data.message;
                                    el.style.color = '#2e7d32';
                                } else {
                                    el.innerHTML = '❌ ' + (r.data || 'Unknown error');
                                    el.style.color = '#c62828';
                                }
                            }
                        })
                        .catch(function(e) {
                            btn.disabled = false;
                            if (el) { el.innerHTML = '❌ ' + e.message; el.style.color = '#c62828'; }
                        });
                });
            });
        })();

        // ═══════════════════════════════════════════════════════════
        //  Anti-Orphan Audit handler
        // ═══════════════════════════════════════════════════════════
        (function() {
            var key = '<?php echo esc_js( $country_key ); ?>';
            var nonce = '<?php echo wp_create_nonce( 'dba_admin_nonce' ); ?>';

            document.querySelectorAll('.dba-geo-run-audit[data-country="' + key + '"]').forEach(function(btn) {
                btn.addEventListener('click', function() {
                    btn.disabled = true;
                    var el = document.querySelector('.dba-geo-audit-result-' + key);
                    if (el) { el.innerHTML = '⏳ Running orphan audit…'; el.style.color = '#555'; }

                    var data = new FormData();
                    data.append('action', 'dba_geo_run_orphan_audit');
                    data.append('nonce', nonce);
                    data.append('country_key', key);

                    fetch(ajaxurl, { method: 'POST', body: data })
                        .then(safeJson)
                        .then(function(r) {
                            btn.disabled = false;
                            if (el) {
                                if (r.success) {
                                    var d = r.data;
                                    el.innerHTML = '✅ Audit complete — Total: ' + d.total + ' | Orphaned: ' + d.orphaned + ' | Fixed: ' + d.fixed;
                                    el.style.color = d.fixed > 0 ? '#2e7d32' : '#555';
                                    if (d.fixed > 0) {
                                        btn.innerHTML = '🔧 Fix All Orphans Now (' + (d.orphaned - d.fixed) + ')';
                                        if (d.orphaned - d.fixed <= 0) btn.disabled = true;
                                    }
                                } else {
                                    el.innerHTML = '❌ ' + (r.data || 'Unknown error');
                                    el.style.color = '#c62828';
                                }
                            }
                        })
                        .catch(function(e) {
                            btn.disabled = false;
                            if (el) { el.innerHTML = '❌ ' + e.message; el.style.color = '#c62828'; }
                        });
                });
            });
        })();

        </script>
        <?php
    }
}
