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

class PIPEBU_Admin {

    public static function init(): void {
        if ( ! is_admin() ) return;
        add_action( 'admin_menu',            [ __CLASS__, 'register_menu' ] );
        add_action( 'admin_enqueue_scripts', [ __CLASS__, 'enqueue_assets' ] );
        add_action( 'wp_ajax_pipebu_upload_images',    [ __CLASS__, 'ajax_upload_images' ] );
        add_action( 'wp_ajax_pipebu_queue_job',        [ __CLASS__, 'ajax_queue_job' ] );
        add_action( 'wp_ajax_pipebu_poll_job',         [ __CLASS__, 'ajax_poll_job' ] );
        add_action( 'wp_ajax_pipebu_publish',          [ __CLASS__, 'ajax_publish' ] );
        add_action( 'wp_ajax_pipebu_search_products',  [ __CLASS__, 'ajax_search_products' ] );
        add_action( 'wp_ajax_pipebu_search_posts',     [ __CLASS__, 'ajax_search_posts' ] );
        // GSC OAuth + data actions.
        add_action( 'wp_ajax_pipebu_gsc_callback',     [ __CLASS__, 'ajax_gsc_callback' ] );
        add_action( 'wp_ajax_pipebu_gsc_disconnect',   [ __CLASS__, 'ajax_gsc_disconnect' ] );
        add_action( 'wp_ajax_pipebu_gsc_set_site',     [ __CLASS__, 'ajax_gsc_set_site' ] );
        add_action( 'wp_ajax_pipebu_gsc_take_baseline',[ __CLASS__, 'ajax_gsc_take_baseline' ] );
        add_action( 'wp_ajax_pipebu_clear_sec_log',    [ __CLASS__, 'ajax_clear_sec_log' ] );
        add_action( 'wp_ajax_pipebu_report_failure',   [ __CLASS__, 'ajax_report_failure' ] );
        // PB badge on WC product list.
        add_filter( 'manage_product_posts_columns',       [ __CLASS__, 'add_pb_column' ] );
        add_action( 'manage_product_posts_custom_column', [ __CLASS__, 'render_pb_column' ], 10, 2 );
    }

    public static function register_menu(): void {
        add_menu_page(
            __( 'Pipeline Buster', 'pipeline-buster' ),
            __( 'Pipeline Buster', 'pipeline-buster' ),
            'manage_woocommerce',
            'pipeline-buster',
            [ __CLASS__, 'render_main_page' ],
            'dashicons-superhero',
            58
        );
        add_submenu_page( 'pipeline-buster',
            __( 'New Product', 'pipeline-buster' ),
            __( 'New Product', 'pipeline-buster' ),
            'manage_woocommerce', 'pipeline-buster',
            [ __CLASS__, 'render_main_page' ]
        );
        add_submenu_page( 'pipeline-buster',
            __( 'Settings', 'pipeline-buster' ),
            __( 'Settings', 'pipeline-buster' ),
            'manage_options', 'pipeline-buster-settings',
            [ 'PIPEBU_Settings', 'render_settings_page' ]
        );
        add_submenu_page( 'pipeline-buster',
            __( 'Help & Docs', 'pipeline-buster' ),
            __( 'Help & Docs', 'pipeline-buster' ),
            'manage_woocommerce', 'pipeline-buster-help',
            [ __CLASS__, 'render_help_page' ]
        );
        add_submenu_page( 'pipeline-buster',
            __( 'Reports', 'pipeline-buster' ),
            __( 'Reports', 'pipeline-buster' ),
            'manage_options', 'pipeline-buster-reports',
            [ __CLASS__, 'render_reports_page' ]
        );
    }

    public static function enqueue_assets( string $hook ): void {
        if ( strpos( $hook, 'pipeline-buster' ) === false ) return;
        wp_enqueue_media();
        wp_enqueue_style( 'pipebu-admin', PIPEBU_PLUGIN_URL . 'assets/css/pb-admin.css', [], PIPEBU_VERSION );
        wp_enqueue_script( 'pipebu-admin', PIPEBU_PLUGIN_URL . 'assets/js/pb-admin.js', [ 'jquery' ], PIPEBU_VERSION, true );
        $q_is_dev  = PIPEBU_Quota::is_dev_mode();
        $q_is_paid = (bool) apply_filters( 'pipebu_has_paid_license', false );
        wp_localize_script( 'pipebu-admin', 'PIPEBU', [
            'ajaxurl'    => admin_url( 'admin-ajax.php' ),
            'nonce'      => wp_create_nonce( 'pipebu_nonce' ),
            'max_images' => PIPEBU_MAX_IMAGES,
            'max_mb'     => PIPEBU_MAX_MB,
            'ui_mode'    => PIPEBU_Settings::ui_mode(),
            'depths'     => PIPEBU_Settings::content_depths(),
            'tones'      => PIPEBU_Settings::tones(),
            'languages'  => PIPEBU_Settings::languages(),
            'lang_ui'    => PIPEBU_Settings::lang_ui_strings(),
            'templates'  => self::howto_templates(),
            'quota'      => [
                'used'        => PIPEBU_Quota::get_used(),
                'limit'       => PIPEBU_Quota::FREE_LIMIT,
                'remaining'   => $q_is_dev ? PHP_INT_MAX : PIPEBU_Quota::get_remaining(),
                'unlimited'   => $q_is_dev,
                'is_paid'     => $q_is_paid,
                'upgrade_url' => 'https://checkout.freemius.com/plugin/27716/plan/45802/licenses/1/',
            ],
            'strings'    => [
                'uploading'          => __( 'Uploading images…', 'pipeline-buster' ),
                'queuing'            => __( 'Sending to AI…', 'pipeline-buster' ),
                'processing'         => __( 'AI is analyzing your images… this takes 20–40 seconds.', 'pipeline-buster' ),
                'processing_guide'   => __( 'AI is reading your manual… this takes 20–40 seconds.', 'pipeline-buster' ),
                'publishing'         => __( 'Publishing…', 'pipeline-buster' ),
                'error'              => __( 'Something went wrong. Please try again.', 'pipeline-buster' ),
                /* translators: %d: maximum number of images allowed */
                'too_many'           => sprintf( __( 'Max %d images allowed. Please remove some.', 'pipeline-buster' ), absint( PIPEBU_MAX_IMAGES ) ),
                /* translators: %d: maximum upload size in megabytes */
                'too_large'          => sprintf( __( 'Total upload size exceeds %dMB limit. Use smaller or fewer images.', 'pipeline-buster' ), absint( PIPEBU_MAX_MB ) ),
                'no_images'          => __( 'Please upload at least one image.', 'pipeline-buster' ),
                'timeout'            => __( 'Generation timed out — the server may be busy. Please try again.', 'pipeline-buster' ),
                'name_required'      => __( 'Product name is required.', 'pipeline-buster' ),
                'howto_title_required' => __( 'How To title is required.', 'pipeline-buster' ),
                'search_placeholder' => __( 'Type to search existing products…', 'pipeline-buster' ),
                'no_product_linked'    => __( 'No product linked — How To will be published standalone.', 'pipeline-buster' ),
                'custom_tone_empty'    => __( 'Custom tone selected but no style reference added. Generate with Professional tone instead?', 'pipeline-buster' ),
                'custom_use_pro'       => __( 'Use Professional', 'pipeline-buster' ),
                'custom_add_ref'       => __( 'Add Style Reference', 'pipeline-buster' ),
                'quota_title'              => __( 'Free limit reached', 'pipeline-buster' ),
                /* translators: %d: number of free products included */
                'quota_msg'                => sprintf( __( 'You\'ve used all %d free products included with Pipeline Buster. Upgrade to keep going.', 'pipeline-buster' ), absint( PIPEBU_Quota::FREE_LIMIT ) ),
                'quota_upgrade'            => __( 'Upgrade Now &#8594;', 'pipeline-buster' ),
                'quota_later'              => __( 'Maybe later', 'pipeline-buster' ),
                'credits_exhausted_title'  => __( 'Credits exhausted', 'pipeline-buster' ),
                'credits_exhausted_msg'    => __( 'You\'ve used all your product credits. Purchase more to keep publishing.', 'pipeline-buster' ),
                'credits_buy_more'         => __( 'Buy More Credits &#8594;', 'pipeline-buster' ),
                'processing_colors'        => __( 'AI is analyzing images and generating color variations…', 'pipeline-buster' ),
                'sec_clear_confirm'        => __( 'Clear all security events? This cannot be undone.', 'pipeline-buster' ),
            ],
        ] );
    }

    // -------------------------------------------------------------------------
    // How To templates definition (passed to JS)
    // -------------------------------------------------------------------------

    public static function howto_templates(): array {
        return [
            'none'         => 'AI Decides — Let the AI choose the best structure for this product.',
            'step_by_step' => 'Step-by-Step — Numbered steps with a specs table. Best for technical devices.',
            'narrative'    => 'Narrative Guide — Flowing prose style. Best for lifestyle and vaping products.',
            'quick_start'  => 'Quick Start — Concise and scannable. Key steps only. Best for simple devices.',
        ];
    }

    // -------------------------------------------------------------------------
    // Main page
    // -------------------------------------------------------------------------

