<?php defined('ABSPATH') || exit;

/**
 * Show only the last 2 path segments + ID to keep the input readable.
 * Full path is always available on hover via the title attribute.
 */
function jra_tax_short_label(string $label): string {
    preg_match('/\[(\d+)\]$/', $label, $m);
    $idPart = isset($m[1]) ? ' [' . $m[1] . ']' : '';
    $path   = trim(preg_replace('/\s*\[\d+\]$/', '', $label));
    $parts  = explode(' > ', $path);
    if (count($parts) <= 2) {
        return $label;
    }
    return '… ' . implode(' > ', array_slice($parts, -2)) . $idPart;
}

/**
 * @var array               $attrMappings   Current attr mappings ['color' => 'pa_colour', ...]
 * @var int[]               $excluded        Excluded WC category IDs
 * @var object[]            $wcAttributes    From wc_get_attribute_taxonomies()
 * @var string              $activeAttr      Google attribute being viewed for term mappings
 * @var string[]            $googleAttrs     ['color', 'size', ...]
 */

$googleAttrLabels = [
    'color'     => 'Color',
    'size'      => 'Size',
    'material'  => 'Material',
    'pattern'   => 'Pattern',
    'age_group' => 'Age group',
    'gender'    => 'Gender',
];

// Load term mappings for the active attribute
$termMappings = [];
if ($activeAttr) {
    global $wpdb;
    $table = $wpdb->prefix . 'jra_merchant_term_mappings';
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter
    $rows  = $wpdb->get_results(
        $wpdb->prepare("SELECT local_value, google_value FROM {$table} WHERE google_attribute = %s ORDER BY local_value", $activeAttr) // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
    );
    foreach ((array)$rows as $row) {
        $termMappings[$row->local_value] = $row->google_value;
    }

    // Also load all WC terms for the mapped attribute (to pre-populate local values)
    $mappedTaxonomy   = $attrMappings[$activeAttr] ?? '';
    $availableTerms   = [];
    if ($mappedTaxonomy && taxonomy_exists($mappedTaxonomy)) {
        $wcTerms = get_terms(['taxonomy' => $mappedTaxonomy, 'hide_empty' => false]);
        foreach ((is_array($wcTerms) ? $wcTerms : []) as $term) {
            $availableTerms[$term->name] = $termMappings[$term->name] ?? '';
        }
    }
}

