<?php
/**
 * Settings Page Template
 *
 * @var array $settings Current plugin settings
 * @var array $encryption_status Encryption key storage status
 */

$models = Claude_AI_Copywriter_Settings_Page::get_available_models();
$user_roles = Claude_AI_Copywriter_Settings_Page::get_user_roles();
$research_providers = Claude_AI_Copywriter_Research_Engine::get_providers();
?>

<div class="wrap claude-ai-settings claude-ai-wrap">
    <?php
    $kc_page_title = __( 'Settings', 'claude-ai-copywriter' );
    $kc_page_desc  = __( 'Configure your API connection, brand voice, personas, and integrations.', 'claude-ai-copywriter' );
    include CLAUDE_AI_COPYWRITER_PATH . 'admin/partials/kc-page-header.php';
    ?>

    <?php settings_errors( 'claude_ai_settings' ); ?>

    <div class="claude-settings-container">
        <!-- Tab Navigation -->
        <h2 class="nav-tab-wrapper">
            <a href="#general" class="nav-tab nav-tab-active"><?php _e( 'General', 'claude-ai-copywriter' ); ?></a>

            <a href="#api-key" class="nav-tab"><?php _e( 'API Keys & Integrations', 'claude-ai-copywriter' ); ?></a>
            <a href="#research" class="nav-tab"><?php _e( 'Research', 'claude-ai-copywriter' ); ?></a>
            <a href="#permissions" class="nav-tab"><?php _e( 'Permissions', 'claude-ai-copywriter' ); ?></a>
            <a href="#security" class="nav-tab"><?php _e( 'Security', 'claude-ai-copywriter' ); ?></a>
            <a href="#license" class="nav-tab"><?php _e( '🔑 License', 'claude-ai-copywriter' ); ?></a>
            <?php if ( ! Claude_AI_Copywriter_License_Manager::is_premium() ) : ?>
            <a href="#upgrade" class="nav-tab" style="color:#7c3aed; font-weight:600;"><?php _e( '⬆️ Upgrade', 'claude-ai-copywriter' ); ?></a>
            <?php else : ?>
            <a href="#upgrade" class="nav-tab"><?php _e( '⬆️ Plans', 'claude-ai-copywriter' ); ?></a>
            <?php endif; ?>
            <a href="#manual" class="nav-tab"><?php _e( '📖 Manual', 'claude-ai-copywriter' ); ?></a>
            <a href="#debug" class="nav-tab"><?php _e( 'Debug Log', 'claude-ai-copywriter' ); ?></a>
        </h2>

        <form method="post" action="" id="claude-settings-form">
            <?php wp_nonce_field( 'claude_ai_settings_save' ); ?>

            <!-- General Settings Tab -->
            <div id="general" class="tab-content active">
                <h2><?php _e( 'General Settings', 'claude-ai-copywriter' ); ?></h2>

                <table class="form-table">
                    <tr>
                        <th scope="row">
                            <label for="model"><?php _e( 'AI Model', 'claude-ai-copywriter' ); ?></label>
                        </th>
                        <td>
                            <select name="model" id="model" class="regular-text">
                                <?php foreach ( $models as $value => $label ) : ?>
                                    <option value="<?php echo esc_attr( $value ); ?>" <?php selected( $settings['model'] ?? 'claude-sonnet-4-6', $value ); ?>>
                                        <?php echo esc_html( $label ); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <p class="description">
                                <?php _e( 'Sonnet offers the best balance of capability and speed. Opus is most capable but slower. Haiku is fastest but less capable.', 'claude-ai-copywriter' ); ?>
                            </p>
                        </td>
                    </tr>

                    <tr>
                        <th scope="row">
                            <label for="max_tokens"><?php _e( 'Max Tokens', 'claude-ai-copywriter' ); ?></label>
                        </th>
                        <td>
                            <input type="number" name="max_tokens" id="max_tokens" value="<?php echo esc_attr( $settings['max_tokens'] ?? 4096 ); ?>" min="256" max="8192" step="256" class="small-text">
                            <p class="description">
                                <?php _e( 'Maximum length of generated content (256-8192). Higher values allow longer output but cost more.', 'claude-ai-copywriter' ); ?>
                            </p>
                        </td>
                    </tr>

                    <tr>
                        <th scope="row">
                            <label for="cache_duration"><?php _e( 'Cache Duration', 'claude-ai-copywriter' ); ?></label>
                        </th>
                        <td>
                            <input type="number" name="cache_duration" id="cache_duration" value="<?php echo esc_attr( $settings['cache_duration'] ?? 24 ); ?>" min="1" max="168" class="small-text">
                            <span><?php _e( 'hours', 'claude-ai-copywriter' ); ?></span>
                            <p class="description">
                                <?php _e( 'How long to cache content analysis results (1-168 hours).', 'claude-ai-copywriter' ); ?>
                            </p>
                        </td>
                    </tr>

                    <tr>
                        <th scope="row">
                            <label for="enable_research"><?php _e( 'Research Engine', 'claude-ai-copywriter' ); ?></label>
                        </th>
                        <td>
                            <label>
                                <input type="checkbox" name="enable_research" id="enable_research" value="1" <?php checked( $settings['enable_research'] ?? true, 1 ); ?>>
                                <?php _e( 'Enable web research integration', 'claude-ai-copywriter' ); ?>
                            </label>
                            <p class="description">
                                <?php _e( 'Allow web research when generating content.', 'claude-ai-copywriter' ); ?>
                            </p>
                        </td>
                    </tr>

                    <tr>
                        <th scope="row">
                            <label for="aio_geo_default"><?php _e( 'AI Search Optimization', 'claude-ai-copywriter' ); ?></label>
                        </th>
                        <td>
                            <label>
                                <input type="checkbox" name="aio_geo_default" id="aio_geo_default" value="1" <?php checked( $settings['aio_geo_default'] ?? true, 1 ); ?>>
                                <?php _e( 'Enable AIO/GEO optimization by default in Copywriting Studio', 'claude-ai-copywriter' ); ?>
                            </label>
                            <p class="description">
                                <?php _e( 'When enabled, all generated content is automatically optimized for AI search engines (Google AI Overviews, ChatGPT, Perplexity) with E-E-A-T signals, structured data schema markup, FAQ sections, and entity optimization. Recommended ON for the AI era. Users can toggle per-generation in Studio.', 'claude-ai-copywriter' ); ?>
                            </p>
                        </td>
                    </tr>

                    <tr>
                        <th scope="row">
                            <label for="auto_inject_schema"><?php _e( 'Schema Auto-Inject', 'claude-ai-copywriter' ); ?></label>
                        </th>
                        <td>
                            <label>
                                <input type="checkbox" name="auto_inject_schema" id="auto_inject_schema" value="1" <?php checked( $settings['auto_inject_schema'] ?? false, 1 ); ?>>
                                <?php _e( 'Auto-inject JSON-LD schema into <code>&lt;head&gt;</code> for posts that have saved schema markup', 'claude-ai-copywriter' ); ?>
                            </label>
                            <p class="description">
                                <?php _e( 'When enabled, any post with a KineticCopy-generated schema (saved via "Save as Draft Post" with content type "Schema Markup") will have its JSON-LD automatically output in <code>wp_head</code>. Disable if your SEO plugin handles schema separately.', 'claude-ai-copywriter' ); ?>
                            </p>
                        </td>
                    </tr>

                    <tr>
                        <th scope="row">
                            <label for="default_tone_template_id"><?php _e( 'Default Tone Template', 'claude-ai-copywriter' ); ?></label>
                        </th>
                        <td>
                            <?php $all_templates = Claude_AI_Copywriter_Tone_Manager::get_user_templates( get_current_user_id() ); ?>
                            <select name="default_tone_template_id" id="default_tone_template_id" class="regular-text">
                                <option value="0"><?php _e( ' -  None (raw AI voice)  - ', 'claude-ai-copywriter' ); ?></option>
                                <?php foreach ( $all_templates as $tmpl ) : ?>
                                    <option value="<?php echo esc_attr( $tmpl->id ); ?>" <?php selected( (int)( $settings['default_tone_template_id'] ?? 0 ), (int) $tmpl->id ); ?>>
                                        <?php echo esc_html( $tmpl->template_name ); ?>
                                        <?php if ( $tmpl->is_global ) : ?><em style="color:#999;"> (global)</em><?php endif; ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <p class="description">
                                <?php _e( 'Auto-applied in Copywriting Studio when no tone is explicitly chosen. Site Intelligence will suggest the best match after scanning your site. Set to "None" for default AI voice.', 'claude-ai-copywriter' ); ?>
                            </p>
                        </td>
                    </tr>

                    <tr>
                        <th scope="row">
                            <?php _e( 'Supported Post Types', 'claude-ai-copywriter' ); ?>
                        </th>
                        <td>
                            <?php
                            $all_public     = get_post_types( array( 'public' => true ), 'objects' );
                            $saved_types    = $settings['supported_post_types'] ?? array();
                            // Default ON when nothing saved yet
                            if ( empty( $saved_types ) ) {
                                $saved_types = array_keys( $all_public );
                            }
                            foreach ( $all_public as $pt ) :
                            ?>
                            <label style="display:block;margin-bottom:4px;">
                                <input type="checkbox" name="supported_post_types[]" value="<?php echo esc_attr( $pt->name ); ?>"
                                    <?php checked( in_array( $pt->name, $saved_types, true ) ); ?>>
                                <?php echo esc_html( $pt->labels->name ); ?>
                                <span style="color:#999;font-size:12px;">(<?php echo esc_html( $pt->name ); ?>)</span>
                            </label>
                            <?php endforeach; ?>
                            <p class="description">
                                <?php _e( 'Which post types KineticCopy scans, analyses, and adds tools to. Recommended: keep all enabled for full brand alignment. Uncheck post types you want to exclude.', 'claude-ai-copywriter' ); ?>
                            </p>
                        </td>
                    </tr>

                    <tr>
                        <th scope="row">
                            <label for="enable_breakdance"><?php _e( 'Breakdance Integration', 'claude-ai-copywriter' ); ?></label>
                        </th>
                        <td>
                            <label>
                                <input type="checkbox" name="enable_breakdance" id="enable_breakdance" value="1" <?php checked( $settings['enable_breakdance'] ?? false, 1 ); ?>>
                                <?php _e( 'Enable Breakdance page builder integration', 'claude-ai-copywriter' ); ?>
                            </label>
                            <p class="description">
                                <?php _e( 'Add KineticCopy tools to the Breakdance builder interface.', 'claude-ai-copywriter' ); ?>
                            </p>
                        </td>
                    </tr>

                    <tr>
                        <th scope="row">
                            <label for="debug_mode"><?php _e( 'Debug Mode', 'claude-ai-copywriter' ); ?></label>
                        </th>
                        <td>
                            <label>
                                <input type="checkbox" name="debug_mode" id="debug_mode" value="1" <?php checked( $settings['debug_mode'] ?? 0, 1 ); ?>>
                                <?php _e( 'Enable debug logging in browser console', 'claude-ai-copywriter' ); ?>
                            </label>
                            <p class="description">
                                <?php _e( 'When enabled, detailed debug information will be logged to the browser console (F12 → Console tab). Helpful for troubleshooting issues.', 'claude-ai-copywriter' ); ?>
                            </p>
                        </td>
                    </tr>
                </table>

                <!-- Brand Voice & Custom Instructions -->
                <h3 style="margin-top:32px; margin-bottom:8px;"><?php _e( 'Your Brand Voice', 'claude-ai-copywriter' ); ?></h3>
                <p class="description" style="margin-bottom:16px;">
                    <?php _e( 'Paste your brand guidelines, tone rules, key messages, or any custom instructions here. KineticCopy will apply them to every piece of content it generates - on top of the built-in methodology. Migrating from ChatGPT? Paste your custom instructions directly here.', 'claude-ai-copywriter' ); ?>
                </p>
                <table class="form-table">
                    <tr>
                        <th scope="row">
                            <label for="custom_copy_instructions"><?php _e( 'Brand Voice & Instructions', 'claude-ai-copywriter' ); ?></label>
                        </th>
                        <td>
                            <textarea
                                name="custom_copy_instructions"
                                id="custom_copy_instructions"
                                rows="8"
                                class="large-text"
                                placeholder="<?php esc_attr_e( 'Example:\n- Always use "you" and "your" - never "one"\n- Avoid jargon. Write at an 8th-grade reading level.\n- Brand values: bold, practical, no-nonsense\n- Never use: "leverage", "synergy", "game-changer"\n- Target: founders who want results, not fluff', 'claude-ai-copywriter' ); ?>"
                            ><?php echo esc_textarea( get_option( 'claude_ai_custom_copy_instructions', '' ) ); ?></textarea>
                            <p class="description">
                                <?php _e( 'These instructions are injected into every generation request. Keep them focused - shorter is often better. The plugin\'s built-in KineticCopy methodology already handles the strategic layer; this is for your specific brand rules.', 'claude-ai-copywriter' ); ?>
                            </p>
                        </td>
                    </tr>
                </table>
            </div>

            <!-- Brand Strategy moved to My Brand page (KineticCopy > My Brand) -->
            <div id="api-key" class="tab-content">
                <h2><?php _e( 'API Keys & Integrations', 'claude-ai-copywriter' ); ?></h2>

                <!-- Sub-tab navigation -->
                <div class="kc-subtab-nav">
                    <button type="button" class="kc-subtab-btn kc-subtab-active" data-subtab="subtab-providers">
                        <span class="dashicons dashicons-admin-network" style="font-size:14px; width:14px; height:14px; line-height:14px; margin-right:4px; vertical-align:middle;"></span>
                        <?php _e( 'AI Providers', 'claude-ai-copywriter' ); ?>
                    </button>
                    <button type="button" class="kc-subtab-btn" data-subtab="subtab-integrations">
                        <span style="font-size:14px; margin-right:4px; vertical-align:middle;">&#x26A1;</span>
                        <?php _e( 'Integrations', 'claude-ai-copywriter' ); ?>
                    </button>
                </div>

                <!-- ═══ SUB-TAB: AI Providers ═══ -->
                <div id="subtab-providers" class="kc-subtab-content kc-subtab-visible">
                <?php
                // Pre-compute saved key status for all providers
                $prov_anthropic = new Claude_AI_Copywriter_Claude_API();
                $prov_has_anthropic = $prov_anthropic->has_api_key();
                $prov_uid = get_current_user_id();
                $prov_kc_raw  = get_user_meta( $prov_uid, 'kineticcopy_kilocode_key', true );
                $prov_has_kc  = ! empty( $prov_kc_raw );
                $prov_or_raw  = get_user_meta( $prov_uid, 'kineticcopy_openrouter_key', true );
                $prov_has_or  = ! empty( $prov_or_raw );
                ?>

                    <div class="kinetic-info-banner">
                        <h3><span class="dashicons dashicons-admin-network"></span> <?php _e( 'Connect an AI Provider', 'claude-ai-copywriter' ); ?></h3>
                        <p><?php _e( 'KineticCopy uses Claude models to power AI generation. You can connect directly via Anthropic, or through KiloCode or OpenRouter - all three serve Anthropic Claude models. You only need ONE provider key.', 'claude-ai-copywriter' ); ?></p>
                        <ul>
                            <li><?php _e( 'Pay only for what you use - no subscription required from any provider', 'claude-ai-copywriter' ); ?></li>
                            <li><?php _e( 'All keys are encrypted with AES-256 before storage', 'claude-ai-copywriter' ); ?></li>
                            <li><?php _e( 'Already have a Claude subscription? You still need a separate API key (the API and claude.ai are separate products)', 'claude-ai-copywriter' ); ?></li>
                        </ul>
                    </div>

                    <!-- Anthropic (Direct) -->
                    <div style="margin-top:24px; padding:20px; background:#ffffff; border:1px solid #e5e7eb; border-left:4px solid <?php echo $prov_has_anthropic ? '#16a34a' : '#d97706'; ?>; border-radius:5px; max-width:720px;">
                        <h3 style="margin:0 0 4px; display:flex; align-items:center; gap:8px; font-size:14px;">
                            <?php _e( 'Anthropic (Direct)', 'claude-ai-copywriter' ); ?>
                            <span style="font-size:11px; background:#fef3c7; color:#92400e; padding:2px 8px; border-radius:3px; font-weight:500;"><?php _e( 'Recommended', 'claude-ai-copywriter' ); ?></span>
                            <?php if ( $prov_has_anthropic ) : ?>
                                <span style="font-size:11px; background:#dcfce7; color:#166534; padding:2px 8px; border-radius:3px; font-weight:500;">&#10003; <?php _e( 'Key saved', 'claude-ai-copywriter' ); ?></span>
                            <?php endif; ?>
                        </h3>
                        <p style="margin:0 0 12px; color:#6b7280; font-size:12px;">
                            <?php printf(
                                __( 'Get your API key from %s', 'claude-ai-copywriter' ),
                                '<a href="https://console.anthropic.com/settings/keys" target="_blank" rel="noopener noreferrer">console.anthropic.com</a>'
                            ); ?>
                        </p>

                        <table class="form-table" style="margin:0;">
                            <tr>
                                <th scope="row" style="padding:6px 0; width:130px; font-size:13px;">
                                    <label for="claude-api-key"><?php _e( 'API Key', 'claude-ai-copywriter' ); ?></label>
                                </th>
                                <td style="padding:6px 0;">
                                    <input type="password" id="claude-api-key" class="regular-text" placeholder="sk-ant-api03-xxxxx" autocomplete="off" onkeydown="if(event.key==='Enter'){event.preventDefault();document.getElementById('save-api-key').click();return false;}">
                                </td>
                            </tr>
                            <tr>
                                <th scope="row" style="padding:6px 0; font-size:13px;">
                                    <label for="key-name"><?php _e( 'Key Name', 'claude-ai-copywriter' ); ?></label>
                                </th>
                                <td style="padding:6px 0;">
                                    <input type="text" id="key-name" class="regular-text" value="Default" placeholder="<?php esc_attr_e( 'Default', 'claude-ai-copywriter' ); ?>" onkeydown="if(event.key==='Enter'){event.preventDefault();document.getElementById('save-api-key').click();return false;}">
                                    <p class="description" style="margin-top:4px;"><?php _e( 'Optional label to identify this key.', 'claude-ai-copywriter' ); ?></p>
                                </td>
                            </tr>
                        </table>

                        <div style="margin-top:10px; display:flex; gap:10px; align-items:center;">
                            <button type="button" id="test-api-key" class="button" onclick="kcTestAnthropicKey(event)"><?php _e( 'Test Key', 'claude-ai-copywriter' ); ?></button>
                            <button type="button" id="save-api-key" class="button button-primary" onclick="kcSaveAnthropicKey(event)"><?php _e( 'Save Key', 'claude-ai-copywriter' ); ?></button>
                        </div>
                        <div id="api-key-status" style="margin-top:8px; display:none;"></div>
                        <script>
                        (function(){
                            var KC_AJAX  = '<?php echo esc_js( admin_url( 'admin-ajax.php' ) ); ?>';
                            var KC_NONCE = '<?php echo esc_js( wp_create_nonce( 'claude_ai_nonce' ) ); ?>';

                            function kcStatus(html, type) {
                                var d = document.getElementById('api-key-status');
                                var colors = { success: {bg:'#dcfce7',border:'#bbf7d0',text:'#166534'}, error: {bg:'#fee2e2',border:'#fecaca',text:'#991b1b'}, info: {bg:'#eff6ff',border:'#bfdbfe',text:'#1e40af'} };
                                var c = colors[type] || colors.info;
                                d.style.cssText = 'margin-top:8px;padding:10px 14px;border-radius:5px;font-size:13px;background:'+c.bg+';border:1px solid '+c.border+';color:'+c.text+';display:block;';
                                d.innerHTML = html;
                            }

                            window.kcSaveAnthropicKey = function(e) {
                                e.preventDefault(); e.stopImmediatePropagation();
                                var btn = document.getElementById('save-api-key');
                                var key = (document.getElementById('claude-api-key').value || '').trim();
                                var name = (document.getElementById('key-name').value || 'Default').trim();
                                if (!key) { kcStatus('Please enter an API key.', 'error'); return; }
                                btn.disabled = true; btn.textContent = 'Saving...';
                                kcStatus('Saving&hellip;', 'info');
                                var fd = new FormData();
                                fd.append('action', 'claude_save_api_key');
                                fd.append('nonce', KC_NONCE);
                                fd.append('api_key', key);
                                fd.append('key_name', name);
                                fetch(KC_AJAX, { method:'POST', body:fd, credentials:'same-origin' })
                                    .then(function(r){ return r.json(); })
                                    .then(function(resp){
                                        if (resp.success) {
                                            document.getElementById('claude-api-key').value = '';
                                            kcStatus('&#10003; API key saved successfully!', 'success');
                                            var card = btn.closest('div[style]');
                                            if (card) card.style.borderLeftColor = '#16a34a';
                                        } else {
                                            kcStatus('&#10007; ' + ((resp.data && resp.data.message) || 'Save failed.'), 'error');
                                        }
                                    })
                                    .catch(function(err){ kcStatus('&#10007; Network error: ' + err, 'error'); })
                                    .finally(function(){ btn.disabled = false; btn.textContent = '<?php echo esc_js( __( 'Save Key', 'claude-ai-copywriter' ) ); ?>'; });
                            };

                            window.kcTestAnthropicKey = function(e) {
                                e.preventDefault(); e.stopImmediatePropagation();
                                var btn = document.getElementById('test-api-key');
                                var key = (document.getElementById('claude-api-key').value || '').trim();
                                if (!key) { kcStatus('Please enter an API key first.', 'error'); return; }
                                btn.disabled = true; btn.textContent = 'Testing...';
                                kcStatus('Testing connection with Anthropic&hellip;', 'info');
                                var fd = new FormData();
                                fd.append('action', 'claude_test_api_key');
                                fd.append('nonce', KC_NONCE);
                                fd.append('api_key', key);
                                fetch(KC_AJAX, { method:'POST', body:fd, credentials:'same-origin' })
                                    .then(function(r){ return r.json(); })
                                    .then(function(resp){
                                        if (resp.success) {
                                            kcStatus('&#10003; ' + ((resp.data && resp.data.message) || 'API key is valid!'), 'success');
                                        } else {
                                            kcStatus('&#10007; ' + ((resp.data && resp.data.message) || 'Key test failed.'), 'error');
                                        }
                                    })
                                    .catch(function(err){ kcStatus('&#10007; Network error: ' + err, 'error'); })
                                    .finally(function(){ btn.disabled = false; btn.textContent = '<?php echo esc_js( __( 'Test Key', 'claude-ai-copywriter' ) ); ?>'; });
                            };
                        })();
                        </script>
                    </div>

                    <!-- KiloCode -->
                    <div style="margin-top:16px; padding:20px; background:#ffffff; border:1px solid #e5e7eb; border-left:4px solid <?php echo $prov_has_kc ? '#16a34a' : '#6366f1'; ?>; border-radius:5px; max-width:720px;">
                        <h3 style="margin:0 0 4px; display:flex; align-items:center; gap:8px; font-size:14px;">
                            <?php _e( 'KiloCode', 'claude-ai-copywriter' ); ?>
                            <span style="font-size:11px; background:#eef2ff; color:#4338ca; padding:2px 8px; border-radius:3px; font-weight:500;"><?php _e( 'Claude via KiloCode', 'claude-ai-copywriter' ); ?></span>
                            <?php if ( $prov_has_kc ) : ?>
                                <span style="font-size:11px; background:#dcfce7; color:#166534; padding:2px 8px; border-radius:3px; font-weight:500;">&#10003; <?php _e( 'Key saved', 'claude-ai-copywriter' ); ?></span>
                            <?php endif; ?>
                        </h3>
                        <p style="margin:0 0 12px; color:#6b7280; font-size:12px;">
                            <?php printf(
                                __( 'Get your API key from %s - KiloCode provides access to Claude models with additional features.', 'claude-ai-copywriter' ),
                                '<a href="https://kilocode.ai/dashboard" target="_blank" rel="noopener noreferrer">kilocode.ai/dashboard</a>'
                            ); ?>
                        </p>

                        <table class="form-table" style="margin:0;">
                            <tr>
                                <th scope="row" style="padding:6px 0; width:130px; font-size:13px;">
                                    <label for="kilocode-api-key"><?php _e( 'API Key', 'claude-ai-copywriter' ); ?></label>
                                </th>
                                <td style="padding:6px 0;">
                                    <input type="password" id="kilocode-api-key" class="regular-text" placeholder="kc-xxxxx" autocomplete="off" onkeydown="if(event.key==='Enter'){event.preventDefault();document.getElementById('save-kilocode-key').click();return false;}">
                                </td>
                            </tr>
                        </table>

                        <div style="margin-top:10px; display:flex; gap:10px; align-items:center;">
                            <button type="button" id="save-kilocode-key" class="button button-primary"><?php _e( 'Save Key', 'claude-ai-copywriter' ); ?></button>
                            <span id="kilocode-key-status" style="font-size:12px; color:#6b7280;"></span>
                        </div>
                    </div>

                    <!-- OpenRouter -->
                    <div style="margin-top:16px; padding:20px; background:#ffffff; border:1px solid #e5e7eb; border-left:4px solid <?php echo $prov_has_or ? '#16a34a' : '#10b981'; ?>; border-radius:5px; max-width:720px;">
                        <h3 style="margin:0 0 4px; display:flex; align-items:center; gap:8px; font-size:14px;">
                            <?php _e( 'OpenRouter', 'claude-ai-copywriter' ); ?>
                            <span style="font-size:11px; background:#ecfdf5; color:#065f46; padding:2px 8px; border-radius:3px; font-weight:500;"><?php _e( 'Claude via OpenRouter', 'claude-ai-copywriter' ); ?></span>
                            <?php if ( $prov_has_or ) : ?>
                                <span style="font-size:11px; background:#dcfce7; color:#166534; padding:2px 8px; border-radius:3px; font-weight:500;">&#10003; <?php _e( 'Key saved', 'claude-ai-copywriter' ); ?></span>
                            <?php endif; ?>
                        </h3>
                        <p style="margin:0 0 12px; color:#6b7280; font-size:12px;">
                            <?php printf(
                                __( 'Get your API key from %s - OpenRouter provides access to Claude and other models through a unified API.', 'claude-ai-copywriter' ),
                                '<a href="https://openrouter.ai/keys" target="_blank" rel="noopener noreferrer">openrouter.ai/keys</a>'
                            ); ?>
                        </p>

                        <table class="form-table" style="margin:0;">
                            <tr>
                                <th scope="row" style="padding:6px 0; width:130px; font-size:13px;">
                                    <label for="openrouter-api-key"><?php _e( 'API Key', 'claude-ai-copywriter' ); ?></label>
                                </th>
                                <td style="padding:6px 0;">
                                    <input type="password" id="openrouter-api-key" class="regular-text" placeholder="sk-or-v1-xxxxx" autocomplete="off" onkeydown="if(event.key==='Enter'){event.preventDefault();document.getElementById('save-openrouter-key').click();return false;}">
                                </td>
                            </tr>
                        </table>

                        <div style="margin-top:10px; display:flex; gap:10px; align-items:center;">
                            <button type="button" id="save-openrouter-key" class="button button-primary"><?php _e( 'Save Key', 'claude-ai-copywriter' ); ?></button>
                            <span id="openrouter-key-status" style="font-size:12px; color:#6b7280;"></span>
                        </div>
                    </div>

                </div><!-- /subtab-providers -->

                <!-- ═══ SUB-TAB: Integrations ═══ -->
                <div id="subtab-integrations" class="kc-subtab-content">
                <!-- KineticLaunch Sync -->
                <?php
                $kb_status = class_exists( 'Claude_AI_KineticBrand_Integration' )
                    ? Claude_AI_KineticBrand_Integration::get_status()
                    : [ 'connected' => false, 'project_id' => '', 'last_sync' => '', 'sync_error' => '', 'api_key_set' => false ];
                ?>
                <div style="margin-top:32px; padding:20px; background:#ffffff; border:1px solid #e5e7eb; border-left:4px solid #e8d98e; border-radius:5px; max-width:720px;">
                    <h3 style="margin:0 0 4px; display:flex; align-items:center; gap:8px;">
                        <span style="color:#374151;">&#x26A1;</span>
                        <?php _e( 'KineticLaunch Sync', 'claude-ai-copywriter' ); ?>
                        <?php if ( $kb_status['api_key_set'] ) : ?>
                            <span style="font-size:11px; background:#fef9c3; color:#374151; padding:2px 8px; border-radius:3px; font-weight:500;">
                                <?php echo $kb_status['last_sync'] ? esc_html__( 'Connected', 'claude-ai-copywriter' ) : esc_html__( 'Credentials saved', 'claude-ai-copywriter' ); ?>
                            </span>
                        <?php endif; ?>
                    </h3>
                    <p style="margin:0 0 16px; color:#374151; font-size:13px;">
                        <?php _e( 'Pull your completed brand strategy from KineticLaunch: voice rules, positioning, vocabulary, competitors. Overwrites fields below with your latest strategy data.', 'claude-ai-copywriter' ); ?>
                    </p>

                    <?php if ( $kb_status['sync_error'] ) : ?>
                        <div style="margin-bottom:12px; padding:10px 14px; background:#fee2e2; border:1px solid #fca5a5; border-radius:6px; color:#991b1b; font-size:12px;">
                            <?php echo esc_html( $kb_status['sync_error'] ); ?>
                        </div>
                    <?php endif; ?>

                    <table class="form-table" style="margin:0;">
                        <tr>
                            <th scope="row" style="padding:6px 0; width:160px; font-size:13px;">
                                <label for="kb_api_key"><?php _e( 'API Key', 'claude-ai-copywriter' ); ?></label>
                            </th>
                            <td style="padding:6px 0;">
                                <input type="password" id="kb_api_key" class="regular-text"
                                    placeholder="kb_xxxxxxxxxxxxxxxx"
                                    value="<?php echo $kb_status['api_key_set'] ? str_repeat('&bull;', 16) : ''; ?>"
                                    autocomplete="off" />
                                <p class="description" style="margin-top:4px;"><?php _e( 'Generate in KineticLaunch &rarr; Settings &rarr; Integrations &rarr; Brand Context Export.', 'claude-ai-copywriter' ); ?></p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row" style="padding:6px 0; font-size:13px;">
                                <label for="kb_project_id"><?php _e( 'Project ID', 'claude-ai-copywriter' ); ?></label>
                            </th>
                            <td style="padding:6px 0;">
                                <input type="text" id="kb_project_id" class="regular-text"
                                    placeholder="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
                                    value="<?php echo esc_attr( $kb_status['project_id'] ); ?>"
                                    autocomplete="off" />
                                <p class="description" style="margin-top:4px;"><?php _e( 'UUID shown in KineticLaunch after generating your key.', 'claude-ai-copywriter' ); ?></p>
                            </td>
                        </tr>
                    </table>

                    <div style="margin-top:12px; display:flex; gap:10px; align-items:center; flex-wrap:wrap;">
                        <button type="button" id="kb-save-creds" class="button button-secondary"><?php _e( 'Save credentials', 'claude-ai-copywriter' ); ?></button>
                        <button type="button" id="kb-sync-now" class="button button-primary" <?php echo $kb_status['api_key_set'] ? '' : 'disabled'; ?>>
                            &#x26A1; <?php _e( 'Sync Now', 'claude-ai-copywriter' ); ?>
                        </button>
                        <?php if ( $kb_status['api_key_set'] ) : ?>
                            <button type="button" id="kb-clear-creds" class="button button-link-delete" style="color:#dc2626;"><?php _e( 'Disconnect', 'claude-ai-copywriter' ); ?></button>
                        <?php endif; ?>
                        <span id="kb-status-msg" style="font-size:12px; color:#6b7280;"></span>
                    </div>

                    <?php if ( $kb_status['last_sync'] ) : ?>
                        <p style="margin-top:10px; font-size:12px; color:#6b7280;">
                            <?php printf( esc_html__( 'Last synced: %s', 'claude-ai-copywriter' ), esc_html( $kb_status['last_sync'] ) ); ?>
                        </p>
                    <?php endif; ?>
                </div>

                <script>
                (function($){
                    var nonce = '<?php echo esc_js( wp_create_nonce( "claude_ai_settings_save" ) ); ?>';
                    function setMsg(msg, color) { $('#kb-status-msg').text(msg).css('color', color||'#6b7280'); }
                    $('#kb-save-creds').on('click', function() {
                        var apiKey = $('#kb_api_key').val(), projectId = $('#kb_project_id').val();
                        if (!projectId) { setMsg('Project ID required.','#dc2626'); return; }
                        if (apiKey && apiKey.indexOf('\u2022') !== -1) apiKey = '';
                        setMsg('Saving...');
                        $.post(ajaxurl, { action:'kineticbrand_save_creds', nonce:nonce, api_key:apiKey, project_id:projectId }, function(r){
                            if (r.success) { setMsg(r.data.message,'#16a34a'); $('#kb-sync-now').prop('disabled',false); }
                            else { setMsg(r.data,'#dc2626'); }
                        });
                    });
                    $('#kb-sync-now').on('click', function() {
                        var $b=$(this).prop('disabled',true).text('Syncing...');
                        setMsg('');
                        $.post(ajaxurl, { action:'kineticbrand_sync', nonce:nonce }, function(r){
                            if (r.success) { setMsg('Synced '+r.data.project+' ('+r.data.fields.length+' fields).','#16a34a'); setTimeout(function(){ location.reload(); },1500); }
                            else { setMsg(r.data,'#dc2626'); }
                        }).always(function(){ $b.prop('disabled',false).html('&#x26A1; Sync Now'); });
                    });
                    $('#kb-clear-creds').on('click', function() {
                        if (!confirm('Disconnect KineticLaunch? Fields keep current values.')) return;
                        $.post(ajaxurl, { action:'kineticbrand_clear_creds', nonce:nonce }, function(r){ if(r.success) location.reload(); });
                    });
                })(jQuery);
                </script>

                <!-- Calendar Push Webhook UI (Studio+ / calendar feature) -->
                <?php if ( Claude_AI_Copywriter_License_Manager::has_feature( 'calendar' ) ) : ?>
                <?php
                $calendar_push_secret = get_option( 'kineticcopy_calendar_push_secret', '' );
                $calendar_push_webhook_url = rest_url( 'kineticcopy/v1/calendar-push' );
                ?>
                <div style="margin-top:32px; padding:20px; background:#ffffff; border:1px solid #e5e7eb; border-left:4px solid #e8d98e; border-radius:5px; max-width:720px;">
                    <h3 style="margin:0 0 4px; display:flex; align-items:center; gap:8px;">
                        <span style="color:#374151;">📅</span>
                        <?php _e( 'Calendar Push Webhook', 'claude-ai-copywriter' ); ?>
                        <?php if ( ! empty( $calendar_push_secret ) ) : ?>
                            <span style="font-size:11px; background:#fef9c3; color:#374151; padding:2px 8px; border-radius:3px; font-weight:500;">
                                <?php _e( 'Configured', 'claude-ai-copywriter' ); ?>
                            </span>
                        <?php endif; ?>
                    </h3>
                    <p style="margin:0 0 16px; color:#374151; font-size:13px;">
                        <?php _e( 'Receive calendar entry briefs from KineticLaunch, generate long-form content, and send drafts back via webhook.', 'claude-ai-copywriter' ); ?>
                    </p>

                    <table class="form-table" style="margin:0;">
                        <tr>
                            <th scope="row" style="padding:6px 0; width:160px; font-size:13px;">
                                <label><?php _e( 'Webhook URL', 'claude-ai-copywriter' ); ?></label>
                            </th>
                            <td style="padding:6px 0;">
                                <input type="text" value="<?php echo esc_attr( $calendar_push_webhook_url ); ?>"
                                    class="regular-text" readonly style="background:#f3f4f6; cursor:pointer;"
                                    onclick="this.select();" />
                                <p class="description" style="margin-top:4px;">
                                    <?php _e( 'Copy this URL into KineticLaunch → Calendar Push settings.', 'claude-ai-copywriter' ); ?>
                                </p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row" style="padding:6px 0; font-size:13px;">
                                <label for="cp_secret"><?php _e( 'Webhook Secret', 'claude-ai-copywriter' ); ?></label>
                            </th>
                            <td style="padding:6px 0;">
                                <input type="password" id="cp_secret" class="regular-text"
                                    placeholder="Generate a secure random secret"
                                    value="<?php echo ! empty( $calendar_push_secret ) ? str_repeat( '•', min( 16, strlen( $calendar_push_secret ) ) ) : ''; ?>"
                                    autocomplete="off" />
                                <p class="description" style="margin-top:4px;">
                                    <?php _e( 'Set a strong secret (32+ characters). KineticLaunch must send this header to authenticate.', 'claude-ai-copywriter' ); ?>
                                </p>
                            </td>
                        </tr>
                    </table>

                    <div style="margin-top:12px; display:flex; gap:10px; align-items:center; flex-wrap:wrap;">
                        <button type="button" id="cp-save-secret" class="button button-secondary"><?php _e( 'Save Secret', 'claude-ai-copywriter' ); ?></button>
                        <button type="button" id="cp-test-webhook" class="button button-secondary">
                            ✓ <?php _e( 'Test Connection', 'claude-ai-copywriter' ); ?>
                        </button>
                        <span id="cp-status-msg" style="font-size:12px; color:#6b7280;"></span>
                    </div>
                </div>

                <script>
                (function($){
                    var nonce = '<?php echo esc_js( wp_create_nonce( "claude_ai_settings_save" ) ); ?>';
                    function setMsg(msg, color) { $('#cp-status-msg').text(msg).css('color', color||'#6b7280'); }
                    
                    $('#cp-save-secret').on('click', function() {
                        var secret = $('#cp_secret').val();
                        if (!secret || secret.indexOf('\u2022') !== -1) {
                            setMsg('Enter or change the secret.','#dc2626');
                            return;
                        }
                        if (secret.length < 16) {
                            setMsg('Secret should be at least 16 characters.','#dc2626');
                            return;
                        }
                        setMsg('Saving...');
                        $.post(ajaxurl, { action:'claude_save_calendar_push_secret', nonce:nonce, secret:secret }, function(r){
                            if (r.success) { 
                                setMsg('✓ Secret saved.','#16a34a'); 
                                setTimeout(function(){ location.reload(); },1000);
                            } else { 
                                setMsg(r.data,'#dc2626'); 
                            }
                        });
                    });

                    $('#cp-test-webhook').on('click', function() {
                        var secret = $('#cp_secret').val();
                        if (!secret) {
                            setMsg('Save the secret first.','#dc2626');
                            return;
                        }
                        var $b = $(this).prop('disabled', true).text('Testing...');
                        setMsg('');
                        $.ajax({
                            type: 'POST',
                            url: '<?php echo esc_js( rest_url( 'kineticcopy/v1/calendar-push/test' ) ); ?>',
                            contentType: 'application/json',
                            headers: {
                                'x-webhook-secret': secret
                            },
                            data: JSON.stringify({}),
                            success: function(r) {
                                setMsg('✓ Webhook connection valid.','#16a34a');
                            },
                            error: function(xhr) {
                                var msg = xhr.status === 401 ? 'Invalid secret.' : 'Connection failed.';
                                setMsg(msg,'#dc2626');
                            },
                            complete: function() {
                                $b.prop('disabled', false).text('✓ Test Connection');
                            }
                        });
                    });
                })(jQuery);
                </script>

                <!-- Content Generation Toggles (v1.8.0) -->
                <div style="margin-top:24px; padding:20px; background:#ffffff; border:1px solid #e5e7eb; border-left:4px solid #16a34a; border-radius:5px; max-width:720px;">
                    <h3 style="margin:0 0 12px; font-size:14px; font-weight:600; color:#1d2327;">
                        <?php _e( 'Content Generation', 'claude-ai-copywriter' ); ?>
                    </h3>
                    <table class="form-table" style="margin:0;">
                        <tr>
                            <th style="width:220px; padding:8px 10px 8px 0; font-size:13px;">
                                <?php _e( 'Auto-generate on calendar push', 'claude-ai-copywriter' ); ?>
                            </th>
                            <td style="padding:8px 0;">
                                <label>
                                    <input type="checkbox"
                                           name="kc_auto_generate_on_push"
                                           id="kc_auto_generate_on_push"
                                           value="1"
                                           <?php checked( ! empty( $settings['kc_auto_generate_on_push'] ) ); ?>>
                                    <?php _e( 'Automatically generate full content when KineticLaunch pushes a calendar entry. If off, a draft is created with the brief so you can generate manually from the post editor.', 'claude-ai-copywriter' ); ?>
                                </label>
                            </td>
                        </tr>
                        <tr>
                            <th style="width:220px; padding:8px 10px 8px 0; font-size:13px;">
                                <?php _e( 'Auto-publish on scheduled date', 'claude-ai-copywriter' ); ?>
                            </th>
                            <td style="padding:8px 0;">
                                <label>
                                    <input type="checkbox"
                                           name="kc_auto_publish"
                                           id="kc_auto_publish"
                                           value="1"
                                           <?php checked( ! empty( $settings['kc_auto_publish'] ) ); ?>>
                                    <?php _e( 'Set generated posts to "Scheduled" for the campaign date. If off, posts remain as drafts until you manually approve and publish.', 'claude-ai-copywriter' ); ?>
                                </label>
                                <p style="margin:4px 0 0; color:#6b7280; font-size:12px;">
                                    <?php _e( 'Requires auto-generate to be enabled above.', 'claude-ai-copywriter' ); ?>
                                </p>
                            </td>
                        </tr>
                    </table>
                    <div style="margin-top:12px;">
                        <button type="button" id="kc-save-generation-settings" class="button button-primary">
                            <?php _e( 'Save Generation Settings', 'claude-ai-copywriter' ); ?>
                        </button>
                        <span id="kc-gen-settings-msg" style="margin-left:10px; font-size:13px; display:none;"></span>
                    </div>
                </div>
                <script>
                (function($){
                    $('#kc-save-generation-settings').on('click', function() {
                        var $btn = $(this);
                        var $msg = $('#kc-gen-settings-msg');
                        var nonce = '<?php echo esc_js( wp_create_nonce( 'claude_ai_settings_save' ) ); ?>';
                        $btn.prop('disabled', true).text('Saving...');
                        $.post(ajaxurl, {
                            action:                    'claude_save_settings',
                            nonce:                     nonce,
                            kc_auto_generate_on_push:  $('#kc_auto_generate_on_push').is(':checked') ? 1 : 0,
                            kc_auto_publish:           $('#kc_auto_publish').is(':checked') ? 1 : 0,
                        }, function(r) {
                            $btn.prop('disabled', false).text('Save Generation Settings');
                            if (r.success) {
                                $msg.text('Saved!').css('color', '#16a34a').show().delay(2500).fadeOut();
                            } else {
                                $msg.text('Error saving settings.').css('color', '#dc2626').show();
                            }
                        });
                    });
                })(jQuery);
                </script>

                <?php else : ?>
                <div style="margin-top:32px; padding:20px; background:#faf5ff; border:1px solid #e9d5ff; border-left:4px solid #7c3aed; border-radius:5px; max-width:720px;">
                    <h3 style="margin:0 0 8px; display:flex; align-items:center; gap:8px; color:#374151;">
                        <span>📅</span> <?php _e( 'Calendar Push Webhook', 'claude-ai-copywriter' ); ?>
                        <span style="font-size:11px; background:#7c3aed; color:#fff; padding:2px 8px; border-radius:3px; font-weight:500;"><?php _e( 'Studio+', 'claude-ai-copywriter' ); ?></span>
                    </h3>
                    <p style="margin:0 0 12px; color:#374151; font-size:13px;">
                        <?php _e( 'Receive calendar entry briefs from KineticLaunch, generate long-form content, and send drafts back automatically. Included in all KineticCopy plans.', 'claude-ai-copywriter' ); ?>
                    </p>
                    <a href="<?php echo esc_url( admin_url( 'admin.php?page=kineticcopy-settings&tab=upgrade' ) ); ?>" class="button button-primary" style="background:#7c3aed; border-color:#6d28d9;">
                        <?php _e( 'Upgrade KineticCopy', 'claude-ai-copywriter' ); ?>
                    </a>
                </div>
                <?php endif; ?>

                <!-- Substack Integration -->
                <div style="margin-top:32px; padding:20px; background:#ffffff; border:1px solid #e5e7eb; border-left:4px solid #ff6719; border-radius:5px; max-width:720px;">
                    <h3 style="margin:0 0 4px; display:flex; align-items:center; gap:8px; font-size:15px;">
                        <span>📧</span> <?php _e( 'Substack', 'claude-ai-copywriter' ); ?>
                        <span style="font-size:11px; background:#fff7ed; color:#c2410c; padding:2px 8px; border-radius:3px; font-weight:500;"><?php _e( 'Email-to-post', 'claude-ai-copywriter' ); ?></span>
                    </h3>
                    <p style="margin:0 0 12px; color:#6b7280; font-size:13px;">
                        <?php _e( 'Send Substack posts from your library directly to your Substack draft queue. Find your publication email at: Substack Dashboard &rarr; Settings &rarr; Email &rarr; "Post via email".', 'claude-ai-copywriter' ); ?>
                    </p>
                    <table class="form-table" style="margin:0;">
                        <tr>
                            <th scope="row" style="padding:6px 0; width:160px; font-size:13px;">
                                <label for="kc-substack-email"><?php _e( 'Publication Email', 'claude-ai-copywriter' ); ?></label>
                            </th>
                            <td style="padding:6px 0;">
                                <input type="email" id="kc-substack-email" class="regular-text"
                                    placeholder="yourpublication@substack.com"
                                    value="<?php echo esc_attr( get_option( 'kineticcopy_substack_email', '' ) ); ?>"
                                    autocomplete="off" />
                                <p class="description" style="margin-top:4px;"><?php _e( 'Posts arrive as drafts in your Substack dashboard for review before publishing.', 'claude-ai-copywriter' ); ?></p>
                            </td>
                        </tr>
                    </table>
                    <div style="margin-top:12px; display:flex; gap:10px; align-items:center;">
                        <button type="button" id="kc-save-substack-email" class="button button-secondary"><?php _e( 'Save', 'claude-ai-copywriter' ); ?></button>
                        <span id="kc-substack-status" style="font-size:12px; color:#6b7280;"></span>
                    </div>
                </div>
                <script>
                (function($){
                    var nonce = '<?php echo esc_js( wp_create_nonce( "claude_ai_settings_save" ) ); ?>';
                    $('#kc-save-substack-email').on('click', function() {
                        var email = $.trim($('#kc-substack-email').val());
                        if (!email) { $('#kc-substack-status').text('<?php echo esc_js( __( 'Enter your Substack publication email first.', 'claude-ai-copywriter' ) ); ?>').css('color','#dc2626'); return; }
                        $('#kc-substack-status').text('<?php echo esc_js( __( 'Saving...', 'claude-ai-copywriter' ) ); ?>').css('color','#6b7280');
                        $.post(ajaxurl, { action: 'kineticcopy_save_substack_email', nonce: nonce, email: email }, function(r) {
                            if (r.success) { $('#kc-substack-status').text('<?php echo esc_js( __( '✓ Saved.', 'claude-ai-copywriter' ) ); ?>').css('color','#16a34a'); }
                            else { $('#kc-substack-status').text(r.data || '<?php echo esc_js( __( 'Save failed.', 'claude-ai-copywriter' ) ); ?>').css('color','#dc2626'); }
                        });
                    });
                })(jQuery);
                </script>

                </div><!-- /subtab-integrations -->

                <!-- Sub-tab switching JS -->
                <script>
                (function($){
                    $('.kc-subtab-btn').on('click', function(e) {
                        e.preventDefault();
                        var target = $(this).data('subtab');
                        $('.kc-subtab-btn').removeClass('kc-subtab-active');
                        $(this).addClass('kc-subtab-active');
                        $('.kc-subtab-content').removeClass('kc-subtab-visible');
                        $('#' + target).addClass('kc-subtab-visible');
                    });

                    // Helper: inject a "Key saved" badge into the provider card heading
                    function kcShowSavedBadge($card) {
                        if ($card.find('.kc-key-saved-badge').length === 0) {
                            $card.find('h3').append('<span class="kc-key-saved-badge" style="font-size:11px;background:#dcfce7;color:#166534;padding:2px 8px;border-radius:3px;font-weight:500;margin-left:4px;">&#10003; <?php echo esc_js( __( 'Key saved', 'claude-ai-copywriter' ) ); ?></span>');
                        }
                        $card.css('border-left-color', '#16a34a');
                    }

                    // KiloCode save
                    $('#save-kilocode-key').on('click', function() {
                        var key = $('#kilocode-api-key').val().trim();
                        if (!key) { $('#kilocode-key-status').text('Please enter a key.').css('color','#dc2626'); return; }
                        $('#kilocode-key-status').text('Saving...').css('color','#6b7280');
                        var $card = $(this).closest('div[style*="border-left"]');
                        $.post(ajaxurl, {
                            action: 'kineticcopy_save_provider_key',
                            nonce: '<?php echo esc_js( wp_create_nonce( "claude_ai_settings_save" ) ); ?>',
                            provider: 'kilocode',
                            api_key: key
                        }, function(r) {
                            if (r.success) {
                                $('#kilocode-key-status').text('Key saved.').css('color','#16a34a');
                                $('#kilocode-api-key').val('');
                                kcShowSavedBadge($card);
                            } else {
                                $('#kilocode-key-status').text(r.data || 'Save failed.').css('color','#dc2626');
                            }
                        });
                    });

                    // OpenRouter save
                    $('#save-openrouter-key').on('click', function() {
                        var key = $('#openrouter-api-key').val().trim();
                        if (!key) { $('#openrouter-key-status').text('Please enter a key.').css('color','#dc2626'); return; }
                        $('#openrouter-key-status').text('Saving...').css('color','#6b7280');
                        var $card = $(this).closest('div[style*="border-left"]');
                        $.post(ajaxurl, {
                            action: 'kineticcopy_save_provider_key',
                            nonce: '<?php echo esc_js( wp_create_nonce( "claude_ai_settings_save" ) ); ?>',
                            provider: 'openrouter',
                            api_key: key
                        }, function(r) {
                            if (r.success) {
                                $('#openrouter-key-status').text('Key saved.').css('color','#16a34a');
                                $('#openrouter-api-key').val('');
                                kcShowSavedBadge($card);
                            } else {
                                $('#openrouter-key-status').text(r.data || 'Save failed.').css('color','#dc2626');
                            }
                        });
                    });
                })(jQuery);
                </script>

            </div>

            <!-- Research Settings Tab -->
            <div id="research" class="tab-content">
                <h2><?php _e( 'Research API Settings', 'claude-ai-copywriter' ); ?></h2>

                <table class="form-table">
                    <tr>
                        <th scope="row">
                            <label for="research_api_provider"><?php _e( 'Search Provider', 'claude-ai-copywriter' ); ?></label>
                        </th>
                        <td>
                            <select name="research_api_provider" id="research_api_provider" class="regular-text">
                                <option value=""><?php _e( 'None (Disable Research)', 'claude-ai-copywriter' ); ?></option>
                                <?php foreach ( $research_providers as $value => $label ) : ?>
                                    <option value="<?php echo esc_attr( $value ); ?>" <?php selected( $settings['research_api_provider'] ?? '', $value ); ?>>
                                        <?php echo esc_html( $label ); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <p class="description">
                                <?php _e( 'Choose which search API to use for research. DuckDuckGo requires no API key but has limited results.', 'claude-ai-copywriter' ); ?>
                            </p>
                        </td>
                    </tr>

                    <tr class="research-api-field google-fields">
                        <th scope="row">
                            <label for="google_search_api_key"><?php _e( 'Google API Key', 'claude-ai-copywriter' ); ?></label>
                        </th>
                        <td>
                            <input type="password" name="google_search_api_key" id="google_search_api_key" class="regular-text" value="<?php echo esc_attr( $settings['google_search_api_key'] ?? '' ); ?>" autocomplete="off">
                            <p class="description">
                                <?php printf(
                                    __( 'Get from %s', 'claude-ai-copywriter' ),
                                    '<a href="https://console.cloud.google.com/apis/credentials" target="_blank">Google Cloud Console</a>'
                                ); ?>
                            </p>
                        </td>
                    </tr>

                    <tr class="research-api-field google-fields">
                        <th scope="row">
                            <label for="google_search_cx"><?php _e( 'Google Search CX', 'claude-ai-copywriter' ); ?></label>
                        </th>
                        <td>
                            <input type="text" name="google_search_cx" id="google_search_cx" class="regular-text" value="<?php echo esc_attr( $settings['google_search_cx'] ?? '' ); ?>">
                            <p class="description">
                                <?php printf(
                                    __( 'Custom Search Engine ID from %s', 'claude-ai-copywriter' ),
                                    '<a href="https://programmablesearchengine.google.com/" target="_blank">Programmable Search Engine</a>'
                                ); ?>
                            </p>
                        </td>
                    </tr>

                    <tr class="research-api-field bing-fields">
                        <th scope="row">
                            <label for="bing_search_api_key"><?php _e( 'Bing API Key', 'claude-ai-copywriter' ); ?></label>
                        </th>
                        <td>
                            <input type="password" name="bing_search_api_key" id="bing_search_api_key" class="regular-text" value="<?php echo esc_attr( $settings['bing_search_api_key'] ?? '' ); ?>" autocomplete="off">
                            <p class="description">
                                <?php printf(
                                    __( 'Get from %s', 'claude-ai-copywriter' ),
                                    '<a href="https://www.microsoft.com/en-us/bing/apis/bing-web-search-api" target="_blank">Bing Web Search API</a>'
                                ); ?>
                            </p>
                        </td>
                    </tr>

                    <tr class="research-api-field brave-fields">
                        <th scope="row">
                            <label for="brave_search_api_key"><?php _e( 'Brave API Key', 'claude-ai-copywriter' ); ?></label>
                        </th>
                        <td>
                            <input type="password" name="brave_search_api_key" id="brave_search_api_key" class="regular-text" value="<?php echo esc_attr( $settings['brave_search_api_key'] ?? '' ); ?>" autocomplete="off">
                            <p class="description">
                                <?php printf(
                                    __( 'Get from %s', 'claude-ai-copywriter' ),
                                    '<a href="https://brave.com/search/api/" target="_blank">Brave Search API</a>'
                                ); ?>
                            </p>
                        </td>
                    </tr>

                    <tr class="research-api-field serper-fields">
                        <th scope="row">
                            <label for="serper_api_key"><?php _e( 'Serper API Key', 'claude-ai-copywriter' ); ?></label>
                        </th>
                        <td>
                            <input type="password" name="serper_api_key" id="serper_api_key" class="regular-text" value="<?php echo esc_attr( $settings['serper_api_key'] ?? '' ); ?>" autocomplete="off">
                            <p class="description">
                                <?php printf(
                                    __( 'Get a free key (2,500 searches/month) from %s', 'claude-ai-copywriter' ),
                                    '<a href="https://serper.dev" target="_blank">serper.dev</a>'
                                ); ?>
                            </p>
                        </td>
                    </tr>

                    <tr class="research-api-field perplexity-fields">
                        <th scope="row">
                            <label for="perplexity_api_key"><?php _e( 'Perplexity API Key', 'claude-ai-copywriter' ); ?></label>
                        </th>
                        <td>
                            <input type="password" name="perplexity_api_key" id="perplexity_api_key" class="regular-text" value="<?php echo esc_attr( $settings['perplexity_api_key'] ?? '' ); ?>" autocomplete="off">
                            <p class="description">
                                <?php printf(
                                    __( 'Get your key from %s', 'claude-ai-copywriter' ),
                                    '<a href="https://www.perplexity.ai/settings/api" target="_blank">Perplexity API</a>'
                                ); ?>
                            </p>
                        </td>
                    </tr>
                </table>
            </div>

            <!-- Permissions Tab -->
            <div id="permissions" class="tab-content">
                <h2><?php _e( 'User Permissions', 'claude-ai-copywriter' ); ?></h2>

                <table class="form-table">
                    <tr>
                        <th scope="row">
                            <?php _e( 'Allowed Roles', 'claude-ai-copywriter' ); ?>
                        </th>
                        <td>
                            <?php
                            $allowed_roles = $settings['allowed_roles'] ?? array( 'administrator', 'editor' );
                            foreach ( $user_roles as $role_slug => $role_name ) :
                            ?>
                                <label style="display: block; margin-bottom: 5px;">
                                    <input type="checkbox" name="allowed_roles[]" value="<?php echo esc_attr( $role_slug ); ?>" <?php checked( in_array( $role_slug, $allowed_roles ) ); ?>>
                                    <?php echo esc_html( $role_name ); ?>
                                </label>
                            <?php endforeach; ?>
                            <p class="description">
                                <?php _e( 'Select which user roles can access KineticCopy features.', 'claude-ai-copywriter' ); ?>
                            </p>
                        </td>
                    </tr>
                </table>
            </div>

            <!-- Security Tab -->
            <div id="security" class="tab-content">
                <h2><?php _e( 'Security & Encryption', 'claude-ai-copywriter' ); ?></h2>

                <table class="form-table">
                    <tr>
                        <th scope="row">
                            <?php _e( 'Encryption Status', 'claude-ai-copywriter' ); ?>
                        </th>
                        <td>
                            <p><strong><?php _e( 'Encryption Method:', 'claude-ai-copywriter' ); ?></strong> AES-256-CTR</p>
                            <p><strong><?php _e( 'Key Storage Location:', 'claude-ai-copywriter' ); ?></strong> <?php echo esc_html( $encryption_status['location'] ); ?></p>

                            <?php if ( ! $encryption_status['secure'] ) : ?>
                                <div class="notice notice-warning inline">
                                    <p><?php echo esc_html( $encryption_status['recommendation'] ); ?></p>
                                    <details>
                                        <summary style="cursor: pointer; color: #2271b1;"><?php _e( 'Show wp-config.php snippet', 'claude-ai-copywriter' ); ?></summary>
                                        <pre style="background: #f0f0f1; padding: 10px; margin-top: 10px; overflow-x: auto;"><?php echo esc_html( Claude_AI_Copywriter_Encryption::generate_config_snippet() ); ?></pre>
                                    </details>
                                </div>
                            <?php else : ?>
                                <div class="notice notice-success inline">
                                    <p><?php _e( 'Encryption keys are stored securely in wp-config.php', 'claude-ai-copywriter' ); ?></p>
                                </div>
                            <?php endif; ?>
                        </td>
                    </tr>

                    <tr>
                        <th scope="row">
                            <?php _e( 'Data Storage', 'claude-ai-copywriter' ); ?>
                        </th>
                        <td>
                            <p><?php _e( 'The following data is stored in your WordPress database:', 'claude-ai-copywriter' ); ?></p>
                            <ul style="list-style: disc; margin-left: 20px;">
                                <li><?php _e( 'Encrypted API keys (AES-256 with unique IVs)', 'claude-ai-copywriter' ); ?></li>
                                <li><?php _e( 'Tone templates and personas', 'claude-ai-copywriter' ); ?></li>
                                <li><?php _e( 'Saved content snippets', 'claude-ai-copywriter' ); ?></li>
                                <li><?php _e( 'Content analysis cache (expires based on cache duration)', 'claude-ai-copywriter' ); ?></li>
                            </ul>
                            <p class="description">
                                <?php _e( 'All sensitive data is encrypted. Cache data expires automatically. Use the uninstall feature to remove all data when deactivating the plugin.', 'claude-ai-copywriter' ); ?>
                            </p>
                        </td>
                    </tr>
                </table>
            </div>

            <!-- License Tab -->
            <div id="license" class="tab-content">
                <h2><?php _e( 'KineticCopy Premium License', 'claude-ai-copywriter' ); ?></h2>

                <?php
                $lic_is_premium   = Claude_AI_Copywriter_License_Manager::is_premium();
                $lic_tier         = Claude_AI_Copywriter_License_Manager::get_tier();
                $lic_masked_key   = Claude_AI_Copywriter_License_Manager::get_masked_key();
                $lic_status       = Claude_AI_Copywriter_License_Manager::get_cached_status();
                $lic_error        = get_option( Claude_AI_Copywriter_License_Manager::OPT_LICENSE_ERROR, '' );
                $lic_checked_at   = (int) get_option( Claude_AI_Copywriter_License_Manager::OPT_LICENSE_CHECKED, 0 );
                $lic_nonce        = wp_create_nonce( 'kineticcopy_license_nonce' );
                // True only when a real license key is stored and validated - NOT just trial
                $lic_has_real_key = ! empty( $lic_masked_key );
                $lic_is_trial     = Claude_AI_Copywriter_License_Manager::is_trial_active();
                $lic_trial_days   = Claude_AI_Copywriter_License_Manager::get_trial_days_remaining();
                ?>

                <!-- Current status card -->
                <div style="padding:20px; background:#ffffff; border:1px solid #e5e7eb; border-left:4px solid <?php echo $lic_is_premium ? '#16a34a' : '#9ca3af'; ?>; border-radius:5px; max-width:720px; margin-bottom:24px;">
                    <div style="display:flex; align-items:center; gap:10px; margin-bottom:8px;">
                        <span style="font-size:20px;"><?php echo $lic_is_premium ? '✅' : '🔒'; ?></span>
                        <h3 style="margin:0; font-size:16px; color:#111827;">
                            <?php
                            if ( $lic_has_real_key && $lic_is_premium ) {
                                echo sprintf( __( 'Premium Active - %s tier', 'claude-ai-copywriter' ), esc_html( ucfirst( $lic_tier ) ) );
                            } elseif ( $lic_is_trial ) {
                                echo sprintf(
                                    _n( 'Trial Active - %d day remaining', 'Trial Active - %d days remaining', $lic_trial_days, 'claude-ai-copywriter' ),
                                    $lic_trial_days
                                );
                            } else {
                                echo __( 'Free Version', 'claude-ai-copywriter' );
                            }
                            ?>
                        </h3>
                    </div>

                    <?php if ( $lic_has_real_key && $lic_is_premium ) : ?>
                        <p style="margin:0 0 8px; font-size:13px; color:#374151;">
                            <?php printf( __( 'Key: %s', 'claude-ai-copywriter' ), '<code>' . esc_html( $lic_masked_key ) . '</code>' ); ?>
                        </p>
                        <?php if ( ! empty( $lic_status['activations_used'] ) ) : ?>
                            <p style="margin:0 0 8px; font-size:12px; color:#6b7280;">
                                <?php printf(
                                    __( 'Activations: %d of %d used', 'claude-ai-copywriter' ),
                                    (int) $lic_status['activations_used'],
                                    (int) ( $lic_status['activations_max'] ?? 3 )
                                ); ?>
                            </p>
                        <?php endif; ?>
                        <?php if ( ! empty( $lic_status['updates_until'] ) ) : ?>
                            <p style="margin:0 0 8px; font-size:12px; color:#6b7280;">
                                <?php printf( __( 'Updates until: %s', 'claude-ai-copywriter' ), esc_html( date_i18n( get_option( 'date_format' ), strtotime( $lic_status['updates_until'] ) ) ) ); ?>
                            </p>
                        <?php endif; ?>
                        <?php if ( $lic_checked_at ) : ?>
                            <p style="margin:0; font-size:11px; color:#9ca3af;">
                                <?php printf( __( 'Last verified: %s', 'claude-ai-copywriter' ), esc_html( human_time_diff( $lic_checked_at, time() ) . ' ago' ) ); ?>
                            </p>
                        <?php endif; ?>
                    <?php elseif ( $lic_is_trial ) : ?>
                        <p style="margin:0; font-size:13px; color:#374151;">
                            <?php _e( 'You\'re using the 7-day free trial. Enter your license key below to activate your purchased plan.', 'claude-ai-copywriter' ); ?>
                        </p>
                    <?php else : ?>
                        <p style="margin:0; font-size:13px; color:#6b7280;">
                            <?php _e( 'Enter your license key below to unlock premium features: calendar sync, campaigns, drag-and-drop editing, multi-channel publishing, and more.', 'claude-ai-copywriter' ); ?>
                        </p>
                    <?php endif; ?>
                </div>

                <?php if ( $lic_error ) : ?>
                    <div style="margin-bottom:16px; padding:10px 14px; background:#fee2e2; border:1px solid #fca5a5; border-radius:6px; color:#991b1b; font-size:12px; max-width:720px;">
                        <?php echo esc_html( $lic_error ); ?>
                    </div>
                <?php endif; ?>

                <!-- Activate / Deactivate -->
                <div style="padding:20px; background:#ffffff; border:1px solid #e5e7eb; border-radius:5px; max-width:720px;">
                    <?php if ( ! $lic_has_real_key ) : ?>
                        <table class="form-table" style="margin:0;">
                            <tr>
                                <th scope="row" style="padding:6px 0; width:160px; font-size:13px;">
                                    <label for="kc_license_key"><?php _e( 'License Key', 'claude-ai-copywriter' ); ?></label>
                                </th>
                                <td style="padding:6px 0;">
                                    <input type="text" id="kc_license_key" class="regular-text"
                                        placeholder="KB-XXXX-XXXX-XXXX-XXXX"
                                        autocomplete="off"
                                        style="font-family:monospace; letter-spacing:1px;" />
                                    <p class="description" style="margin-top:4px;">
                                        <?php _e( 'Enter your KineticCopy Premium license key. You received this via email after purchase.', 'claude-ai-copywriter' ); ?>
                                    </p>
                                </td>
                            </tr>
                        </table>
                        <div style="margin-top:12px; display:flex; gap:10px; align-items:center;">
                            <button type="button" id="kc-activate-license" class="button button-primary">
                                🔑 <?php _e( 'Activate License', 'claude-ai-copywriter' ); ?>
                            </button>
                            <span id="kc-license-msg" style="font-size:12px; color:#6b7280;"></span>
                        </div>
                    <?php else : ?>
                        <div style="display:flex; gap:10px; align-items:center; flex-wrap:wrap;">
                            <button type="button" id="kc-check-license" class="button button-secondary">
                                ↻ <?php _e( 'Re-verify License', 'claude-ai-copywriter' ); ?>
                            </button>
                            <button type="button" id="kc-deactivate-license" class="button" style="color:#dc2626; border-color:#dc2626;">
                                <?php _e( 'Deactivate License', 'claude-ai-copywriter' ); ?>
                            </button>
                            <span id="kc-license-msg" style="font-size:12px; color:#6b7280;"></span>
                        </div>
                    <?php endif; ?>
                </div>

                <!-- Premium features list -->
                <?php if ( $lic_is_premium && ! empty( $lic_status['features'] ) ) : ?>
                    <div style="margin-top:20px; padding:16px 20px; background:#f0fdf4; border:1px solid #bbf7d0; border-radius:5px; max-width:720px;">
                        <h4 style="margin:0 0 8px; font-size:13px; color:#166534;"><?php _e( 'Active Premium Features', 'claude-ai-copywriter' ); ?></h4>
                        <div style="display:flex; flex-wrap:wrap; gap:8px;">
                            <?php foreach ( $lic_status['features'] as $feat ) : ?>
                                <span style="display:inline-block; padding:3px 10px; background:#dcfce7; border-radius:4px; font-size:12px; color:#166534;">
                                    ✓ <?php echo esc_html( str_replace( '_', ' ', ucfirst( $feat ) ) ); ?>
                                </span>
                            <?php endforeach; ?>
                        </div>
                    </div>
                <?php endif; ?>

                <!-- Activation Info (this site only - full management at licensing portal) -->
                <?php if ( $lic_has_real_key && $lic_is_premium ) : ?>
                    <div style="margin-top:20px; padding:16px 20px; background:#ffffff; border:1px solid #e5e7eb; border-left:4px solid #6366f1; border-radius:5px; max-width:720px;">
                        <h4 style="margin:0 0 8px; font-size:13px; color:#111827;">
                            <?php _e( 'This Site', 'claude-ai-copywriter' ); ?>
                        </h4>
                        <p style="margin:0 0 4px; font-size:12px; color:#374151;">
                            <code style="font-size:11px; background:#f3f4f6; padding:2px 6px; border-radius:3px;"><?php echo esc_html( home_url() ); ?></code>
                            <span style="color:#16a34a; font-weight:500; margin-left:6px;">✓ <?php _e( 'Activated', 'claude-ai-copywriter' ); ?></span>
                        </p>
                        <?php if ( ! empty( $lic_status['activations_used'] ) && ! empty( $lic_status['activations_max'] ) ) : ?>
                            <p style="margin:4px 0 0; font-size:11px; color:#9ca3af;">
                                <?php printf(
                                    __( 'Using %d of %d activation slots.', 'claude-ai-copywriter' ),
                                    (int) $lic_status['activations_used'],
                                    (int) $lic_status['activations_max']
                                ); ?>
                                <?php if ( (int) $lic_status['activations_max'] > 1 ) : ?>
                                    <a href="https://licensing.kineticbrain.ai" target="_blank" style="color:#4338ca; text-decoration:none; margin-left:4px;">
                                        <?php _e( 'Manage all sites →', 'claude-ai-copywriter' ); ?>
                                    </a>
                                <?php endif; ?>
                            </p>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>

                <!-- Agency: Manage All Activations (only shown when activations_max > 1) -->
                <?php if ( $lic_has_real_key && $lic_is_premium && (int) ( $lic_status['activations_max'] ?? 1 ) > 1 ) : ?>
                    <div id="kc-manage-activations" style="margin-top:20px; padding:20px; background:#ffffff; border:1px solid #e5e7eb; border-radius:5px; max-width:720px;">
                        <div style="display:flex; align-items:center; justify-content:space-between; margin-bottom:12px;">
                            <h4 style="margin:0; font-size:13px; color:#111827;">
                                🖥️ <?php _e( 'All Activated Sites', 'claude-ai-copywriter' ); ?>
                                <span id="kc-slot-counter" style="font-weight:400; color:#6b7280; font-size:12px; margin-left:8px;">
                                    (<?php printf(
                                        __( '%d of %d slots used', 'claude-ai-copywriter' ),
                                        (int) ( $lic_status['activations_used'] ?? 0 ),
                                        (int) ( $lic_status['activations_max'] ?? 3 )
                                    ); ?>)
                                </span>
                            </h4>
                            <button type="button" id="kc-load-sites" class="button button-secondary" style="font-size:12px;">
                                ↺ <?php _e( 'Load Sites', 'claude-ai-copywriter' ); ?>
                            </button>
                        </div>
                        <div id="kc-activations-list" style="font-size:12px; color:#6b7280; min-height:32px;">
                            <?php _e( 'Click "Load Sites" to see all activated sites.', 'claude-ai-copywriter' ); ?>
                        </div>
                    </div>
                <?php endif; ?>
            </div>

            <script>
            (function($){
                var licNonce       = '<?php echo esc_js( $lic_nonce ); ?>';
                var licCurrentSite = '<?php echo esc_js( home_url() ); ?>';
                var licSlotsMax    = <?php echo (int) ( $lic_status['activations_max'] ?? 3 ); ?>;
                function licMsg(msg, color) { $('#kc-license-msg').text(msg).css('color', color||'#6b7280'); }

                $('#kc-activate-license').on('click', function() {
                    var key = $('#kc_license_key').val().trim();
                    if (!key) { licMsg('Please enter a license key.','#dc2626'); return; }
                    var $b = $(this).prop('disabled', true);
                    licMsg('Validating...');
                    $.post(ajaxurl, { action:'kineticcopy_activate_license', nonce:licNonce, license_key:key }, function(r){
                        if (r.success) {
                            licMsg('✓ ' + r.data.message, '#16a34a');
                            setTimeout(function(){ location.reload(); }, 1200);
                        } else {
                            licMsg(r.data, '#dc2626');
                        }
                    }).fail(function(){ licMsg('Connection error.','#dc2626'); })
                      .always(function(){ $b.prop('disabled', false); });
                });

                $('#kc-deactivate-license').on('click', function() {
                    if (!confirm('<?php echo esc_js( __( 'Deactivate your license? You can re-activate later.', 'claude-ai-copywriter' ) ); ?>')) return;
                    var $b = $(this).prop('disabled', true);
                    licMsg('Deactivating...');
                    $.post(ajaxurl, { action:'kineticcopy_deactivate_license', nonce:licNonce }, function(r){
                        if (r.success) {
                            licMsg('License deactivated.', '#6b7280');
                            setTimeout(function(){ location.reload(); }, 1000);
                        } else { licMsg(r.data, '#dc2626'); }
                    }).always(function(){ $b.prop('disabled', false); });
                });

                $('#kc-check-license').on('click', function() {
                    var $b = $(this).prop('disabled', true).text('Checking...');
                    licMsg('');
                    $.post(ajaxurl, { action:'kineticcopy_check_license', nonce:licNonce }, function(r){
                        if (r.success) { licMsg('✓ ' + r.data.message, '#16a34a'); }
                        else { licMsg(r.data, '#dc2626'); }
                    }).fail(function(){ licMsg('Connection error.','#dc2626'); })
                      .always(function(){ $b.prop('disabled', false).text('↻ Re-verify License'); });
                });

                // Agency: load all activated sites
                $('#kc-load-sites').on('click', function() {
                    var $b = $(this).prop('disabled', true).text('Loading...');
                    $('#kc-activations-list').html('<span style="color:#9ca3af;">Fetching sites…</span>');
                    $.post(ajaxurl, { action:'kineticcopy_list_activations', nonce:licNonce }, function(r){
                        if (r.success && r.data.activations) {
                            var sites = r.data.activations;
                            licSlotsMax = r.data.activations_max || licSlotsMax;
                            if (!sites.length) {
                                $('#kc-activations-list').html('<span style="color:#9ca3af;">No activations found.</span>');
                                return;
                            }
                            var html = '<table style="width:100%; border-collapse:collapse;">'
                                     + '<thead><tr>'
                                     + '<th style="text-align:left; padding:6px 8px; border-bottom:1px solid #e5e7eb; color:#374151; font-weight:600;">Site URL</th>'
                                     + '<th style="text-align:left; padding:6px 8px; border-bottom:1px solid #e5e7eb; color:#374151; font-weight:600;">Activated</th>'
                                     + '<th style="padding:6px 8px; border-bottom:1px solid #e5e7eb;"></th>'
                                     + '</tr></thead><tbody>';
                            $.each(sites, function(i, site) {
                                var dateStr = site.activated_at ? new Date(site.activated_at).toLocaleDateString() : ' - ';
                                var sNorm = site.site_url.replace(/^https?:\/\/(www\.)?/, '').replace(/\/$/, '');
                                var cNorm = licCurrentSite.replace(/^https?:\/\/(www\.)?/, '').replace(/\/$/, '');
                                var isCurrent = (sNorm === cNorm);
                                html += '<tr style="border-bottom:1px solid #f3f4f6;">'
                                      + '<td style="padding:6px 8px;"><code style="font-size:11px; background:#f3f4f6; padding:2px 5px; border-radius:3px;">' + site.site_url + '</code>'
                                      + (isCurrent ? ' <span style="color:#16a34a; font-size:10px; font-weight:600;">✓ this site</span>' : '') + '</td>'
                                      + '<td style="padding:6px 8px; color:#6b7280;">' + dateStr + '</td>'
                                      + '<td style="padding:6px 8px; text-align:right;">'
                                      + (isCurrent ? '<span style="font-size:11px; color:#9ca3af;">current</span>'
                                          : '<button type="button" class="button kc-remove-site" data-site="' + site.site_url + '" style="font-size:11px; color:#dc2626; border-color:#dc2626; height:auto; padding:2px 8px;">Remove</button>')
                                      + '</td></tr>';
                            });
                            html += '</tbody></table>';
                            $('#kc-activations-list').html(html);
                            $('#kc-slot-counter').text('(' + r.data.activations_used + ' of ' + licSlotsMax + ' slots used)');
                        } else {
                            $('#kc-activations-list').html('<span style="color:#dc2626;">' + (r.data || 'Error fetching sites.') + '</span>');
                        }
                    }).fail(function(){ $('#kc-activations-list').html('<span style="color:#dc2626;">Connection error.</span>'); })
                      .always(function(){ $b.prop('disabled', false).text('↺ Load Sites'); });
                });

                // Agency: remove a specific site activation
                $(document).on('click', '.kc-remove-site', function() {
                    var siteUrl = $(this).data('site');
                    if (!confirm('Remove activation for:\n' + siteUrl + '\n\nThis frees up a slot - you can reactivate later.')) return;
                    var $btn = $(this).prop('disabled', true).text('Removing…');
                    $.post(ajaxurl, { action:'kineticcopy_remove_activation', nonce:licNonce, site_url:siteUrl }, function(r){
                        if (r.success) {
                            $btn.closest('tr').fadeOut(300, function(){ $(this).remove(); });
                            if (r.data.activations_used !== undefined) {
                                $('#kc-slot-counter').text('(' + r.data.activations_used + ' of ' + licSlotsMax + ' slots used)');
                            }
                        } else {
                            $btn.prop('disabled', false).text('Remove');
                            alert(r.data || 'Error removing site.');
                        }
                    }).fail(function(){ $btn.prop('disabled', false).text('Remove'); alert('Connection error.'); });
                });
            })(jQuery);
            </script>

            <!-- Upgrade Tab -->
            <div id="upgrade" class="tab-content">
                <?php
                $up_is_premium = Claude_AI_Copywriter_License_Manager::is_premium();
                $up_tier       = strtolower( Claude_AI_Copywriter_License_Manager::get_tier() );
                $up_plans = [
                    'solo'       => [ 'name'=>'Solo',       'emoji'=>'🧑‍💻', 'annual'=>79,  'ltd'=>199, 'sites'=>'1',         'popular'=>false ],
                    'studio'     => [ 'name'=>'Studio',     'emoji'=>'🏢',  'annual'=>199, 'ltd'=>399, 'sites'=>'3',         'popular'=>true  ],
                    'agency'     => [ 'name'=>'Agency',     'emoji'=>'🚀',  'annual'=>349, 'ltd'=>599, 'sites'=>'25',        'popular'=>false ],
                    'enterprise' => [ 'name'=>'Enterprise', 'emoji'=>'🏛️',  'annual'=>599, 'ltd'=>999, 'sites'=>'Unlimited', 'popular'=>false ],
                ];
                // All tiers get the same features. Only site count differs.
                // Enterprise adds dedicated support channel.
                $up_shared_features = [
                    'Writing DNA profiling',
                    '43 copywriting formats',
                    'Unlimited generations (BYOK)',
                    'Brain AI Assistant',
                    'Rewrite with Tone',
                    'AEO/GEO schema markup',
                    'KineticLaunch brand context + Calendar Sync',
                    'Content Library and pinned posts',
                ];
                $up_features = [
                    'solo'       => array_merge( $up_shared_features, [ 'Email support', '1 site activation' ] ),
                    'studio'     => array_merge( $up_shared_features, [ 'Email support', '3 site activations' ] ),
                    'agency'     => array_merge( $up_shared_features, [ 'Priority support', '25 site activations' ] ),
                    'enterprise' => array_merge( $up_shared_features, [ 'Dedicated support channel', 'Unlimited site activations' ] ),
                ];
                $up_tier_order  = [ 'solo'=>0, 'studio'=>1, 'agency'=>2, 'enterprise'=>3 ];
                $up_current_idx = $up_tier_order[ $up_tier ] ?? -1;
                $up_buy_links   = [
                    'solo'       => 'https://buy.stripe.com/aFabJ030z7nn2o5ae9gYU04',
                    'studio'     => 'https://buy.stripe.com/8x2dR8at1fTT4wd0DzgYU05',
                    'agency'     => 'https://buy.stripe.com/eVq4gybx5ePP9Qx5XTgYU06',
                    'enterprise' => 'https://buy.stripe.com/fZu4gy0SrcHHbYFfytgYU07',
                ];
                $up_ltd_links   = [
                    'solo'       => 'https://buy.stripe.com/7sYeVc6cL0YZ6El1HDgYU00',
                    'studio'     => 'https://buy.stripe.com/3cI28q58H9vvfaR0DzgYU01',
                    'agency'     => 'https://buy.stripe.com/28E6oGfNldLL1k13PLgYU02',
                    'enterprise' => 'https://buy.stripe.com/4gMeVc1Wv4bb3s94TPgYU03',
                ];
                ?>

                <?php if ( $up_is_premium ) : ?>
                    <div style="display:flex; gap:16px; align-items:flex-start; margin-bottom:24px; flex-wrap:wrap;">
                        <div style="flex:1; min-width:240px; padding:16px 20px; background:#f0fdf4; border:1px solid #bbf7d0; border-radius:3px; display:flex; align-items:center; gap:12px;">
                            <span style="font-size:24px;">✅</span>
                            <div>
                                <strong style="font-size:14px; color:#166534;">You're on KineticCopy <?php echo esc_html( ucfirst( $up_tier ) ); ?></strong>
                                <p style="margin:2px 0 0; font-size:12px; color:#374151;">Manage your license at <a href="https://licensing.kineticbrain.ai" target="_blank" style="color:#4338ca;">licensing.kineticbrain.ai</a></p>
                            </div>
                        </div>
                        <div style="flex-shrink:0; max-width:300px; padding:12px 16px; background:#eff6ff; border:1px solid #bfdbfe; border-radius:3px; display:flex; gap:10px; align-items:flex-start;">
                            <span style="font-size:16px; flex-shrink:0;">💡</span>
                            <div>
                                <strong style="font-size:12px; color:#1e3a8a; display:block; margin-bottom:2px;"><?php _e( 'Already a KineticLaunch subscriber?', 'claude-ai-copywriter' ); ?></strong>
                                <p style="margin:0; font-size:11px; color:#374151; line-height:1.4;">
                                    <?php _e( 'Launch T2+ includes KineticCopy Premium. Connect in the', 'claude-ai-copywriter' ); ?>
                                    <a href="#" class="kc-tab-link" data-tab="license" style="color:#2563eb;"><?php _e( 'License tab', 'claude-ai-copywriter' ); ?></a>
                                    <?php _e( 'to auto-unlock.', 'claude-ai-copywriter' ); ?>
                                </p>
                            </div>
                        </div>
                    </div>
                <?php else : ?>
                    <h2 style="margin:0 0 4px; font-size:20px; color:#111827;"><?php _e( 'Upgrade to KineticCopy Premium', 'claude-ai-copywriter' ); ?></h2>
                    <p style="margin:0 0 24px; font-size:13px; color:#6b7280;"><?php _e( 'Every feature included in every tier. Pick the plan that fits your site count. Bring your own Anthropic API key - no per-generation fees from us.', 'claude-ai-copywriter' ); ?></p>
                <?php endif; ?>

                <!-- Plan cards grid -->
                <div style="display:grid; grid-template-columns:repeat(auto-fit, minmax(200px, 1fr)); gap:16px; margin-bottom:24px;">

                <!-- Free tier card -->
                <div style="padding:20px; background:<?php echo ! $up_is_premium ? '#f0f9ff' : '#fafafa'; ?>; border:1px solid <?php echo ! $up_is_premium ? '#0284c7' : '#e5e7eb'; ?>; border-radius:10px; position:relative; display:flex; flex-direction:column;">
                    <?php if ( ! $up_is_premium ) : ?>
                        <span style="position:absolute; top:-10px; left:50%; transform:translateX(-50%); background:#0284c7; color:#fff; font-size:10px; font-weight:700; padding:2px 10px; border-radius:20px; white-space:nowrap;">YOUR PLAN</span>
                    <?php endif; ?>
                    <div style="font-size:22px; margin-bottom:4px;">🆓</div>
                    <div style="font-size:15px; font-weight:700; color:#111827; margin-bottom:2px;"><?php _e( 'Free', 'claude-ai-copywriter' ); ?></div>
                    <div style="font-size:11px; color:#6b7280; margin-bottom:12px;"><?php _e( '1 site', 'claude-ai-copywriter' ); ?></div>
                    <div style="margin-bottom:4px;"><span style="font-size:22px; font-weight:800; color:#111827;">$0</span><span style="font-size:11px; color:#6b7280;">/forever</span></div>
                    <div style="font-size:11px; color:transparent; margin-bottom:14px;">-</div>
                    <ul style="margin:0 0 16px; padding:0; list-style:none; flex:1;">
                        <li style="font-size:11px; color:#374151; padding:2px 0; display:flex; gap:6px;"><span style="color:#16a34a; flex-shrink:0;">✓</span><?php _e( 'Core copywriting formats', 'claude-ai-copywriter' ); ?></li>
                        <li style="font-size:11px; color:#374151; padding:2px 0; display:flex; gap:6px;"><span style="color:#16a34a; flex-shrink:0;">✓</span><?php _e( 'Content Library', 'claude-ai-copywriter' ); ?></li>
                        <li style="font-size:11px; color:#374151; padding:2px 0; display:flex; gap:6px;"><span style="color:#16a34a; flex-shrink:0;">✓</span><?php _e( 'BRAIN AI assistant', 'claude-ai-copywriter' ); ?></li>
                        <li style="font-size:11px; color:#374151; padding:2px 0; display:flex; gap:6px;"><span style="color:#16a34a; flex-shrink:0;">✓</span><?php _e( 'Bring your own API key', 'claude-ai-copywriter' ); ?></li>
                        <li style="font-size:11px; color:#9ca3af; padding:2px 0; display:flex; gap:6px;"><span style="color:#d1d5db; flex-shrink:0;">-</span><?php _e( 'Writing DNA profiling', 'claude-ai-copywriter' ); ?></li>
                        <li style="font-size:11px; color:#9ca3af; padding:2px 0; display:flex; gap:6px;"><span style="color:#d1d5db; flex-shrink:0;">-</span><?php _e( 'All 43 formats', 'claude-ai-copywriter' ); ?></li>
                        <li style="font-size:11px; color:#9ca3af; padding:2px 0; display:flex; gap:6px;"><span style="color:#d1d5db; flex-shrink:0;">-</span><?php _e( 'KineticLaunch sync', 'claude-ai-copywriter' ); ?></li>
                        <li style="font-size:11px; color:#9ca3af; padding:2px 0; display:flex; gap:6px;"><span style="color:#d1d5db; flex-shrink:0;">-</span><?php _e( 'AEO/GEO schema markup', 'claude-ai-copywriter' ); ?></li>
                    </ul>
                    <?php if ( ! $up_is_premium ) : ?>
                        <span style="display:block; text-align:center; padding:8px; background:#e0f2fe; border-radius:6px; font-size:12px; color:#0369a1; font-weight:600;"><?php _e( 'Active', 'claude-ai-copywriter' ); ?></span>
                    <?php else : ?>
                        <span style="display:block; text-align:center; padding:8px; background:#f3f4f6; border-radius:6px; font-size:11px; color:#9ca3af;"><?php _e( 'Included', 'claude-ai-copywriter' ); ?></span>
                    <?php endif; ?>
                </div>

                <?php foreach ( $up_plans as $plan_key => $plan ) :
                    $plan_idx    = $up_tier_order[ $plan_key ] ?? 0;
                    $is_current  = ( $up_is_premium && $plan_key === $up_tier );
                    $is_upgrade  = ( $up_is_premium && $plan_idx > $up_current_idx );
                    $border_col  = $is_current ? '#16a34a' : ( $plan['popular'] ? '#7c3aed' : '#e5e7eb' );
                    $bg_col      = $is_current ? '#f0fdf4' : ( $plan['popular'] ? '#faf5ff' : '#ffffff' );
                ?>
                    <div style="padding:20px; background:<?php echo $bg_col; ?>; border:1px solid <?php echo $border_col; ?>; border-radius:10px; position:relative; display:flex; flex-direction:column;">
                        <?php if ( $plan['popular'] && ! $is_current ) : ?>
                            <span style="position:absolute; top:-10px; left:50%; transform:translateX(-50%); background:#7c3aed; color:#fff; font-size:10px; font-weight:700; padding:2px 10px; border-radius:20px; white-space:nowrap; letter-spacing:.5px;">MOST POPULAR</span>
                        <?php endif; ?>
                        <?php if ( $is_current ) : ?>
                            <span style="position:absolute; top:-10px; left:50%; transform:translateX(-50%); background:#16a34a; color:#fff; font-size:10px; font-weight:700; padding:2px 10px; border-radius:20px; white-space:nowrap;">YOUR PLAN</span>
                        <?php endif; ?>
                        <div style="font-size:22px; margin-bottom:4px;"><?php echo $plan['emoji']; ?></div>
                        <div style="font-size:15px; font-weight:700; color:#111827; margin-bottom:2px;"><?php echo esc_html( $plan['name'] ); ?></div>
                        <div style="font-size:11px; color:#6b7280; margin-bottom:12px;"><?php echo esc_html( $plan['sites'] ); ?> site<?php echo $plan['sites']==='1' ? '' : 's'; ?></div>
                        <div style="margin-bottom:4px;">
                            <span style="font-size:22px; font-weight:800; color:#111827;">$<?php echo $plan['annual']; ?></span>
                            <span style="font-size:11px; color:#6b7280;">/yr</span>
                        </div>
                        <div style="font-size:11px; color:#9ca3af; margin-bottom:14px;">or $<?php echo $plan['ltd']; ?> one-time</div>
                        <ul style="margin:0 0 16px; padding:0; list-style:none; flex:1;">
                        <?php foreach ( $up_features[ $plan_key ] as $feat ) : ?>
                            <li style="font-size:11px; color:#374151; padding:2px 0; display:flex; gap:6px;">
                                <span style="color:#16a34a; flex-shrink:0;">✓</span><?php echo esc_html( $feat ); ?>
                            </li>
                        <?php endforeach; ?>
                        </ul>
                        <?php if ( $is_current ) : ?>
                            <span style="display:block; text-align:center; padding:8px; background:#dcfce7; border-radius:6px; font-size:12px; color:#166534; font-weight:600;">Active</span>
                        <?php elseif ( ! $up_is_premium || $is_upgrade ) : ?>
                            <a href="<?php echo esc_url( $up_buy_links[ $plan_key ] ); ?>" target="_blank"
                               style="display:block; text-align:center; padding:8px 12px; background:<?php echo $plan['popular'] ? '#7c3aed' : '#1d4ed8'; ?>; color:#fff; border-radius:6px; font-size:12px; font-weight:600; text-decoration:none; margin-bottom:6px;">
                                <?php echo $is_upgrade ? __( 'Upgrade - Annual →', 'claude-ai-copywriter' ) : __( 'Get Started - Annual →', 'claude-ai-copywriter' ); ?>
                            </a>
                            <a href="<?php echo esc_url( $up_ltd_links[ $plan_key ] ); ?>" target="_blank"
                               style="display:block; text-align:center; padding:5px 12px; background:transparent; color:#6b7280; border:1px solid #e5e7eb; border-radius:6px; font-size:11px; font-weight:500; text-decoration:none;">
                                <?php _e( 'Lifetime deal (one-time) →', 'claude-ai-copywriter' ); ?>
                            </a>
                        <?php else : ?>
                            <span style="display:block; text-align:center; padding:8px; background:#f3f4f6; border-radius:6px; font-size:11px; color:#9ca3af;">Lower tier</span>
                        <?php endif; ?>
                    </div>
                <?php endforeach; ?>
                </div>

                <?php if ( ! $up_is_premium ) : ?>
                <!-- KineticLaunch auto-unlock notice (non-premium: show below cards) -->
                <div style="padding:14px 18px; background:#eff6ff; border:1px solid #bfdbfe; border-radius:3px; display:flex; gap:12px; align-items:flex-start;">
                    <span style="font-size:20px; flex-shrink:0;">💡</span>
                    <div>
                        <strong style="font-size:13px; color:#1e3a8a;"><?php _e( 'Already a KineticLaunch subscriber?', 'claude-ai-copywriter' ); ?></strong>
                        <p style="margin:4px 0 0; font-size:12px; color:#374151;">
                            <?php _e( 'KineticLaunch T2 Launch+ plans include KineticCopy Premium at no extra cost. Connect your KineticLaunch account in the', 'claude-ai-copywriter' ); ?>
                            <a href="#" class="kc-tab-link" data-tab="license" style="color:#2563eb;"><?php _e( 'License tab', 'claude-ai-copywriter' ); ?></a>
                            <?php _e( 'to auto-unlock.', 'claude-ai-copywriter' ); ?>
                        </p>
                    </div>
                </div>
                <?php endif; ?>

                <!-- KineticLaunch cross-promo (gated by option - flip kineticcopy_show_launch_promo to 1 when ready) -->
                <?php if ( get_option( 'kineticcopy_show_launch_promo', false ) ) : ?>
                <div style="max-width:760px; margin-top:20px; padding:20px 24px; background:linear-gradient(135deg, #fef9c3 0%, #fef3c7 50%, #fff7ed 100%); border:1px solid #fbbf24; border-radius:10px; display:flex; gap:16px; align-items:center;">
                    <div style="flex-shrink:0; font-size:32px;">&#x26A1;</div>
                    <div style="flex:1;">
                        <strong style="font-size:15px; color:#1c1917; display:block; margin-bottom:4px;"><?php _e( 'Get the full brand strategy pipeline', 'claude-ai-copywriter' ); ?></strong>
                        <p style="margin:0 0 10px; font-size:12px; color:#44403c; line-height:1.5;">
                            <?php _e( 'KineticLaunch is the all-in-one launch strategy platform that powers KineticCopy. Go from idea to validated brand, go-to-market strategy, and marketing calendar - with AI doing the heavy lifting. Launch subscribers get KineticCopy Premium included.', 'claude-ai-copywriter' ); ?>
                        </p>
                        <a href="https://launch.kineticbrain.ai" target="_blank"
                           style="display:inline-block; padding:8px 18px; background:#1c1917; color:#fef9c3; border-radius:6px; font-size:13px; font-weight:600; text-decoration:none;">
                            <?php _e( 'Learn about KineticLaunch →', 'claude-ai-copywriter' ); ?>
                        </a>
                    </div>
                </div>
                <?php endif; ?>

            </div>

            <!-- Manual Tab -->
            <div id="manual" class="tab-content" style="padding:0 !important;">

                <?php
                /* ── Manual sections: icon, title, group, breadcrumb_group, when_to_use, tip, link, steps ── */
                $settings_url = admin_url( 'admin.php?page=kineticcopy-settings' );
                $studio_url   = admin_url( 'admin.php?page=kineticcopy' );
                $library_url  = admin_url( 'admin.php?page=kineticcopy-library' );
                $cal_url      = admin_url( 'admin.php?page=kineticcopy-calendar' );
                $brand_url    = admin_url( 'admin.php?page=kineticcopy-brand' );

                $sections = array(
                    array(
                        'icon'  => '🚀',
                        'group' => __( 'Getting Started', 'claude-ai-copywriter' ),
                        'title' => __( 'Add Your API Key', 'claude-ai-copywriter' ),
                        'link'  => $settings_url . '&tab=api',
                        'when_to_use' => array(
                            __( 'First time setting up KineticCopy', 'claude-ai-copywriter' ),
                            __( 'Replacing an expired or rotated Anthropic key', 'claude-ai-copywriter' ),
                            __( 'Troubleshooting "no API key" errors', 'claude-ai-copywriter' ),
                        ),
                        'tip'   => __( 'You need an Anthropic API account (console.anthropic.com) - separate from a Claude.ai subscription. New accounts receive a small free credit. Your key is stored encrypted; KineticCopy never exposes it in plain text.', 'claude-ai-copywriter' ),
                        'steps' => array(
                            __( 'Click the <strong>API Keys &amp; Integrations</strong> tab at the top of this page.', 'claude-ai-copywriter' ),
                            __( 'You need an Anthropic API key - this is <em>separate</em> from a Claude.ai Pro subscription. Go to <a href="https://console.anthropic.com/settings/keys" target="_blank">console.anthropic.com/settings/keys</a>, sign in (or create a free account), and click <strong>Create Key</strong>.', 'claude-ai-copywriter' ),
                            __( 'Copy the key - it starts with <code>sk-ant-api03-…</code>. You will only see it once, so copy it now.', 'claude-ai-copywriter' ),
                            __( 'Paste the key into the API Key field in KineticCopy and click <strong>Test Key</strong>. You should see a green "Valid key" message. If you see an error, double-check you copied the full key with no extra spaces.', 'claude-ai-copywriter' ),
                            __( 'Click <strong>Save Key</strong>. Your key is stored encrypted - KineticCopy never exposes it in plain text.', 'claude-ai-copywriter' ),
                            __( 'Once saved, the Copywriting Studio, Content Library, and all generation features become active. You will be charged by Anthropic directly for the AI tokens you use - KineticCopy never charges a separate per-generation fee.', 'claude-ai-copywriter' ),
                        ),
                    ),
                    array(
                        'icon'  => '⚡',
                        'group' => __( 'Getting Started', 'claude-ai-copywriter' ),
                        'title' => __( 'Connect KineticLaunch', 'claude-ai-copywriter' ),
                        'link'  => $settings_url . '&tab=integrations',
                        'when_to_use' => array(
                            __( 'You use KineticLaunch for brand strategy and want copy that automatically matches your voice', 'claude-ai-copywriter' ),
                            __( 'You have a KineticLaunch T2 (Launch) licence and want to activate KineticCopy Premium for free', 'claude-ai-copywriter' ),
                            __( 'Your brand personas or calendar entries should flow into generated copy', 'claude-ai-copywriter' ),
                        ),
                        'tip'   => __( 'KineticLaunch T2 users get KineticCopy Premium included - no separate licence needed. After connecting, the sync runs every 24 h automatically. Force a sync any time with the Sync Now button.', 'claude-ai-copywriter' ),
                        'steps' => array(
                            __( 'KineticLaunch is a separate tool at <a href="https://launch.kineticbrain.ai" target="_blank">launch.kineticbrain.ai</a> that holds your brand strategy - positioning, voice, personas, competitors, marketing calendar, and launch plan. Connecting it means all of that flows automatically into KineticCopy, so every piece of content you generate is already on-strategy.', 'claude-ai-copywriter' ),
                            __( 'In KineticLaunch: go to <strong>Settings → Integrations → Brand Context Export</strong>. Generate an API key and copy your Project UUID (a long string like <code>xxxxxxxx-xxxx-…</code>).', 'claude-ai-copywriter' ),
                            __( 'In KineticCopy: click <strong>API Keys &amp; Integrations</strong>, scroll to the <em>KineticLaunch Sync</em> section, paste both values, and click <strong>Save credentials</strong>.', 'claude-ai-copywriter' ),
                            __( 'Click <strong>⚡ Sync Now</strong>. KineticCopy will pull your brand strategy from KineticLaunch. You should see a "Sync successful" confirmation with the timestamp.', 'claude-ai-copywriter' ),
                            __( 'After syncing, your brand voice, positioning, personas, and calendar briefs are automatically injected into every generation prompt - you will not need to explain your brand to the AI each time.', 'claude-ai-copywriter' ),
                            __( '<strong>KineticLaunch T2 (Launch) or higher:</strong> your KineticCopy Premium tier is unlocked automatically via the sync connection - no separate licence key needed. You will see "Premium (via KineticLaunch)" in the Licence tab.', 'claude-ai-copywriter' ),
                            __( 'The connection re-syncs automatically every 24 hours. You can force a manual sync any time with the Sync Now button.', 'claude-ai-copywriter' ),
                        ),
                    ),
                    array(
                        'icon'  => '✍️',
                        'group' => __( 'Studio', 'claude-ai-copywriter' ),
                        'title' => __( 'Copywriting Studio', 'claude-ai-copywriter' ),
                        'link'  => $studio_url,
                        'when_to_use' => array(
                            __( 'Generating a new piece of content from scratch', 'claude-ai-copywriter' ),
                            __( 'You want full control over type, tone, persona, and length', 'claude-ai-copywriter' ),
                            __( 'Trying out different tones for the same brief', 'claude-ai-copywriter' ),
                        ),
                        'tip' => __( 'The more context you give in the "Topic & context" field, the better the output. Include the product name, the key message, who it\'s for, and any must-have points.', 'claude-ai-copywriter' ),
                        'steps' => array(
                            __( 'Find the <strong>Copywriting Studio</strong> in the top-level <strong>KineticCopy</strong> WordPress menu item (left sidebar).', 'claude-ai-copywriter' ),
                            __( '<strong>Content type:</strong> choose from 43 formats - Blog Post, Sales Page, Landing Page Copy, Email Newsletter, LinkedIn Post, FAQ, Case Study, White Paper, Product Description, and many more. Each format has its own structure rules and tone guidance built in.', 'claude-ai-copywriter' ),
                            __( '<strong>Topic &amp; context:</strong> describe what you want to write. Be specific - include the product name, the main message, who it\'s for, and any key points you want covered. The more context, the better the result.', 'claude-ai-copywriter' ),
                            __( '<strong>Tone blending:</strong> drag the sliders to mix up to 5 tones at once (professional, conversational, urgent, empathetic, witty, etc.). The AI blends them proportionally. You can also load a saved Tone Template with one click instead of adjusting sliders manually.', 'claude-ai-copywriter' ),
                            __( '<strong>Persona targeting:</strong> select who you are writing for. Generic personas (e.g. "Small Business Owner", "Millennial") are always available. If KineticLaunch is connected, your custom brand personas appear here too. If you have no KineticLaunch personas, set them up in Launch first.', 'claude-ai-copywriter' ),
                            __( '<strong>Audience type:</strong> choose B2B, B2C, or Niche. This shapes vocabulary complexity, the level of assumed knowledge, and the overall framing of the content - B2B gets more formal and data-driven; B2C gets more emotional and direct.', 'claude-ai-copywriter' ),
                            __( '<strong>Word count / length:</strong> set an approximate target. KineticCopy uses this as a guide - longer formats (white papers, long-form blogs) will always be longer than short-form (social posts, headlines).', 'claude-ai-copywriter' ),
                            __( '<strong>Model routing:</strong> KineticCopy automatically picks the right AI model. Headlines, CTAs, and short copy use Haiku (fast, low cost). Standard blog posts and newsletters use Sonnet. Long-form, high-stakes content like Sales Pages and White Papers use Opus for the best quality. You can override this in Settings → General.', 'claude-ai-copywriter' ),
                            __( 'Click <strong>Generate</strong> and wait for the result to appear. Generation typically takes 10–40 seconds depending on length. The output appears in the result panel below the form.', 'claude-ai-copywriter' ),
                            __( 'Once generated, you can <strong>Copy to clipboard</strong>, <strong>Copy to post editor</strong> (if you came from an open WP post), <strong>Regenerate</strong> (reruns the same prompt), or <strong>Save as Snippet</strong> - which saves the <em>prompt</em> (not the output) to your Content Library so you can re-run it in one click any time.', 'claude-ai-copywriter' ),
                        ),
                    ),
                    array(
                        'icon'  => '🔁',
                        'group' => __( 'Studio', 'claude-ai-copywriter' ),
                        'title' => __( 'Rewrite with Tone', 'claude-ai-copywriter' ),
                        'when_to_use' => array(
                            __( 'You have existing copy you want to re-pitch without rewriting it completely', 'claude-ai-copywriter' ),
                            __( 'A post feels too formal (or too casual) and needs a tone shift', 'claude-ai-copywriter' ),
                            __( 'A/B testing the same message in different tones', 'claude-ai-copywriter' ),
                        ),
                        'steps' => array(
                            __( 'Rewrite with Tone lets you instantly change the tone of any existing text - yours or AI-generated - without rewriting it from scratch.', 'claude-ai-copywriter' ),
                            __( 'In the WordPress post editor (Gutenberg or Classic), select the text you want to rewrite.', 'claude-ai-copywriter' ),
                            __( 'The KineticCopy toolbar appears above the selected text. Click <strong>Rewrite with Tone</strong> (the KineticCopy icon in the toolbar).', 'claude-ai-copywriter' ),
                            __( 'A tone picker slides open. Choose a tone: Punchy, Formal, Persuasive, Empathetic, Conversational, Humorous, or Authoritative.', 'claude-ai-copywriter' ),
                            __( 'Click <strong>Rewrite</strong>. A before/after comparison appears - your original on the left, the rewritten version on the right.', 'claude-ai-copywriter' ),
                            __( 'Review the diff. Click <strong>Accept</strong> to replace the selected text, <strong>Reject</strong> to keep the original, or <strong>Tweak</strong> to choose a different tone.', 'claude-ai-copywriter' ),
                            __( 'WordPress saves a revision automatically when you accept - so you can always roll back via the WP Revisions panel if needed.', 'claude-ai-copywriter' ),
                        ),
                    ),
                    array(
                        'icon'  => '📚',
                        'group' => __( 'Library & Calendar', 'claude-ai-copywriter' ),
                        'title' => __( 'Content Library', 'claude-ai-copywriter' ),
                        'link'  => $library_url,
                        'when_to_use' => array(
                            __( 'Finding and re-running previously generated prompts', 'claude-ai-copywriter' ),
                            __( 'Organizing content by project, client, or campaign using folders', 'claude-ai-copywriter' ),
                            __( 'Saving your own custom prompts for one-click reuse', 'claude-ai-copywriter' ),
                        ),
                        'tip' => __( '"Save as Snippet" saves the prompt, not the output. The output is already saved as a library item. Running the snippet again with fresh context produces new, updated copy.', 'claude-ai-copywriter' ),
                        'steps' => array(
                            __( 'Find the <strong>Content Library</strong> in the <strong>KineticCopy</strong> WordPress menu. Every generation from Copywriting Studio is saved here automatically - you never lose a result.', 'claude-ai-copywriter' ),
                            __( '<strong>Search &amp; filter:</strong> use the search bar to find content by keyword, or filter by content type (Blog Post, Email, etc.) using the dropdown. You can also filter by folder.', 'claude-ai-copywriter' ),
                            __( '<strong>Folders:</strong> click the folder badge on any item (shown with a 📁 icon and a small arrow) to move it into a folder. In the dialog that opens, type a new folder name or choose from existing ones. Folders help you organise content by project, client, or campaign. To rename or delete a folder, use the Folders button in the library toolbar.', 'claude-ai-copywriter' ),
                            __( '<strong>Pin:</strong> click the pin icon on any item to pin it to the top of the library. Use this for your most-used prompts or best-performing content.', 'claude-ai-copywriter' ),
                            __( '<strong>Add a custom prompt:</strong> click the <strong>+</strong> button in the library toolbar to save a prompt you\'ve written yourself - not AI output. Choose the content type from the dropdown, paste your prompt text, add tags if useful, and click Save. This prompt now lives in your library and can be run from Studio in one click.', 'claude-ai-copywriter' ),
                            __( '<strong>Re-run a saved prompt:</strong> click the play button on any saved prompt to open it in Copywriting Studio pre-filled and ready to generate.', 'claude-ai-copywriter' ),
                            __( '<strong>Edit:</strong> click the edit (pencil) icon on any item to update the title, content, or folder.', 'claude-ai-copywriter' ),
                            __( '<strong>Delete:</strong> click the bin icon on any item to delete it. This is permanent - deleted items are not recoverable.', 'claude-ai-copywriter' ),
                            __( '<strong>Tip - Save as Snippet vs. saving output:</strong> when you use "Save as Snippet" after a generation, it saves the <em>prompt</em>, not the AI output. This is intentional - the idea is that your prompt is the reusable asset. The output is already saved separately as a library item. Running the snippet again with fresh context produces new, updated output.', 'claude-ai-copywriter' ),
                        ),
                    ),
                    array(
                        'icon'  => '📅',
                        'group' => __( 'Library & Calendar', 'claude-ai-copywriter' ),
                        'title' => __( 'Content Calendar', 'claude-ai-copywriter' ),
                        'link'  => $cal_url,
                        'when_to_use' => array(
                            __( 'Planning your content schedule a week, month, or quarter ahead', 'claude-ai-copywriter' ),
                            __( 'Viewing content pushed from KineticLaunch as calendar entries', 'claude-ai-copywriter' ),
                            __( 'Running content generation directly from scheduled brief entries', 'claude-ai-copywriter' ),
                        ),
                        'steps' => array(
                            __( 'The <strong>Content Calendar</strong> is found in the <strong>KineticCopy</strong> menu. It shows content scheduled from <a href="https://launch.kineticbrain.ai" target="_blank">KineticLaunch™</a> and your WordPress publish schedule, combined in one view.', 'claude-ai-copywriter' ),
                            __( '<strong>View modes:</strong> switch between List (all upcoming items), Week (7-day layout), Month (standard calendar grid), and Year (heat-map - darker colours = more content that day). Click any date in Year view to jump to that month.', 'claude-ai-copywriter' ),
                            __( '<strong>Calendar entries from KineticLaunch:</strong> each entry shows the campaign name, channel (blog, email, LinkedIn, etc.), and the scheduled date. Click an entry to see the full brief - topic, tone direction, keywords, hashtags, and image prompt suggestions.', 'claude-ai-copywriter' ),
                            __( '<strong>Generate from a brief:</strong> click the entry, then click <strong>Generate Content</strong>. KineticCopy opens the Copywriting Studio pre-filled with the brief details - topic, content type, and tone already set. Review and click Generate.', 'claude-ai-copywriter' ),
                            __( '<strong>Status sync:</strong> when you publish or schedule a WordPress post, its status syncs back to KineticLaunch automatically. The calendar entry turns green (published) or shows the scheduled date. This keeps your plan and reality in sync without manual updates.', 'claude-ai-copywriter' ),
                            __( 'If the calendar is empty: make sure KineticLaunch is connected (see Step 2) and that you have calendar entries in your KineticLaunch marketing calendar. Click <strong>⚡ Sync Now</strong> in the Integrations tab to pull the latest entries.', 'claude-ai-copywriter' ),
                        ),
                    ),
                    array(
                        'icon'  => '🏢',
                        'group' => __( 'Brand Tools', 'claude-ai-copywriter' ),
                        'title' => __( 'My Brand - Writing DNA', 'claude-ai-copywriter' ),
                        'link'  => $brand_url,
                        'when_to_use' => array(
                            __( 'Setting up your brand voice for the first time', 'claude-ai-copywriter' ),
                            __( 'You do not use KineticLaunch but want brand-consistent copy', 'claude-ai-copywriter' ),
                            __( 'Your brand voice changed and you need to update the DNA profile', 'claude-ai-copywriter' ),
                        ),
                        'tip' => __( 'No existing content? Write 3 short paragraphs in the voice you want to achieve and use those as samples. Even invented examples help KineticCopy calibrate better than nothing.', 'claude-ai-copywriter' ),
                        'steps' => array(
                            __( 'Find <strong>My Brand</strong> in the <strong>KineticCopy</strong> WordPress menu. This is where you teach KineticCopy your writing voice so AI output sounds like you - not a generic assistant.', 'claude-ai-copywriter' ),
                            __( '<strong>Writing DNA samples:</strong> paste 3–5 examples of your best existing writing. These should be content you are proud of and that represents how you actually write - blog posts, email intros, social captions, sales copy. Aim for at least 200 words total across all samples.', 'claude-ai-copywriter' ),
                            __( 'Click <strong>Extract Writing DNA</strong>. KineticCopy sends your samples to Claude, which analyses them for: sentence length and variety, vocabulary richness and complexity, tone markers, how you open and close content, recurring phrases and stylistic habits, and formality level.', 'claude-ai-copywriter' ),
                            __( 'The extracted DNA profile is saved and automatically injected into every future generation prompt. You do not need to do anything else - KineticCopy handles the injection silently.', 'claude-ai-copywriter' ),
                            __( '<strong>If KineticLaunch is connected:</strong> your brand strategy data (positioning statement, tone pillars, ideal customer personas, competitor context) also appears on this page for reference. KineticCopy uses this alongside your Writing DNA - strategy provides the direction, Writing DNA provides the voice.', 'claude-ai-copywriter' ),
                            __( '<strong>When to update:</strong> if your brand goes through a refresh, you enter a new market, or your tone intentionally shifts, paste new samples and re-extract. The updated profile replaces the old one immediately.', 'claude-ai-copywriter' ),
                            __( '<strong>No existing content?</strong> Write 3 short paragraphs in the voice you want to achieve and use those as samples. Even invented examples help KineticCopy calibrate better than no samples at all.', 'claude-ai-copywriter' ),
                        ),
                    ),
                    array(
                        'icon'  => '📊',
                        'group' => __( 'Advanced Tools', 'claude-ai-copywriter' ),
                        'title' => __( 'AEO / GEO Schema Markup', 'claude-ai-copywriter' ),
                        'when_to_use' => array(
                            __( 'You want your content to appear in AI-generated answers (ChatGPT, Perplexity, Google AI Overview)', 'claude-ai-copywriter' ),
                            __( 'You publish FAQ, How-To, or Product pages and want rich result eligibility', 'claude-ai-copywriter' ),
                            __( 'Your SEO strategy targets answer-engine and generative search placements, not just traditional blue links', 'claude-ai-copywriter' ),
                        ),
                        'tip' => __( 'Start with your FAQ and How-To pages - these get the highest visibility lift from schema markup in AI-generated answers.', 'claude-ai-copywriter' ),
                        'steps' => array(
                            __( 'AEO (Answer Engine Optimisation) and GEO (Generative Engine Optimisation) help your content appear in AI-generated answers - ChatGPT, Perplexity, Google AI Overview - not just traditional search results. KineticCopy generates the technical JSON-LD schema markup that makes this possible.', 'claude-ai-copywriter' ),
                            __( 'Open any WordPress post or page. Scroll below the editor and look for the <strong>KineticCopy Schema</strong> meta box.', 'claude-ai-copywriter' ),
                            __( 'Click <strong>Generate Schema</strong>. KineticCopy reads your post content and automatically picks the right schema type - FAQPage for FAQ content, HowTo for step-by-step guides, Article for blog posts, Product for product pages, LocalBusiness for business/contact pages.', 'claude-ai-copywriter' ),
                            __( 'Review the generated JSON-LD that appears in the meta box. You can edit it manually if needed.', 'claude-ai-copywriter' ),
                            __( '<strong>Auto-inject:</strong> go to <strong>Settings → General</strong> and enable <em>Auto-inject schema</em>. With this on, KineticCopy automatically adds the saved schema to your page\'s <code>&lt;head&gt;</code> on every page load - no copy-paste, no Yoast, no additional plugin needed.', 'claude-ai-copywriter' ),
                            __( '<strong>Validate your schema:</strong> after publishing, paste your page URL into <a href="https://search.google.com/test/rich-results" target="_blank">Google\'s Rich Results Test</a> to confirm the schema is being picked up correctly.', 'claude-ai-copywriter' ),
                            __( 'Schema does not override your existing Yoast/RankMath schema - KineticCopy adds complementary markup. If you see conflicts, disable auto-inject and add the markup manually via your SEO plugin.', 'claude-ai-copywriter' ),
                        ),
                    ),
                    array(
                        'icon'  => '🔍',
                        'group' => __( 'Advanced Tools', 'claude-ai-copywriter' ),
                        'title' => __( 'Research Engine', 'claude-ai-copywriter' ),
                        'when_to_use' => array(
                            __( 'Writing fact-heavy blog posts, industry roundups, or trend articles where accuracy matters', 'claude-ai-copywriter' ),
                            __( 'You need current data, statistics, or competitor details injected into your content automatically', 'claude-ai-copywriter' ),
                            __( 'You want AI-generated content grounded in real sources, not just training data', 'claude-ai-copywriter' ),
                        ),
                        'tip' => __( 'Research is most valuable for analytical blog posts and comparisons. For pure brand copy or creative writing where voice matters more than facts, you can leave it off to save generation time.', 'claude-ai-copywriter' ),
                        'steps' => array(
                            __( 'The Research Engine pulls live web data into your content generation - so AI-written content is grounded in real, current information rather than training data alone.', 'claude-ai-copywriter' ),
                            __( 'First, set up a research provider: go to <strong>Settings → Research</strong> tab. <strong>Perplexity AI</strong> is recommended - it returns AI-summarised search results that integrate cleanly with generation. Paste your Perplexity API key and save.', 'claude-ai-copywriter' ),
                            __( 'Alternatively you can use <strong>Serper</strong> (Google Search API), <strong>Brave Search</strong>, or <strong>Bing Search</strong>. Each needs its own API key - links to get keys are shown in the Research settings.', 'claude-ai-copywriter' ),
                            __( 'In Copywriting Studio, before generating, toggle on the <strong>Enable Research</strong> switch. KineticCopy will search the web for your topic and inject the findings as context into the generation prompt.', 'claude-ai-copywriter' ),
                            __( 'Best for: fact-heavy blog posts, industry trend articles, product comparisons, and any content where accuracy or freshness matters. Less useful for brand voice copy, sales content, or creative writing where voice matters more than facts.', 'claude-ai-copywriter' ),
                            __( 'Research adds a few seconds to generation time. If a research call fails (rate limit or key issue), KineticCopy falls back to standard generation automatically and shows a notice.', 'claude-ai-copywriter' ),
                        ),
                    ),
                    array(
                        'icon'  => '🎨',
                        'group' => __( 'Studio', 'claude-ai-copywriter' ),
                        'title' => __( 'Tone Templates', 'claude-ai-copywriter' ),
                        'when_to_use' => array(
                            __( 'You switch between tone profiles regularly (e.g. launch sales mode vs. nurture emails)', 'claude-ai-copywriter' ),
                            __( 'You have a tone slider combination you have dialled in perfectly and want to reuse with one click', 'claude-ai-copywriter' ),
                            __( 'You manage multiple campaigns or audiences that each need a distinct voice', 'claude-ai-copywriter' ),
                        ),
                        'tip' => __( 'Name templates after the use case, not the tone - "Launch Week Sales" is easier to remember than "Urgent + Persuasive".', 'claude-ai-copywriter' ),
                        'steps' => array(
                            __( 'Tone Templates let you save your favourite tone slider combinations as named presets - so you can switch between "Sales Mode" and "Friendly Blog" in one click instead of adjusting five sliders every time.', 'claude-ai-copywriter' ),
                            __( 'Find <strong>Tone Templates</strong> in the <strong>KineticCopy</strong> WordPress menu.', 'claude-ai-copywriter' ),
                            __( 'Click <strong>New Template</strong>. Give it a name (e.g. "Authority Blog", "Launch Sales Mode", "Warm Newsletter") and set your slider values. Click <strong>Save Template</strong>.', 'claude-ai-copywriter' ),
                            __( 'In Copywriting Studio, the tone picker shows a <strong>Templates</strong> tab. Click any saved template to instantly load those slider values.', 'claude-ai-copywriter' ),
                            __( 'You can create as many templates as you need - one per campaign type, content format, or audience segment. Edit or delete templates any time from the Tone Templates page.', 'claude-ai-copywriter' ),
                        ),
                    ),
                    array(
                        'icon'  => '👤',
                        'group' => __( 'Brand Tools', 'claude-ai-copywriter' ),
                        'title' => __( 'Brand Personas', 'claude-ai-copywriter' ),
                        'when_to_use' => array(
                            __( 'Your content targets very different audience segments (e.g. B2B decision-makers vs. individual creators)', 'claude-ai-copywriter' ),
                            __( 'You want AI output to speak directly to a specific type of reader, not a generic audience', 'claude-ai-copywriter' ),
                            __( 'Your KineticLaunch personas are defined and you want them available in Copywriting Studio', 'claude-ai-copywriter' ),
                        ),
                        'tip' => __( 'Custom personas from KineticLaunch produce the most targeted copy. Generic personas are a solid starting point while you build out your brand strategy.', 'claude-ai-copywriter' ),
                        'steps' => array(
                            __( 'Personas define <em>who</em> your content is written for - their age, role, pain points, goals, and language level. When a persona is active in Copywriting Studio, every generation is framed to speak directly to that person.', 'claude-ai-copywriter' ),
                            __( '<strong>Built-in generic personas</strong> are available by default - Millennial Professional, Small Business Owner, Solopreneur, Enterprise Decision-Maker, and more. These work without any setup.', 'claude-ai-copywriter' ),
                            __( '<strong>KineticLaunch personas:</strong> if KineticLaunch is connected and you have defined custom personas there, they sync across automatically and appear in the Copywriting Studio persona picker alongside the generic ones.', 'claude-ai-copywriter' ),
                            __( 'To show <em>only</em> your KineticLaunch personas (hide the generic ones): go to <strong>Settings → General</strong> and enable <em>Only show KineticLaunch personas</em>.', 'claude-ai-copywriter' ),
                            __( 'To define custom personas without KineticLaunch: create them directly in <a href="https://launch.kineticbrain.ai" target="_blank">KineticLaunch™</a> under the Personas section, then sync. KineticLaunch is the primary persona management tool in the KineticBrain ecosystem.', 'claude-ai-copywriter' ),
                        ),
                    ),
                    array(
                        'icon'  => '🧠',
                        'group' => __( 'BRAIN', 'claude-ai-copywriter' ),
                        'title' => __( 'BRAIN AI Assistant', 'claude-ai-copywriter' ),
                        'when_to_use' => array(
                            __( 'You want to refine, rephrase, or improve specific text without going through the full Copywriting Studio', 'claude-ai-copywriter' ),
                            __( 'You have a strategic question about brand voice, content angle, or how to frame something for your audience', 'claude-ai-copywriter' ),
                            __( 'You want a quick how-to answer about any KineticCopy feature', 'claude-ai-copywriter' ),
                        ),
                        'tip' => __( 'BRAIN resets between page loads - if you get a great rewrite or idea, copy it to your clipboard or save it to the Content Library before navigating away.', 'claude-ai-copywriter' ),
                        'steps' => array(
                            __( 'BRAIN is your always-on AI writing assistant, accessible from every KineticCopy admin page via the floating chat icon in the bottom-right corner. Click it to open the chat panel.', 'claude-ai-copywriter' ),
                            __( '<strong>What BRAIN knows:</strong> when KineticLaunch is connected, BRAIN has full context of your brand - voice, positioning, personas, competitors. It writes <em>in your brand voice</em> without you needing to explain it each time.', 'claude-ai-copywriter' ),
                            __( '<strong>What you can ask BRAIN:</strong><br>- "Rewrite this headline to be more punchy"<br>- "Give me 5 subject line variations for this email"<br>- "What\'s a stronger way to open this blog post?"<br>- "Make this call to action more urgent"<br>- "Explain what AEO schema markup is and why I need it"<br>- "How do I connect KineticLaunch?"', 'claude-ai-copywriter' ),
                            __( 'BRAIN remembers what you say during the session, so you can have a back-and-forth conversation - ask for a rewrite, then say "make it shorter" and it refines the previous result.', 'claude-ai-copywriter' ),
                            __( 'BRAIN uses <strong>Claude Sonnet</strong> by default for a balance of speed and quality. For longer, more complex writing tasks, BRAIN automatically steps up to a higher model.', 'claude-ai-copywriter' ),
                            __( 'The chat history is session-only - it resets when you navigate away. If you want to save a BRAIN output, copy it to your clipboard or Content Library before closing the panel.', 'claude-ai-copywriter' ),
                        ),
                    ),
                    array(
                        'icon'  => '🔑',
                        'group' => __( 'Settings & Plans', 'claude-ai-copywriter' ),
                        'title' => __( 'Licence &amp; Plans', 'claude-ai-copywriter' ),
                        'link'  => $settings_url . '#license',
                        'when_to_use' => array(
                            __( 'Activating a paid licence key you received from KineticBrain or AppSumo', 'claude-ai-copywriter' ),
                            __( 'Checking which tier you are on and what Premium features are unlocked', 'claude-ai-copywriter' ),
                            __( 'Moving a licence from one WordPress site to another', 'claude-ai-copywriter' ),
                        ),
                        'steps' => array(
                            __( '<strong>Free tier:</strong> KineticCopy works immediately with no licence key. You get core copywriting (most formats), the Content Library, BRAIN AI assistant, and BYOK. Writing DNA profiling, all 43 formats, KineticLaunch Calendar Sync, and AEO/GEO schema markup require a paid licence.', 'claude-ai-copywriter' ),
                            __( 'To activate a paid licence: go to <strong>Settings → 🔑 License</strong> tab. Paste your licence key (format: <code>KB-XXXX-XXXX-XXXX-XXXX</code>) and click <strong>Activate</strong>.', 'claude-ai-copywriter' ),
                            __( 'Your licence tier (Solo / Studio / Agency / Enterprise) determines how many WordPress sites you can activate. You can see your current usage in the Licence tab.', 'claude-ai-copywriter' ),
                            __( '<strong>Agency / Enterprise:</strong> manage which sites are activated via the portal at <a href="https://licensing.kineticbrain.ai" target="_blank">licensing.kineticbrain.ai</a>. You can deactivate a site there to free up a slot and move it to a different installation.', 'claude-ai-copywriter' ),
                            __( '<strong>KineticLaunch T2+ subscribers:</strong> no separate KineticCopy licence key is needed. Connect KineticLaunch (see Step 2) and your Copy Premium tier activates automatically. The Licence tab will show "Premium (via KineticLaunch)".', 'claude-ai-copywriter' ),
                            __( 'To deactivate this site manually: click <strong>Deactivate</strong> in the Licence tab. This frees up a licence slot and downgrades this installation to the Free tier. Your content and settings are preserved.', 'claude-ai-copywriter' ),
                            __( 'To upgrade or purchase a plan, visit <a href="https://copy.kineticbrain.ai#pricing" target="_blank">copy.kineticbrain.ai</a>.', 'claude-ai-copywriter' ),
                        ),
                    ),
                    array(
                        'icon'  => '🧱',
                        'group' => __( 'Integrations', 'claude-ai-copywriter' ),
                        'title' => __( 'Breakdance Integration (Premium)', 'claude-ai-copywriter' ),
                        'when_to_use' => array(
                            __( 'You build pages with the Breakdance page builder and want to generate copy without leaving the canvas', 'claude-ai-copywriter' ),
                            __( 'You need to quickly fill a text section while designing a layout', 'claude-ai-copywriter' ),
                            __( 'You want a compact Studio interface embedded directly in your page builder workflow', 'claude-ai-copywriter' ),
                        ),
                        'tip' => __( 'Breakdance integration activates automatically once your paid licence key is verified - no extra configuration needed.', 'claude-ai-copywriter' ),
                        'steps' => array(
                            __( 'If your WordPress site uses the Breakdance page builder, KineticCopy adds a native <strong>KineticCopy</strong> custom element you can drop directly into any Breakdance layout.', 'claude-ai-copywriter' ),
                            __( 'In Breakdance, open the element panel and search for <strong>KineticCopy</strong>. Drag it onto your canvas.', 'claude-ai-copywriter' ),
                            __( 'The element shows a compact Studio interface inline - choose content type, write your prompt, set word count, and click Generate. The output fills the element.', 'claude-ai-copywriter' ),
                            __( 'Use <strong>Copy to clipboard</strong> from within the element to paste the result into a text block next to it, or use <strong>Insert into post</strong> to send it to the classic post editor.', 'claude-ai-copywriter' ),
                            __( 'The Breakdance integration requires a <strong>paid KineticCopy licence</strong> (Solo or above). It activates automatically once your licence is verified.', 'claude-ai-copywriter' ),
                            __( 'KineticCopy also works with Gutenberg, Classic Editor, Elementor, Divi, and Bricks - core features live in the WordPress admin and are not tied to any single builder.', 'claude-ai-copywriter' ),
                        ),
                    ),
                    array(
                        'icon'  => '🆘',
                        'group' => __( 'Help & Support', 'claude-ai-copywriter' ),
                        'title' => __( 'Troubleshooting &amp; Support', 'claude-ai-copywriter' ),
                        'link'  => $settings_url . '#debug',
                        'when_to_use' => array(
                            __( 'A generation failed and you are not sure why', 'claude-ai-copywriter' ),
                            __( 'Your API key is not being accepted or keeps showing invalid', 'claude-ai-copywriter' ),
                            __( 'You need to contact support and want to include the right diagnostic information', 'claude-ai-copywriter' ),
                        ),
                        'steps' => array(
                            __( '<strong>Generation fails or returns an error:</strong> go to <strong>Settings → Debug Log</strong> tab and look for red error lines. The most common causes are an invalid or expired API key, insufficient Anthropic credits, or a PHP memory limit below 128MB.', 'claude-ai-copywriter' ),
                            __( '<strong>API key shows invalid:</strong> make sure you copied the full key including the <code>sk-ant-api03-</code> prefix. Keys expire if you delete them in the Anthropic console - generate a new one and re-save.', 'claude-ai-copywriter' ),
                            __( '<strong>KineticLaunch sync fails:</strong> check that your KineticLaunch API key and Project UUID are correct. In KineticLaunch, go to Settings → Integrations and verify the key is still active. Re-paste and sync again.', 'claude-ai-copywriter' ),
                            __( '<strong>Content Library is empty after generating:</strong> check browser console for JS errors. Ensure the KineticCopy database tables were created correctly - deactivate and reactivate the plugin to re-run the installer.', 'claude-ai-copywriter' ),
                            __( '<strong>Licence not activating:</strong> check your internet connection. The licence validator contacts the KineticBrain licence server. If on a local or restricted server, temporarily whitelist <code>licensing.kineticbrain.ai</code> in your firewall.', 'claude-ai-copywriter' ),
                            __( '<strong>Debug Log:</strong> go to <strong>Settings → Debug Log</strong> tab. Copy the full log and include it in any support request - it shows exactly what happened.', 'claude-ai-copywriter' ),
                            __( '<strong>Contact support:</strong> email <a href="mailto:support@kineticbrain.ai">support@kineticbrain.ai</a> with your WordPress version, PHP version, KineticCopy version (v' . CLAUDE_AI_COPYWRITER_VERSION . '), and the Debug Log contents. We respond within 1 business day.', 'claude-ai-copywriter' ),
                            __( 'AppSumo users: post your question in the AppSumo Q&amp;A for your deal - our team reviews all questions daily.', 'claude-ai-copywriter' ),
                        ),
                    ),
                );
                ?>

                <?php
                /* Build group index for sidebar nav */
                $kc_groups_order    = array();
                $kc_groups_sections = array();
                foreach ( $sections as $idx => $section ) {
                    $grp = isset( $section['group'] ) ? $section['group'] : __( 'Other', 'claude-ai-copywriter' );
                    if ( ! in_array( $grp, $kc_groups_order, true ) ) {
                        $kc_groups_order[]        = $grp;
                        $kc_groups_sections[ $grp ] = array();
                    }
                    $kc_groups_sections[ $grp ][] = $idx;
                }
                ?>
                <style>
                /* ── KineticCopy Manual - KDS v2 two-panel layout ── */
                .kc-manual-wrap {
                    display: flex;
                    height: calc(100vh - 196px);
                    min-height: 500px;
                    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, sans-serif;
                    border-top: 1px solid #E5E1D8;
                }
                /* Sidebar */
                .kc-manual-sidebar {
                    width: 234px;
                    flex-shrink: 0;
                    background: #FBFAF7;
                    border-right: 1px solid #E5E1D8;
                    display: flex;
                    flex-direction: column;
                    overflow: hidden;
                }
                .kc-manual-search-wrap {
                    padding: 12px 12px 10px;
                    border-bottom: 1px solid #E5E1D8;
                    background: #FBFAF7;
                }
                .kc-manual-search {
                    width: 100%;
                    padding: 7px 10px;
                    border: 1px solid #E5E1D8;
                    border-radius: 5px;
                    font-size: 12px;
                    background: #fff;
                    color: #1a1a1a;
                    box-sizing: border-box;
                    outline: none;
                }
                .kc-manual-search:focus {
                    border-color: #D6263A;
                    box-shadow: 0 0 0 2px rgba(214,38,58,.12);
                }
                .kc-manual-nav {
                    flex: 1;
                    overflow-y: auto;
                    padding: 6px 0 16px;
                }
                .kc-manual-group-label {
                    padding: 10px 14px 4px;
                    font-size: 10px;
                    font-weight: 700;
                    text-transform: uppercase;
                    letter-spacing: .07em;
                    color: #9ca3af;
                }
                .kc-manual-nav-item {
                    display: flex;
                    align-items: center;
                    gap: 8px;
                    padding: 7px 14px;
                    cursor: pointer;
                    font-size: 12.5px;
                    color: #1a1a1a;
                    border-left: 3px solid transparent;
                    transition: background .1s, border-color .1s, color .1s;
                    user-select: none;
                    line-height: 1.3;
                }
                .kc-manual-nav-item:hover { background: #F3F0EA; color: #D6263A; }
                .kc-manual-nav-item.kc-man-active {
                    background: rgba(214,38,58,.07);
                    border-left-color: #D6263A;
                    color: #D6263A;
                    font-weight: 600;
                }
                .kc-manual-nav-item.kc-man-hidden { display: none; }
                .kc-manual-nav-icon { font-size: 14px; flex-shrink: 0; line-height: 1; }
                .kc-manual-nav-text { flex: 1; }
                .kc-manual-no-results {
                    padding: 20px 14px;
                    font-size: 12px;
                    color: #9ca3af;
                    text-align: center;
                    display: none;
                }
                .kc-manual-group-block.kc-grp-hidden .kc-manual-group-label { display: none; }
                /* Content area */
                .kc-manual-content {
                    flex: 1;
                    overflow-y: auto;
                    background: #fff;
                }
                .kc-manual-section-panel {
                    display: none;
                    padding: 28px 36px 44px;
                    max-width: 800px;
                }
                .kc-manual-section-panel.kc-man-active { display: block; }
                .kc-manual-breadcrumb {
                    font-size: 11px;
                    color: #9ca3af;
                    margin-bottom: 16px;
                    display: flex;
                    align-items: center;
                    gap: 5px;
                }
                .kc-manual-section-header {
                    display: flex;
                    align-items: flex-start;
                    gap: 14px;
                    margin-bottom: 22px;
                }
                .kc-manual-section-icon { font-size: 30px; line-height: 1; flex-shrink: 0; margin-top: 1px; }
                .kc-manual-title-wrap { flex: 1; }
                .kc-manual-section-title {
                    font-size: 21px;
                    font-weight: 700;
                    color: #111827;
                    margin: 0 0 10px;
                    line-height: 1.2;
                }
                .kc-manual-open-btn {
                    display: inline-flex;
                    align-items: center;
                    gap: 5px;
                    padding: 6px 14px;
                    background: #D6263A;
                    color: #fff !important;
                    font-size: 12px;
                    font-weight: 600;
                    border-radius: 5px;
                    text-decoration: none !important;
                    border: none;
                    cursor: pointer;
                    transition: background .15s;
                    line-height: 1.4;
                }
                .kc-manual-open-btn:hover { background: #A6172A; }
                /* When to use callout */
                .kc-manual-when {
                    background: #FBFAF7;
                    border: 1px solid #E5E1D8;
                    border-left: 4px solid #D6263A;
                    border-radius: 5px;
                    padding: 14px 18px;
                    margin-bottom: 26px;
                }
                .kc-manual-when-label {
                    font-size: 10px;
                    font-weight: 700;
                    text-transform: uppercase;
                    letter-spacing: .08em;
                    color: #D6263A;
                    margin: 0 0 9px;
                }
                .kc-manual-when ul { margin: 0; padding-left: 18px; }
                .kc-manual-when ul li {
                    font-size: 13px;
                    line-height: 1.6;
                    color: #374151;
                    margin-bottom: 3px;
                }
                .kc-manual-when ul li:last-child { margin-bottom: 0; }
                /* Steps */
                .kc-manual-steps-label {
                    font-size: 10px;
                    font-weight: 700;
                    text-transform: uppercase;
                    letter-spacing: .07em;
                    color: #9ca3af;
                    margin: 0 0 12px;
                }
                .kc-manual-steps {
                    margin: 0;
                    padding-left: 0;
                    list-style: none;
                    counter-reset: kc-step;
                }
                .kc-manual-steps > li {
                    counter-increment: kc-step;
                    display: flex;
                    gap: 13px;
                    margin-bottom: 15px;
                    font-size: 13.5px;
                    line-height: 1.65;
                    color: #2d2d2d;
                }
                .kc-manual-steps > li::before {
                    content: counter(kc-step);
                    flex-shrink: 0;
                    width: 22px;
                    height: 22px;
                    background: #D6263A;
                    color: #fff;
                    font-size: 11px;
                    font-weight: 700;
                    border-radius: 50%;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    margin-top: 3px;
                }
                .kc-manual-steps > li code {
                    background: #f3f4f6;
                    padding: 1px 5px;
                    border-radius: 3px;
                    font-size: 12px;
                    font-family: SFMono-Regular, Consolas, "Liberation Mono", Menlo, monospace;
                }
                .kc-manual-steps > li a { color: #D6263A; }
                .kc-manual-steps > li strong { font-weight: 600; }
                /* Pro tip callout */
                .kc-manual-tip {
                    background: rgba(214,38,58,.04);
                    border: 1px solid rgba(214,38,58,.18);
                    border-left: 4px solid #D6263A;
                    border-radius: 5px;
                    padding: 14px 18px;
                    margin-top: 26px;
                }
                .kc-manual-tip-label {
                    font-size: 10px;
                    font-weight: 700;
                    text-transform: uppercase;
                    letter-spacing: .08em;
                    color: #D6263A;
                    margin: 0 0 7px;
                }
                .kc-manual-tip p {
                    margin: 0;
                    font-size: 13px;
                    line-height: 1.65;
                    color: #4a1a22;
                }
                </style>

                <div class="kc-manual-wrap">
                    <!-- Sidebar nav -->
                    <div class="kc-manual-sidebar">
                        <div class="kc-manual-search-wrap">
                            <input type="text" class="kc-manual-search" id="kc-man-search"
                                   placeholder="<?php esc_attr_e( 'Search sections\xe2\x80\xa6', 'claude-ai-copywriter' ); ?>">
                        </div>
                        <nav class="kc-manual-nav" id="kc-man-nav">
                            <?php foreach ( $kc_groups_order as $grp ) : ?>
                            <div class="kc-manual-group-block" data-grp="<?php echo esc_attr( $grp ); ?>">
                                <div class="kc-manual-group-label"><?php echo esc_html( $grp ); ?></div>
                                <?php foreach ( $kc_groups_sections[ $grp ] as $idx ) :
                                    $s = $sections[ $idx ];
                                    $nav_text = wp_strip_all_tags( $s['title'] );
                                ?>
                                <div class="kc-manual-nav-item<?php echo 0 === $idx ? ' kc-man-active' : ''; ?>"
                                     data-idx="<?php echo (int) $idx; ?>"
                                     data-search="<?php echo esc_attr( strtolower( $nav_text . ' ' . $grp ) ); ?>">
                                    <span class="kc-manual-nav-icon"><?php echo $s['icon']; ?></span>
                                    <span class="kc-manual-nav-text"><?php echo esc_html( $nav_text ); ?></span>
                                </div>
                                <?php endforeach; ?>
                            </div>
                            <?php endforeach; ?>
                            <div class="kc-manual-no-results" id="kc-man-no-results">
                                <?php _e( 'No sections match your search.', 'claude-ai-copywriter' ); ?>
                            </div>
                        </nav>
                    </div>

                    <!-- Content panels -->
                    <div class="kc-manual-content" id="kc-man-content">
                        <?php foreach ( $sections as $idx => $section ) :
                            $has_link  = ! empty( $section['link'] );
                            $has_when  = ! empty( $section['when_to_use'] );
                            $has_tip   = ! empty( $section['tip'] );
                            $grp_label = isset( $section['group'] ) ? $section['group'] : '';
                            $title_raw = wp_strip_all_tags( $section['title'] );
                        ?>
                        <div class="kc-manual-section-panel<?php echo 0 === $idx ? ' kc-man-active' : ''; ?>"
                             data-idx="<?php echo (int) $idx; ?>">

                            <?php if ( $grp_label ) : ?>
                            <div class="kc-manual-breadcrumb">
                                <span><?php echo esc_html( $grp_label ); ?></span>
                                <span>&rsaquo;</span>
                                <span><?php echo esc_html( $title_raw ); ?></span>
                            </div>
                            <?php endif; ?>

                            <div class="kc-manual-section-header">
                                <span class="kc-manual-section-icon"><?php echo $section['icon']; ?></span>
                                <div class="kc-manual-title-wrap">
                                    <h2 class="kc-manual-section-title"><?php echo wp_kses_post( $section['title'] ); ?></h2>
                                    <?php if ( $has_link ) : ?>
                                    <a href="<?php echo esc_url( $section['link'] ); ?>" class="kc-manual-open-btn">
                                        <?php esc_html_e( 'Open this page', 'claude-ai-copywriter' ); ?> &rarr;
                                    </a>
                                    <?php endif; ?>
                                </div>
                            </div>

                            <?php if ( $has_when ) : ?>
                            <div class="kc-manual-when">
                                <div class="kc-manual-when-label"><?php esc_html_e( 'WHEN TO USE', 'claude-ai-copywriter' ); ?></div>
                                <ul>
                                    <?php foreach ( $section['when_to_use'] as $item ) : ?>
                                    <li><?php echo wp_kses_post( $item ); ?></li>
                                    <?php endforeach; ?>
                                </ul>
                            </div>
                            <?php endif; ?>

                            <div class="kc-manual-steps-label"><?php esc_html_e( 'HOW IT WORKS', 'claude-ai-copywriter' ); ?></div>
                            <ol class="kc-manual-steps">
                                <?php foreach ( $section['steps'] as $step ) : ?>
                                <li><?php echo wp_kses_post( $step ); ?></li>
                                <?php endforeach; ?>
                            </ol>

                            <?php if ( $has_tip ) : ?>
                            <div class="kc-manual-tip">
                                <div class="kc-manual-tip-label"><?php esc_html_e( 'PRO TIP', 'claude-ai-copywriter' ); ?></div>
                                <p><?php echo wp_kses_post( $section['tip'] ); ?></p>
                            </div>
                            <?php endif; ?>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>

                <script>
                jQuery(document).ready(function($) {
                    var $items    = $('.kc-manual-nav-item');
                    var $panels   = $('.kc-manual-section-panel');
                    var $search   = $('#kc-man-search');
                    var $noRes    = $('#kc-man-no-results');
                    var $content  = $('#kc-man-content');

                    function showSection(idx) {
                        $items.removeClass('kc-man-active');
                        $panels.removeClass('kc-man-active');
                        $items.filter('[data-idx="' + idx + '"]').addClass('kc-man-active');
                        $panels.filter('[data-idx="' + idx + '"]').addClass('kc-man-active');
                        $content.scrollTop(0);
                    }

                    $items.on('click', function() { showSection($(this).data('idx')); });

                    $search.on('input', function() {
                        var q = $(this).val().toLowerCase().trim();
                        var any = false;
                        $items.each(function() {
                            var match = !q || ($(this).data('search') + '').indexOf(q) !== -1;
                            $(this).toggleClass('kc-man-hidden', !match);
                            if (match) any = true;
                        });
                        $('.kc-manual-group-block').each(function() {
                            var vis = $(this).find('.kc-manual-nav-item:not(.kc-man-hidden)').length > 0;
                            $(this).toggleClass('kc-grp-hidden', !vis);
                        });
                        $noRes.toggle(!any);
                        if (q && $('.kc-manual-nav-item.kc-man-active.kc-man-hidden').length) {
                            var $first = $items.filter(':not(.kc-man-hidden)').first();
                            if ($first.length) showSection($first.data('idx'));
                        }
                    });
                });
                </script>
            </div>

            <!-- Debug Log Tab -->
            <div id="debug" class="tab-content">
                <h2><?php _e( 'Debug Log', 'claude-ai-copywriter' ); ?></h2>

                <p><?php _e( 'All JavaScript debug messages are recorded here. You can copy this log to troubleshoot issues.', 'claude-ai-copywriter' ); ?></p>

                <div style="margin: 20px 0;">
                    <button type="button" id="copy-debug-log" class="button"><?php _e( 'Copy Log to Clipboard', 'claude-ai-copywriter' ); ?></button>
                    <button type="button" id="clear-debug-log" class="button"><?php _e( 'Clear Log', 'claude-ai-copywriter' ); ?></button>
                </div>

                <textarea id="claude-debug-output" readonly style="width: 100%; height: 500px; font-family: monospace; font-size: 12px; padding: 10px; background: #f5f5f5; border: 1px solid #ccc;"></textarea>
            </div>

            <!-- Onboarding restart (wired to window.kcRestartOnboarding) -->
            <div style="margin-bottom:16px; padding:14px 16px; background:#f6f7f7; border:1px solid #dcdcde; border-radius:4px; display:flex; align-items:center; justify-content:space-between; flex-wrap:wrap; gap:8px;">
                <div>
                    <strong style="font-size:13px; color:#111827;"><?php _e( 'Setup Wizard', 'claude-ai-copywriter' ); ?></strong>
                    <p style="margin:2px 0 0; font-size:12px; color:#6b7280;"><?php _e( 'Walkthrough the main features of KineticCopy step by step.', 'claude-ai-copywriter' ); ?></p>
                </div>
                <button type="button" class="button" onclick="if(typeof kcRestartOnboarding==='function'){kcRestartOnboarding();}else{alert('<?php echo esc_js( __( 'Reload the page and try again.', 'claude-ai-copywriter' ) ); ?>');}">
                    <?php _e( '▶ Restart Onboarding Wizard', 'claude-ai-copywriter' ); ?>
                </button>
            </div>

            <p class="submit">
                <input type="submit" name="claude_ai_settings_submit" class="button button-primary" value="<?php esc_attr_e( 'Save All Settings', 'claude-ai-copywriter' ); ?>">
            </p>
        </form>
    </div>
</div>

<script>
jQuery(document).ready(function($) {
    // Tab switching
    $('.nav-tab').on('click', function(e) {
        e.preventDefault();
        var target = $(this).attr('href');

        $('.nav-tab').removeClass('nav-tab-active');
        $(this).addClass('nav-tab-active');

        $('.tab-content').removeClass('active');
        $(target).addClass('active');
    });

    // Cross-tab links (e.g. "License tab" link in Upgrade tab)
    $(document).on('click', '.kc-tab-link', function(e) {
        e.preventDefault();
        var tab = '#' + $(this).data('tab');
        $('.nav-tab[href="' + tab + '"]').trigger('click');
        $('html, body').animate({ scrollTop: 0 }, 200);
    });

    // Show/hide research API fields based on provider
    function toggleResearchFields() {
        var provider = $('#research_api_provider').val();
        $('.research-api-field').hide();
        if (provider === 'google') {
            $('.google-fields').show();
        } else if (provider === 'bing') {
            $('.bing-fields').show();
        } else if (provider === 'brave') {
            $('.brave-fields').show();
        } else if (provider === 'serper') {
            $('.serper-fields').show();
        } else if (provider === 'perplexity') {
            $('.perplexity-fields').show();
        }
    }

    $('#research_api_provider').on('change', toggleResearchFields);
    toggleResearchFields();

    // Debug log copy button
    $('#copy-debug-log').on('click', function() {
        var logText = $('#claude-debug-output').val();
        navigator.clipboard.writeText(logText).then(function() {
            alert('Debug log copied to clipboard!');
        }).catch(function() {
            // Fallback
            $('#claude-debug-output').select();
            document.execCommand('copy');
            alert('Debug log copied to clipboard!');
        });
    });

    // Clear debug log
    $('#clear-debug-log').on('click', function() {
        if (confirm('Clear all debug logs?')) {
            window.ClaudeAI.debugLog = [];
            $('#claude-debug-output').val('');
        }
    });
});
</script>
