<?php
/**
 * My Brand Page Template
 *
 * @var array $bs            claude_ai_brand_strategy option
 * @var array $settings      claude_ai_copywriter_settings option
 * @var array $personas      All personas for current user
 * @var array $si_status     Site Intelligence status array
 * @var array $si_settings   Site Intelligence option
 *
 * @package Claude_AI_Copywriter
 */

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

$bs_completeness = 0;
$bs_fields_total = 16;
$bs_fields_filled = 0;
foreach ( [ 'positioning','problem_solved','taglines','target_audience','target_audience_secondary','audience_pains','keywords','voice','elevator_pitch','tone_description','writing_style','personality','pillars','key_messages','competitors','pricing' ] as $f ) {
    if ( ! empty( $bs[ $f ] ) ) {
        $bs_fields_filled++;
    }
}
$bs_completeness = round( ( $bs_fields_filled / $bs_fields_total ) * 100 );
?>

<div class="wrap claude-ai-settings claude-ai-wrap">
    <?php
    $kc_page_title = __( 'My Brand', 'claude-ai-copywriter' );
    $kc_page_desc  = __( 'Your brand brain — voice, audience, strategy, and site intelligence in one place. The more you fill in, the smarter KineticCopy gets.', 'claude-ai-copywriter' );
    include CLAUDE_AI_COPYWRITER_PATH . 'admin/partials/kc-page-header.php';
    ?>

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

    <div class="claude-settings-container">

        <!-- Tab Navigation -->
        <h2 class="nav-tab-wrapper">
            <a href="#brand-strategy" class="nav-tab nav-tab-active">
                ⚡ <?php _e( 'Brand Strategy', 'claude-ai-copywriter' ); ?>
                <?php if ( $bs_completeness > 0 ) : ?>
                    <span style="font-size:11px; margin-left:6px; background:<?php echo $bs_completeness >= 75 ? '#d1fae5' : '#fef3c7'; ?>; color:<?php echo $bs_completeness >= 75 ? '#065f46' : '#92400e'; ?>; padding:1px 6px; border-radius:10px;"><?php echo $bs_completeness; ?>%</span>
                <?php endif; ?>
            </a>
            <a href="#site-intelligence" class="nav-tab">
                <?php _e( 'Site Intelligence', 'claude-ai-copywriter' ); ?>
                <?php if ( ! empty( $si_status['available'] ) ) : ?>
                    <span style="font-family:'JetBrains Mono',monospace; font-size:10px; font-weight:400; margin-left:6px; color:#16a34a; letter-spacing:0.04em;"><?php _e( 'Active', 'claude-ai-copywriter' ); ?></span>
                <?php endif; ?>
            </a>
            <a href="#personas" class="nav-tab">
                <?php _e( 'Personas', 'claude-ai-copywriter' ); ?>
                <?php $user_persona_count = count( array_filter( $personas, fn($p) => ! $p->is_global ) ); ?>
                <?php if ( $user_persona_count > 0 ) : ?>
                    <span style="font-size:11px; margin-left:6px; background:#ede9fe; color:#4c1d95; padding:1px 6px; border-radius:10px;"><?php echo $user_persona_count; ?></span>
                <?php endif; ?>
            </a>
        </h2>

        <!-- ═══════════════════════════════════════════════════
             TAB: BRAND STRATEGY
             ═══════════════════════════════════════════════════ -->
        <form method="post" action="" id="kc-my-brand-form">
            <?php wp_nonce_field( 'kc_my_brand_save' ); ?>
            <input type="hidden" name="kc_my_brand_save" value="1">

            <div id="brand-strategy" class="tab-content active">

                <p style="color:var(--kinetic-text-secondary,#6b7280); margin-bottom:24px; max-width:720px;">
                    <?php _e( 'This is the brain of KineticCopy. Fill in what you know - even partial info makes every generation significantly smarter. Each field is injected into the system prompt in compressed form, so KineticCopy writes from your brand\'s strategic foundation, not a blank slate.', 'claude-ai-copywriter' ); ?>
                </p>

                <!-- PERSONA SETTINGS (pinned top) -->
                <div style="background:#faf5ff; border:1px solid #ede9fe; border-radius:6px; padding:16px 20px; margin-bottom:28px; max-width:720px;">
                    <h3 style="margin:0 0 8px; font-size:13px; text-transform:uppercase; letter-spacing:.06em; color:#6d28d9;"><?php _e( 'Persona Settings', 'claude-ai-copywriter' ); ?></h3>
                    <label style="display:flex; align-items:flex-start; gap:8px; cursor:pointer;">
                        <input type="checkbox" name="show_branded_personas_only" id="show_branded_personas_only" value="1"
                            <?php checked( $settings['show_branded_personas_only'] ?? false, 1 ); ?>
                            style="margin-top:3px; flex-shrink:0;">
                        <span>
                            <strong><?php _e( 'Branded Personas Only', 'claude-ai-copywriter' ); ?></strong><br>
                            <span style="font-size:12px; color:#6b7280;"><?php _e( 'Only show your KineticLaunch personas in Copywriting Studio (hide generic defaults). Recommended ON when KineticLaunch is connected.', 'claude-ai-copywriter' ); ?></span>
                        </span>
                    </label>
                </div>

                <!-- CORE IDENTITY -->
                <h3 style="margin-top:8px; margin-bottom:4px; font-size:13px; text-transform:uppercase; letter-spacing:.06em; color:var(--kinetic-text-secondary,#6b7280);"><?php _e( 'Core Identity', 'claude-ai-copywriter' ); ?></h3>
                <table class="form-table" style="margin-top:0;">
                    <tr>
                        <th scope="row"><label for="bs_positioning"><?php _e( 'Brand Positioning', 'claude-ai-copywriter' ); ?></label></th>
                        <td>
                            <textarea name="bs_positioning" id="bs_positioning" rows="3" class="large-text"
                                placeholder="<?php esc_attr_e( 'What you do, for whom, and why you\'re different. Example: We help freelance designers charge 3x more by teaching premium positioning - without a big portfolio or cold outreach.', 'claude-ai-copywriter' ); ?>"
                            ><?php echo esc_textarea( $bs['positioning'] ?? '' ); ?></textarea>
                            <p class="description"><?php _e( 'One clear paragraph. Anchors every piece of content to your core promise.', 'claude-ai-copywriter' ); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="bs_problem_solved"><?php _e( 'Problem You Solve', 'claude-ai-copywriter' ); ?></label></th>
                        <td>
                            <textarea name="bs_problem_solved" id="bs_problem_solved" rows="2" class="large-text"
                                placeholder="<?php esc_attr_e( 'Freelance designers undercharge because they position themselves as technicians, not strategists. They compete on price instead of value.', 'claude-ai-copywriter' ); ?>"
                            ><?php echo esc_textarea( $bs['problem_solved'] ?? '' ); ?></textarea>
                            <p class="description"><?php _e( 'The specific pain your product or service eliminates. Informs hooks, headlines, and CTAs.', 'claude-ai-copywriter' ); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="bs_taglines"><?php _e( 'Taglines', 'claude-ai-copywriter' ); ?></label></th>
                        <td>
                            <textarea name="bs_taglines" id="bs_taglines" rows="2" class="large-text"
                                placeholder="<?php esc_attr_e( "Charge what you're worth.\nPremium by design.", 'claude-ai-copywriter' ); ?>"
                            ><?php echo esc_textarea( $bs['taglines'] ?? '' ); ?></textarea>
                            <p class="description"><?php _e( 'One per line. Used in CTAs, headlines, and social hooks.', 'claude-ai-copywriter' ); ?></p>
                        </td>
                    </tr>
                </table>

                <!-- AUDIENCE -->
                <h3 style="margin-top:24px; margin-bottom:4px; font-size:13px; text-transform:uppercase; letter-spacing:.06em; color:var(--kinetic-text-secondary,#6b7280);"><?php _e( 'Audience', 'claude-ai-copywriter' ); ?></h3>
                <table class="form-table" style="margin-top:0;">
                    <tr>
                        <th scope="row"><label for="bs_target_audience"><?php _e( 'Primary Audience', 'claude-ai-copywriter' ); ?></label></th>
                        <td>
                            <textarea name="bs_target_audience" id="bs_target_audience" rows="2" class="large-text"
                                placeholder="<?php esc_attr_e( 'Freelance graphic designers and brand designers, 3-8 years experience, earning $40-80k, want to break the $100k ceiling without working more hours.', 'claude-ai-copywriter' ); ?>"
                            ><?php echo esc_textarea( $bs['target_audience'] ?? '' ); ?></textarea>
                            <p class="description"><?php _e( 'Who you are primarily writing for. Be specific - age, role, situation, aspiration.', 'claude-ai-copywriter' ); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="bs_target_audience_secondary"><?php _e( 'Secondary Audience', 'claude-ai-copywriter' ); ?></label></th>
                        <td>
                            <textarea name="bs_target_audience_secondary" id="bs_target_audience_secondary" rows="2" class="large-text"
                                placeholder="<?php esc_attr_e( 'Creative agency owners who want to hire and develop their team\'s pricing confidence.', 'claude-ai-copywriter' ); ?>"
                            ><?php echo esc_textarea( $bs['target_audience_secondary'] ?? '' ); ?></textarea>
                            <p class="description"><?php _e( 'Optional. When present, KineticCopy can write content that resonates with both segments.', 'claude-ai-copywriter' ); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="bs_audience_pains"><?php _e( 'Pain Points & Objections', 'claude-ai-copywriter' ); ?></label></th>
                        <td>
                            <textarea name="bs_audience_pains" id="bs_audience_pains" rows="4" class="large-text"
                                placeholder="<?php esc_attr_e( "- \"Clients will just go to someone cheaper if I raise my rates\"\n- \"I don't have enough experience to charge premium prices yet\"\n- Imposter syndrome when presenting prices to big companies", 'claude-ai-copywriter' ); ?>"
                            ><?php echo esc_textarea( $bs['audience_pains'] ?? '' ); ?></textarea>
                            <p class="description"><?php _e( 'The fears, objections, and blockers your audience has. KineticCopy uses these to write copy that handles objections before they surface.', 'claude-ai-copywriter' ); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="bs_keywords"><?php _e( 'Target Keywords', 'claude-ai-copywriter' ); ?></label></th>
                        <td>
                            <textarea name="bs_keywords" id="bs_keywords" rows="2" class="large-text"
                                placeholder="<?php esc_attr_e( 'freelance pricing, premium design rates, how to charge more as a designer, value-based pricing for creatives', 'claude-ai-copywriter' ); ?>"
                            ><?php echo esc_textarea( $bs['keywords'] ?? '' ); ?></textarea>
                            <p class="description"><?php _e( 'Comma-separated. Woven in naturally as topic anchors, not keyword stuffing.', 'claude-ai-copywriter' ); ?></p>
                        </td>
                    </tr>
                </table>

                <!-- VOICE & PERSONALITY -->
                <h3 style="margin-top:24px; margin-bottom:4px; font-size:13px; text-transform:uppercase; letter-spacing:.06em; color:var(--kinetic-text-secondary,#6b7280);"><?php _e( 'Voice & Personality', 'claude-ai-copywriter' ); ?></h3>
                <table class="form-table" style="margin-top:0;">
                    <tr>
                        <th scope="row"><label for="bs_elevator_pitch"><?php _e( 'Elevator Pitch', 'claude-ai-copywriter' ); ?></label></th>
                        <td>
                            <textarea name="bs_elevator_pitch" id="bs_elevator_pitch" rows="2" class="large-text"
                                placeholder="<?php esc_attr_e( 'I teach freelance designers how to charge premium rates by repositioning themselves as strategic partners - not pixel pushers. Most of my students double their rates within 90 days.', 'claude-ai-copywriter' ); ?>"
                            ><?php echo esc_textarea( $bs['elevator_pitch'] ?? '' ); ?></textarea>
                            <p class="description"><?php _e( '2-3 sentences. Used in bios, introductions, and ad copy.', 'claude-ai-copywriter' ); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="bs_voice"><?php _e( 'Brand Voice Rules', 'claude-ai-copywriter' ); ?></label></th>
                        <td>
                            <textarea name="bs_voice" id="bs_voice" rows="5" class="large-text"
                                placeholder="<?php esc_attr_e( "DO: Direct, confident, data-backed, a little irreverent\nDO: Use contractions - sounds human\nNEVER: Corporate buzzwords (leverage, synergy, game-changer)\nNEVER: Passive voice\nNEVER: Start with I or We", 'claude-ai-copywriter' ); ?>"
                            ><?php echo esc_textarea( $bs['voice'] ?? '' ); ?></textarea>
                            <p class="description"><?php _e( '3-5 DO/NEVER rules. The more specific, the more recognisable the output.', 'claude-ai-copywriter' ); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="bs_tone_description"><?php _e( 'Tone Description', 'claude-ai-copywriter' ); ?></label></th>
                        <td>
                            <textarea name="bs_tone_description" id="bs_tone_description" rows="2" class="large-text"
                                placeholder="<?php esc_attr_e( 'Confident mentor who has been there. Warm but direct. Challenges assumptions without being preachy. Never talks down. Slightly irreverent toward corporate convention.', 'claude-ai-copywriter' ); ?>"
                            ><?php echo esc_textarea( $bs['tone_description'] ?? '' ); ?></textarea>
                            <p class="description"><?php _e( 'The emotional register of your brand. Think: how would your brand sound if it were a person talking?', 'claude-ai-copywriter' ); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="bs_writing_style"><?php _e( 'Writing Style', 'claude-ai-copywriter' ); ?></label></th>
                        <td>
                            <textarea name="bs_writing_style" id="bs_writing_style" rows="2" class="large-text"
                                placeholder="<?php esc_attr_e( 'Short punchy sentences. One idea per paragraph. Occasional sentence fragments for rhythm. No fluff introductions - get to the point in sentence one.', 'claude-ai-copywriter' ); ?>"
                            ><?php echo esc_textarea( $bs['writing_style'] ?? '' ); ?></textarea>
                            <p class="description"><?php _e( 'Sentence structure, rhythm, paragraph length preferences. Shapes how the copy reads, not just what it says.', 'claude-ai-copywriter' ); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="bs_personality"><?php _e( 'Brand Archetype & Personality', 'claude-ai-copywriter' ); ?></label></th>
                        <td>
                            <textarea name="bs_personality" id="bs_personality" rows="2" class="large-text"
                                placeholder="<?php esc_attr_e( "Archetype: The Sage / The Rebel\nTraits: Direct, pragmatic, empathetic, results-driven\nValues: Autonomy, craft, fairness, growth", 'claude-ai-copywriter' ); ?>"
                            ><?php echo esc_textarea( $bs['personality'] ?? '' ); ?></textarea>
                            <p class="description"><?php _e( 'Archetype, traits, and values. Guides the emotional undercurrent of every piece.', 'claude-ai-copywriter' ); ?></p>
                        </td>
                    </tr>
                </table>

                <!-- CONTENT & COMPETITIVE -->
                <h3 style="margin-top:24px; margin-bottom:4px; font-size:13px; text-transform:uppercase; letter-spacing:.06em; color:var(--kinetic-text-secondary,#6b7280);"><?php _e( 'Content & Competitive', 'claude-ai-copywriter' ); ?></h3>
                <table class="form-table" style="margin-top:0;">
                    <tr>
                        <th scope="row"><label for="bs_pillars"><?php _e( 'Content Pillars', 'claude-ai-copywriter' ); ?></label></th>
                        <td>
                            <textarea name="bs_pillars" id="bs_pillars" rows="3" class="large-text"
                                placeholder="<?php esc_attr_e( "1. Pricing psychology - help creatives charge what they're worth\n2. Client management - scope, feedback, difficult clients\n3. Portfolio positioning - making work speak to the right buyers", 'claude-ai-copywriter' ); ?>"
                            ><?php echo esc_textarea( $bs['pillars'] ?? '' ); ?></textarea>
                            <p class="description"><?php _e( '3-5 recurring themes all your content maps to. Keeps output on-topic and avoids generic angles.', 'claude-ai-copywriter' ); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="bs_key_messages"><?php _e( 'Key Messages / Value Props', 'claude-ai-copywriter' ); ?></label></th>
                        <td>
                            <textarea name="bs_key_messages" id="bs_key_messages" rows="4" class="large-text"
                                placeholder="<?php esc_attr_e( "- You don't need more clients - you need better-paying ones\n- Premium pricing is a positioning decision, not a numbers game\n- Your process is your product - document and charge for it", 'claude-ai-copywriter' ); ?>"
                            ><?php echo esc_textarea( $bs['key_messages'] ?? '' ); ?></textarea>
                            <p class="description"><?php _e( '3-4 core ideas that should echo across everything you publish. KineticCopy weaves these in naturally.', 'claude-ai-copywriter' ); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="bs_competitors"><?php _e( 'Competitors', 'claude-ai-copywriter' ); ?></label></th>
                        <td>
                            <textarea name="bs_competitors" id="bs_competitors" rows="3" class="large-text"
                                placeholder="<?php esc_attr_e( "Competitor A - budget option, high volume\nCompetitor B - enterprise, complex setup\nYour angle: mid-market, done-with-you, fast results", 'claude-ai-copywriter' ); ?>"
                            ><?php echo esc_textarea( $bs['competitors'] ?? '' ); ?></textarea>
                            <p class="description"><?php _e( 'Optional. KineticCopy positions your content to differentiate - without naming competitors unless asked.', 'claude-ai-copywriter' ); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="bs_pricing"><?php _e( 'Pricing & Tiers', 'claude-ai-copywriter' ); ?></label></th>
                        <td>
                            <textarea name="bs_pricing" id="bs_pricing" rows="5" class="large-text"
                                placeholder="<?php esc_attr_e( "Model: Subscription\nBilling: Monthly / Annual\nRange: Entry $29 - Recommended $79 - Premium $149\n- Starter: $29/mo - freelancers, 1 project\n- Growth: $79/mo - agencies, 5 projects\n- Pro: $149/mo - unlimited projects", 'claude-ai-copywriter' ); ?>"
                            ><?php echo esc_textarea( $bs['pricing'] ?? '' ); ?></textarea>
                            <p class="description"><?php _e( 'Pricing model, tiers, and price points. KineticCopy will use the actual prices in sales copy and landing pages - do not leave blank if price accuracy matters.', 'claude-ai-copywriter' ); ?></p>
                        </td>
                    </tr>
                </table>

                <p class="submit" style="margin-top:24px;">
                    <button type="submit" class="button button-primary button-large">
                        <?php _e( 'Save Brand Strategy', 'claude-ai-copywriter' ); ?>
                    </button>
                    <?php if ( $bs_completeness > 0 ) : ?>
                        <span style="margin-left:12px; color:var(--kinetic-text-secondary,#6b7280); font-size:13px;">
                            <?php printf( __( '%d of %d fields complete', 'claude-ai-copywriter' ), $bs_fields_filled, $bs_fields_total ); ?>
                        </span>
                    <?php endif; ?>
                </p>

            </div><!-- #brand-strategy -->
        </form>

        <!-- ═══════════════════════════════════════════════════
             TAB: SITE INTELLIGENCE
             ═══════════════════════════════════════════════════ -->
        <div id="site-intelligence" class="tab-content">

            <p style="color:var(--kinetic-text-secondary,#6b7280); margin-bottom:24px; max-width:720px;">
                <?php _e( 'Site Intelligence scans your existing content so KineticCopy knows your writing history, topic coverage, and style - making new generations more contextually accurate.', 'claude-ai-copywriter' ); ?>
            </p>

            <!-- Status card -->
            <div style="display:grid; grid-template-columns:repeat(auto-fit,minmax(200px,1fr)); gap:16px; margin-bottom:24px; max-width:800px;">
                <div style="background:#fff; border:1px solid #e5e7eb; border-left:4px solid <?php echo ! empty( $si_status['available'] ) ? '#16a34a' : '#d97706'; ?>; border-radius:5px; padding:16px;">
                    <div style="font-size:11px; text-transform:uppercase; letter-spacing:.06em; color:#6b7280; margin-bottom:4px;"><?php _e( 'Status', 'claude-ai-copywriter' ); ?></div>
                    <div style="font-size:16px; font-weight:600; color:<?php echo ! empty( $si_status['available'] ) ? '#065f46' : '#92400e'; ?>;">
                        <?php echo ! empty( $si_status['available'] ) ? __( 'Active', 'claude-ai-copywriter' ) : __( 'Not configured', 'claude-ai-copywriter' ); ?>
                    </div>
                </div>
                <?php if ( ! empty( $si_status['post_count'] ) ) : ?>
                <div style="background:#fff; border:1px solid #e5e7eb; border-radius:5px; padding:16px;">
                    <div style="font-size:11px; text-transform:uppercase; letter-spacing:.06em; color:#6b7280; margin-bottom:4px;"><?php _e( 'Posts Indexed', 'claude-ai-copywriter' ); ?></div>
                    <div style="font-size:24px; font-weight:700; color:#111827;"><?php echo number_format( $si_status['post_count'] ); ?></div>
                </div>
                <?php endif; ?>
                <?php if ( ! empty( $si_status['last_scan'] ) ) : ?>
                <div style="background:#fff; border:1px solid #e5e7eb; border-radius:5px; padding:16px;">
                    <div style="font-size:11px; text-transform:uppercase; letter-spacing:.06em; color:#6b7280; margin-bottom:4px;"><?php _e( 'Last Scan', 'claude-ai-copywriter' ); ?></div>
                    <div style="font-size:14px; font-weight:500; color:#374151;"><?php echo esc_html( human_time_diff( strtotime( $si_status['last_scan'] ), time() ) . ' ' . __( 'ago', 'claude-ai-copywriter' ) ); ?></div>
                </div>
                <?php endif; ?>
            </div>

            <!-- Scan button -->
            <div style="margin-bottom:24px; display:flex; gap:12px; align-items:center; flex-wrap:wrap;">
                <button type="button" id="kc-si-scan-btn" class="button button-primary">
                    <span class="dashicons dashicons-search" style="margin-top:3px;"></span>
                    <?php _e( 'Scan Site Now', 'claude-ai-copywriter' ); ?>
                </button>
                <span id="kc-si-scan-status" style="font-size:13px; color:#6b7280;"></span>
            </div>

            <!-- SI Settings form -->
            <form method="post" action="options.php" id="kc-si-settings-form">
                <?php settings_fields( 'claude_ai_copywriter_site_intelligence' ); ?>
                <table class="form-table" style="max-width:720px;">
                    <tr>
                        <th scope="row"><?php _e( 'Enable Site Intelligence', 'claude-ai-copywriter' ); ?></th>
                        <td>
                            <label>
                                <input type="checkbox" name="claude_ai_copywriter_site_intelligence[enabled]" value="1"
                                    <?php checked( $si_settings['enabled'] ?? true, 1 ); ?>>
                                <?php _e( 'Inject site content context into AI generations', 'claude-ai-copywriter' ); ?>
                            </label>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="si-rescan-days"><?php _e( 'Auto-Rescan Every', 'claude-ai-copywriter' ); ?></label></th>
                        <td>
                            <input type="number" id="si-rescan-days" name="claude_ai_copywriter_site_intelligence[auto_rescan_days]"
                                value="<?php echo absint( $si_settings['auto_rescan_days'] ?? 7 ); ?>" min="1" max="30" class="small-text">
                            <?php _e( 'days', 'claude-ai-copywriter' ); ?>
                            <p class="description"><?php _e( 'How often to automatically re-index your site content.', 'claude-ai-copywriter' ); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="si-max-posts"><?php _e( 'Max Posts to Scan', 'claude-ai-copywriter' ); ?></label></th>
                        <td>
                            <input type="number" id="si-max-posts" name="claude_ai_copywriter_site_intelligence[max_posts]"
                                value="<?php echo absint( $si_settings['max_posts'] ?? 200 ); ?>" min="10" max="1000" class="small-text">
                            <p class="description"><?php _e( 'Limits scan to the most recent N posts to keep context focused.', 'claude-ai-copywriter' ); ?></p>
                        </td>
                    </tr>
                </table>
                <?php submit_button( __( 'Save Intelligence Settings', 'claude-ai-copywriter' ) ); ?>
            </form>

            <!-- Site Intelligence link removed — page requires manage_options and is hidden from nav -->

        </div><!-- #site-intelligence -->

        <!-- ═══════════════════════════════════════════════════
             TAB: PERSONAS
             ═══════════════════════════════════════════════════ -->
        <div id="personas" class="tab-content">

            <p style="color:var(--kinetic-text-secondary,#6b7280); margin-bottom:16px; max-width:720px;">
                <?php _e( 'Personas tell KineticCopy exactly who to write for. Select one in Copywriting Studio to tailor every generation to that specific reader.', 'claude-ai-copywriter' ); ?>
            </p>

            <div style="margin-bottom:16px; display:flex; gap:12px; align-items:center;">
                <button type="button" id="kc-add-persona-btn" class="button button-primary">
                    + <?php _e( 'Add Persona', 'claude-ai-copywriter' ); ?>
                </button>
            </div>

            <!-- Add / Edit form (hidden by default) -->
            <div id="kc-persona-form-wrap" style="display:none; background:#f9fafb; border:1px solid #e5e7eb; border-radius:5px; padding:20px; margin-bottom:20px; max-width:720px;">
                <h3 style="margin-top:0;" id="kc-persona-form-title"><?php _e( 'New Persona', 'claude-ai-copywriter' ); ?></h3>
                <input type="hidden" id="kc-persona-editing-id" value="">
                <table class="form-table" style="margin-top:0;">
                    <tr>
                        <th scope="row"><label for="kc-persona-name"><?php _e( 'Persona Name', 'claude-ai-copywriter' ); ?></label></th>
                        <td><input type="text" id="kc-persona-name" class="regular-text" placeholder="<?php esc_attr_e( 'e.g. Ambitious Freelancer, Budget-Conscious SME', 'claude-ai-copywriter' ); ?>"></td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="kc-persona-demographics"><?php _e( 'Demographics', 'claude-ai-copywriter' ); ?></label></th>
                        <td>
                            <textarea id="kc-persona-demographics" rows="3" class="large-text"
                                placeholder="<?php esc_attr_e( "Age: 28-40\nRole: Freelance designer\nIncome: $40-80k\nLocation: US/UK/AU urban", 'claude-ai-copywriter' ); ?>"></textarea>
                            <p class="description"><?php _e( 'Age, role, income, location, family situation.', 'claude-ai-copywriter' ); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="kc-persona-psychographics"><?php _e( 'Psychographics', 'claude-ai-copywriter' ); ?></label></th>
                        <td>
                            <textarea id="kc-persona-psychographics" rows="3" class="large-text"
                                placeholder="<?php esc_attr_e( "Goals: Double rates within a year\nFears: Losing clients if they raise prices\nValues: Creative freedom, fair recognition", 'claude-ai-copywriter' ); ?>"></textarea>
                            <p class="description"><?php _e( 'Goals, fears, values, interests, motivations.', 'claude-ai-copywriter' ); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="kc-persona-communication"><?php _e( 'Communication Style', 'claude-ai-copywriter' ); ?></label></th>
                        <td>
                            <textarea id="kc-persona-communication" rows="2" class="large-text"
                                placeholder="<?php esc_attr_e( 'Direct, peer-to-peer tone. Lead with results. Avoid corporate jargon. Short paragraphs.', 'claude-ai-copywriter' ); ?>"></textarea>
                            <p class="description"><?php _e( 'How to speak TO this persona. Guides tone and framing.', 'claude-ai-copywriter' ); ?></p>
                        </td>
                    </tr>
                </table>
                <div style="display:flex; gap:8px; margin-top:12px;">
                    <button type="button" id="kc-persona-save-btn" class="button button-primary"><?php _e( 'Save Persona', 'claude-ai-copywriter' ); ?></button>
                    <button type="button" id="kc-persona-cancel-btn" class="button"><?php _e( 'Cancel', 'claude-ai-copywriter' ); ?></button>
                    <span id="kc-persona-save-status" style="font-size:13px; color:#6b7280; align-self:center;"></span>
                </div>
            </div>

            <!-- Persona list -->
            <div id="kc-persona-list" style="max-width:800px;">

                <?php
                $user_id = get_current_user_id();
                $user_personas    = array_filter( $personas, fn($p) => ! $p->is_global );
                $default_personas = array_filter( $personas, fn($p) => $p->is_global );
                ?>

                <?php if ( ! empty( $user_personas ) ) : ?>
                <h4 style="margin:0 0 8px; font-size:12px; text-transform:uppercase; letter-spacing:.06em; color:#6b7280;"><?php _e( 'Your Personas', 'claude-ai-copywriter' ); ?></h4>
                <table class="wp-list-table widefat fixed striped" style="margin-bottom:24px;">
                    <thead>
                        <tr>
                            <th style="width:30%"><?php _e( 'Name', 'claude-ai-copywriter' ); ?></th>
                            <th><?php _e( 'Communication Style', 'claude-ai-copywriter' ); ?></th>
                            <th style="width:120px;"><?php _e( 'Actions', 'claude-ai-copywriter' ); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ( $user_personas as $persona ) : ?>
                        <tr data-persona-id="<?php echo (int) $persona->id; ?>">
                            <td>
                                <strong><?php echo esc_html( $persona->persona_name ); ?></strong>
                                <?php if ( ! empty( $persona->demographics ) ) : ?>
                                <div style="font-size:12px; color:#6b7280; margin-top:2px; white-space:pre-line;"><?php echo esc_html( is_array( $persona->demographics ) ? implode( ', ', array_filter( $persona->demographics ) ) : substr( (string) $persona->demographics, 0, 80 ) ); ?></div>
                                <?php endif; ?>
                            </td>
                            <td style="font-size:13px; color:#374151;"><?php echo esc_html( substr( $persona->communication_style ?? '', 0, 120 ) ); ?></td>
                            <td>
                                <button type="button" class="button button-small kc-edit-persona"
                                    data-id="<?php echo (int) $persona->id; ?>"
                                    data-name="<?php echo esc_attr( $persona->persona_name ); ?>"
                                    data-demographics="<?php echo esc_attr( is_array( $persona->demographics ) ? implode( "\n", array_map( fn($k,$v) => "{$k}: {$v}", array_keys( $persona->demographics ), $persona->demographics ) ) : (string)($persona->demographics ?? '') ); ?>"
                                    data-psychographics="<?php echo esc_attr( is_array( $persona->psychographics ) ? implode( "\n", array_map( fn($k,$v) => "{$k}: {$v}", array_keys( $persona->psychographics ), $persona->psychographics ) ) : (string)($persona->psychographics ?? '') ); ?>"
                                    data-communication="<?php echo esc_attr( $persona->communication_style ?? '' ); ?>"
                                ><?php _e( 'Edit', 'claude-ai-copywriter' ); ?></button>
                                <button type="button" class="button button-small kc-delete-persona" data-id="<?php echo (int) $persona->id; ?>" style="color:#dc2626; border-color:#dc2626;"><?php _e( 'Delete', 'claude-ai-copywriter' ); ?></button>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                <?php else : ?>
                <div class="kc-persona-empty-state">
                    <p><?php _e( 'No custom personas yet. Create your first one to target writing to a specific reader.', 'claude-ai-copywriter' ); ?></p>
                    <button type="button" class="button button-primary kc-trigger-add-persona"><?php _e( '+ Add Your First Persona', 'claude-ai-copywriter' ); ?></button>
                </div>
                <?php endif; ?>

                <?php if ( ! empty( $default_personas ) ) : ?>
                <details style="margin-top:16px;">
                    <summary style="font-size:12px; text-transform:uppercase; letter-spacing:.06em; color:#6b7280; cursor:pointer; margin-bottom:8px;"><?php _e( 'Default Personas', 'claude-ai-copywriter' ); ?> (<?php echo count( $default_personas ); ?>)</summary>
                    <table class="wp-list-table widefat fixed striped" style="margin-top:8px; opacity:.85;">
                        <tbody>
                            <?php foreach ( $default_personas as $persona ) : ?>
                            <tr>
                                <td style="width:30%;"><strong><?php echo esc_html( $persona->persona_name ); ?></strong></td>
                                <td style="font-size:13px; color:#374151;"><?php echo esc_html( substr( $persona->communication_style ?? '', 0, 120 ) ); ?></td>
                                <td style="width:80px; font-size:12px; color:#9ca3af;"><?php _e( 'Default', 'claude-ai-copywriter' ); ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </details>
                <?php endif; ?>

            </div><!-- #kc-persona-list -->

        </div><!-- #personas -->

    </div><!-- .claude-settings-container -->