// WC categories tree for exclusion multi-select
$allCategories = get_terms(['taxonomy' => 'product_cat', 'hide_empty' => false, 'orderby' => 'name']);
?>
<div class="wrap jra-merchant">
    <h1>Google Merchant Feed — Mappings</h1>

    <div class="jra-two-col">

        <!-- ================================================================ -->
        <!-- Left: attribute mappings + category exclusions                    -->
        <!-- ================================================================ -->
        <div>
            <div class="jra-card">
                <h2>Variant attribute mappings</h2>
                <p>Map each Google variant attribute to the WooCommerce product attribute that carries that information. Only attributes used for product variations need to be mapped.</p>

                <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')) ?>">
                    <?php wp_nonce_field('jra_merchant_attr_mappings') ?>
                    <input type="hidden" name="action" value="jra_merchant_save_attr_mappings">

                    <table class="widefat">
                        <thead>
                            <tr><th>Google attribute</th><th>WooCommerce attribute</th></tr>
                        </thead>
                        <tbody>
                            <?php foreach ($googleAttrs as $gAttr): ?>
                            <tr>
                                <td>
                                    <strong><?php echo esc_html($googleAttrLabels[$gAttr] ?? $gAttr) ?></strong>
                                    <?php if (!empty($attrMappings[$gAttr])): ?>
                                        <br><a href="<?php echo esc_url(admin_url('admin.php?page=jra-merchant-feed-mappings&attr=' . $gAttr)) ?>" style="font-size:11px;">edit term values →</a>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <select name="mapping[<?php echo esc_attr($gAttr) ?>]">
                                        <option value="">— not mapped —</option>
                                        <?php foreach ($wcAttributes as $wcAttr): ?>
                                            <?php $slug = 'pa_' . $wcAttr->attribute_name; ?>
                                            <option value="<?php echo esc_attr($slug) ?>"
                                                <?php echo selected($attrMappings[$gAttr] ?? '', $slug, false) ?>>
                                                <?php echo esc_html($wcAttr->attribute_label) ?> (<?php echo esc_html($slug) ?>)
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>

                    <?php if ($isPremium): ?>
                    <h2 style="margin-top:24px;">Excluded categories</h2>
                    <p>Products in these WooCommerce categories will not be pushed to Google Merchant Center.</p>

                    <select name="excluded_categories[]" multiple size="10" style="width:100%;max-width:400px;">
                        <?php foreach ((array)$allCategories as $cat): ?>
                            <option value="<?php echo esc_attr($cat->term_id) ?>"
                                <?php echo in_array((int)$cat->term_id, $excluded, true) ? 'selected' : '' ?>>
                                <?php echo esc_html($cat->name) ?> (<?php echo (int)$cat->count ?> products)
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <p class="description">Hold Ctrl / Cmd to select multiple categories.</p>
                    <?php else: ?>
                    <h2 style="margin-top:24px;">Excluded categories <span style="font-size:12px;color:#9e2f7f;font-weight:normal;">— Pro</span></h2>
                    <p style="color:#666;">Upgrade to Pro to exclude products by category.</p>
                    <?php endif; ?>

                    <?php submit_button('Save mappings') ?>
                </form>
            </div>
        </div>

        <!-- ================================================================ -->
        <!-- Right: term value mappings for a single Google attribute          -->
        <!-- ================================================================ -->
        <div>
            <?php
            $fixedGoogleValues = [
                'gender'    => ['male', 'female', 'unisex'],
                'age_group' => ['newborn', 'infant', 'toddler', 'kids', 'adult'],
            ];
            ?>
            <?php if ($activeAttr && isset($googleAttrLabels[$activeAttr])): ?>
            <?php $fixedOptions = $fixedGoogleValues[$activeAttr] ?? null; ?>
            <div class="jra-card">
                <h2>Term value mappings — <?php echo esc_html($googleAttrLabels[$activeAttr]) ?></h2>
                <p>
                    Map WooCommerce term names to the values Google expects.
                    <?php if ($fixedOptions): ?>
                    Google only accepts the values shown in the dropdown.
                    <?php else: ?>
                    Leave Google value blank to use the WooCommerce name as-is.
                    <?php endif; ?>
                </p>

                <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')) ?>">
                    <?php wp_nonce_field('jra_merchant_term_mappings') ?>
                    <input type="hidden" name="action" value="jra_merchant_save_term_mappings">
                    <input type="hidden" name="google_attribute" value="<?php echo esc_attr($activeAttr) ?>">

                    <table class="widefat" id="jra-term-mappings">
                        <thead>
                            <tr><th>WooCommerce term (local)</th><th>Google value</th><th></th></tr>
                        </thead>
                        <tbody>
                            <?php
                            $allLocalKeys = array_unique(array_merge(array_keys($availableTerms), array_keys($termMappings)));
                            sort($allLocalKeys);

                            foreach ($allLocalKeys as $localValue):
                                $googleValue = $termMappings[$localValue] ?? '';
                            ?>
                            <tr>
                                <td>
                                    <input type="text" name="local_value[]" value="<?php echo esc_attr($localValue) ?>"
                                           class="regular-text" placeholder="Local term name">
                                </td>
                                <td>
                                    <?php if ($fixedOptions): ?>
                                    <select name="google_value[]">
                                        <option value="">— select —</option>
                                        <?php foreach ($fixedOptions as $opt): ?>
                                        <option value="<?php echo esc_attr($opt) ?>"<?php echo selected($googleValue, $opt, false) ?>><?php echo esc_html($opt) ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                    <?php else: ?>
                                    <input type="text" name="google_value[]" value="<?php echo esc_attr($googleValue) ?>"
                                           class="regular-text" placeholder="Google value">
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <button type="button" class="button jra-remove-row">×</button>
                                </td>
                            </tr>
                            <?php endforeach; ?>

                            <?php if (empty($allLocalKeys)): ?>
                            <tr>
                                <td><input type="text" name="local_value[]" value="" class="regular-text" placeholder="Local term name"></td>
                                <td>
                                    <?php if ($fixedOptions): ?>
                                    <select name="google_value[]">
                                        <option value="">— select —</option>
                                        <?php foreach ($fixedOptions as $opt): ?>
                                        <option value="<?php echo esc_attr($opt) ?>"><?php echo esc_html($opt) ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                    <?php else: ?>
                                    <input type="text" name="google_value[]" value="" class="regular-text" placeholder="Google value">
                                    <?php endif; ?>
                                </td>
                                <td><button type="button" class="button jra-remove-row">×</button></td>
                            </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>

                    <p>
                        <button type="button" class="button" id="jra-add-term-row">+ Add row</button>
                    </p>

                    <?php submit_button('Save term mappings') ?>
                </form>

                <?php
                $js  = 'var jraTermData=' . wp_json_encode(['fixedOptions' => $fixedOptions]) . ';';
                $js .= <<<'JRAJS'