    public static function render_main_page(): void {
        if ( ! current_user_can( 'manage_woocommerce' ) ) {
            wp_die( esc_html__( 'Permission denied.', 'pipeline-buster' ) );
        }
        if ( ! PIPEBU_Settings::api_key() ) {
            echo '<div class="wrap"><div class="notice notice-warning"><p>' .
                sprintf(
                    /* translators: %s: URL to the Settings page */
                    wp_kses( __( '&#128640; Pipeline Buster needs an API key. <a href="%s">Go to Settings →</a>', 'pipeline-buster' ),
                        [ 'a' => [ 'href' => [] ] ] ),
                    esc_url( admin_url( 'admin.php?page=pipeline-buster-settings' ) )
                ) . '</p></div></div>';
            return;
        }

        $tones     = PIPEBU_Settings::tones();
        $depths    = PIPEBU_Settings::content_depths();
        $templates = self::howto_templates();
        $mode      = PIPEBU_Settings::ui_mode();
        ?>
        <div class="wrap pb-wrap">

            <!-- Page banner — always visible -->
            <div class="pb-page-banner-wrap">
                <img src="<?php echo esc_url( PIPEBU_PLUGIN_URL . 'assets/img/pb-banner.png' ); ?>" alt="Pipeline Buster" class="pb-page-banner" />
            </div>

            <!-- Quota strip — hidden in dev mode, credit strip for paid, progress bar for free -->
            <?php if ( ! PIPEBU_Quota::is_dev_mode() ) : ?>
            <?php if ( (bool) apply_filters( 'pipebu_has_paid_license', false ) ) :
                $q_credits = PIPEBU_Quota::get_credit_balance();
                $q_class   = $q_credits === 0 ? 'pb-quota-strip--full' : ( $q_credits <= 2 ? 'pb-quota-strip--low' : '' );
            ?>
            <div class="pb-quota-strip <?php echo esc_attr( $q_class ); ?>">
                <div class="pb-quota-left">
                    <?php if ( $q_credits === 0 ) : ?>
                        <span class="pb-quota-label"><?php esc_html_e( 'Credits exhausted &mdash;', 'pipeline-buster' ); ?></span>
                        <a href="<?php echo esc_url( 'https://checkout.freemius.com/plugin/27716/plan/45802/licenses/1/' ); ?>" class="pb-quota-upgrade-link" target="_blank" rel="noopener"><?php esc_html_e( 'Buy more credits', 'pipeline-buster' ); ?></a>
                    <?php else : ?>
                        <span class="pb-quota-label">
                            <?php printf(
                                /* translators: %d: credits remaining */
                                esc_html__( '%d product credit(s) remaining', 'pipeline-buster' ),
                                absint( $q_credits )
                            ); ?>
                        </span>
                    <?php endif; ?>
                </div>
            </div>
            <?php else :
                $q_used      = PIPEBU_Quota::get_used();
                $q_limit     = PIPEBU_Quota::FREE_LIMIT;
                $q_remaining = PIPEBU_Quota::get_remaining();
                $q_pct       = $q_limit > 0 ? round( ( $q_used / $q_limit ) * 100 ) : 0;
                $q_class     = $q_remaining === 0 ? 'pb-quota-strip--full' : ( $q_remaining <= 1 ? 'pb-quota-strip--low' : '' );
            ?>
            <div class="pb-quota-strip <?php echo esc_attr( $q_class ); ?>">
                <div class="pb-quota-left">
                    <?php if ( $q_remaining === 0 ) : ?>
                        <span class="pb-quota-label">Free limit reached &mdash;</span>
                        <a href="#" class="pb-quota-upgrade-link"><?php esc_html_e( 'Upgrade to continue', 'pipeline-buster' ); ?></a>
                    <?php else : ?>
                        <span class="pb-quota-label">
                            <?php printf(
                                /* translators: %1$d: products used, %2$d: product limit */
                                esc_html__( 'Free plan: %1$d of %2$d products used', 'pipeline-buster' ),
                                absint( $q_used ), absint( $q_limit )
                            ); ?>
                        </span>
                    <?php endif; ?>
                </div>
                <div class="pb-quota-track">
                    <div class="pb-quota-fill" style="width:<?php echo esc_attr( $q_pct ); ?>%"></div>
                </div>
            </div>
            <?php endif; ?>
            <?php endif; ?>

            <!-- Header -->
            <div class="pb-header">
                <div class="pb-header-inner">
                    <div class="pb-brand">
                        <span class="pb-rocket">&#128640;</span>
                        <div>
                            <h1 class="pb-title">Pipeline Buster</h1>
                            <p class="pb-tagline"><?php esc_html_e( 'Drop images. Get a product. Done.', 'pipeline-buster' ); ?></p>
                        </div>
                    </div>
                </div>
                <div class="pb-mode-row">
                    <span class="pb-mode-label"><?php esc_html_e( 'Review Mode:', 'pipeline-buster' ); ?></span>
                    <button type="button" class="pb-mode-btn <?php echo $mode === 'simple' ? 'active' : ''; ?>" data-mode="simple">
                        <?php esc_html_e( 'Simple', 'pipeline-buster' ); ?>
                    </button>
                    <button type="button" class="pb-mode-btn <?php echo $mode === 'expert' ? 'active' : ''; ?>" data-mode="expert">
                        <?php esc_html_e( 'Expert', 'pipeline-buster' ); ?>
                    </button>
                    <span class="pb-mode-desc"><?php echo $mode === 'expert'
                        ? esc_html__( 'Full review — all fields visible.', 'pipeline-buster' )
                        : esc_html__( 'Guided — essentials only.', 'pipeline-buster' ); ?></span>
                </div>
            </div>

            <!-- Step indicators -->
            <div class="pb-steps" id="pb-steps">
                <div class="pb-step active" id="pb-step-1"><span class="pb-step-num">1</span><?php esc_html_e( 'Upload', 'pipeline-buster' ); ?></div>
                <div class="pb-step-arrow">›</div>
                <div class="pb-step" id="pb-step-2"><span class="pb-step-num">2</span><?php esc_html_e( 'Generate', 'pipeline-buster' ); ?></div>
                <div class="pb-step-arrow">›</div>
                <div class="pb-step" id="pb-step-3"><span class="pb-step-num">3</span><?php esc_html_e( 'Review', 'pipeline-buster' ); ?></div>
                <div class="pb-step-arrow">›</div>
                <div class="pb-step" id="pb-step-4"><span class="pb-step-num">4</span><?php esc_html_e( 'Done', 'pipeline-buster' ); ?></div>
            </div>

            <!-- PANEL 1: Upload -->
            <div id="pb-panel-1" class="pb-panel">
                <div class="pb-card">

                    <!-- Input Mode toggle -->
                    <div class="pb-input-mode-row">
                        <span class="pb-input-mode-label"><?php esc_html_e( 'What are you creating?', 'pipeline-buster' ); ?></span>
                        <div class="pb-input-mode-tabs">
                            <button type="button" class="pb-input-tab active" data-input-mode="standard">
                                &#128722; <?php esc_html_e( 'New Product + How To', 'pipeline-buster' ); ?>
                            </button>
                            <button type="button" class="pb-input-tab" data-input-mode="guide">
                                &#128214; <?php esc_html_e( 'How To Only (Guide Mode)', 'pipeline-buster' ); ?>
                            </button>
                        </div>
                    </div>

                    <!-- Guide Mode: Product selector -->
                    <div id="pb-guide-product-wrap" class="pb-guide-product-wrap" style="display:none">
                        <div class="pb-guide-product-inner">
                            <label class="pb-guide-product-label">
                                &#128279; <?php esc_html_e( 'Link to an existing product', 'pipeline-buster' ); ?>
                                <span class="pb-optional"><?php esc_html_e( '(optional)', 'pipeline-buster' ); ?></span>
                            </label>
                            <div class="pb-product-search-wrap">
                                <input type="text" id="pb-product-search" class="widefat pb-product-search-input"
                                    placeholder="<?php esc_attr_e( 'Type to search existing products…', 'pipeline-buster' ); ?>" autocomplete="off" />
                                <div id="pb-product-results" class="pb-product-results" style="display:none"></div>
                            </div>
                            <div id="pb-product-selected" class="pb-product-selected" style="display:none">
                                <span id="pb-product-selected-name"></span>
                                <button type="button" id="pb-product-clear" class="pb-product-clear" title="<?php esc_attr_e( 'Clear selection', 'pipeline-buster' ); ?>">&#215;</button>
                            </div>
                            <p class="pb-hint" id="pb-guide-hint"><?php esc_html_e( 'If linked, the How To post will be automatically connected to this product.', 'pipeline-buster' ); ?></p>
                        </div>
                    </div>

                    <h2 id="pb-upload-heading"><?php esc_html_e( 'Upload Product Images', 'pipeline-buster' ); ?></h2>
                    <p class="pb-hint" id="pb-upload-hint"><?php
                    printf(
                        /* translators: %1$d: maximum number of images, %2$d: maximum upload size in megabytes */
                        esc_html__( 'Include product photos, packaging, and manual pages. Max %1$d images, %2$dMB total.', 'pipeline-buster' ),
                        absint( PIPEBU_MAX_IMAGES ), absint( PIPEBU_MAX_MB )
                    ); ?></p>

                    <!-- Color variation option — hidden in Guide Mode -->
                    <div id="pb-colors-wrap" class="pb-colors-wrap">
                        <label class="pb-checkbox-label">
                            <input type="checkbox" id="pb-has-colors" />
                            <?php esc_html_e( 'This product comes in multiple colors', 'pipeline-buster' ); ?>
                        </label>
                        <div id="pb-colors-guide" class="pb-colors-guide" style="display:none">
                            <p class="pb-colors-guide-title"><?php esc_html_e( 'How it works:', 'pipeline-buster' ); ?></p>
                            <ul class="pb-colors-guide-list">
                                <li><?php esc_html_e( 'Upload one photo per color variant', 'pipeline-buster' ); ?></li>
                                <li><?php esc_html_e( 'AI reads each image and names the color', 'pipeline-buster' ); ?></li>
                                <li><?php esc_html_e( 'Each color becomes a separate variation with its own image and price', 'pipeline-buster' ); ?></li>
                            </ul>
                        </div>
                    </div>

                    <div id="pb-dropzone" class="pb-dropzone">
                        <span class="pb-drop-icon">&#128247;</span>
                        <p id="pb-dropzone-label"><?php esc_html_e( 'Drag & drop images here', 'pipeline-buster' ); ?></p>
                        <label for="pb-file-input" class="pb-browse-btn">
                            <?php esc_html_e( '+ Browse Files', 'pipeline-buster' ); ?>
                        </label>
                        <input type="file" id="pb-file-input" multiple accept="image/jpeg,image/png,image/webp,image/gif" style="display:none" />
                    </div>

                    <div id="pb-upload-progress" class="pb-upload-progress" style="display:none">
                        <div class="pb-upload-bar-wrap">
                            <div class="pb-upload-bar-fill" id="pb-upload-fill"></div>
                        </div>
                        <p id="pb-upload-status"></p>
                    </div>

                    <div id="pb-size-bar" class="pb-size-bar" style="display:none">
                        <span id="pb-size-text">0 MB / <?php echo esc_html( PIPEBU_MAX_MB ); ?> MB</span>
                        <span id="pb-count-text">0 / <?php echo esc_html( PIPEBU_MAX_IMAGES ); ?> images</span>
                    </div>

                    <div id="pb-preview-grid" class="pb-preview-grid"></div>

                    <div id="pb-img-legend" class="pb-img-legend" style="display:none">
                        <span class="pb-legend-item"><span class="pb-legend-dot pb-legend-dot--green"></span><?php esc_html_e( 'Hero', 'pipeline-buster' ); ?></span>
                        <span class="pb-legend-item"><span class="pb-legend-dot pb-legend-dot--teal"></span><?php esc_html_e( 'How To', 'pipeline-buster' ); ?></span>
                        <span class="pb-legend-item"><span class="pb-legend-dot pb-legend-dot--yellow"></span><?php esc_html_e( 'Manual', 'pipeline-buster' ); ?> <em><?php esc_html_e( '— click to tag', 'pipeline-buster' ); ?></em></span>
                    </div>
                    <p class="pb-hero-hint" id="pb-hero-hint" style="display:none"><?php esc_html_e( 'First = Hero (dark teal) · Last = How To (teal) · Click middle images to tag as Manual (yellow)', 'pipeline-buster' ); ?></p>

                    <!-- Content options (shown after upload) -->
                    <div id="pb-generate-options" style="display:none">
                        <div class="pb-options-row">
                            <!-- Tone & Style — top left -->
                            <div class="pb-option-group">
                                <label><?php esc_html_e( 'Tone & Style', 'pipeline-buster' ); ?></label>
                                <div class="pb-pill-group" id="pb-tone-pills">
                                    <?php foreach ( $tones as $key => $label ) :
                                        $parts     = explode( ' — ', $label );
                                        $classes = 'pb-pill' . ( $key === 'professional' ? ' active' : '' );
                                        ?>
                                        <button type="button" class="<?php echo esc_attr( $classes ); ?>"
                                                data-value="<?php echo esc_attr( $key ); ?>">
                                            <?php echo esc_html( $parts[0] ); ?>
                                        </button>
                                    <?php endforeach; ?>
                                </div>
                                <p class="pb-option-desc" id="pb-tone-desc">
                                    <?php echo esc_html( explode( ' — ', $tones['professional'] )[1] ); ?>
                                </p>
                                <textarea id="pb-custom-style" class="pb-custom-style widefat"
                                          rows="2" placeholder="<?php esc_attr_e( 'Describe your brand voice… e.g. "Bold, no-nonsense, speaks directly to vapers who know their gear."', 'pipeline-buster' ); ?>"
                                          style="display:none"></textarea>
                                <p class="pb-custom-style-tip" style="display:none; margin-top:6px; font-size:0.82em; color:#527070;">
                                    <?php esc_html_e( 'Tip: write your brief in any language and Pipeline Buster generates the entire listing — description, How To guide, and SEO fields — in that language. Write in Spanish, get Spanish content.', 'pipeline-buster' ); ?>
                                </p>
                                <!-- Tone Reference Selector -->
                                <div id="pb-tone-ref-wrap" style="display:none">
                                    <p class="pb-tone-ref-or"><?php esc_html_e( '— or pick an existing post as your style reference —', 'pipeline-buster' ); ?></p>
                                    <div class="pb-product-search-wrap">
                                        <input type="text" id="pb-tone-ref-search" class="widefat pb-product-search-input"
                                            placeholder="<?php esc_attr_e( 'Search How To posts or product descriptions…', 'pipeline-buster' ); ?>" autocomplete="off" />
                                        <div id="pb-tone-ref-results" class="pb-product-results" style="display:none"></div>
                                    </div>
                                    <div id="pb-tone-ref-selected" class="pb-product-selected" style="display:none">
                                        <span id="pb-tone-ref-selected-name"></span>
                                        <button type="button" id="pb-tone-ref-clear" class="pb-product-clear" title="<?php esc_attr_e( 'Clear', 'pipeline-buster' ); ?>">&#215;</button>
                                    </div>
                                </div>
                                <!-- Custom tone guard warning / upgrade prompt -->
                                <div id="pb-custom-guard" class="pb-custom-guard" style="display:none">
                                    <span class="pb-guard-icon">&#9888;</span>
                                    <span id="pb-guard-msg"></span>
                                    <div class="pb-guard-actions">
                                        <button type="button" class="pb-btn-secondary pb-btn-sm" id="pb-guard-use-pro"><?php esc_html_e( 'Use Professional', 'pipeline-buster' ); ?></button>
                                        <button type="button" class="pb-btn-secondary pb-btn-sm" id="pb-guard-add-ref"><?php esc_html_e( 'Add Style Reference', 'pipeline-buster' ); ?></button>
                                    </div>
                                </div>
                            </div>

                            <!-- Output Language — top right -->
                            <div class="pb-option-group">
                                <label for="pb-output-language"><?php esc_html_e( 'Output Language', 'pipeline-buster' ); ?></label>
                                <select id="pb-output-language" class="pb-language-select">
                                    <?php foreach ( PIPEBU_Settings::languages() as $code => $label ) : ?>
                                        <option value="<?php echo esc_attr( $code ); ?>"><?php echo esc_html( $label ); ?></option>
                                    <?php endforeach; ?>
                                </select>
                                <p class="pb-option-desc" style="margin-top:6px;"><?php echo wp_kses( __( 'AI writes all fields in this language &mdash; or leave Auto and write your Custom brief in your target language. Both work.', 'pipeline-buster' ), [] ); ?></p>
                            </div>

                            <!-- Content Depth — bottom left -->
                            <div class="pb-option-group">
                                <label><?php esc_html_e( 'Content Depth', 'pipeline-buster' ); ?></label>
                                <div class="pb-pill-group" id="pb-depth-pills">
                                    <?php foreach ( $depths as $key => $label ) :
                                        $parts = explode( ' — ', $label );
                                        ?>
                                        <button type="button" class="pb-pill <?php echo $key === 'standard' ? 'active' : ''; ?>"
                                                data-value="<?php echo esc_attr( $key ); ?>">
                                            <?php echo esc_html( $parts[0] ); ?>
                                        </button>
                                    <?php endforeach; ?>
                                </div>
                                <p class="pb-option-desc" id="pb-depth-desc">
                                    <?php echo esc_html( explode( ' — ', $depths['standard'] )[1] ); ?>
                                </p>
                            </div>
                        </div>


                        <!-- How To Format Template — skeleton cards -->
                        <div class="pb-template-section">
                            <label class="pb-template-label">&#128203; <?php esc_html_e( 'How To Format Template', 'pipeline-buster' ); ?></label>
                            <div class="pb-template-cards" id="pb-template-cards">

                                <!-- AI Decides -->
                                <div class="pb-template-card active" data-value="none">
                                    <div class="pb-tcard-name"><?php esc_html_e( 'AI Decides', 'pipeline-buster' ); ?></div>
                                    <div class="pb-tcard-skeleton pb-skel-ai">
                                        <div class="pb-skel-icon">&#10022;</div>
                                        <div class="pb-skel pb-sw70"></div>
                                        <div class="pb-skel pb-sw90"></div>
                                        <div class="pb-skel pb-sw55"></div>
                                    </div>
                                    <div class="pb-tcard-desc"><?php esc_html_e( 'AI chooses the best structure', 'pipeline-buster' ); ?></div>
                                </div>

                                <!-- Step-by-Step -->
                                <div class="pb-template-card" data-value="step_by_step">
                                    <div class="pb-tcard-name"><?php esc_html_e( 'Step-by-Step', 'pipeline-buster' ); ?></div>
                                    <div class="pb-tcard-skeleton pb-skel-steps">
                                        <div class="pb-skel pb-sw80"></div>
                                        <div class="pb-skel-table-mini">
                                            <span></span><span></span>
                                            <span></span><span></span>
                                        </div>
                                        <div class="pb-skel-row"><span class="pb-skel-num-dot">1</span><span class="pb-skel pb-sw60"></span></div>
                                        <div class="pb-skel-row"><span class="pb-skel-num-dot">2</span><span class="pb-skel pb-sw50"></span></div>
                                        <div class="pb-skel-row"><span class="pb-skel-num-dot">3</span><span class="pb-skel pb-sw70"></span></div>
                                        <div class="pb-skel-row"><span class="pb-skel-bullet-dot">•</span><span class="pb-skel pb-sw55"></span></div>
                                    </div>
                                    <div class="pb-tcard-desc"><?php esc_html_e( 'Numbered steps + specs table', 'pipeline-buster' ); ?></div>
                                </div>

                                <!-- Narrative -->
                                <div class="pb-template-card" data-value="narrative">
                                    <div class="pb-tcard-name"><?php esc_html_e( 'Narrative', 'pipeline-buster' ); ?></div>
                                    <div class="pb-tcard-skeleton pb-skel-narrative">
                                        <div class="pb-skel pb-sw100"></div>
                                        <div class="pb-skel pb-sw90"></div>
                                        <div class="pb-skel pb-sw70"></div>
                                        <div class="pb-skel pb-sw100"></div>
                                        <div class="pb-skel pb-sw80"></div>
                                        <div class="pb-skel pb-sw45"></div>
                                    </div>
                                    <div class="pb-tcard-desc"><?php esc_html_e( 'Flowing prose, lifestyle tone', 'pipeline-buster' ); ?></div>
                                </div>

                                <!-- Quick Start -->
                                <div class="pb-template-card" data-value="quick_start">
                                    <div class="pb-tcard-name"><?php esc_html_e( 'Quick Start', 'pipeline-buster' ); ?></div>
                                    <div class="pb-tcard-skeleton pb-skel-quick">
                                        <div class="pb-skel pb-sw65 pb-skel-title"></div>
                                        <div class="pb-skel-row"><span class="pb-skel-bullet-dot">▸</span><span class="pb-skel pb-sw55"></span></div>
                                        <div class="pb-skel-row"><span class="pb-skel-bullet-dot">▸</span><span class="pb-skel pb-sw45"></span></div>
                                        <div class="pb-skel-row"><span class="pb-skel-num-dot">1</span><span class="pb-skel pb-sw40"></span></div>
                                        <div class="pb-skel-row"><span class="pb-skel-num-dot">2</span><span class="pb-skel pb-sw35"></span></div>
                                        <div class="pb-skel-row"><span class="pb-skel-num-dot">3</span><span class="pb-skel pb-sw50"></span></div>
                                    </div>
                                    <div class="pb-tcard-desc"><?php esc_html_e( 'Concise, scannable, fast', 'pipeline-buster' ); ?></div>
                                </div>

                            </div>
                        </div>

                        <div class="pb-generate-bar">
                            <button type="button" class="pb-btn-primary" id="pb-generate-btn">
                                &#9889; <?php esc_html_e( 'Analyze & Generate Content', 'pipeline-buster' ); ?>
                            </button>
                        </div>
                    </div>
                </div>

                <!-- Processing state -->
                <div id="pb-processing" class="pb-card pb-processing" style="display:none">
                    <div class="pb-spinner-wrap">
                        <div class="pb-spinner"></div>
                    </div>
                    <h3 id="pb-processing-msg"><?php esc_html_e( 'AI is analyzing your images…', 'pipeline-buster' ); ?></h3>
                    <p class="pb-processing-sub"><?php esc_html_e( 'This typically takes 20–40 seconds. Hang tight.', 'pipeline-buster' ); ?></p>
                    <div class="pb-processing-bar"><div class="pb-processing-fill"></div></div>
                </div>
            </div>

            <!-- PANEL 2: SIMPLE mode review -->
            <div id="pb-panel-2-simple" class="pb-panel" style="display:none">
                <div class="pb-card">
                    <h2><?php esc_html_e( 'Quick Review', 'pipeline-buster' ); ?></h2>
                    <p class="pb-hint"><?php esc_html_e( 'Confirm the essentials. Everything else was auto-filled.', 'pipeline-buster' ); ?></p>

                    <div class="pb-field">
                        <label><?php esc_html_e( 'Product Name', 'pipeline-buster' ); ?></label>
                        <input type="text" id="pb_name_s" class="widefat" />
                    </div>
                    <div class="pb-field-row">
                        <div class="pb-field">
                            <label><?php esc_html_e( 'Regular Price ($)', 'pipeline-buster' ); ?></label>
                            <input type="number" id="pb_reg_s" step="0.01" min="0" class="pb-short-field" />
                        </div>
                        <div class="pb-field">
                            <label><?php esc_html_e( 'Sale Price ($)', 'pipeline-buster' ); ?></label>
                            <input type="number" id="pb_sale_s" step="0.01" min="0" class="pb-short-field" />
                        </div>
                        <div class="pb-field">
                            <label><?php esc_html_e( 'Stock Qty', 'pipeline-buster' ); ?></label>
                            <input type="number" id="pb_stock_s" min="0" class="pb-short-field" />
                        </div>
                    </div>
                    <div class="pb-field">
                        <label><?php esc_html_e( 'Categories', 'pipeline-buster' ); ?></label>
                        <div id="pb-cat-simple" class="pb-category-picker">
                            <?php self::render_category_checkboxes(); ?>
                        </div>
                    </div>

                    <!-- Color rows (color variation mode) -->
                    <div id="pb-color-rows-simple" class="pb-color-rows-wrap" style="display:none"></div>

                    <!-- Template badge (Simple mode) -->
                    <div id="pb-template-badge" style="display:none"></div>
                    <div id="pb-ai-summary" class="pb-ai-summary">
                        <h4><?php esc_html_e( 'AI Generated', 'pipeline-buster' ); ?></h4>
                        <div id="pb-ai-summary-inner"></div>
                    </div>

                    <div class="pb-action-bar">
                        <div class="pb-action-left">
                            <button type="button" class="pb-btn-secondary" id="pb-to-expert-btn">
                                &#9998; <?php esc_html_e( 'Switch to Expert View', 'pipeline-buster' ); ?>
                            </button>
                            <button type="button" class="pb-start-over-link" id="pb-simple-startover-btn">
                                &#8592; <?php esc_html_e( 'Start Over', 'pipeline-buster' ); ?>
                            </button>
                        </div>
                        <button type="button" class="pb-btn-primary" id="pb-publish-simple-btn">
                            &#128640; <?php esc_html_e( 'Publish Product', 'pipeline-buster' ); ?>
                        </button>
                    </div>
                </div>
            </div>

            <!-- PANEL 3: EXPERT mode review (also used for Guide Mode review) -->
            <div id="pb-panel-2-expert" class="pb-panel" style="display:none">
                <div class="pb-review-grid" id="pb-review-grid">
                    <div class="pb-card pb-product-col" id="pb-product-col">
                        <h2><?php esc_html_e( 'Product Details', 'pipeline-buster' ); ?></h2>
                        <div class="pb-field">
                            <label><?php esc_html_e( 'Product Name', 'pipeline-buster' ); ?></label>
                            <input type="text" id="pb_name_e" class="widefat" />
                        </div>
                        <div class="pb-field-row">
                            <div class="pb-field">
                                <label><?php esc_html_e( 'Regular Price ($)', 'pipeline-buster' ); ?></label>
                                <input type="number" id="pb_reg_e" step="0.01" min="0" class="pb-short-field" />
                            </div>
                            <div class="pb-field">
                                <label><?php esc_html_e( 'Sale Price ($)', 'pipeline-buster' ); ?></label>
                                <input type="number" id="pb_sale_e" step="0.01" min="0" class="pb-short-field" />
                            </div>
                            <div class="pb-field">
                                <label><?php esc_html_e( 'Stock Qty', 'pipeline-buster' ); ?></label>
                                <input type="number" id="pb_stock_e" min="0" class="pb-short-field" />
                            </div>
                        </div>
                        <!-- Color rows (color variation mode) -->
                        <div id="pb-color-rows-expert" class="pb-color-rows-wrap" style="display:none"></div>

                        <div class="pb-field">
                            <label><?php esc_html_e( 'Short Description', 'pipeline-buster' ); ?></label>
                            <textarea id="pb_short_e" rows="3" class="widefat"></textarea>
                        </div>
                        <div class="pb-field">
                            <label><?php esc_html_e( 'Full Description', 'pipeline-buster' ); ?></label>
                            <textarea id="pb_desc_e" rows="12" class="widefat"></textarea>
                        </div>
                        <div class="pb-field">
                            <label><?php esc_html_e( 'Categories', 'pipeline-buster' ); ?></label>
                            <div id="pb-cat-expert" class="pb-category-picker">
                                <?php self::render_category_checkboxes( 'expert' ); ?>
                            </div>
                        </div>
                        <h3><?php esc_html_e( 'Yoast SEO', 'pipeline-buster' ); ?></h3>
                        <div class="pb-field">
                            <label><?php esc_html_e( 'Focus Keyword', 'pipeline-buster' ); ?></label>
                            <input type="text" id="pb_kw_e" class="widefat" />
                        </div>
                        <div class="pb-field">
                            <label><?php esc_html_e( 'Meta Description', 'pipeline-buster' ); ?>
                                <span id="pb-meta-count" class="pb-char-count">0/155</span>
                                <span class="pb-seo-dot" id="pb-meta-dot"></span>
                            </label>
                            <textarea id="pb_meta_e" rows="2" class="widefat" maxlength="155"></textarea>
                        </div>
                    </div>
                    <div class="pb-card pb-howto-col">
                        <h2><?php esc_html_e( 'How To Post', 'pipeline-buster' ); ?></h2>
                        <!-- Template card preview — full card (Expert) -->
                        <div id="pb-template-card-preview" style="display:none"></div>
                        <!-- Guide Mode: shows linked product info -->
                        <div id="pb-guide-product-badge" class="pb-guide-product-badge" style="display:none">
                            <span class="pb-badge-label">&#128279; <?php esc_html_e( 'Linked Product:', 'pipeline-buster' ); ?></span>
                            <span id="pb-guide-product-badge-name" class="pb-badge-name"></span>
                        </div>
                        <div class="pb-field">
                            <label><?php esc_html_e( 'Post Title', 'pipeline-buster' ); ?></label>
                            <input type="text" id="pb_howto_title_e" class="widefat" />
                        </div>
                        <div class="pb-field">
                            <label><?php esc_html_e( 'Post Content', 'pipeline-buster' ); ?></label>
                            <textarea id="pb_howto_content_e" rows="20" class="widefat"></textarea>
                        </div>
                        <div class="pb-field">
                            <label><?php esc_html_e( 'How To Meta Description', 'pipeline-buster' ); ?>
                                <span class="pb-seo-dot" id="pb-howto-meta-dot"></span>
                            </label>
                            <textarea id="pb_howto_meta_e" rows="2" class="widefat" maxlength="155"></textarea>
                        </div>
                        <div class="pb-field">
                            <label><?php esc_html_e( 'Focus Keyword', 'pipeline-buster' ); ?></label>
                            <input type="text" id="pb_howto_kw_e" class="widefat" />
                        </div>
                        <div id="pb-confidence" class="pb-notice" style="display:none">
                            <strong><?php esc_html_e( 'AI Notes:', 'pipeline-buster' ); ?></strong>
                            <span id="pb-confidence-text"></span>
                        </div>
                    </div>
                </div>
                <div class="pb-action-bar">
                    <button type="button" class="pb-btn-secondary" id="pb-back-btn">&#9998; <?php esc_html_e( 'Switch to Basic View', 'pipeline-buster' ); ?></button>
                    <button type="button" class="pb-btn-primary" id="pb-publish-expert-btn">
                        &#128640; <?php esc_html_e( 'Publish Product + How To Post', 'pipeline-buster' ); ?>
                    </button>
                </div>
            </div>

            <!-- PANEL 4: Success -->
            <div id="pb-panel-success" class="pb-panel" style="display:none">
                <div class="pb-card pb-success-card">
                    <div class="pb-success-icon">&#10003;</div>
                    <h2><?php esc_html_e( 'Done!', 'pipeline-buster' ); ?></h2>
                    <p id="pb-publish-status-msg" class="pb-success-status"></p>
                    <div id="pb-success-links" class="pb-success-links"></div>
                    <button type="button" class="pb-btn-primary" id="pb-restart-btn">
                        + <?php esc_html_e( 'Add Another Product', 'pipeline-buster' ); ?>
                    </button>
                </div>
            </div>

            <!-- PANEL: Quota exceeded upgrade wall -->
            <div id="pb-panel-quota" class="pb-panel" style="display:none">
                <div class="pb-card pb-quota-wall">
                    <div class="pb-quota-wall-icon">&#128640;</div>
                    <h2><?php esc_html_e( 'Free limit reached', 'pipeline-buster' ); ?></h2>
                    <p><?php
                    printf(
                        /* translators: %d: number of free products included */
                        esc_html__( 'You\'ve used all %d free products included with Pipeline Buster.', 'pipeline-buster' ),
                        absint( PIPEBU_Quota::FREE_LIMIT )
                    ); ?></p>
                    <p class="pb-quota-wall-sub"><?php esc_html_e( 'Upgrade to keep publishing without limits.', 'pipeline-buster' ); ?></p>
                    <a href="#" class="pb-btn-primary pb-quota-upgrade-btn" id="pb-quota-upgrade-btn" target="_blank">
                        <?php esc_html_e( 'Upgrade Now', 'pipeline-buster' ); ?> &#8594;
                    </a>
                    <div class="pb-quota-wall-later">
                        <button type="button" class="pb-quota-later-btn" id="pb-quota-later-btn">
                            <?php esc_html_e( 'Maybe later', 'pipeline-buster' ); ?>
                        </button>
                    </div>
                </div>
            </div>

        </div><!-- .pb-wrap -->

        <?php
    }

