<?php

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

class AIEO_DMM_Brand_Extras extends AIEO_DMM_Module_Base {

    public function get_id()       { return 'brand_extras'; }
    public function get_label()    { return __('Brand Extras', 'ai-eshop-optimizer'); }
    public function get_priority() { return 76; }
    public function get_group()    { return 'visuals'; }

    public function register_hooks() {
        add_action('wp_ajax_aieo_dmm_brand_extras_save', array($this, 'ajax_save'));

        
        
        
        $migrator_file = AIEO_DIR . 'includes/dmm/migrators/class-aieo-dmm-brand-pods-migrator.php';
        if (file_exists($migrator_file)) {
            require_once $migrator_file;
            if (class_exists('AIEO_DMM_Brand_Pods_Migrator')) {
                AIEO_DMM_Brand_Pods_Migrator::register();
            }
        }

        if (!is_admin()) { return; }

        foreach (AIEO_DMM_Brand_Extras_Data::managed_taxonomies() as $tax) {
            
            
            
            add_action($tax . '_edit_form_fields', array($this, 'render_term_extras'), 1, 2);
            add_action('edited_'  . $tax,         array($this, 'save_term_extras'),    10, 2);
            add_action('created_' . $tax,         array($this, 'save_term_extras'),    10, 2);
        }
        add_action('admin_enqueue_scripts', array($this, 'enqueue_term_admin_assets'));
    }

    
    public function render_term_extras($term, $taxonomy) {
        if (!is_object($term) || !isset($term->term_id)) { return; }
        if (!in_array($taxonomy, AIEO_DMM_Brand_Extras_Data::managed_taxonomies(), true)) { return; }

        $row = AIEO_DMM_Brand_Extras_Data::get($taxonomy, (int) $term->term_id);
        $logo_url    = $row['logo_image_id'] ? wp_get_attachment_image_url((int) $row['logo_image_id'], 'medium') : '';
        $hero_url    = $row['hero_image_id'] ? wp_get_attachment_image_url((int) $row['hero_image_id'], 'medium') : '';
        $supplier_label = '';
        if ($row['supplier_term_id']) {
            $sup_term = get_term((int) $row['supplier_term_id']);
            if ($sup_term && !is_wp_error($sup_term)) { $supplier_label = $sup_term->name; }
        }
        ?>
        <tr class="form-field aieo-ce-panel-row">
            <th colspan="2" style="padding:0;">
                <div class="aieo-ce-panel" data-aieo-ce-panel data-term-id="<?php echo (int) $term->term_id; ?>" data-taxonomy="<?php echo esc_attr($taxonomy); ?>">
                    <?php wp_nonce_field('aieo_be_term_edit_' . (int) $term->term_id, 'aieo_be_nonce'); ?>
                    <div class="aieo-ce-panel-head">
                        <h2><?php esc_html_e('AIEO Brand Extras', 'ai-eshop-optimizer'); ?></h2>
                        <p class="description"><?php esc_html_e('Stored in wp_aieo_dmm_brand_extras + wp_aieo_dmm_term_relations. Replaces the Pods pwb-brand fields. Pods data above (if still present) keeps its existing storage during the transition.', 'ai-eshop-optimizer'); ?></p>
                    </div>

                    <nav class="aieo-ce-tabs" role="tablist">
                        <button type="button" class="aieo-ce-tab is-active" data-aieo-ce-tab="hero"    role="tab" aria-selected="true"><?php esc_html_e('Hero', 'ai-eshop-optimizer'); ?></button>
                        <button type="button" class="aieo-ce-tab"           data-aieo-ce-tab="about"   role="tab" aria-selected="false"><?php esc_html_e('About', 'ai-eshop-optimizer'); ?></button>
                        <button type="button" class="aieo-ce-tab"           data-aieo-ce-tab="catalog" role="tab" aria-selected="false"><?php esc_html_e('Catalog', 'ai-eshop-optimizer'); ?></button>
                        <button type="button" class="aieo-ce-tab"           data-aieo-ce-tab="footer"  role="tab" aria-selected="false"><?php esc_html_e('Footer', 'ai-eshop-optimizer'); ?></button>
                        <button type="button" class="aieo-ce-tab"           data-aieo-ce-tab="related" role="tab" aria-selected="false"><?php esc_html_e('Related', 'ai-eshop-optimizer'); ?></button>
                    </nav>

                    <!-- ── Tab: Hero ─────────────────────────────────────── -->
                    <div class="aieo-ce-tabpanel is-active" data-aieo-ce-pane="hero" role="tabpanel">
                        <div class="aieo-ce-grid-2">
                            <div class="aieo-ce-field aieo-ce-image-field" data-aieo-ce-image="logo">
                                <label><?php esc_html_e('Brand logo', 'ai-eshop-optimizer'); ?></label>
                                <div class="aieo-ce-image-preview"<?php echo $logo_url ? '' : ' style="display:none;"'; ?>>
                                    <?php if ($logo_url): ?><img src="<?php echo esc_url($logo_url); ?>" alt="" /><?php endif; ?>
                                </div>
                                <input type="hidden" name="aieo_be[logo_image_id]" value="<?php echo (int) $row['logo_image_id']; ?>" />
                                <button type="button" class="button aieo-ce-image-pick"><?php esc_html_e('Select / change', 'ai-eshop-optimizer'); ?></button>
                                <button type="button" class="button-link aieo-ce-image-clear"<?php echo $logo_url ? '' : ' style="display:none;"'; ?>><?php esc_html_e('Remove', 'ai-eshop-optimizer'); ?></button>
                                <p class="description"><?php esc_html_e('Used in brand badges, sidebar, brand archive header. Square or wide-aspect.', 'ai-eshop-optimizer'); ?></p>
                            </div>
                            <div class="aieo-ce-field aieo-ce-image-field" data-aieo-ce-image="hero">
                                <label><?php esc_html_e('Hero / banner image', 'ai-eshop-optimizer'); ?></label>
                                <div class="aieo-ce-image-preview"<?php echo $hero_url ? '' : ' style="display:none;"'; ?>>
                                    <?php if ($hero_url): ?><img src="<?php echo esc_url($hero_url); ?>" alt="" /><?php endif; ?>
                                </div>
                                <input type="hidden" name="aieo_be[hero_image_id]" value="<?php echo (int) $row['hero_image_id']; ?>" />
                                <button type="button" class="button aieo-ce-image-pick"><?php esc_html_e('Select / change', 'ai-eshop-optimizer'); ?></button>
                                <button type="button" class="button-link aieo-ce-image-clear"<?php echo $hero_url ? '' : ' style="display:none;"'; ?>><?php esc_html_e('Remove', 'ai-eshop-optimizer'); ?></button>
                                <p class="description"><?php esc_html_e('Wide banner shown on the brand archive page header.', 'ai-eshop-optimizer'); ?></p>
                            </div>
                        </div>
                        <div class="aieo-ce-field">
                            <label for="aieo-be-headline"><?php esc_html_e('Headline (one-liner)', 'ai-eshop-optimizer'); ?></label>
                            <input type="text" id="aieo-be-headline" name="aieo_be[headline]" value="<?php echo esc_attr((string) $row['headline']); ?>" class="large-text" />
                            <p class="description"><?php esc_html_e('Short tagline rendered next to the brand logo on the archive header.', 'ai-eshop-optimizer'); ?></p>
                        </div>
                    </div>

                    <!-- ── Tab: About ────────────────────────────────────── -->
                    <div class="aieo-ce-tabpanel" data-aieo-ce-pane="about" role="tabpanel">
                        <div class="aieo-ce-field aieo-ce-rich-field">
                            <label for="aieo_be_history_text"><?php esc_html_e('Brand history', 'ai-eshop-optimizer'); ?></label>
                            <?php wp_editor(
                                (string) $row['history_text'],
                                'aieo_be_history_text',
                                array(
                                    'textarea_name' => 'aieo_be[history_text]',
                                    'textarea_rows' => 8,
                                    'media_buttons' => true,
                                    'teeny'         => false,
                                    'quicktags'     => true,
                                )
                            ); ?>
                        </div>
                        <div class="aieo-ce-field aieo-ce-rich-field">
                            <label for="aieo_be_ambassadors_text"><?php esc_html_e('Brand ambassadors', 'ai-eshop-optimizer'); ?></label>
                            <?php wp_editor(
                                (string) $row['ambassadors_text'],
                                'aieo_be_ambassadors_text',
                                array(
                                    'textarea_name' => 'aieo_be[ambassadors_text]',
                                    'textarea_rows' => 5,
                                    'media_buttons' => true,
                                    'teeny'         => false,
                                    'quicktags'     => true,
                                )
                            ); ?>
                        </div>
                        <div class="aieo-ce-field aieo-ce-rich-field">
                            <label for="aieo_be_importer_text"><?php esc_html_e('Importer / distributor info', 'ai-eshop-optimizer'); ?></label>
                            <?php wp_editor(
                                (string) $row['importer_text'],
                                'aieo_be_importer_text',
                                array(
                                    'textarea_name' => 'aieo_be[importer_text]',
                                    'textarea_rows' => 4,
                                    'media_buttons' => false,
                                    'teeny'         => true,
                                    'quicktags'     => true,
                                )
                            ); ?>
                            <p class="description"><?php esc_html_e('Short paragraph about who imports / distributes this brand in your country.', 'ai-eshop-optimizer'); ?></p>
                        </div>
                    </div>

                    <!-- ── Tab: Catalog ──────────────────────────────────── -->
                    <div class="aieo-ce-tabpanel" data-aieo-ce-pane="catalog" role="tabpanel">
                        <div class="aieo-ce-grid-2">
                            <div class="aieo-ce-field">
                                <label for="aieo-be-website"><?php esc_html_e('Brand website', 'ai-eshop-optimizer'); ?></label>
                                <input type="url" id="aieo-be-website" name="aieo_be[website_url]" value="<?php echo esc_url((string) $row['website_url']); ?>" class="large-text" placeholder="https://" />
                                <p class="description"><?php esc_html_e('Linked from the brand archive header.', 'ai-eshop-optimizer'); ?></p>
                            </div>
                            <div class="aieo-ce-field">
                                <label><?php esc_html_e('Promotional brand?', 'ai-eshop-optimizer'); ?></label>
                                <label class="aieo-ce-radio">
                                    <input type="radio" name="aieo_be[promo]" value="1" <?php checked((int) $row['promo'], 1); ?> />
                                    <?php esc_html_e('Yes — feature in promo blocks', 'ai-eshop-optimizer'); ?>
                                </label><br>
                                <label class="aieo-ce-radio">
                                    <input type="radio" name="aieo_be[promo]" value="0" <?php checked((int) $row['promo'], 0); ?> />
                                    <?php esc_html_e('No', 'ai-eshop-optimizer'); ?>
                                </label>
                            </div>
                        </div>
                        <div class="aieo-ce-grid-2">
                            <div class="aieo-ce-field">
                                <label for="aieo-be-priority"><?php esc_html_e('Priority (sort weight)', 'ai-eshop-optimizer'); ?></label>
                                <input type="number" id="aieo-be-priority" name="aieo_be[priority]" value="<?php echo (int) $row['priority']; ?>" step="1" />
                                <p class="description"><?php esc_html_e('Higher = surfaced earlier in brand lists. 0 = default.', 'ai-eshop-optimizer'); ?></p>
                            </div>
                            <div class="aieo-ce-field">
                                <label for="aieo-be-bias"><?php esc_html_e('Brand bias (0.00 – 1.00)', 'ai-eshop-optimizer'); ?></label>
                                <input type="range" id="aieo-be-bias" name="aieo_be[bias]" min="0" max="1" step="0.01" value="<?php echo esc_attr(number_format((float) $row['bias'], 2, '.', '')); ?>"
                                       oninput="this.nextElementSibling.textContent = parseFloat(this.value).toFixed(2);" />
                                <span class="aieo-ce-range-value"><?php echo esc_html(number_format((float) $row['bias'], 2, '.', '')); ?></span>
                                <p class="description"><?php esc_html_e('Influences product ranking when the brand is among multiple matches. 0 = no bias.', 'ai-eshop-optimizer'); ?></p>
                            </div>
                        </div>
                        <div class="aieo-ce-grid-2">
                            <div class="aieo-ce-field">
                                <?php $aieo_be_default_margin = class_exists('AIEO_DMM') ? (int) round(AIEO_DMM::get_gross_margin_pct()) : 60; ?>
                                <label for="aieo-be-margin"><?php esc_html_e('Gross profit margin (%)', 'ai-eshop-optimizer'); ?></label>
                                <input type="number" id="aieo-be-margin" name="aieo_be[gross_margin]" min="1" max="99" step="0.5"
                                       value="<?php echo ($row['gross_margin'] === null || $row['gross_margin'] === '') ? '' : esc_attr(rtrim(rtrim(number_format((float) $row['gross_margin'], 2, '.', ''), '0'), '.')); ?>"
                                       placeholder="<?php echo esc_attr(sprintf( __('inherits %d', 'ai-eshop-optimizer'), $aieo_be_default_margin)); ?>" />
                                <p class="description"><?php esc_html_e('Gross margin on this brand’s products. Leave blank to inherit the store default (Tools). Drives each product’s Cost of Goods.', 'ai-eshop-optimizer'); ?></p>
                            </div>
                            <div class="aieo-ce-field"></div>
                        </div>
                        <div class="aieo-ce-grid-2">
                            <div class="aieo-ce-field">
                                <label for="aieo-be-supplier"><?php esc_html_e('Supplier (single)', 'ai-eshop-optimizer'); ?></label>
                                <input type="text" id="aieo-be-supplier-display" value="<?php echo esc_attr($supplier_label); ?>" placeholder="<?php esc_attr_e('— none —', 'ai-eshop-optimizer'); ?>" readonly class="regular-text" />
                                <input type="hidden" name="aieo_be[supplier_term_id]" value="<?php echo (int) ($row['supplier_term_id'] ?? 0); ?>" />
                                <p class="description"><?php esc_html_e('Linked supplier term. Editable once Supplier Extras ships in Phase 5b.', 'ai-eshop-optimizer'); ?></p>
                            </div>
                            <div class="aieo-ce-field">
                                <label><?php esc_html_e('Gallery (multimedia)', 'ai-eshop-optimizer'); ?></label>
                                <div class="aieo-be-gallery-preview">
                                    <?php foreach ((array) $row['gallery_image_ids'] as $aid):
                                        $thumb = wp_get_attachment_image_url((int) $aid, 'thumbnail');
                                        if (!$thumb) { continue; }
                                    ?>
                                        <div class="aieo-be-gallery-item" data-id="<?php echo (int) $aid; ?>">
                                            <img src="<?php echo esc_url($thumb); ?>" alt="" />
                                            <button type="button" class="aieo-be-gallery-remove" aria-label="<?php esc_attr_e('Remove', 'ai-eshop-optimizer'); ?>">&times;</button>
                                            <input type="hidden" name="aieo_be[gallery_image_ids][]" value="<?php echo (int) $aid; ?>" />
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                                <button type="button" class="button aieo-be-gallery-add"><?php esc_html_e('Add images', 'ai-eshop-optimizer'); ?></button>
                                <p class="description"><?php esc_html_e('Optional brand multimedia (campaign visuals, packshots).', 'ai-eshop-optimizer'); ?></p>
                            </div>
                        </div>
                    </div>

                    <!-- ── Tab: Footer ───────────────────────────────────── -->
                    <div class="aieo-ce-tabpanel" data-aieo-ce-pane="footer" role="tabpanel">
                        <div class="aieo-ce-field aieo-ce-rich-field">
                            <label for="aieo_be_footer_text"><?php esc_html_e('Footer text (bottom of brand archive)', 'ai-eshop-optimizer'); ?></label>
                            <?php wp_editor(
                                (string) $row['footer_text'],
                                'aieo_be_footer_text',
                                array(
                                    'textarea_name' => 'aieo_be[footer_text]',
                                    'textarea_rows' => 8,
                                    'media_buttons' => true,
                                    'teeny'         => false,
                                    'quicktags'     => true,
                                )
                            ); ?>
                            <p class="description"><?php esc_html_e('Rendered under the product grid on the brand archive page. SEO-friendly long-form content.', 'ai-eshop-optimizer'); ?></p>
                        </div>
                    </div>

                    <!-- ── Tab: Related ──────────────────────────────────── -->
                    <div class="aieo-ce-tabpanel" data-aieo-ce-pane="related" role="tabpanel">
                        <?php
                        
                        
                        if (class_exists('AIEO_DMM_Related_Tab')) {
                            AIEO_DMM_Related_Tab::render($taxonomy, (int) $term->term_id);
                        } else {
                            echo '<p>' . esc_html__('Related-tab component unavailable.', 'ai-eshop-optimizer') . '</p>';
                        }
                        ?>
                    </div>
                </div>
            </th>
        </tr>
        <?php
    }

    
    public function save_term_extras($term_id, $tt_id = 0) {
        $term_id = (int) $term_id;
        if (!$term_id) { return; }
        if (empty($_POST['aieo_be_nonce']) || !wp_verify_nonce(
            sanitize_key(wp_unslash($_POST['aieo_be_nonce'])),
            'aieo_be_term_edit_' . $term_id
        )) {
            return;
        }
        if (empty($_POST['aieo_be']) || !is_array($_POST['aieo_be'])) { return; }

        $term = get_term($term_id);
        if (!$term || is_wp_error($term)) { return; }
        if (!in_array($term->taxonomy, AIEO_DMM_Brand_Extras_Data::managed_taxonomies(), true)) { return; }

        $raw = wp_unslash($_POST['aieo_be']);
        if (!is_array($raw)) { return; }

        $patch = array();
        if (isset($raw['logo_image_id']))    { $patch['logo_image_id']    = (int) $raw['logo_image_id']; }
        if (isset($raw['hero_image_id']))    { $patch['hero_image_id']    = (int) $raw['hero_image_id']; }
        if (isset($raw['headline']))         { $patch['headline']         = sanitize_text_field((string) $raw['headline']); }
        if (isset($raw['history_text']))     { $patch['history_text']     = wp_kses_post((string) $raw['history_text']); }
        if (isset($raw['ambassadors_text'])) { $patch['ambassadors_text'] = wp_kses_post((string) $raw['ambassadors_text']); }
        if (isset($raw['importer_text']))    { $patch['importer_text']    = wp_kses_post((string) $raw['importer_text']); }
        if (isset($raw['website_url']))      { $patch['website_url']      = esc_url_raw((string) $raw['website_url']); }
        if (isset($raw['promo']))            { $patch['promo']            = !empty($raw['promo']) ? 1 : 0; }
        if (isset($raw['priority']))         { $patch['priority']         = (int) $raw['priority']; }
        if (isset($raw['bias']))             { $patch['bias']             = (float) $raw['bias']; }
        if (isset($raw['gross_margin'])) {
            $gm = trim((string) $raw['gross_margin']);
            $patch['gross_margin'] = ($gm === '') ? null : (float) $gm; 
        }
        if (isset($raw['supplier_term_id'])) { $patch['supplier_term_id'] = (int) $raw['supplier_term_id']; }
        if (isset($raw['footer_text']))      { $patch['footer_text']      = wp_kses_post((string) $raw['footer_text']); }
        if (isset($raw['gallery_image_ids']) && is_array($raw['gallery_image_ids'])) {
            $patch['gallery_image_ids'] = array_map('intval', $raw['gallery_image_ids']);
        }

        AIEO_DMM_Brand_Extras_Data::save($term->taxonomy, $term_id, $patch);
    }

    
    public function ajax_save() {
        AIEO_DMM::verify_ajax_request();
        wp_send_json_error(array('message' => 'not_implemented'), 501);
    }

    
    public function enqueue_term_admin_assets($hook) {
        if ($hook !== 'term.php') { return; }
        $tax = isset($_GET['taxonomy']) ? sanitize_key(wp_unslash($_GET['taxonomy'])) : '';
        if (!in_array($tax, AIEO_DMM_Brand_Extras_Data::managed_taxonomies(), true)) { return; }

        wp_enqueue_media();
        if (function_exists('wp_enqueue_editor')) { wp_enqueue_editor(); }

        
        
        
        wp_enqueue_style(
            'aieo-dmm-category-extras-admin',
            AIEO_URI . 'assets/css/aieo-dmm-category-extras-admin.css',
            array(), AIEO_VERSION
        );
        wp_enqueue_script(
            'aieo-dmm-category-extras-admin',
            AIEO_URI . 'assets/js/aieo-dmm-category-extras-admin.js',
            array('jquery'), AIEO_VERSION, true
        );
        wp_localize_script('aieo-dmm-category-extras-admin', 'aieoCategoryExtras', array(
            'ajaxurl' => admin_url('admin-ajax.php'),
            'nonce'   => wp_create_nonce(AIEO_DMM::NONCE_ACTION),
            'i18n'    => array(
                'noResults' => __('No matches.', 'ai-eshop-optimizer'),
                'searching' => __('Searching…', 'ai-eshop-optimizer'),
                'pickImage' => __('Select image', 'ai-eshop-optimizer'),
                'useImage'  => __('Use this image', 'ai-eshop-optimizer'),
            ),
        ));
    }

    
    public function render_subtab() {
        echo '<div class="aieo-dmm-section">';
        echo '<h2>' . esc_html__('Brand Extras', 'ai-eshop-optimizer') . '</h2>';
        echo '<p class="description">' . esc_html__('Pods-free per-brand metadata (logo, history, ambassadors, gallery, website, priority, bias, supplier, footer text). Edit individual brands at WooCommerce → Products → Brands → click a brand. Relationships are stored bidirectionally in wp_aieo_dmm_term_relations.', 'ai-eshop-optimizer') . '</p>';

        global $wpdb;
        $brand_count = (int) $wpdb->get_var("SELECT COUNT(*) FROM " . AIEO_DMM_Brand_Extras_Data::table());
        $rel_count   = (int) $wpdb->get_var("SELECT COUNT(*) FROM " . AIEO_DMM_Term_Relations::table());

        echo '<table class="form-table"><tbody>';
        echo '<tr><th>' . esc_html__('Brand metadata rows', 'ai-eshop-optimizer') . '</th><td>' . esc_html(number_format_i18n($brand_count)) . '</td></tr>';
        echo '<tr><th>' . esc_html__('Term-relation edges', 'ai-eshop-optimizer') . '</th><td>' . esc_html(number_format_i18n($rel_count)) . '</td></tr>';
        echo '</tbody></table>';

        
        
        
        if (class_exists('AIEO_DMM_Brand_Pods_Migrator') && AIEO_DMM_Brand_Pods_Migrator::has_pods_source()) {
            $audit = AIEO_DMM_Brand_Pods_Migrator::audit();
            $nonce = wp_create_nonce('aieo_brand_pods_migrate');
            $ajax  = admin_url('admin-ajax.php');

            echo '<div class="aieo-dmm-card" style="margin-top:18px;padding:14px;border:1px solid #e5e7eb;border-radius:8px;background:#fff;">';
            echo '<h3 style="margin-top:0;">' . esc_html__('Pods → Brand Extras migrator', 'ai-eshop-optimizer') . '</h3>';
            echo '<p>';
            echo sprintf(
                
                esc_html__('Pods is active on the `%1$s` taxonomy. %2$d brand terms total, %3$d already migrated.', 'ai-eshop-optimizer'),
                esc_html($audit['taxonomy']),
                (int) $audit['brand_terms'],
                (int) $audit['already_migrated']
            );
            echo '</p>';
            echo '<p>';
            echo '<button type="button" class="button button-primary" id="aieo-brand-pods-run">' . esc_html__('Run migration', 'ai-eshop-optimizer') . '</button>';
            echo ' <span id="aieo-brand-pods-status" style="margin-left:10px;font-size:13px;color:#646970;"></span>';
            echo '</p>';
            ?>
            <script>
            (function(){
                var btn = document.getElementById('aieo-brand-pods-run');
                if (!btn) return;
                var status = document.getElementById('aieo-brand-pods-status');
                var NONCE = <?php echo wp_json_encode($nonce); ?>;
                var AJAX  = <?php echo wp_json_encode($ajax); ?>;
                function post(action, params) {
                    var fd = new FormData();
                    fd.append('action', action);
                    fd.append('nonce', NONCE);
                    Object.keys(params || {}).forEach(function(k){ fd.append(k, params[k]); });
                    return fetch(AJAX, {method:'POST',credentials:'same-origin',body:fd}).then(function(r){return r.json();});
                }
                btn.addEventListener('click', function(){
                    var cursor = 0, total = 0, migrated = 0, errors = 0, done = false;
                    btn.disabled = true;
                    function tick(){
                        if (done) return;
                        status.textContent = '<?php echo esc_js(__('Migrating brands… processed', 'ai-eshop-optimizer')); ?> ' + total;
                        status.style.color = '#646970';
                        post('aieo_brand_pods_migrate_run', {cursor: cursor, batch_size: 50}).then(function(j){
                            if (!j || !j.success) {
                                status.textContent = '<?php echo esc_js(__('Failed.', 'ai-eshop-optimizer')); ?>';
                                status.style.color = '#b91c1c';
                                done = true; btn.disabled = false; return;
                            }
                            var d = j.data || {};
                            total    += (d.processed | 0);
                            migrated += (d.migrated  | 0);
                            errors   += (d.errors && d.errors.length ? d.errors.length : 0);
                            if (d.errors && d.errors.length) console.warn('Brand migration warnings:', d.errors);
                            if (d.done) {
                                status.textContent = '<?php echo esc_js(__('Done. Migrated', 'ai-eshop-optimizer')); ?> ' + migrated + ' / ' + total + (errors ? (' · ' + errors + ' <?php echo esc_js(__('errors', 'ai-eshop-optimizer')); ?>') : '');
                                status.style.color = '#15803d';
                                done = true; btn.disabled = false;
                            } else {
                                cursor = (d.next_cursor | 0);
                                setTimeout(tick, 30);
                            }
                        });
                    }
                    tick();
                });
            })();
            </script>
            <?php
            echo '</div>';
        } else {
            echo '<p class="description" style="margin-top:14px;color:#9ca3af;">' . esc_html__('Pods is not active here, so the Pods → Brand Extras migrator is hidden. Brand fields can be edited directly on each brand term-edit screen.', 'ai-eshop-optimizer') . '</p>';
        }
        echo '</div>';
    }
}