document.addEventListener('DOMContentLoaded',function(){
    var fixedOptions=jraTermData.fixedOptions;
    function googleValueCell(){
        if(fixedOptions){
            var opts='<option value="">— select —</option>';
            fixedOptions.forEach(function(o){opts+='<option value="'+o+'">'+o+'</option>';});
            return '<select name="google_value[]">'+opts+'</select>';
        }
        return '<input type="text" name="google_value[]" value="" class="regular-text" placeholder="Google value">';
    }
    document.getElementById('jra-add-term-row').addEventListener('click',function(){
        var tbody=document.querySelector('#jra-term-mappings tbody');
        var row=document.createElement('tr');
        row.innerHTML='<td><input type="text" name="local_value[]" value="" class="regular-text" placeholder="Local term name"></td>'
            +'<td>'+googleValueCell()+'</td>'
            +'<td><button type="button" class="button jra-remove-row">×</button></td>';
        tbody.appendChild(row);
    });
});
JRAJS;
                wp_add_inline_script('jra-admin-footer',$js);
                ?>
            </div>
            <?php else: ?>
            <div class="jra-card">
                <h2>Term value mappings</h2>
                <p>Map your WooCommerce term names to the values Google expects for each attribute. Click an attribute below to edit its mappings.</p>
                <?php
                $mappedAttrs = array_filter($attrMappings);
                if (!empty($mappedAttrs)): ?>
                <ul style="margin:0 0 16px;">
                    <?php foreach ($googleAttrs as $gAttr):
                        if (empty($attrMappings[$gAttr])) continue; ?>
                    <li style="margin-bottom:4px;">
                        <a href="<?php echo esc_url(admin_url('admin.php?page=jra-merchant-feed-mappings&attr=' . $gAttr)) ?>">
                            <?php echo esc_html($googleAttrLabels[$gAttr] ?? $gAttr) ?>
                        </a>
                        <span style="color:#999;font-size:12px;">— mapped from <code><?php echo esc_html($attrMappings[$gAttr]) ?></code></span>
                    </li>
                    <?php endforeach; ?>
                </ul>
                <?php else: ?>
                <p style="color:#999;">No attributes mapped yet — save an attribute mapping on the left first, then the <em>edit term values</em> link will appear here.</p>
                <?php endif; ?>
                <p style="color:#666;font-size:12px;margin-top:8px;">Common examples:</p>
                <ul style="list-style:disc;margin-left:20px;font-size:12px;color:#555;">
                    <li><strong>Gender:</strong> "Mens" → <code>male</code>, "Womens" → <code>female</code>, "Kids" → <code>unisex kids</code></li>
                    <li><strong>Age group:</strong> "Adult" → <code>adult</code>, "Kids" → <code>kids</code></li>
                </ul>
            </div>
            <?php endif; ?>
        </div>

    </div><!-- .jra-two-col -->

    <!-- ================================================================ -->
    <!-- Google Product Category mapping (Pro)                              -->
    <!-- ================================================================ -->
    <?php if (!$isPremium): ?>
    <div class="jra-card" style="margin-top:24px;">
        <h2>Google Product Category <span style="font-size:12px;color:#9e2f7f;font-weight:normal;">— Pro</span></h2>
        <p style="color:#666;">Upgrade to Pro to map WooCommerce categories to Google's taxonomy.</p>
    </div>
    <?php else: ?>
    <div class="jra-card" style="margin-top:24px;">
        <h2>Google Product Category</h2>
        <p>
            Map WooCommerce categories to Google's taxonomy. Start typing a category name to search.
            Products in unmatched categories use the default from Settings.
            For variations, the parent product's category is used.
        </p>

        <div style="display:flex;align-items:center;gap:16px;margin-bottom:16px;padding:10px 12px;background:#f6f7f7;border:1px solid #e6e7e8;border-radius:2px;">
            <?php if ($taxonomyUpdatedAt): ?>
            <span style="font-size:12px;color:#666;">
                Taxonomy cached: <strong><?php echo esc_html($taxonomyUpdatedAt) ?> UTC</strong>
                (<?php echo number_format(count($googleTaxonomy)) ?> categories)
            </span>
            <?php else: ?>
            <span style="font-size:12px;color:#d63638;">Taxonomy not yet downloaded — click Refresh to load it.</span>
            <?php endif; ?>
            <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')) ?>" style="margin:0;">
                <?php wp_nonce_field('jra_merchant_refresh_taxonomy') ?>
                <input type="hidden" name="action" value="jra_merchant_refresh_taxonomy">
                <button type="submit" class="button button-small">↻ Refresh taxonomy</button>
            </form>
            <a href="https://www.google.com/basepages/producttype/taxonomy-with-ids.en-GB.txt"
               target="_blank" style="font-size:12px;">View full taxonomy list ↗</a>
        </div>

        <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')) ?>">
            <?php wp_nonce_field('jra_merchant_google_cat_map') ?>
            <input type="hidden" name="action" value="jra_merchant_save_google_cat_map">

            <table class="widefat striped" id="jra-google-cat-table" style="margin-bottom:10px;">
                <thead>
                    <tr>
                        <th>WooCommerce category</th>
                        <th>Google taxonomy</th>
                        <th style="width:40px;"></th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    $shownAny = false;
                    foreach ((array) $allCategories as $cat):
                        if (!isset($googleCategoryMap[$cat->term_id])) continue;
                        $shownAny    = true;
                        $taxId       = $googleCategoryMap[$cat->term_id];
                        $taxLabel    = isset($googleTaxonomy[$taxId]) ? $googleTaxonomy[$taxId] . ' [' . $taxId . ']' : $taxId;
                        $taxDisplay  = jra_tax_short_label($taxLabel);
                    ?>
                    <tr>
                        <td>
                            <select name="cat_term_id[]" style="width:100%;max-width:280px;">
                                <option value="">— select category —</option>
                                <?php foreach ((array) $allCategories as $c): ?>
                                <option value="<?php echo esc_attr($c->term_id) ?>"
                                    <?php echo selected($c->term_id, $cat->term_id, false) ?>>
                                    <?php echo esc_html($c->name) ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </td>
                        <td>
                            <div class="jra-tax-ac" style="position:relative;">
                                <input type="text" class="jra-tax-search regular-text"
                                       value="<?php echo esc_attr($taxDisplay) ?>"
                                       title="<?php echo esc_attr($taxLabel) ?>"
                                       placeholder="Type to search Google taxonomy…"
                                       autocomplete="off" style="width:100%;">
                                <input type="hidden" name="cat_taxonomy_id[]"
                                       class="jra-tax-id" value="<?php echo esc_attr($taxId) ?>">
                                <div class="jra-tax-results"></div>
                            </div>
                        </td>
                        <td><button type="button" class="button jra-remove-row">×</button></td>
                    </tr>
                    <?php endforeach; ?>
                    <?php if (!$shownAny): ?>
                    <tr>
                        <td>
                            <select name="cat_term_id[]" style="width:100%;max-width:280px;">
                                <option value="">— select category —</option>
                                <?php foreach ((array) $allCategories as $c): ?>
                                <option value="<?php echo esc_attr($c->term_id) ?>"><?php echo esc_html($c->name) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </td>
                        <td>
                            <div class="jra-tax-ac" style="position:relative;">
                                <input type="text" class="jra-tax-search regular-text"
                                       placeholder="Type to search Google taxonomy…"
                                       autocomplete="off" style="width:100%;">
                                <input type="hidden" name="cat_taxonomy_id[]" class="jra-tax-id" value="">
                                <div class="jra-tax-results"></div>
                            </div>
                        </td>
                        <td><button type="button" class="button jra-remove-row">×</button></td>
                    </tr>
                    <?php endif; ?>
                </tbody>
            </table>

            <p>
                <button type="button" class="button" id="jra-add-google-cat-row">+ Add row</button>
            </p>
            <?php submit_button('Save Google category mappings') ?>
        </form>

        <?php
        $js  = 'var jraGoogleCatData=' . wp_json_encode([
            'cats' => array_map(fn($c) => ['id' => $c->term_id, 'name' => $c->name], (array) $allCategories),
        ]) . ';';
        $js .= <<<'JRAJS'