    // -------------------------------------------------------------------------
    // Helper: render category checkboxes
    // -------------------------------------------------------------------------

    private static function render_category_checkboxes( string $suffix = 'simple' ): void {
        $cats = get_terms( [ 'taxonomy' => 'product_cat', 'hide_empty' => false ] );
        if ( is_wp_error( $cats ) ) return;
        foreach ( $cats as $cat ) {
            printf(
                '<label><input type="checkbox" class="pb-cat-%s" value="%d" /> %s</label>',
                esc_attr( $suffix ),
                esc_attr( $cat->term_id ),
                esc_html( $cat->name )
            );
        }
    }

    // -------------------------------------------------------------------------
    // AJAX: Upload images
    // -------------------------------------------------------------------------

    public static function ajax_upload_images(): void {
        check_ajax_referer( 'pipebu_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_woocommerce' ) ) {
            wp_send_json_error( [ 'message' => __( 'Permission denied.', 'pipeline-buster' ) ] );
        }

        if ( empty( $_FILES['images'] ) ) {
            wp_send_json_error( [ 'message' => __( 'No files received.', 'pipeline-buster' ) ] );
        }

        require_once ABSPATH . 'wp-admin/includes/image.php';
        require_once ABSPATH . 'wp-admin/includes/file.php';
        require_once ABSPATH . 'wp-admin/includes/media.php';