</div><!-- .wrap -->

<script>
(function($){
    // ─── Tab switching ────────────────────────────────────────────────────────
    var $tabs   = $('.nav-tab-wrapper .nav-tab');
    var $panes  = $('.claude-settings-container .tab-content');

    function activateTab(hash) {
        var target = hash || '#brand-strategy';
        $tabs.removeClass('nav-tab-active');
        $panes.removeClass('active').hide();
        $tabs.filter('[href="' + target + '"]').addClass('nav-tab-active');
        $(target).addClass('active').show();
    }

    $tabs.on('click', function(e){
        e.preventDefault();
        var hash = $(this).attr('href');
        activateTab(hash);
        history.replaceState(null, '', location.pathname + location.search + hash);
    });

    // Honour URL hash on load
    if (location.hash && $('.nav-tab[href="' + location.hash + '"]').length) {
        activateTab(location.hash);
    } else {
        $panes.not('#brand-strategy').hide();
        $('#brand-strategy').show();
    }

    // ─── Site Intelligence: scan button ──────────────────────────────────────
    $('#kc-si-scan-btn').on('click', function(){
        var $btn = $(this);
        var $status = $('#kc-si-scan-status');
        $btn.prop('disabled', true).text('<?php esc_js( _e( 'Scanning...', 'claude-ai-copywriter' ) ); ?>');
        $status.text('');

        $.post(ajaxurl, {
            action: 'claude_scan_site',
            nonce: '<?php echo wp_create_nonce('claude_scan_site'); ?>'
        }, function(res){
            $btn.prop('disabled', false).html('<span class="dashicons dashicons-search" style="margin-top:3px;"></span> <?php esc_js( _e( 'Scan Site Now', 'claude-ai-copywriter' ) ); ?>');
            if (res.success) {
                $status.css('color','#16a34a').text(res.data.message || '<?php esc_js( _e( 'Scan complete.', 'claude-ai-copywriter' ) ); ?>');
            } else {
                $status.css('color','#dc2626').text(res.data.message || '<?php esc_js( _e( 'Scan failed.', 'claude-ai-copywriter' ) ); ?>');
            }
        }).fail(function(){
            $btn.prop('disabled', false);
            $status.css('color','#dc2626').text('<?php esc_js( _e( 'Request failed. Please try again.', 'claude-ai-copywriter' ) ); ?>');
        });
    });

    // ─── Personas: Add / Cancel ───────────────────────────────────────────────
    function openPersonaForm(editData) {
        var $form = $('#kc-persona-form-wrap');
        if (editData) {
            $('#kc-persona-form-title').text('<?php esc_js( _e( 'Edit Persona', 'claude-ai-copywriter' ) ); ?>');
            $('#kc-persona-editing-id').val(editData.id);
            $('#kc-persona-name').val(editData.name);
            $('#kc-persona-demographics').val(editData.demographics);
            $('#kc-persona-psychographics').val(editData.psychographics);
            $('#kc-persona-communication').val(editData.communication);
        } else {
            $('#kc-persona-form-title').text('<?php esc_js( _e( 'New Persona', 'claude-ai-copywriter' ) ); ?>');
            $('#kc-persona-editing-id').val('');
            $('#kc-persona-name, #kc-persona-demographics, #kc-persona-psychographics, #kc-persona-communication').val('');
        }
        $('#kc-persona-save-status').text('');
        $form.slideDown(200);
        $('#kc-persona-name').focus();
    }

    $('#kc-add-persona-btn, .kc-trigger-add-persona').on('click', function(){
        openPersonaForm(null);
    });

    $('#kc-persona-cancel-btn').on('click', function(){
        $('#kc-persona-form-wrap').slideUp(200);
    });

    // Edit persona
    $(document).on('click', '.kc-edit-persona', function(){
        openPersonaForm({
            id:             $(this).data('id'),
            name:           $(this).data('name'),
            demographics:   $(this).data('demographics'),
            psychographics: $(this).data('psychographics'),
            communication:  $(this).data('communication')
        });
        $('html,body').animate({ scrollTop: $('#kc-persona-form-wrap').offset().top - 60 }, 200);
    });

    // Save persona (create or update)
    $('#kc-persona-save-btn').on('click', function(){
        var editingId = $('#kc-persona-editing-id').val();
        var name      = $('#kc-persona-name').val().trim();
        var $status   = $('#kc-persona-save-status');

        if (!name) {
            $status.css('color','#dc2626').text('<?php esc_js( _e( 'Persona name is required.', 'claude-ai-copywriter' ) ); ?>');
            return;
        }

        var action   = editingId ? 'claude_update_persona' : 'claude_create_persona';
        var postData = {
            action:              action,
            nonce:               '<?php echo wp_create_nonce('claude_persona_management'); ?>',
            persona_name:        name,
            demographics:        $('#kc-persona-demographics').val(),
            psychographics:      $('#kc-persona-psychographics').val(),
            communication_style: $('#kc-persona-communication').val(),
        };
        if (editingId) postData.persona_id = editingId;

        $('#kc-persona-save-btn').prop('disabled', true);
        $status.css('color','#6b7280').text('<?php esc_js( _e( 'Saving...', 'claude-ai-copywriter' ) ); ?>');

        $.post(ajaxurl, postData, function(res){
            $('#kc-persona-save-btn').prop('disabled', false);
            if (res.success) {
                $status.css('color','#16a34a').text('<?php esc_js( _e( 'Saved!', 'claude-ai-copywriter' ) ); ?>');
                setTimeout(function(){ location.reload(); }, 800);
            } else {
                $status.css('color','#dc2626').text(res.data.message || '<?php esc_js( _e( 'Error saving persona.', 'claude-ai-copywriter' ) ); ?>');
            }
        }).fail(function(){
            $('#kc-persona-save-btn').prop('disabled', false);
            $status.css('color','#dc2626').text('<?php esc_js( _e( 'Request failed.', 'claude-ai-copywriter' ) ); ?>');
        });
    });

    // Delete persona
    $(document).on('click', '.kc-delete-persona', function(){
        if (!confirm('<?php esc_js( _e( 'Delete this persona? This cannot be undone.', 'claude-ai-copywriter' ) ); ?>')) return;
        var personaId = $(this).data('id');
        var $row      = $(this).closest('tr');

        $.post(ajaxurl, {
            action:     'claude_delete_persona',
            nonce:      '<?php echo wp_create_nonce('claude_persona_management'); ?>',
            persona_id: personaId
        }, function(res){
            if (res.success) {
                $row.fadeOut(300, function(){ $(this).remove(); });
            } else {
                alert(res.data.message || '<?php esc_js( _e( 'Could not delete persona.', 'claude-ai-copywriter' ) ); ?>');
            }
        });
    });

}(jQuery));
</script>
