<?php
/**
 * TamRank Taxonomy Meta
 *
 * Adds SEO + Social meta fields to taxonomy term edit screens
 * (categories, tags, custom taxonomies). Matches the post meta box UI.
 */

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

class TamRank_Taxonomy_Meta
{
    public function __construct()
    {
        add_action('admin_init', array($this, 'register_taxonomy_hooks'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_term_scripts'));
    }

    /**
     * Register edit_form_fields and save hooks for all public taxonomies.
     */
    public function register_taxonomy_hooks()
    {
        $taxonomies = get_taxonomies(array('public' => true));

        foreach ($taxonomies as $taxonomy) {
            add_action("{$taxonomy}_edit_form_fields", array($this, 'render_term_fields'), 10, 2);
            add_action("edited_{$taxonomy}", array($this, 'save_term_fields'), 10, 2);
        }
    }

    /**
     * Enqueue styles + media uploader on term edit screen.
     */
    public function enqueue_term_scripts($hook)
    {
        if ($hook !== 'term.php') {
            return;
        }

        wp_enqueue_style(
            'tamrank-meta-boxes',
            TAM_RANK_PLUGIN_URL . 'assets/css/tamrank-meta-boxes.css',
            array('tamrank-variables'),
            TAM_RANK_VERSION
        );

        // Live counter on the advanced robots directives panel.
        wp_enqueue_script(
            'tamrank-robots',
            TAM_RANK_PLUGIN_URL . 'assets/js/tr-robots.js',
            array(),
            TAM_RANK_VERSION,
            true
        );

        // Green upload-button styling (moved out of an inline <style> for wp.org compliance).
        wp_add_inline_style('tamrank-meta-boxes', '
            .tam-rank-meta-box .tam-btn.tam-btn-green {
                background: var(--tr-color-primary) !important;
                color: white !important;
                border: 2px solid var(--tr-color-primary) !important;
                text-shadow: none !important;
                box-shadow: none !important;
                padding: 10px 20px !important;
                border-radius: 8px !important;
                font-size: 13px !important;
                font-weight: 600 !important;
                line-height: 1.4 !important;
                height: auto !important;
                min-height: auto !important;
                display: inline-flex !important;
                align-items: center !important;
                gap: 6px !important;
                cursor: pointer !important;
                transition: all 0.2s ease !important;
            }
            .tam-rank-meta-box .tam-btn.tam-btn-green:hover {
                background: var(--tr-color-primary-hover) !important;
                border-color: var(--tr-color-primary-hover) !important;
                transform: translateY(-2px);
                box-shadow: 0 6px 14px rgba(16, 185, 129, 0.3) !important;
            }
        ');

        // Media uploader for social image
        wp_enqueue_media();

        // Src-less handle to carry the term-meta UI JS (moved out of an inline <script>
        // for wp.org compliance); term.php has no other TamRank script handle.
        wp_register_script('tamrank-taxonomy-meta', false, array('jquery'), TAM_RANK_VERSION, true);
        wp_enqueue_script('tamrank-taxonomy-meta');
    }

    /**
     * SVG info icon helper (matches post meta box).
     */
    private function info_icon()
    {
        return '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">'
            . '<circle cx="12" cy="12" r="10" stroke="var(--tr-color-info)" stroke-width="2" fill="none" />'
            . '<path d="M12 16V12M12 8H12.01" stroke="var(--tr-color-info)" stroke-width="2" stroke-linecap="round" />'
            . '</svg>';
    }

    /**
     * No-image placeholder SVG for social previews.
     */
    private function no_image_placeholder()
    {
        return '<div class="tam-no-image"><svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="#ccc" stroke-width="1.5">'
            . '<rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect>'
            . '<circle cx="8.5" cy="8.5" r="1.5"></circle>'
            . '<polyline points="21 15 16 10 5 21"></polyline>'
            . '</svg></div>';
    }

    /**
     * Render SEO + Social fields on taxonomy term edit screen.
     */
    public function render_term_fields($term, $taxonomy)
    {
        wp_nonce_field('tamrank_term_meta_nonce', 'tamrank_term_meta_nonce');

        // SEO fields
        $meta_title       = get_term_meta($term->term_id, '_tam_rank_meta_title', true);
        $meta_description = get_term_meta($term->term_id, '_tam_rank_meta_description', true);
        $focus_keyword    = get_term_meta($term->term_id, '_tam_rank_focus_keyword', true);
        $noindex          = (bool) get_term_meta($term->term_id, '_tam_rank_noindex', true);
        $nofollow         = (bool) get_term_meta($term->term_id, '_tam_rank_nofollow', true);
        $robots_advanced  = tamrank_get_robots_directive_values($term->term_id, 'term');
        $canonical        = get_term_meta($term->term_id, '_tam_rank_canonical', true);

        // Social fields
        $social_title       = get_term_meta($term->term_id, '_tam_rank_social_title', true);
        $social_description = get_term_meta($term->term_id, '_tam_rank_social_description', true);
        $social_image       = get_term_meta($term->term_id, '_tam_rank_social_image', true);

        $term_link = get_term_link($term);
        if (is_wp_error($term_link)) {
            $term_link = '';
        }

        // Social display values (fallbacks)
        $display_title = !empty($social_title) ? $social_title : (!empty($meta_title) ? $meta_title : $term->name);
        $display_description = !empty($social_description) ? $social_description : (!empty($meta_description) ? $meta_description : $term->description);
        $domain = wp_parse_url(home_url(), PHP_URL_HOST);

        // Calculate score
        $score_data = TamRank_Meta_Calculator::analyze([
            'title'         => $meta_title ?: $term->name,
            'description'   => $meta_description,
            'focus_keyword' => $focus_keyword,
            'slug'          => $term->slug,
        ]);
        $live_score  = $score_data['total_score'];
        $score_color = TamRank_Meta_Calculator::get_score_color($live_score);
        ?>
        <tr class="form-field">
            <td colspan="2" style="padding: 0;">
                <div class="tam-rank-meta-box" style="margin-top: 24px;">
                    <!-- Header -->
                    <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 4px;">
                        <svg width="24" height="24" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <rect x="4" y="4" width="32" height="32" rx="8" fill="#1e293b"/>
                            <rect x="10" y="10" width="20" height="5" rx="2" fill="#10b981"/>
                            <rect x="15" y="10" width="5" height="20" rx="2" fill="#10b981"/>
                            <rect x="22" y="18" width="5" height="12" rx="2" fill="#10b981" opacity="0.5"/>
                        </svg>
                        <span style="font-size: 15px; font-weight: 600; color: var(--tr-color-slate-800); font-family: var(--tr-font-family);">
                            TamRank SEO
                        </span>
                    </div>

                    <!-- Tab Navigation -->
                    <div class="tam-meta-tabs">
                        <button type="button" class="tam-meta-tab active" data-tab="seo">
                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                <circle cx="11" cy="11" r="8" stroke="currentColor" stroke-width="2" />
                                <path d="M21 21L16.65 16.65" stroke="currentColor" stroke-width="2" stroke-linecap="round" />
                            </svg>
                            <?php echo esc_html(tamrank__('tab_seo', 'SEO')); ?>
                        </button>
                        <button type="button" class="tam-meta-tab" data-tab="social">
                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                <path d="M18 2H15C13.6739 2 12.4021 2.52678 11.4645 3.46447C10.5268 4.40215 10 5.67392 10 7V10H7V14H10V22H14V14H17L18 10H14V7C14 6.73478 14.1054 6.48043 14.2929 6.29289C14.4804 6.10536 14.7348 6 15 6H18V2Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
                            </svg>
                            <?php echo esc_html(tamrank__('tab_social', 'Social')); ?>
                        </button>
                        <?php
                        // "Request indexing" for this term archive — the same
                        // action and the same handler as the posts-list row
                        // action (Frans, 19 Aug), on the tab bar's own line and
                        // pushed to the far right (Sam, 26 Aug), exactly like the
                        // post editor. Renders nothing on a non-public taxonomy,
                        // on a term without a resolvable archive URL, or without
                        // Search Console connected.
                        if (class_exists('TamRank_Indexing')) {
                            TamRank_Indexing::render_edit_screen_action('term', $term->term_id);
                        }
                        ?>
                    </div>

                    <!-- SEO Tab Content -->
                    <div class="tam-meta-tab-content active" id="tam-tab-seo">
                        <div class="tam-seo-layout">
                            <!-- Left Column: Score & Tips -->
                            <div class="tam-seo-sidebar">
                                <div class="tam-score-card">
                                    <h3 class="tam-score-card__title">
                                        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="var(--tr-color-primary)" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                            <path d="M3 3V21H21" />
                                            <path d="M18 9L13 14L9 10L3 16" />
                                        </svg>
                                        <?php echo esc_html(tamrank__('optimization_score', 'Optimization Score')); ?>
                                    </h3>
                                    <div class="tam-score-card__value">
                                        <span class="tam-score-card__number" style="color: <?php echo esc_attr($score_color); ?>;">
                                            <?php echo intval($live_score); ?>%
                                        </span>
                                    </div>
                                    <div class="tam-score-card__bar">
                                        <div class="tam-score-card__fill" style="width: <?php echo intval($live_score); ?>%; background: <?php echo esc_attr($score_color); ?>;"></div>
                                    </div>
                                    <p class="tam-score-card__hint">
                                        <?php echo esc_html(tamrank__('live_update_message', 'Updates live as you type')); ?>
                                    </p>
                                </div>

                                <div class="tam-tips-card">
                                    <h4 class="tam-tips-card__title">
                                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="var(--tr-color-status-attention)" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                            <path d="M12 2L15.09 8.26L22 9.27L17 14.14L18.18 21.02L12 17.77L5.82 21.02L7 14.14L2 9.27L8.91 8.26L12 2Z" />
                                        </svg>
                                        <?php echo esc_html(tamrank__('improvements', 'Improvements')); ?>
                                    </h4>
                                    <div class="tam-tips-card__list">
                                        <?php
                                        $has_tips = false;
                                        foreach ($score_data['details'] as $check) {
                                            if (!empty($check['issues'])) {
                                                $has_tips = true;
                                                foreach ($check['issues'] as $issue) {
                                                    echo '<p class="tam-tip tam-tip--failed"><span class="tam-tip__icon">&#10005;</span> ' . esc_html($issue) . '</p>';
                                                }
                                            } elseif (!empty($check['passed'])) {
                                                echo '<p class="tam-tip tam-tip--passed"><span class="tam-tip__icon">&#10003;</span> ' . esc_html($check['name']) . '</p>';
                                            }
                                        }
                                        if (!$has_tips && $live_score >= 80) {
                                            echo '<p class="tam-tips-card__empty">' . esc_html(tamrank__('looking_good', 'Looking good!')) . '</p>';
                                        }
                                        ?>
                                    </div>
                                </div>
                            </div>

                            <!-- Right Column: SEO Fields -->
                            <div class="tam-seo-fields">
                                <!-- Focus Keyword -->
                                <div class="tam-field-group">
                                    <label for="tamrank-term-focus-keyword">
                                        <?php echo esc_html(tamrank__('focus_keyword', 'Focus Keyword')); ?>
                                        <?php echo tamrank_render_info_tooltip(tamrank__('focus_keyword_tooltip', 'The main keyword you want this page to rank for. Use this word in your title, description and content for better visibility.')); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- returns escaped, plugin-generated tooltip markup (helper escapes text + attributes internally) ?>
                                    </label>
                                    <input type="text"
                                           id="tamrank-term-focus-keyword"
                                           name="_tam_rank_focus_keyword"
                                           value="<?php echo esc_attr($focus_keyword); ?>"
                                           class="tam-input"
                                    />
                                </div>

                                <!-- Meta Title -->
                                <div class="tam-field-group">
                                    <label for="tamrank-term-meta-title">
                                        <?php echo esc_html(tamrank__('meta_title', 'Meta Title')); ?>
                                        <?php echo tamrank_render_info_tooltip(tamrank__('meta_title_tooltip', 'The title that appears in search results. Keep it between 30-60 characters for best display.')); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- returns escaped, plugin-generated tooltip markup (helper escapes text + attributes internally) ?>
                                    </label>
                                    <input type="text"
                                           id="tamrank-term-meta-title"
                                           name="_tam_rank_meta_title"
                                           value="<?php echo esc_attr($meta_title); ?>"
                                           class="tam-input"
                                           maxlength="70"
                                           placeholder="<?php echo esc_attr($term->name); ?>"
                                    />
                                </div>

                                <!-- Meta Description -->
                                <div class="tam-field-group">
                                    <label for="tamrank-term-meta-description">
                                        <?php echo esc_html(tamrank__('meta_description', 'Meta Description')); ?>
                                        <?php echo tamrank_render_info_tooltip(tamrank__('meta_description_tooltip', 'A short summary of the page content. This text appears under the title in search results and helps users decide whether to click on your link.')); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- returns escaped, plugin-generated tooltip markup (helper escapes text + attributes internally) ?>
                                    </label>
                                    <textarea id="tamrank-term-meta-description"
                                              name="_tam_rank_meta_description"
                                              rows="3"
                                              class="tam-input tam-textarea"
                                              maxlength="200"
                                    ><?php echo esc_textarea($meta_description); ?></textarea>
                                </div>

                                <!-- Canonical URL -->
                                <div class="tam-field-group">
                                    <label for="tamrank-term-canonical">
                                        <?php echo esc_html(tamrank__('canonical_url', 'Canonical URL')); ?>
                                        <?php echo tamrank_render_info_tooltip(tamrank__('canonical_url_tooltip', 'The canonical URL helps search engines understand which version of a page is the main version. Only use this for duplicate content to prevent search engines from deducting points.')); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- returns escaped, plugin-generated tooltip markup (helper escapes text + attributes internally) ?>
                                    </label>
                                    <input type="url"
                                           id="tamrank-term-canonical"
                                           name="_tam_rank_canonical"
                                           value="<?php echo esc_url($canonical); ?>"
                                           class="tam-input"
                                           placeholder="<?php echo esc_url($term_link); ?>"
                                    />
                                    <span class="tr-field-card__hint"><?php echo esc_html(tamrank__('leave_empty_for_auto', 'Leave empty for automatic')); ?></span>
                                </div>

                                <!-- Robots -->
                                <div class="tam-field-group tr-robots">
                                    <label><?php echo esc_html(tamrank__('robots_label', 'Robots')); ?></label>
                                    <div class="tr-robots__grid">
                                        <?php
                                        tamrank_render_robots_checkbox(array(
                                            'id'      => 'term-_tam_rank_noindex',
                                            'name'    => '_tam_rank_noindex',
                                            'checked' => $noindex,
                                            'label'   => tamrank__('noindex_label', 'Noindex'),
                                            'desc'    => tamrank__('noindex_help', 'Hide this page from search engines'),
                                        ));

                                        tamrank_render_robots_checkbox(array(
                                            'id'      => 'term-_tam_rank_nofollow',
                                            'name'    => '_tam_rank_nofollow',
                                            'checked' => $nofollow,
                                            'label'   => tamrank__('nofollow_label', 'Nofollow'),
                                            'desc'    => tamrank__('nofollow_help', 'Don\'t follow links on this page'),
                                        ));
                                        ?>
                                    </div>
                                    <?php tamrank_render_advanced_robots_fields($robots_advanced, 'term'); ?>
                                </div><!-- /.tam-field-group (robots) -->

                                <!-- Google Preview -->
                                <div class="tam-field-group">
                                    <h4 class="tam-section-title"><?php tamrank_e('google_preview', 'Google Preview'); ?></h4>
                                    <div class="google-preview">
                                        <div class="preview-url"><?php echo esc_url($term_link); ?></div>
                                        <div class="preview-title" id="term-preview-title"><?php echo esc_html($meta_title ?: $term->name); ?></div>
                                        <div class="preview-description" id="term-preview-desc"><?php echo esc_html($meta_description); ?></div>
                                    </div>
                                </div>
                            </div><!-- /.tam-seo-fields -->
                        </div><!-- /.tam-seo-layout -->
                    </div><!-- /SEO Tab -->

                    <!-- Social Tab Content -->
                    <div class="tam-meta-tab-content" id="tam-tab-social">
                        <div class="tam-social-tab-content">
                            <div class="tam-social-layout">
                                <!-- Left Column: Input Fields -->
                                <div class="tam-social-sidebar">
                                    <!-- Social Title -->
                                    <div class="tam-field-group">
                                        <div class="tam-field-header">
                                            <label for="tamrank-term-social-title">
                                                <?php echo esc_html(tamrank__('social_title', 'Social Title')); ?>
                                                <?php echo tamrank_render_info_tooltip(tamrank__('social_title_tooltip', 'This title is used for Facebook, X (Twitter), LinkedIn and other social media. Leave empty to use the SEO title.')); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- returns escaped, plugin-generated tooltip markup (helper escapes text + attributes internally) ?>
                                            </label>
                                        </div>
                                        <input type="text"
                                               id="tamrank-term-social-title"
                                               name="_tam_rank_social_title"
                                               value="<?php echo esc_attr($social_title); ?>"
                                               class="tam-input"
                                               placeholder="<?php echo esc_attr($display_title); ?>"
                                        />
                                    </div>

                                    <!-- Social Description -->
                                    <div class="tam-field-group">
                                        <div class="tam-field-header">
                                            <label for="tamrank-term-social-description">
                                                <?php echo esc_html(tamrank__('social_description', 'Social Description')); ?>
                                                <?php echo tamrank_render_info_tooltip(tamrank__('social_description_tooltip', 'This description is shown when your content is shared on social media. Leave empty to use the SEO description.')); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- returns escaped, plugin-generated tooltip markup (helper escapes text + attributes internally) ?>
                                            </label>
                                        </div>
                                        <textarea id="tamrank-term-social-description"
                                                  name="_tam_rank_social_description"
                                                  rows="4"
                                                  class="tam-input tam-textarea"
                                                  placeholder="<?php echo esc_attr(wp_trim_words($display_description, 25, '...')); ?>"
                                        ><?php echo esc_textarea($social_description); ?></textarea>
                                    </div>

                                    <!-- Social Image -->
                                    <div class="tam-field-group">
                                        <label for="tamrank-term-social-image">
                                            <?php echo esc_html(tamrank__('social_image', 'Social Image')); ?>
                                            <?php echo tamrank_render_info_tooltip(tamrank__('social_image_tooltip', 'Upload an image for social media. Recommended size: 1200x630 pixels.')); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- returns escaped, plugin-generated tooltip markup (helper escapes text + attributes internally) ?>
                                        </label>
                                        <input type="hidden" id="tamrank-term-social-image" name="_tam_rank_social_image"
                                               value="<?php echo esc_url($social_image); ?>">

                                        <div class="tam-image-preview" id="term-social-image-preview"
                                             style="<?php echo empty($social_image) ? 'display: none;' : ''; ?>">
                                            <?php if (!empty($social_image)): ?>
                                                <img src="<?php echo esc_url($social_image); ?>" alt="<?php echo esc_attr(tamrank__('social_preview', 'Social preview')); ?>">
                                                <button type="button" class="tam-remove-image" aria-label="<?php echo esc_attr(tamrank__('remove_image', 'Remove image')); ?>" data-tr-tooltip="<?php echo esc_attr(tamrank__('remove_image', 'Remove image')); ?>">&times;</button>
                                            <?php endif; ?>
                                        </div>

                                        <div class="tam-image-upload-buttons">
                                            <button type="button" id="term-upload-social-image" class="button tam-btn tam-btn-green">
                                                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="tam-btn-icon">
                                                    <rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect>
                                                    <circle cx="8.5" cy="8.5" r="1.5"></circle>
                                                    <polyline points="21 15 16 10 5 21"></polyline>
                                                </svg>
                                                <?php echo esc_html(tamrank__('upload_image', 'Upload Image')); ?>
                                            </button>
                                        </div>
                                    </div>
                                </div>

                                <!-- Right Column: Live Previews -->
                                <div>
                                    <h4 class="tam-section-title"><?php tamrank_e('live_previews', 'Live Previews'); ?></h4>

                                    <!-- Facebook Preview -->
                                    <div class="tam-social-preview-card">
                                        <div class="tam-preview-header">
                                            <svg width="20" height="20" viewBox="0 0 24 24" fill="#1877F2">
                                                <path d="M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z" />
                                            </svg>
                                            <span class="tam-preview-header__label tam-preview-header__label--facebook">Facebook</span>
                                        </div>
                                        <div class="tam-preview-body tam-facebook-preview">
                                            <div class="tam-preview-image" id="term-fb-preview-image">
                                                <?php echo wp_kses(!empty($social_image) ? '<img src="' . esc_url($social_image) . '" alt="">' : $this->no_image_placeholder(), array_merge(wp_kses_allowed_html('post'), tam_rank_kses_svg())); ?>
                                            </div>
                                            <div class="tam-preview-content">
                                                <div class="tam-preview-domain"><?php echo esc_html($domain); ?></div>
                                                <div class="tam-preview-title" id="term-fb-preview-title"><?php echo esc_html($display_title); ?></div>
                                                <div class="tam-preview-desc" id="term-fb-preview-desc"><?php echo esc_html(wp_trim_words($display_description, 20, '...')); ?></div>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- X (Twitter) Preview -->
                                    <div class="tam-social-preview-card">
                                        <div class="tam-preview-header">
                                            <svg width="18" height="18" viewBox="0 0 24 24" fill="#000">
                                                <path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z" />
                                            </svg>
                                            <span class="tam-preview-header__label tam-preview-header__label--x">X (Twitter)</span>
                                        </div>
                                        <div class="tam-preview-body tam-twitter-preview">
                                            <div class="tam-preview-image" id="term-x-preview-image">
                                                <?php echo wp_kses(!empty($social_image) ? '<img src="' . esc_url($social_image) . '" alt="">' : $this->no_image_placeholder(), array_merge(wp_kses_allowed_html('post'), tam_rank_kses_svg())); ?>
                                            </div>
                                            <div class="tam-preview-content">
                                                <div class="tam-preview-title" id="term-x-preview-title"><?php echo esc_html($display_title); ?></div>
                                                <div class="tam-preview-desc" id="term-x-preview-desc"><?php echo esc_html(wp_trim_words($display_description, 15, '...')); ?></div>
                                                <div class="tam-preview-domain"><?php echo esc_html($domain); ?></div>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- LinkedIn Preview -->
                                    <div class="tam-social-preview-card">
                                        <div class="tam-preview-header">
                                            <svg width="18" height="18" viewBox="0 0 24 24" fill="#0A66C2">
                                                <path d="M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433c-1.144 0-2.063-.926-2.063-2.065 0-1.138.92-2.063 2.063-2.063 1.14 0 2.064.925 2.064 2.063 0 1.139-.925 2.065-2.064 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z" />
                                            </svg>
                                            <span class="tam-preview-header__label tam-preview-header__label--linkedin">LinkedIn</span>
                                        </div>
                                        <div class="tam-preview-body tam-linkedin-preview">
                                            <div class="tam-preview-image" id="term-li-preview-image">
                                                <?php echo wp_kses(!empty($social_image) ? '<img src="' . esc_url($social_image) . '" alt="">' : $this->no_image_placeholder(), array_merge(wp_kses_allowed_html('post'), tam_rank_kses_svg())); ?>
                                            </div>
                                            <div class="tam-preview-content">
                                                <div class="tam-preview-title" id="term-li-preview-title"><?php echo esc_html($display_title); ?></div>
                                                <div class="tam-preview-domain"><?php echo esc_html($domain); ?></div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div><!-- /Social Tab -->

                </div><!-- /.tam-rank-meta-box -->
            </td>
        </tr>

        <?php ob_start(); ?>
        jQuery(document).ready(function($) {
            // ── i18n labels (from PHP) ──
            var i18n = {
                metaTitle:       <?php echo wp_json_encode(tamrank__('meta_title', 'Meta Title'), JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT); ?>,
                metaDescription: <?php echo wp_json_encode(tamrank__('meta_description', 'Meta Description'), JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT); ?>,
                focusKeyword:    <?php echo wp_json_encode(tamrank__('focus_keyword', 'Focus Keyword'), JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT); ?>,
                urlStructure:    <?php echo wp_json_encode(tamrank__('score_url_structure', 'URL Structure'), JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT); ?>,
                titleShort:      <?php echo wp_json_encode(tamrank__('score_title_short', 'Too short (less than 30 characters)'), JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT); ?>,
                titleLong:       <?php echo wp_json_encode(tamrank__('score_title_long', 'Too long (more than 60 characters)'), JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT); ?>,
                descShort:       <?php echo wp_json_encode(tamrank__('score_desc_short', 'Too short (less than 120 characters)'), JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT); ?>,
                descLong:        <?php echo wp_json_encode(tamrank__('score_desc_long', 'Too long (more than 160 characters)'), JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT); ?>,
                noDesc:          <?php echo wp_json_encode(tamrank__('score_no_desc', 'No meta description set'), JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT); ?>,
                noKeyword:       <?php echo wp_json_encode(tamrank__('score_no_keyword', 'No focus keyword set'), JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT); ?>,
                kwNotInTitle:    <?php echo wp_json_encode(tamrank__('score_kw_not_in_title', 'Focus keyword not present in title'), JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT); ?>,
                kwNotInDesc:     <?php echo wp_json_encode(tamrank__('score_kw_not_in_desc', 'Focus keyword not present in description'), JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT); ?>,
                kwNotInUrl:      <?php echo wp_json_encode(tamrank__('score_kw_not_in_url', 'Focus keyword not in URL'), JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT); ?>,
                noSlug:          <?php echo wp_json_encode(tamrank__('score_no_slug', 'No URL slug set'), JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT); ?>,
                lookingGood:     <?php echo wp_json_encode(tamrank__('looking_good', 'Looking good!'), JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT); ?>
            };
            var termSlug = <?php echo wp_json_encode($term->slug, JSON_HEX_TAG | JSON_HEX_AMP); ?>;
            var defaultTitle = <?php echo wp_json_encode($term->name, JSON_HEX_TAG | JSON_HEX_AMP); ?>;

            // ── Client-side score calculator (mirrors TamRank_Meta_Calculator) ──
            function keywordExists(text, keyword) {
                if (!keyword || !text) return false;
                try {
                    var pattern = new RegExp('\\b' + keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '\\b', 'iu');
                    return pattern.test(text);
                } catch(e) { return text.toLowerCase().indexOf(keyword.toLowerCase()) !== -1; }
            }

            function getScoreColor(score) {
                if (score >= 80) return '#10b981';
                if (score >= 60) return '#14b8a6';
                if (score >= 40) return '#f59e0b';
                return '#f43f5e';
            }

            function analyzeTermSeo() {
                var title = $('#tamrank-term-meta-title').val() || defaultTitle;
                var desc = $('#tamrank-term-meta-description').val();
                var keyword = $('#tamrank-term-focus-keyword').val();
                var score = 0, maxScore = 50;
                var tips = []; // {text, passed}

                // 1. Meta Title (15 pts max)
                var titleLen = title.length;
                if (titleLen >= 30 && titleLen <= 60) {
                    score += 10;
                } else if (titleLen > 0 && titleLen < 30) {
                    score += 3; tips.push({text: i18n.titleShort, passed: false});
                } else if (titleLen > 60) {
                    score += 5; tips.push({text: i18n.titleLong, passed: false});
                }
                if (keyword) {
                    if (keywordExists(title, keyword)) { score += 5; }
                    else { tips.push({text: i18n.kwNotInTitle, passed: false}); }
                }
                if (titleLen >= 30 && titleLen <= 60 && (!keyword || keywordExists(title, keyword))) {
                    tips.push({text: i18n.metaTitle, passed: true});
                }

                // 2. Meta Description (15 pts max)
                var descLen = desc.length;
                if (descLen >= 120 && descLen <= 160) {
                    score += 10;
                } else if (descLen > 0 && descLen < 120) {
                    score += 3; tips.push({text: i18n.descShort, passed: false});
                } else if (descLen > 160) {
                    score += 5; tips.push({text: i18n.descLong, passed: false});
                } else {
                    tips.push({text: i18n.noDesc, passed: false});
                }
                if (keyword) {
                    if (descLen > 0 && keywordExists(desc, keyword)) { score += 5; }
                    else if (descLen > 0) { tips.push({text: i18n.kwNotInDesc, passed: false}); }
                }
                if (descLen >= 120 && descLen <= 160 && (!keyword || keywordExists(desc, keyword))) {
                    tips.push({text: i18n.metaDescription, passed: true});
                }

                // 3. Focus Keyword (10 pts)
                if (keyword) {
                    score += 10;
                    tips.push({text: i18n.focusKeyword, passed: true});
                } else {
                    tips.push({text: i18n.noKeyword, passed: false});
                }

                // 4. URL slug (10 pts max)
                if (termSlug) {
                    score += 5;
                    if (keyword) {
                        var slugKeyword = keyword.toLowerCase().replace(/\s+/g, '-').replace(/[^a-z0-9-]/g, '');
                        if (keywordExists(termSlug, slugKeyword)) { score += 5; }
                        else { tips.push({text: i18n.kwNotInUrl, passed: false}); }
                    }
                    if (!keyword || keywordExists(termSlug, keyword ? keyword.toLowerCase().replace(/\s+/g, '-').replace(/[^a-z0-9-]/g, '') : '')) {
                        tips.push({text: i18n.urlStructure, passed: true});
                    }
                } else {
                    tips.push({text: i18n.noSlug, passed: false});
                }

                var finalScore = Math.min(100, Math.round((score / maxScore) * 100));
                return {score: finalScore, tips: tips};
            }

            function updateTermScore() {
                var result = analyzeTermSeo();
                var color = getScoreColor(result.score);

                // Update score number + bar
                $('.tam-score-card__number').text(result.score + '%').css('color', color);
                $('.tam-score-card__fill').css({width: result.score + '%', background: color});

                // Update tips list
                var html = '';
                var hasFailedTips = false;
                result.tips.forEach(function(tip) {
                    if (tip.passed) {
                        html += '<p class="tam-tip tam-tip--passed"><span class="tam-tip__icon">&#10003;</span> ' + tip.text + '</p>';
                    } else {
                        hasFailedTips = true;
                        html += '<p class="tam-tip tam-tip--failed"><span class="tam-tip__icon">&#10005;</span> ' + tip.text + '</p>';
                    }
                });
                if (!hasFailedTips && result.score >= 80) {
                    html = '<p class="tam-tips-card__empty">' + i18n.lookingGood + '</p>';
                }
                $('.tam-tips-card__list').html(html);

                // Update Google Preview
                $('#term-preview-title').text($('#tamrank-term-meta-title').val() || defaultTitle);
                $('#term-preview-desc').text($('#tamrank-term-meta-description').val());
            }

            // Bind live score to all SEO fields
            $('#tamrank-term-meta-title, #tamrank-term-meta-description, #tamrank-term-focus-keyword').on('input', updateTermScore);
            updateTermScore(); // initial

            // ── Tab switching ──
            $('.tam-rank-meta-box .tam-meta-tab').on('click', function(e) {
                e.preventDefault();
                var tabId = $(this).data('tab');
                var $box = $(this).closest('.tam-rank-meta-box');
                $box.find('.tam-meta-tab').removeClass('active');
                $(this).addClass('active');
                $box.find('.tam-meta-tab-content').removeClass('active');
                $box.find('#tam-tab-' + tabId).addClass('active');
            });

            // ── Social previews live update ──
            var socialDefaultTitle = <?php echo wp_json_encode($display_title, JSON_HEX_TAG | JSON_HEX_AMP); ?>;
            var socialDefaultDesc = <?php echo wp_json_encode($display_description, JSON_HEX_TAG | JSON_HEX_AMP); ?>;

            function updateTermSocialPreviews() {
                var title = $('#tamrank-term-social-title').val() || socialDefaultTitle;
                var desc = $('#tamrank-term-social-description').val() || socialDefaultDesc;
                $('#term-fb-preview-title, #term-x-preview-title, #term-li-preview-title').text(title);
                $('#term-fb-preview-desc').text(desc.length > 100 ? desc.substring(0, 100) + '...' : desc);
                $('#term-x-preview-desc').text(desc.length > 70 ? desc.substring(0, 70) + '...' : desc);
            }

            $('#tamrank-term-social-title, #tamrank-term-social-description').on('input', updateTermSocialPreviews);

            // ── Social image upload ──
            var termMediaUploader;
            $('#term-upload-social-image').on('click', function(e) {
                e.preventDefault();
                if (termMediaUploader) {
                    termMediaUploader.open();
                    return;
                }
                termMediaUploader = wp.media({
                    title: <?php echo wp_json_encode(tamrank__('select_social_image', 'Select Social Image'), JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT); ?>,
                    button: { text: <?php echo wp_json_encode(tamrank__('use_this_image', 'Use this image'), JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT); ?> },
                    multiple: false,
                    library: { type: 'image' }
                });
                termMediaUploader.on('select', function() {
                    var attachment = termMediaUploader.state().get('selection').first().toJSON();
                    var imageUrl = attachment.sizes && attachment.sizes.large ? attachment.sizes.large.url : attachment.url;
                    $('#tamrank-term-social-image').val(imageUrl);
                    updateTermImagePreviews(imageUrl);
                });
                termMediaUploader.open();
            });

            // Remove image
            $(document).on('click', '.tam-rank-meta-box .tam-remove-image', function(e) {
                e.preventDefault();
                $('#tamrank-term-social-image').val('');
                updateTermImagePreviews('');
            });

            function updateTermImagePreviews(imageUrl) {
                var $preview = $('#term-social-image-preview');
                var previewIds = ['#term-fb-preview-image', '#term-x-preview-image', '#term-li-preview-image'];

                if (imageUrl) {
                    $preview.html('<img src="' + imageUrl + '" alt="<?php echo esc_attr(tamrank__('social_preview', 'Social preview')); ?>"><button type="button" class="tam-remove-image" data-tr-tooltip="<?php echo esc_attr(tamrank__('remove_image', 'Remove image')); ?>">&times;</button>').show();
                    previewIds.forEach(function(id) {
                        $(id).html('<img src="' + imageUrl + '" alt="">');
                    });
                } else {
                    $preview.hide().empty();
                    var placeholder = <?php echo wp_json_encode($this->no_image_placeholder(), JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT); ?>;
                    previewIds.forEach(function(id) {
                        $(id).html(placeholder);
                    });
                }
            }

            updateTermSocialPreviews();
        });
        <?php
        wp_add_inline_script('tamrank-taxonomy-meta', ob_get_clean());
    }

    /**
     * Save term meta fields.
     */
    public function save_term_fields($term_id, $tt_id)
    {
        if (!isset($_POST['tamrank_term_meta_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['tamrank_term_meta_nonce'])), 'tamrank_term_meta_nonce')) {
            return;
        }

        if (!current_user_can('edit_term', $term_id)) {
            return;
        }

        $text_fields = array(
            '_tam_rank_meta_title',
            '_tam_rank_focus_keyword',
            '_tam_rank_social_title',
        );

        foreach ($text_fields as $field) {
            if (isset($_POST[$field])) {
                $value = sanitize_text_field(wp_unslash($_POST[$field]));
                if (!empty($value)) {
                    update_term_meta($term_id, $field, $value);
                } else {
                    delete_term_meta($term_id, $field);
                }
            }
        }

        // Textarea fields
        $textarea_fields = array(
            '_tam_rank_meta_description',
            '_tam_rank_social_description',
        );

        foreach ($textarea_fields as $field) {
            if (isset($_POST[$field])) {
                $value = sanitize_textarea_field(wp_unslash($_POST[$field]));
                if (!empty($value)) {
                    update_term_meta($term_id, $field, $value);
                } else {
                    delete_term_meta($term_id, $field);
                }
            }
        }

        // URL fields
        $url_fields = array(
            '_tam_rank_canonical',
            '_tam_rank_social_image',
        );

        foreach ($url_fields as $field) {
            if (isset($_POST[$field])) {
                $value = sanitize_url(wp_unslash($_POST[$field]));
                if (!empty($value)) {
                    update_term_meta($term_id, $field, $value);
                } else {
                    delete_term_meta($term_id, $field);
                }
            }
        }

        // Checkbox fields
        $checkboxes = array('_tam_rank_noindex', '_tam_rank_nofollow');
        foreach ($checkboxes as $field) {
            if (isset($_POST[$field])) {
                update_term_meta($term_id, $field, 1);
            } else {
                delete_term_meta($term_id, $field);
            }
        }

        // Advanced robots directives (noarchive, nosnippet, max-snippet, ...).
        // Nonce and capability were verified at the top of this method; the helper
        // sanitizes every value per directive type before writing.
        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified at the top of save_term_fields(); values are sanitized per directive inside the helper.
        tamrank_save_robots_directives($term_id, wp_unslash($_POST), 'term');
    }
}