        $uploaded = [];
        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- each field sanitized individually below
        $files    = $_FILES['images'];
        $count    = count( $files['name'] );

        for ( $i = 0; $i < $count; $i++ ) {
            $tmp = $files['tmp_name'][$i];
            if ( ! is_uploaded_file( $tmp ) ) {
                continue;
            }
            $file = [
                'name'     => sanitize_file_name( $files['name'][$i] ),
                'type'     => sanitize_mime_type( $files['type'][$i] ),
                'tmp_name' => $tmp,
                'error'    => absint( $files['error'][$i] ),
                'size'     => absint( $files['size'][$i] ),
            ];

            $allowed  = [ 'image/jpeg', 'image/png', 'image/gif', 'image/webp' ];
            $finfo    = finfo_open( FILEINFO_MIME_TYPE );
            $mime     = finfo_file( $finfo, $file['tmp_name'] );
            finfo_close( $finfo );
            if ( ! in_array( $mime, $allowed, true ) ) continue;

            $att_id = media_handle_sideload( $file, 0 );
            if ( is_wp_error( $att_id ) ) continue;

            $uploaded[] = [
                'id'  => $att_id,
                'url' => wp_get_attachment_image_url( $att_id, 'thumbnail' ),
            ];
        }

        if ( empty( $uploaded ) ) {
            wp_send_json_error( [ 'message' => __( 'No valid images could be uploaded.', 'pipeline-buster' ) ] );
        }