document.addEventListener('DOMContentLoaded',function(){
    var allCats=jraGoogleCatData.cats;
    function shortLabel(t){
        var m=t.match(/\[(\d+)\]$/),idP=m?' ['+m[1]+']':'';
        var p=t.replace(/\s*\[\d+\]$/,'').trim().split(' > ');
        return p.length<=2?t:'… '+p.slice(-2).join(' > ')+idP;
    }
    function initTaxAc(container){
        var input=container.querySelector('.jra-tax-search');
        var hidden=container.querySelector('.jra-tax-id');
        var results=container.querySelector('.jra-tax-results');
        var timer;
        input.addEventListener('input',function(){
            var q=this.value.trim();
            hidden.value='';input.title='';clearTimeout(timer);
            if(q.length<2){results.style.display='none';return;}
            timer=setTimeout(function(){
                fetch(jraMappings.ajaxUrl+'?action=jra_merchant_search_taxonomy&q='+encodeURIComponent(q)+'&_ajax_nonce='+jraMappings.nonce)
                    .then(function(r){return r.json();})
                    .then(function(data){
                        var items=data.results||[];
                        results.innerHTML='';
                        if(!items.length){results.innerHTML='<div style="padding:6px 10px;color:#888;font-size:12px;">No results</div>';}
                        else{items.forEach(function(item){var d=document.createElement('div');d.className='jra-tax-result';d.textContent=item.text;d.dataset.id=item.id;results.appendChild(d);});}
                        results.style.display='block';
                    });
            },300);
        });
        results.addEventListener('click',function(e){
            var item=e.target.closest('.jra-tax-result');
            if(!item)return;
            hidden.value=item.dataset.id;input.value=shortLabel(item.textContent);input.title=item.textContent;
            results.style.display='none';
        });
        document.addEventListener('click',function(e){if(!container.contains(e.target))results.style.display='none';});
    }
    document.querySelectorAll('.jra-tax-ac').forEach(initTaxAc);
    function buildCatOptions(){
        var opts='<option value="">— select category —</option>';
        allCats.forEach(function(c){opts+='<option value="'+c.id+'">'+c.name+'</option>';});
        return opts;
    }
    function newAcHtml(){
        return '<div class="jra-tax-ac" style="position:relative;">'
            +'<input type="text" class="jra-tax-search regular-text" placeholder="Type to search Google taxonomy…" autocomplete="off" style="width:100%;">'
            +'<input type="hidden" name="cat_taxonomy_id[]" class="jra-tax-id" value="">'
            +'<div class="jra-tax-results"></div>'
            +'</div>';
    }
    document.getElementById('jra-add-google-cat-row').addEventListener('click',function(){
        var tbody=document.querySelector('#jra-google-cat-table tbody');
        var row=document.createElement('tr');
        row.innerHTML='<td><select name="cat_term_id[]" style="width:100%;max-width:280px;">'+buildCatOptions()+'</select></td>'
            +'<td>'+newAcHtml()+'</td>'
            +'<td><button type="button" class="button jra-remove-row">×</button></td>';
        tbody.appendChild(row);
        initTaxAc(row.querySelector('.jra-tax-ac'));
    });
});
JRAJS;
        wp_add_inline_script('jra-admin-footer',$js);
        ?>
    </div>
    <?php endif; ?>

    <!-- ================================================================ -->
    <!-- Custom Label mappings (Pro)                                        -->
    <!-- ================================================================ -->
    <?php if (!$isPremium): ?>
    <div class="jra-card" style="margin-top:24px;">
        <h2>Custom Label mappings <span style="font-size:12px;color:#9e2f7f;font-weight:normal;">— Pro</span></h2>
        <p style="color:#666;">Upgrade to Pro to configure custom labels for Google Shopping campaigns.</p>
    </div>
    <?php else: ?>
    <div class="jra-card" style="margin-top:24px;">
        <h2>Custom Label mappings</h2>
        <p>
            These labels appear on every product in Google Merchant Center and can be used to segment Shopping campaigns.
            <strong>Labels 0 and 2</strong> are set automatically (sale status and stock level).
            <strong>Label 4</strong> is set per-product in the Merchant Feed tab.
        </p>

        <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')) ?>">
            <?php wp_nonce_field('jra_merchant_custom_label_maps') ?>
            <input type="hidden" name="action" value="jra_merchant_save_custom_label_maps">

            <div style="display:flex;flex-direction:column;gap:24px;">

                <!-- Label 1: tag mapping -->
                <div>
                    <h3 style="margin-top:0;">Custom label 1 — Product tags</h3>
                    <p class="description" style="margin-bottom:10px;">First matching tag wins. For variable products, tags on the parent product are checked.</p>
                    <table class="widefat striped" id="jra-label-tag-table" style="margin-bottom:10px;">
                        <thead>
                            <tr>
                                <th>WooCommerce tag</th>
                                <th style="width:160px;">Label value</th>
                                <th style="width:40px;"></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            $shownTag = false;
                            foreach ($customLabelTagMap as $tagSlug => $labelVal):
                                $shownTag = true;
                            ?>
                            <tr>
                                <td>
                                    <select name="label_tag_slug[]" style="width:100%;">
                                        <option value="">— select tag —</option>
                                        <?php foreach ((array) $allTags as $tag): ?>
                                        <option value="<?php echo esc_attr($tag->slug) ?>"
                                            <?php echo selected($tag->slug, $tagSlug, false) ?>>
                                            <?php echo esc_html($tag->name) ?>
                                        </option>
                                        <?php endforeach; ?>
                                    </select>
                                </td>
                                <td><input type="text" name="label_tag_value[]" value="<?php echo esc_attr($labelVal) ?>" class="regular-text" placeholder="e.g. sale"></td>
                                <td><button type="button" class="button jra-remove-row">×</button></td>
                            </tr>
                            <?php endforeach; ?>
                            <?php if (!$shownTag): ?>
                            <tr>
                                <td>
                                    <select name="label_tag_slug[]" style="width:100%;">
                                        <option value="">— select tag —</option>
                                        <?php foreach ((array) $allTags as $tag): ?>
                                        <option value="<?php echo esc_attr($tag->slug) ?>"><?php echo esc_html($tag->name) ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </td>
                                <td><input type="text" name="label_tag_value[]" value="" class="regular-text" placeholder="e.g. bestseller"></td>
                                <td><button type="button" class="button jra-remove-row">×</button></td>
                            </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                    <button type="button" class="button" id="jra-add-label-tag-row">+ Add row</button>
                </div>

                <!-- Label 3: category mapping -->
                <div>
                    <h3 style="margin-top:0;">Custom label 3 — Product categories</h3>
                    <p class="description" style="margin-bottom:10px;">First matching category wins. For variable products, the parent product's categories are checked.</p>
                    <table class="widefat striped" id="jra-label-cat-table" style="margin-bottom:10px;">
                        <thead>
                            <tr>
                                <th>WooCommerce category</th>
                                <th style="width:160px;">Label value</th>
                                <th style="width:40px;"></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            $shownCat = false;
                            foreach ($customLabelCatMap as $catId => $labelVal):
                                $shownCat = true;
                            ?>
                            <tr>
                                <td>
                                    <select name="label_cat_id[]" style="width:100%;">
                                        <option value="">— select category —</option>
                                        <?php foreach ((array) $allCategories as $c): ?>
                                        <option value="<?php echo esc_attr($c->term_id) ?>"
                                            <?php echo selected($c->term_id, $catId, false) ?>>
                                            <?php echo esc_html($c->name) ?>
                                        </option>
                                        <?php endforeach; ?>
                                    </select>
                                </td>
                                <td><input type="text" name="label_cat_value[]" value="<?php echo esc_attr($labelVal) ?>" class="regular-text" placeholder="e.g. wheels"></td>
                                <td><button type="button" class="button jra-remove-row">×</button></td>
                            </tr>
                            <?php endforeach; ?>
                            <?php if (!$shownCat): ?>
                            <tr>
                                <td>
                                    <select name="label_cat_id[]" style="width:100%;">
                                        <option value="">— select category —</option>
                                        <?php foreach ((array) $allCategories as $c): ?>
                                        <option value="<?php echo esc_attr($c->term_id) ?>"><?php echo esc_html($c->name) ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </td>
                                <td><input type="text" name="label_cat_value[]" value="" class="regular-text" placeholder="e.g. bikes"></td>
                                <td><button type="button" class="button jra-remove-row">×</button></td>
                            </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                    <button type="button" class="button" id="jra-add-label-cat-row">+ Add row</button>
                </div>

            </div>

            <div style="margin-top:16px;padding-top:16px;border-top:1px solid #eee;">
                <table class="widefat striped" style="max-width:500px;margin-bottom:12px;">
                    <thead><tr><th>Label</th><th>Source</th><th>Values</th></tr></thead>
                    <tbody>
                        <tr><td><code>custom_label_0</code></td><td>Automatic</td><td><code>sale</code> or <code>full-price</code></td></tr>
                        <tr><td><code>custom_label_1</code></td><td>Tag mapping (above)</td><td>Your defined values</td></tr>
                        <tr><td><code>custom_label_2</code></td><td>Automatic</td><td><code>in-stock</code>, <code>low-stock</code>, <code>out-of-stock</code>, <code>preorder</code></td></tr>
                        <tr><td><code>custom_label_3</code></td><td>Category mapping (above)</td><td>Your defined values</td></tr>
                        <tr><td><code>custom_label_4</code></td><td>Per-product (Merchant Feed tab)</td><td>Free text</td></tr>
                    </tbody>
                </table>
            </div>

            <?php submit_button('Save custom label mappings') ?>
        </form>

        <?php
        $js  = 'var jraLabelData=' . wp_json_encode([
            'tags' => array_map(fn($t) => ['slug' => $t->slug, 'name' => $t->name], (array) $allTags),
            'cats' => array_map(fn($c) => ['id' => $c->term_id, 'name' => $c->name], (array) $allCategories),
        ]) . ';';
        $js .= <<<'JRAJS'