        wp_send_json_success( [ 'images' => $uploaded ] );
    }

    // -------------------------------------------------------------------------
    // AJAX: Search existing WooCommerce products (for Guide Mode selector)
    // -------------------------------------------------------------------------

    public static function ajax_search_products(): void {
        check_ajax_referer( 'pipebu_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_woocommerce' ) ) {
            wp_send_json_error( [ 'message' => __( 'Permission denied.', 'pipeline-buster' ) ] );
        }

        $q = sanitize_text_field( wp_unslash( $_POST['q'] ?? '' ) );
        if ( strlen( $q ) < 2 ) {
            wp_send_json_success( [] );
            return;
        }

        global $wpdb;

        // Tokenize — split on spaces, hyphens, underscores.
        // Each token becomes its own LIKE condition (OR logic).
        // Also include the full raw query as a token for partial phrase matches.
        $raw_tokens = preg_split( '/[\s\-_]+/', $q );
        $tokens     = array_unique( array_merge( [ $q ], $raw_tokens ) );
        $tokens     = array_filter( $tokens, fn( $t ) => strlen( trim( $t ) ) >= 2 );

        $likes = [];
        foreach ( $tokens as $token ) {
            $likes[] = $wpdb->prepare( 'p.post_title LIKE %s', '%' . $wpdb->esc_like( trim( $token ) ) . '%' );
        }

        $where = implode( ' OR ', $likes );

        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        $post_ids = $wpdb->get_col( "
            SELECT p.ID FROM {$wpdb->posts} p
            WHERE p.post_type = 'product'
              AND p.post_status = 'publish'
              AND ( {$where} )
            ORDER BY p.post_title ASC
            LIMIT 12
        " );

        $results = [];
        foreach ( $post_ids as $post_id ) {
            $results[] = [
                'id'   => (int) $post_id,
                'name' => html_entity_decode( get_the_title( (int) $post_id ), ENT_QUOTES, 'UTF-8' ),
            ];
        }

        wp_send_json_success( $results );
    }

    // -------------------------------------------------------------------------
    // AJAX: Search posts/products for tone reference
    // -------------------------------------------------------------------------

    public static function ajax_search_posts(): void {
        check_ajax_referer( 'pipebu_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_woocommerce' ) ) {
            wp_send_json_error( [ 'message' => __( 'Permission denied.', 'pipeline-buster' ) ] );
        }

        $q = sanitize_text_field( wp_unslash( $_POST['q'] ?? '' ) );
        if ( strlen( $q ) < 2 ) {
            wp_send_json_success( [] );
            return;
        }

        global $wpdb;

        $raw_tokens = preg_split( '/[\s\-_]+/', $q );
        $tokens     = array_unique( array_merge( [ $q ], $raw_tokens ) );
        $tokens     = array_filter( $tokens, fn( $t ) => strlen( trim( $t ) ) >= 2 );

        $likes = [];
        foreach ( $tokens as $token ) {
            $likes[] = $wpdb->prepare( 'p.post_title LIKE %s', '%' . $wpdb->esc_like( trim( $token ) ) . '%' );
        }

        $where = implode( ' OR ', $likes );

        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        $post_ids = $wpdb->get_col( "
            SELECT p.ID FROM {$wpdb->posts} p
            WHERE p.post_type = 'post'
              AND p.post_status = 'publish'
              AND LENGTH(p.post_content) > 5000
              AND ( {$where} )
            ORDER BY p.post_title ASC
            LIMIT 12
        " );

        $results = [];
        foreach ( $post_ids as $post_id ) {
            $results[] = [
                'id'   => (int) $post_id,
                'name' => html_entity_decode( get_the_title( (int) $post_id ), ENT_QUOTES, 'UTF-8' ),
            ];
        }

        wp_send_json_success( $results );
    }

    // -------------------------------------------------------------------------
    // AJAX: Queue async generation job
    // -------------------------------------------------------------------------

    public static function ajax_queue_job(): void {
        check_ajax_referer( 'pipebu_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_woocommerce' ) ) {
            wp_send_json_error( [ 'message' => __( 'Permission denied.', 'pipeline-buster' ) ] );
        }

        $raw_ids = isset( $_POST['attachment_ids'] ) ? sanitize_text_field( wp_unslash( $_POST['attachment_ids'] ) ) : '';
        if ( is_string( $raw_ids ) ) {
            $decoded = json_decode( $raw_ids, true );
            $ids = is_array( $decoded ) ? array_map( 'absint', $decoded ) : [];
        } else {
            $ids = array_map( 'absint', (array) $raw_ids );
        }

        if ( empty( $ids ) ) {
            wp_send_json_error( [ 'message' => __( 'No images provided.', 'pipeline-buster' ) ] );
        }

        // Quota gate — block before any AI API call is made.
        $is_guide  = ! empty( $_POST['guide_mode'] ) && $_POST['guide_mode'] === '1';
        $can       = PIPEBU_Quota::can_publish( $is_guide );
        if ( $can !== true ) {
            if ( $can === 'credits_exhausted' ) {
                PIPEBU_Quota::record_first_wall_hit();
                wp_send_json_error( [
                    'code'    => 'credits_exhausted',
                    'message' => __( 'You have used all your product credits. Purchase more to keep publishing.', 'pipeline-buster' ),
                    'offer'   => PIPEBU_Quota::get_wall_offer(),
                ] );
            } else {
                PIPEBU_Quota::record_first_wall_hit();
                wp_send_json_error( [
                    'code'    => 'quota_exceeded',
                    'message' => sprintf(
                        /* translators: %d: number of free products allowed */
                        __( 'You have used all %d free products. Upgrade Pipeline Buster to continue.', 'pipeline-buster' ),
                        absint( PIPEBU_Quota::FREE_LIMIT )
                    ),
                    'used'    => PIPEBU_Quota::get_used(),
                    'limit'   => PIPEBU_Quota::FREE_LIMIT,
                    'offer'   => PIPEBU_Quota::get_wall_offer(),
                ] );
            }
        }

        $tone_raw = sanitize_text_field( wp_unslash( $_POST['tone'] ?? 'professional' ) );

        $job_id = PIPEBU_Job::queue( $ids );

        $opts = get_option( $job_id, [] );
        $opts['depth']             = sanitize_text_field( wp_unslash( $_POST['depth']        ?? 'standard' ) );
        $opts['tone']              = $tone_raw;
        $opts['custom_style']      = sanitize_textarea_field( wp_unslash( $_POST['custom_style'] ?? '' ) );
        $opts['guide_mode']        = ! empty( $_POST['guide_mode'] ) && $_POST['guide_mode'] === '1';
        $opts['template']          = sanitize_text_field( wp_unslash( $_POST['template']       ?? 'none' ) );
        $opts['tone_reference_id'] = absint( $_POST['tone_reference_id']                        ?? 0 );
        $opts['has_colors']        = ! empty( $_POST['has_colors'] ) && $_POST['has_colors'] === '1';
        $opts['output_language']   = sanitize_text_field( wp_unslash( $_POST['output_language'] ?? '' ) );
        update_option( $job_id, $opts, false );

        wp_send_json_success( [ 'job_id' => $job_id ] );
    }

    // -------------------------------------------------------------------------
    // AJAX: Poll job status
    // -------------------------------------------------------------------------

    public static function ajax_poll_job(): void {
        check_ajax_referer( 'pipebu_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_woocommerce' ) ) {
            wp_send_json_error( [ 'message' => __( 'Permission denied.', 'pipeline-buster' ) ] );
        }

        $job_id = sanitize_text_field( wp_unslash( $_POST['job_id'] ?? '' ) );
        if ( ! $job_id ) {
            wp_send_json_error( [ 'message' => 'Missing job_id.' ] );
        }

        $poll = PIPEBU_Job::poll( $job_id );
        wp_send_json_success( $poll );
    }

    // -------------------------------------------------------------------------
    // AJAX: Publish
    // -------------------------------------------------------------------------

    public static function ajax_publish(): void {
        check_ajax_referer( 'pipebu_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_woocommerce' ) ) {
            wp_send_json_error( [ 'message' => __( 'Permission denied.', 'pipeline-buster' ) ] );
        }

        $guide_mode = ! empty( $_POST['guide_mode'] ) && $_POST['guide_mode'] === '1';

        $has_colors = ! $guide_mode && ! empty( $_POST['has_colors'] ) && $_POST['has_colors'] === '1';

        $colors = [];
        if ( $has_colors && ! empty( $_POST['colors'] ) ) {
            $raw_colors = json_decode( sanitize_text_field( wp_unslash( $_POST['colors'] ) ), true );
            if ( is_array( $raw_colors ) ) {
                foreach ( $raw_colors as $c ) {
                    $name = sanitize_text_field( $c['name'] ?? '' );
                    if ( $name ) {
                        $colors[] = [
                            'name'          => $name,
                            'price'         => sanitize_text_field( $c['price']         ?? '' ),
                            'attachment_id' => absint(              $c['attachment_id']  ?? 0 ),
                        ];
                    }
                }
            }
        }

        $data = [
            'guide_mode'             => $guide_mode,
            'has_colors'             => $has_colors && ! empty( $colors ),
            'colors'                 => $colors,
            'existing_product_id'    => absint( $_POST['existing_product_id'] ?? 0 ),
            'product_name'           => sanitize_text_field( wp_unslash( $_POST['product_name'] ?? '' ) ),
            'short_description'      => wp_kses_post( wp_unslash( $_POST['short_description'] ?? '' ) ),
            'description'            => wp_kses_post( wp_unslash( $_POST['description'] ?? '' ) ),
            'regular_price'          => sanitize_text_field( wp_unslash( $_POST['regular_price'] ?? '' ) ),
            'sale_price'             => sanitize_text_field( wp_unslash( $_POST['sale_price'] ?? '' ) ),
            'stock_quantity'         => sanitize_text_field( wp_unslash( $_POST['stock_quantity'] ?? '' ) ),
            'category_ids'           => isset( $_POST['category_ids'] )
                ? array_map( 'absint', (array) $_POST['category_ids'] ) : [],
            'yoast_focus_keyword'    => sanitize_text_field( wp_unslash( $_POST['yoast_focus_keyword'] ?? '' ) ),
            'yoast_meta_description' => sanitize_text_field( wp_unslash( $_POST['yoast_meta_description'] ?? '' ) ),
            'howto_title'            => sanitize_text_field( wp_unslash( $_POST['howto_title'] ?? '' ) ),
            'howto_content'          => wp_kses_post( wp_unslash( $_POST['howto_content'] ?? '' ) ),
            'howto_meta_description' => sanitize_text_field( wp_unslash( $_POST['howto_meta_description'] ?? '' ) ),
            'attachment_ids'         => isset( $_POST['attachment_ids'] )
                ? array_map( 'absint', (array) $_POST['attachment_ids'] ) : [],
            'hero_index'             => absint( $_POST['hero_index'] ?? 0 ),
        ];

        // Validation.
        if ( $guide_mode ) {
            if ( empty( $data['howto_title'] ) ) {
                wp_send_json_error( [ 'message' => __( 'How To title is required.', 'pipeline-buster' ) ] );
            }
        } else {
            if ( empty( $data['product_name'] ) ) {
                wp_send_json_error( [ 'message' => __( 'Product name is required.', 'pipeline-buster' ) ] );
            }
        }

        $result = PIPEBU_Publisher::publish( $data );
        if ( is_wp_error( $result ) ) {
            wp_send_json_error( [ 'message' => $result->get_error_message() ] );
        }

        // Increment quota counter — both product and Guide Mode count as 1 credit.
        // v2 doctrine: hold the line, don't build billing complexity for a hypothetical.
        PIPEBU_Quota::increment();

        $status = PIPEBU_Settings::publish_status();

        $response = [
            'howto_id'       => $result['howto_id'],
            'howto_url'      => $result['howto_id'] ? get_permalink( $result['howto_id'] ) : null,
            'howto_edit'     => $result['howto_id'] ? get_edit_post_link( $result['howto_id'] ) : null,
            'publish_status' => $status,
            'guide_mode'     => $guide_mode,
        ];

        if ( ! $guide_mode ) {
            $response['product_id']   = $result['product_id'];
            $response['product_url']  = get_permalink( $result['product_id'] );
            $response['product_edit'] = get_edit_post_link( $result['product_id'] );
        } elseif ( ! empty( $result['product_id'] ) ) {
            $response['product_id']   = $result['product_id'];
            $response['product_url']  = get_permalink( $result['product_id'] );
            $response['product_edit'] = get_edit_post_link( $result['product_id'] );
        }

        wp_send_json_success( $response );
    }

    // -------------------------------------------------------------------------
    // GSC OAuth + data handlers
    // -------------------------------------------------------------------------

    /**
     * OAuth callback — Google redirects here after the user approves access.
     * Not a JSON endpoint; redirects to Settings page with status message.
     */
    public static function ajax_gsc_callback(): void {
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_die( esc_html__( 'Permission denied.', 'pipeline-buster' ) );
        }

        $state = isset( $_GET['state'] ) ? sanitize_text_field( wp_unslash( $_GET['state'] ) ) : '';
        if ( ! wp_verify_nonce( $state, 'pipebu_gsc_state' ) ) {
            wp_die( esc_html__( 'Security check failed.', 'pipeline-buster' ) );
        }

        $code = isset( $_GET['code'] ) ? sanitize_text_field( wp_unslash( $_GET['code'] ) ) : '';

        if ( $code && PIPEBU_GSC::handle_callback( $code ) ) {
            wp_safe_redirect( admin_url( 'admin.php?page=pipeline-buster-settings&pb_gsc=connected' ) );
        } else {
            wp_safe_redirect( admin_url( 'admin.php?page=pipeline-buster-settings&pb_gsc=error' ) );
        }
        exit;
    }

    public static function ajax_gsc_disconnect(): void {
        check_ajax_referer( 'pipebu_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( 'Permission denied.' );
        }
        PIPEBU_GSC::disconnect();
        wp_send_json_success( [ 'message' => 'Disconnected.' ] );
    }

    public static function ajax_gsc_set_site(): void {
        check_ajax_referer( 'pipebu_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( 'Permission denied.' );
        }
        $url = isset( $_POST['site_url'] ) ? esc_url_raw( wp_unslash( $_POST['site_url'] ) ) : '';
        if ( ! $url ) {
            wp_send_json_error( 'No site URL provided.' );
        }
        PIPEBU_GSC::set_selected_site( $url );
        wp_send_json_success( [ 'site_url' => $url ] );
    }

    public static function ajax_gsc_take_baseline(): void {
        check_ajax_referer( 'pipebu_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( 'Permission denied.' );
        }
        $baseline = PIPEBU_GSC::take_baseline();
        if ( $baseline === false ) {
            wp_send_json_error( 'Could not retrieve data from Google Search Console. Check your connection.' );
        }
        wp_send_json_success( $baseline );
    }

    // -------------------------------------------------------------------------
    // Reports page
    // -------------------------------------------------------------------------

    public static function render_reports_page(): void {
        $is_paid     = (bool) apply_filters( 'pipebu_has_paid_license', false );
        $is_dev      = PIPEBU_Quota::is_dev_mode();
        $used        = PIPEBU_Quota::get_used();
        $limit       = PIPEBU_Quota::FREE_LIMIT;
        $unlimited   = $is_dev || $is_paid;
        $plan        = $is_dev ? 'Dev Mode' : ( $is_paid ? 'Starter+' : 'Free' );
        $sec_log     = PIPEBU_Quota::get_security_log();
        $sec_count   = count( $sec_log );
        $sec_nonce   = wp_create_nonce( 'pb_clear_sec_log' );
        $upgrade_url = 'https://checkout.freemius.com/plugin/27716/plan/45802/licenses/1/';
        ?>
        <div class="wrap pb-wrap">

            <div class="pb-page-banner-wrap">
                <img src="<?php echo esc_url( PIPEBU_PLUGIN_URL . 'assets/img/pb-banner.png' ); ?>" alt="Pipeline Buster" class="pb-page-banner" />
            </div>

            <div class="pb-reports-wrap">
                <h1 class="pb-reports-title"><?php esc_html_e( 'Reports', 'pipeline-buster' ); ?></h1>

                <!-- ── Usage ── -->
                <div class="pb-reports-section">
                    <h2 class="pb-reports-heading"><?php esc_html_e( 'Usage', 'pipeline-buster' ); ?></h2>
                    <div class="pb-reports-cards">

                        <div class="pb-rcard">
                            <div class="pb-rcard-label"><?php esc_html_e( 'Plan', 'pipeline-buster' ); ?></div>
                            <div class="pb-rcard-value"><?php echo esc_html( $plan ); ?></div>
                            <?php if ( ! $unlimited ) : ?>
                                <a href="<?php echo esc_url( $upgrade_url ); ?>" class="pb-rcard-action" target="_blank" rel="noopener"><?php esc_html_e( 'Upgrade →', 'pipeline-buster' ); ?></a>
                            <?php endif; ?>
                        </div>

                        <div class="pb-rcard">
                            <div class="pb-rcard-label"><?php esc_html_e( 'Products Published', 'pipeline-buster' ); ?></div>
                            <div class="pb-rcard-value">
                                <?php if ( $unlimited ) : ?>
                                    <?php echo esc_html( $used ); ?> <span class="pb-rcard-sub"><?php esc_html_e( '/ unlimited', 'pipeline-buster' ); ?></span>
                                <?php else : ?>
                                    <?php echo esc_html( $used ); ?> <span class="pb-rcard-sub">/ <?php echo esc_html( $limit ); ?></span>
                                <?php endif; ?>
                            </div>
                            <?php if ( ! $unlimited ) : ?>
                                <div class="pb-rcard-bar-wrap">
                                    <div class="pb-rcard-bar" style="width:<?php echo esc_attr( min( 100, round( $used / $limit * 100 ) ) ); ?>%"></div>
                                </div>
                            <?php endif; ?>
                        </div>

                        <div class="pb-rcard">
                            <div class="pb-rcard-label"><?php esc_html_e( 'Quota Status', 'pipeline-buster' ); ?></div>
                            <?php if ( $unlimited ) : ?>
                                <div class="pb-rcard-value pb-rcard-ok"><?php esc_html_e( 'Unlimited', 'pipeline-buster' ); ?></div>
                            <?php elseif ( $used >= $limit ) : ?>
                                <div class="pb-rcard-value pb-rcard-warn"><?php esc_html_e( 'Ceiling reached', 'pipeline-buster' ); ?></div>
                            <?php else : ?>
                                <div class="pb-rcard-value pb-rcard-ok">
                                    <?php echo esc_html( $limit - $used ); ?> <?php esc_html_e( 'remaining', 'pipeline-buster' ); ?>
                                </div>
                            <?php endif; ?>
                        </div>

                    </div>
                </div>

                <!-- ── Security ── -->
                <div class="pb-reports-section">
                    <h2 class="pb-reports-heading">
                        <?php esc_html_e( 'Security', 'pipeline-buster' ); ?>
                        <?php if ( $sec_count > 0 ) : ?>
                            <span class="pb-sec-badge"><?php echo esc_html( $sec_count ); ?></span>
                        <?php endif; ?>
                    </h2>

                    <?php if ( $sec_count === 0 ) : ?>
                        <div class="pb-sec-clean">
                            <span class="pb-sec-clean-icon">&#10003;</span>
                            <?php esc_html_e( 'No tamper attempts detected.', 'pipeline-buster' ); ?>
                        </div>
                    <?php else : ?>
                        <p class="pb-sec-summary">
                            <?php
                            printf(
                                /* translators: %d: number of tamper attempts detected */
                                esc_html( _n( '%d tamper attempt detected on this install.', '%d tamper attempts detected on this install.', $sec_count, 'pipeline-buster' ) ),
                                absint( $sec_count )
                            ); ?>
                        </p>
                        <table class="pb-sec-table widefat striped">
                            <thead>
                                <tr>
                                    <th><?php esc_html_e( 'Date / Time', 'pipeline-buster' ); ?></th>
                                    <th><?php esc_html_e( 'Event Code', 'pipeline-buster' ); ?></th>
                                    <th><?php esc_html_e( 'Description', 'pipeline-buster' ); ?></th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ( $sec_log as $event ) : ?>
                                    <tr>
                                        <td class="pb-sec-time"><?php echo esc_html( $event['time'] ?? '—' ); ?></td>
                                        <td><code class="pb-sec-code"><?php echo esc_html( $event['code'] ?? '—' ); ?></code></td>
                                        <td><?php echo esc_html( $event['label'] ?? '—' ); ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                        <div class="pb-sec-actions">
                            <button type="button" class="button pb-sec-clear-btn"
                                    data-nonce="<?php echo esc_attr( $sec_nonce ); ?>">
                                <?php esc_html_e( 'Clear Security Log', 'pipeline-buster' ); ?>
                            </button>
                        </div>
                    <?php endif; ?>
                </div>

                <p class="pb-reports-footer">
                    <?php echo wp_kses(
                        /* translators: %s: plugin version number */
                        sprintf( __( 'Pipeline Buster v%s &mdash; internal metrics are private and not shared with third parties.', 'pipeline-buster' ), PIPEBU_VERSION ),
                        []
                    ); ?>
                </p>

            </div><!-- .pb-reports-wrap -->
        </div>
        <?php
    }

    public static function ajax_clear_sec_log(): void {
        check_ajax_referer( 'pb_clear_sec_log', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error();
        }
        PIPEBU_Quota::clear_security_log();
        wp_send_json_success();
    }

    // -------------------------------------------------------------------------
    // AJAX: Report process failure (Cases 2, 3, 4 — JS-detected)
    // -------------------------------------------------------------------------

    public static function ajax_report_failure(): void {
        check_ajax_referer( 'pipebu_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_woocommerce' ) ) {
            wp_send_json_error();
        }
        $allowed = [ 'cron_miss', 'process_killed', 'job_not_found' ];
        $type    = sanitize_text_field( wp_unslash( $_POST['failure_type'] ?? '' ) );
        if ( in_array( $type, $allowed, true ) ) {
            PIPEBU_Quota::report_failure( $type );
        }
        wp_send_json_success();
    }

    // -------------------------------------------------------------------------
    // Help & Docs page
    // -------------------------------------------------------------------------

    public static function render_help_page(): void {
        $upgrade_url = 'https://checkout.freemius.com/plugin/27716/plan/45802/licenses/1/';
        ?>
        <div class="wrap pb-wrap">

            <div class="pb-page-banner-wrap">
                <img src="<?php echo esc_url( PIPEBU_PLUGIN_URL . 'assets/img/pb-banner.png' ); ?>" alt="Pipeline Buster" class="pb-page-banner" />
            </div>

            <div class="pb-help-wrap">

                <h1 class="pb-help-title"><?php esc_html_e( 'Help &amp; Documentation', 'pipeline-buster' ); ?></h1>
                <p class="pb-help-intro"><?php esc_html_e( 'Everything you need to get the most out of Pipeline Buster.', 'pipeline-buster' ); ?></p>

                <!-- Getting Started -->
                <details class="pb-help-section" open>
                    <summary class="pb-help-summary"><?php esc_html_e( 'Getting Started', 'pipeline-buster' ); ?></summary>
                    <div class="pb-help-body">
                        <ol class="pb-help-steps">
                            <li><?php echo wp_kses( __( 'Go to <strong>Pipeline Buster → Settings</strong> and paste your API key.', 'pipeline-buster' ), [ 'strong' => [] ] ); ?></li>
                            <li><?php esc_html_e( 'Choose your AI provider (Claude recommended) and model.', 'pipeline-buster' ); ?></li>
                            <li><?php esc_html_e( 'Return to New Product, upload your images, choose depth and tone, and click Generate.', 'pipeline-buster' ); ?></li>
                            <li><?php esc_html_e( 'Review the AI output, adjust any fields, then click Publish.', 'pipeline-buster' ); ?></li>
                        </ol>
                        <p class="pb-help-note"><?php echo wp_kses( __( '<strong>Tip:</strong> Set Publish Status to <em>Draft</em> in Settings while you\'re getting familiar — products won\'t go live until you manually publish them.', 'pipeline-buster' ), [ 'strong' => [], 'em' => [] ] ); ?></p>
                    </div>
                </details>

                <!-- Image Guidelines -->
                <details class="pb-help-section">
                    <summary class="pb-help-summary"><?php esc_html_e( 'Image Guidelines', 'pipeline-buster' ); ?></summary>
                    <div class="pb-help-body">
                        <table class="pb-help-table">
                            <thead><tr><th><?php esc_html_e( 'Role', 'pipeline-buster' ); ?></th><th><?php esc_html_e( 'Position', 'pipeline-buster' ); ?></th><th><?php esc_html_e( 'What to use', 'pipeline-buster' ); ?></th></tr></thead>
                            <tbody>
                                <tr><td><span class="pb-help-dot" style="background:#0d4740"></span><?php esc_html_e( 'Hero', 'pipeline-buster' ); ?></td><td><?php esc_html_e( 'First image', 'pipeline-buster' ); ?></td><td><?php esc_html_e( 'Main product photo — becomes the WooCommerce featured image', 'pipeline-buster' ); ?></td></tr>
                                <tr><td><span class="pb-help-dot" style="background:#00b4a0"></span><?php esc_html_e( 'How To', 'pipeline-buster' ); ?></td><td><?php esc_html_e( 'Last image', 'pipeline-buster' ); ?></td><td><?php esc_html_e( 'Flyer or lifestyle shot — becomes the How To post featured image', 'pipeline-buster' ); ?></td></tr>
                                <tr><td><span class="pb-help-dot" style="background:#f0c429"></span><?php esc_html_e( 'Manual', 'pipeline-buster' ); ?></td><td><?php esc_html_e( 'Any middle image', 'pipeline-buster' ); ?></td><td><?php esc_html_e( 'Click any middle image to tag it as a manual page — AI reads it for specs and instructions', 'pipeline-buster' ); ?></td></tr>
                            </tbody>
                        </table>
                        <p class="pb-help-note">
                            <?php echo wp_kses( __( '<strong>Limits:</strong> 10 images maximum, 20 MB total.', 'pipeline-buster' ), [ 'strong' => [] ] ); ?>
                        </p>
                        <p class="pb-help-note">
                            <?php echo wp_kses( __( '<strong>Image ordering tip:</strong> Browsers upload files in alphabetical or OS order — you can\'t choose the sequence before upload. After your images land in the grid, swap the last image if needed to place your intended How To featured image in the final slot. Roles update automatically.', 'pipeline-buster' ), [ 'strong' => [] ] ); ?>
                        </p>
                    </div>
                </details>

                <!-- Color Variations -->
                <details class="pb-help-section">
                    <summary class="pb-help-summary"><?php esc_html_e( 'Color Variations', 'pipeline-buster' ); ?></summary>
                    <div class="pb-help-body">
                        <p><?php esc_html_e( 'Check "This product comes in multiple colors" before uploading to publish a WooCommerce variable product with one variation per color.', 'pipeline-buster' ); ?></p>
                        <ul class="pb-help-list">
                            <li><?php esc_html_e( 'Upload one photo per color variant', 'pipeline-buster' ); ?></li>
                            <li><?php esc_html_e( 'AI reads each image and assigns a clean, marketable color name (e.g. Midnight Black, Pearl White)', 'pipeline-buster' ); ?></li>
                            <li><?php esc_html_e( 'Each color becomes a separate WooCommerce variation with its own image and price', 'pipeline-buster' ); ?></li>
                        </ul>
                        <p class="pb-help-note"><?php echo wp_kses( __( '<strong>Review step:</strong> After generation, you\'ll see a row for each color — thumbnail, editable name, and price. Adjust before publishing.', 'pipeline-buster' ), [ 'strong' => [] ] ); ?></p>
                        <p class="pb-help-note"><?php echo wp_kses( __( '<strong>Image tip:</strong> Upload images in the same order you want the variations listed. One image per color — no duplicates.', 'pipeline-buster' ), [ 'strong' => [] ] ); ?></p>
                    </div>
                </details>

                <!-- Content Depth -->
                <details class="pb-help-section">
                    <summary class="pb-help-summary"><?php esc_html_e( 'Content Depth', 'pipeline-buster' ); ?></summary>
                    <div class="pb-help-body">
                        <table class="pb-help-table">
                            <thead><tr><th><?php esc_html_e( 'Option', 'pipeline-buster' ); ?></th><th><?php esc_html_e( 'Output', 'pipeline-buster' ); ?></th><th><?php esc_html_e( 'Best for', 'pipeline-buster' ); ?></th></tr></thead>
                            <tbody>
                                <tr><td><?php esc_html_e( 'Minimal', 'pipeline-buster' ); ?></td><td><?php esc_html_e( 'Quick specs + 3–4 bullets', 'pipeline-buster' ); ?></td><td><?php esc_html_e( 'Simple accessories, fast turnaround', 'pipeline-buster' ); ?></td></tr>
                                <tr><td><?php esc_html_e( 'Standard', 'pipeline-buster' ); ?></td><td><?php esc_html_e( 'Full description + key features', 'pipeline-buster' ); ?></td><td><?php esc_html_e( 'Most products — the default sweet spot', 'pipeline-buster' ); ?></td></tr>
                                <tr><td><?php esc_html_e( 'Rich', 'pipeline-buster' ); ?></td><td><?php esc_html_e( 'Long-form, comparisons, use cases', 'pipeline-buster' ); ?></td><td><?php esc_html_e( 'Hero products, high-margin items, SEO targets', 'pipeline-buster' ); ?></td></tr>
                            </tbody>
                        </table>
                    </div>
                </details>

                <!-- Tone & Style -->
                <details class="pb-help-section">
                    <summary class="pb-help-summary"><?php esc_html_e( 'Tone &amp; Style', 'pipeline-buster' ); ?></summary>
                    <div class="pb-help-body">
                        <table class="pb-help-table">
                            <thead><tr><th><?php esc_html_e( 'Tone', 'pipeline-buster' ); ?></th><th><?php esc_html_e( 'Voice', 'pipeline-buster' ); ?></th><th><?php esc_html_e( 'Tier', 'pipeline-buster' ); ?></th></tr></thead>
                            <tbody>
                                <tr><td><?php esc_html_e( 'Professional', 'pipeline-buster' ); ?></td><td><?php esc_html_e( 'Clear, credible, store-ready', 'pipeline-buster' ); ?></td><td><?php esc_html_e( 'Free', 'pipeline-buster' ); ?></td></tr>
                                <tr><td><?php esc_html_e( 'Friendly', 'pipeline-buster' ); ?></td><td><?php esc_html_e( 'Approachable, conversational', 'pipeline-buster' ); ?></td><td><?php esc_html_e( 'Free', 'pipeline-buster' ); ?></td></tr>
                                <tr><td><?php esc_html_e( 'Technical', 'pipeline-buster' ); ?></td><td><?php esc_html_e( 'Spec-forward, enthusiast-grade', 'pipeline-buster' ); ?></td><td><?php esc_html_e( 'Free', 'pipeline-buster' ); ?></td></tr>
                                <tr><td><?php esc_html_e( 'Playful', 'pipeline-buster' ); ?></td><td><?php esc_html_e( 'Energetic, fun, lifestyle brand', 'pipeline-buster' ); ?></td><td><?php esc_html_e( 'Free', 'pipeline-buster' ); ?></td></tr>
                                <tr><td><?php esc_html_e( 'Philosophical', 'pipeline-buster' ); ?></td><td><?php esc_html_e( 'Reflective, elevated, editorial', 'pipeline-buster' ); ?></td><td><?php esc_html_e( 'Free', 'pipeline-buster' ); ?></td></tr>
                                <tr><td><?php esc_html_e( 'Custom', 'pipeline-buster' ); ?></td><td><?php esc_html_e( 'Your own brand voice brief', 'pipeline-buster' ); ?></td><td><?php esc_html_e( 'All', 'pipeline-buster' ); ?></td></tr>
                            </tbody>
                        </table>
                        <p class="pb-help-note"><?php echo wp_kses( __( '<strong>Style Reference:</strong> Instead of writing a brief, pick an existing How To post or product description and PB will match its voice automatically.', 'pipeline-buster' ), [ 'strong' => [] ] ); ?></p>
                    </div>
                </details>

                <!-- Output Language -->
                <details class="pb-help-section">
                    <summary class="pb-help-summary"><?php esc_html_e( 'Output Language', 'pipeline-buster' ); ?></summary>
                    <div class="pb-help-body">
                        <p class="pb-help-note"><?php echo wp_kses( __( 'Pipeline Buster can generate the entire listing — product description, How To guide, and all SEO fields — in any language. Two routes get you there:', 'pipeline-buster' ), [] ); ?></p>
                        <table class="pb-help-table">
                            <thead><tr><th><?php esc_html_e( 'Route', 'pipeline-buster' ); ?></th><th><?php esc_html_e( 'How', 'pipeline-buster' ); ?></th><th><?php esc_html_e( 'Best for', 'pipeline-buster' ); ?></th></tr></thead>
                            <tbody>
                                <tr>
                                    <td><?php esc_html_e( 'Dropdown', 'pipeline-buster' ); ?></td>
                                    <td><?php esc_html_e( 'Select a language from the Output Language menu in Customize', 'pipeline-buster' ); ?></td>
                                    <td><?php esc_html_e( 'Quick, one-click — use any tone', 'pipeline-buster' ); ?></td>
                                </tr>
                                <tr>
                                    <td><?php esc_html_e( 'Custom tone', 'pipeline-buster' ); ?></td>
                                    <td><?php esc_html_e( 'Select Custom tone and write your brand voice brief in your target language', 'pipeline-buster' ); ?></td>
                                    <td><?php esc_html_e( 'Language + specific voice in one instruction', 'pipeline-buster' ); ?></td>
                                </tr>
                            </tbody>
                        </table>
                        <p class="pb-help-note"><?php echo wp_kses( __( '<strong>Supported languages:</strong> English, Spanish, Portuguese, French, German, Italian, Japanese, Chinese (Simplified), Korean, Arabic. Leave Output Language on Auto and the AI will write in English by default (or follow the language of your Custom tone brief).', 'pipeline-buster' ), [ 'strong' => [] ] ); ?></p>
                        <p class="pb-help-note"><?php echo wp_kses( __( '<strong>Combining both:</strong> You can use the dropdown for language <em>and</em> a Custom tone brief — the brief sets the voice, the dropdown locks the language. The two settings work independently. If your brief is written in a different language than the dropdown selection, that\'s fine — the dropdown language always wins. The brief is read for style only.', 'pipeline-buster' ), [ 'strong' => [], 'em' => [] ] ); ?></p>
                    </div>
                </details>

                <!-- How To Templates -->
                <details class="pb-help-section">
                    <summary class="pb-help-summary"><?php esc_html_e( 'How To Templates', 'pipeline-buster' ); ?></summary>
                    <div class="pb-help-body">
                        <table class="pb-help-table">
                            <thead><tr><th><?php esc_html_e( 'Template', 'pipeline-buster' ); ?></th><th><?php esc_html_e( 'Structure', 'pipeline-buster' ); ?></th></tr></thead>
                            <tbody>
                                <tr><td><?php esc_html_e( 'AI Decides', 'pipeline-buster' ); ?></td><td><?php esc_html_e( 'Claude selects the best structure for the product — recommended for most cases', 'pipeline-buster' ); ?></td></tr>
                                <tr><td><?php esc_html_e( 'Step-by-Step', 'pipeline-buster' ); ?></td><td><?php esc_html_e( 'Numbered steps with a specs table — ideal for hardware and devices', 'pipeline-buster' ); ?></td></tr>
                                <tr><td><?php esc_html_e( 'Narrative', 'pipeline-buster' ); ?></td><td><?php esc_html_e( 'Flowing prose with integrated specs — good for lifestyle and consumable products', 'pipeline-buster' ); ?></td></tr>
                                <tr><td><?php esc_html_e( 'Quick Start', 'pipeline-buster' ); ?></td><td><?php esc_html_e( 'Fast-read summary up top with full reference below — works for any product', 'pipeline-buster' ); ?></td></tr>
                            </tbody>
                        </table>
                    </div>
                </details>

                <!-- Guide Mode -->
                <details class="pb-help-section">
                    <summary class="pb-help-summary"><?php esc_html_e( 'Guide Mode', 'pipeline-buster' ); ?></summary>
                    <div class="pb-help-body">
                        <p><?php esc_html_e( 'Guide Mode skips product creation entirely and generates a standalone How To post from your images.', 'pipeline-buster' ); ?></p>
                        <p><?php esc_html_e( 'Use it when a product already exists in your store and you only need the educational content — manual pages, user guides, setup instructions.', 'pipeline-buster' ); ?></p>
                        <ul class="pb-help-list">
                            <li><?php esc_html_e( 'Upload manual pages or reference images', 'pipeline-buster' ); ?></li>
                            <li><?php esc_html_e( 'Optionally link to an existing WooCommerce product', 'pipeline-buster' ); ?></li>
                            <li><?php esc_html_e( 'PB generates the How To post and injects a link into the product\'s short description automatically', 'pipeline-buster' ); ?></li>
                        </ul>
                        <p class="pb-help-note"><?php esc_html_e( 'Guide Mode uses 1 credit per run, same as a full product listing.', 'pipeline-buster' ); ?></p>
                    </div>
                </details>

                <!-- Template Variables -->
                <details class="pb-help-section">
                    <summary class="pb-help-summary"><?php esc_html_e( 'Template Variables', 'pipeline-buster' ); ?></summary>
                    <div class="pb-help-body">
                        <p><?php esc_html_e( 'Use these placeholders in Settings → Short Description Template. PB replaces them at publish time.', 'pipeline-buster' ); ?></p>
                        <table class="pb-help-table">
                            <thead><tr><th><?php esc_html_e( 'Variable', 'pipeline-buster' ); ?></th><th><?php esc_html_e( 'Replaced with', 'pipeline-buster' ); ?></th></tr></thead>
                            <tbody>
                                <tr><td><code>[HOWTO_LINK]</code></td><td><?php esc_html_e( 'URL of the generated How To post', 'pipeline-buster' ); ?></td></tr>
                                <tr><td><code>[PARTS_LINK]</code></td><td><?php esc_html_e( 'Your store homepage URL', 'pipeline-buster' ); ?></td></tr>
                                <tr><td><code>[PRODUCT_LINK]</code></td><td><?php esc_html_e( 'URL of the published product', 'pipeline-buster' ); ?></td></tr>
                            </tbody>
                        </table>
                    </div>
                </details>

                <!-- Troubleshooting -->
                <details class="pb-help-section">
                    <summary class="pb-help-summary"><?php esc_html_e( 'Troubleshooting', 'pipeline-buster' ); ?></summary>
                    <div class="pb-help-body">
                        <table class="pb-help-table">
                            <thead><tr><th><?php esc_html_e( 'Error', 'pipeline-buster' ); ?></th><th><?php esc_html_e( 'Fix', 'pipeline-buster' ); ?></th></tr></thead>
                            <tbody>
                                <tr>
                                    <td><?php esc_html_e( 'cURL error 28 / Operation timed out', 'pipeline-buster' ); ?></td>
                                    <td><?php esc_html_e( 'AI is processing a large image set. Try fewer images (under 6) or reduce file sizes. PB allows up to 300 seconds — if it still times out, your host may have a shorter PHP limit.', 'pipeline-buster' ); ?></td>
                                </tr>
                                <tr>
                                    <td><?php esc_html_e( 'No API key configured', 'pipeline-buster' ); ?></td>
                                    <td><?php /* translators: %s: URL to Settings page */ echo wp_kses( sprintf( __( 'Go to <a href="%s">Pipeline Buster → Settings</a> and enter your API key.', 'pipeline-buster' ), esc_url( admin_url( 'admin.php?page=pipeline-buster-settings' ) ) ), [ 'a' => [ 'href' => [] ] ] ); ?></td>
                                </tr>
                                <tr>
                                    <td><?php esc_html_e( 'Quota exceeded', 'pipeline-buster' ); ?></td>
                                    <td><?php /* translators: %s: URL to upgrade page */ echo wp_kses( sprintf( __( 'You\'ve used all 5 free products. <a href="%s" target="_blank" rel="noopener">Upgrade to Starter+</a> to continue.', 'pipeline-buster' ), esc_url( $upgrade_url ) ), [ 'a' => [ 'href' => [], 'target' => [], 'rel' => [] ] ] ); ?></td>
                                </tr>
                                <tr>
                                    <td><?php esc_html_e( 'Generated content looks truncated', 'pipeline-buster' ); ?></td>
                                    <td><?php esc_html_e( 'Switch to Rich depth — the AI may need more token headroom for complex products.', 'pipeline-buster' ); ?></td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </details>

                <p class="pb-help-footer">
                    <?php echo wp_kses(
                        sprintf(
                            /* translators: %s: plugin version number */
                            __( 'Pipeline Buster v%s by <a href="https://zoa.captelek.net" target="_blank" rel="noopener">ZOA</a> &mdash; <a href="https://pipelinebuster.com" target="_blank" rel="noopener">pipelinebuster.com</a>', 'pipeline-buster' ),
                            PIPEBU_VERSION
                        ),
                        [ 'a' => [ 'href' => [], 'target' => [], 'rel' => [] ] ]
                    ); ?>
                </p>

            </div><!-- .pb-help-wrap -->
        </div><!-- .wrap -->
        <?php
    }

    // -------------------------------------------------------------------------
    // WC product list — "PB" badge column
    // -------------------------------------------------------------------------

    public static function add_pb_column( array $columns ): array {
        $new = [];
        foreach ( $columns as $key => $label ) {
            $new[ $key ] = $label;
            if ( $key === 'name' ) {
                $new['pipebu_generated'] = '<span title="' . esc_attr__( 'Pipeline Buster', 'pipeline-buster' ) . '">PB</span>';
            }
        }
        return $new;
    }

    public static function render_pb_column( string $column, int $post_id ): void {
        if ( $column !== 'pipebu_generated' ) return;
        if ( get_post_meta( $post_id, 'pipebu_generated', true ) ) {
            echo '<span class="pb-wc-badge" title="' . esc_attr__( 'Created with Pipeline Buster', 'pipeline-buster' ) . '">PB</span>';
        }
    }

}