document.addEventListener('DOMContentLoaded',function(){
    var allTags=jraLabelData.tags,allCats=jraLabelData.cats;
    function addRow(tableId,fields){
        var tbody=document.querySelector('#'+tableId+' tbody');
        var row=document.createElement('tr');
        row.innerHTML=fields+'<td><button type="button" class="button jra-remove-row">×</button></td>';
        tbody.appendChild(row);
    }
    document.getElementById('jra-add-label-tag-row').addEventListener('click',function(){
        var opts='<option value="">— select tag —</option>';
        allTags.forEach(function(t){opts+='<option value="'+t.slug+'">'+t.name+'</option>';});
        addRow('jra-label-tag-table',
            '<td><select name="label_tag_slug[]" style="width:100%;">'+opts+'</select></td>'
            +'<td><input type="text" name="label_tag_value[]" class="regular-text" placeholder="e.g. bestseller"></td>'
        );
    });
    document.getElementById('jra-add-label-cat-row').addEventListener('click',function(){
        var opts='<option value="">— select category —</option>';
        allCats.forEach(function(c){opts+='<option value="'+c.id+'">'+c.name+'</option>';});
        addRow('jra-label-cat-table',
            '<td><select name="label_cat_id[]" style="width:100%;">'+opts+'</select></td>'
            +'<td><input type="text" name="label_cat_value[]" class="regular-text" placeholder="e.g. bikes"></td>'
        );
    });
});
JRAJS;
        wp_add_inline_script('jra-admin-footer',$js);
        ?>
    </div>
    <?php endif; ?>

</div>
