<?php
declare(strict_types=1);
// ==================================================
// Nuclear Fancy Pants Edition™ — NUCLEAR+++
// File: /templates/social/facebook-dashboard.php
// Description: Facebook connected dashboard — feed layout with approval mode toggle — NUCLEAR+++
// Last Edited: 2026-04-10
// ==================================================

namespace AutoMarketerAI;

defined('ABSPATH') || exit;

$fb = FacebookAuth::getConnection();
if ($fb === null) {
    $connect_url = FacebookAuth::getAuthUrl();
    include AMAI_PLUGIN_DIR . 'templates/social/facebook-connect.php';
    return;
}

// Tab routing — dashboard (default) or compose
$active_tab = sanitize_key((string) ($_GET['tab'] ?? 'dashboard'));
if (!in_array($active_tab, ['dashboard', 'compose'], true)) {
    $active_tab = 'dashboard';
}
if ($active_tab === 'compose') {
    include AMAI_PLUGIN_DIR . 'templates/manual-post.php';
    return;
}
$page_name        = esc_html((string) ($fb['page_name'] ?? ''));
$page_category    = esc_html((string) ($fb['page_category'] ?? ''));
$page_pic         = esc_url((string) ($fb['page_picture_url'] ?? ''));
$follows_raw      = (int) ($fb['page_followers'] ?? 0);
$page_follows     = number_format($follows_raw) . ' ' . ($follows_raw === 1 ? 'follower' : 'followers');
$connected_at     = esc_html((string) ($fb['connected_at'] ?? ''));
$connected_ago    = $connected_at !== ''
    ? human_time_diff(strtotime($connected_at), current_time('timestamp', true)) . ' ago'
    : '';
$initials         = strtoupper(substr((string) ($fb['page_name'] ?? 'P'), 0, 2));
$disconnect_nonce = wp_create_nonce('amai_fb_disconnect');

$approval_mode       = (get_option('amai_approval_mode', 'review') === 'autopilot') ? 'autopilot' : 'review';
$approval_mode_nonce = wp_create_nonce('amai_save_approval_mode');

global $wpdb;

// --------------------------------------------------
// Autopilot nudge — consecutive approved post streak
// --------------------------------------------------
$show_autopilot_nudge  = false;
$nudge_nonce           = '';
$nudge_dismiss_nonce   = '';
if ($approval_mode === 'review') {
    $dismissed_at = (int) get_user_meta(get_current_user_id(), 'amai_autopilot_nudge_dismissed_at', true);
    $threshold    = (int) get_option('amai_autopilot_nudge_threshold', 20);

    // Walk approved posts from newest to oldest — stop at first non-approved
    $all_statuses = $wpdb->get_results(
        $wpdb->prepare(
            "SELECT id, status FROM `{$wpdb->prefix}amai_scheduled_posts`
             WHERE tenant_id = %s
             ORDER BY id DESC
             LIMIT 200",
            'default'
        ),
        ARRAY_A
    );

    $streak         = 0;
    $latest_post_id = 0;
    foreach ($all_statuses as $row) {
        if ($row['status'] !== 'approved') {
            break;
        }
        if ($latest_post_id === 0) {
            $latest_post_id = (int) $row['id'];
        }
        $streak++;
    }

    // Show nudge if streak meets threshold and user hasn't dismissed since latest approval
    if ($streak >= $threshold && $latest_post_id > $dismissed_at) {
        $show_autopilot_nudge = true;
        $nudge_nonce          = wp_create_nonce('amai_save_approval_mode');
        $nudge_dismiss_nonce  = wp_create_nonce('amai_autopilot_nudge_dismiss');
    }
}

// --------------------------------------------------
// --------------------------------------------------
$channel = 'facebook';
// Batch selection - weekly batches only (manual posts merge into weekly view)
// --------------------------------------------------
$all_batches_raw = $wpdb->get_col(
    $wpdb->prepare(
        "SELECT DISTINCT generation_batch
         FROM `{$wpdb->prefix}amai_scheduled_posts`
         WHERE tenant_id = %s AND channel = 'facebook'
         ORDER BY generation_batch DESC",
        'default'
    )
);
// Weekly batches from automated posts
$all_batches_weekly = array_values(array_filter($all_batches_raw, static fn($b) => (bool) preg_match('/^\d{4}-W\d{2}$/', (string) $b)));
// Derive ISO week keys from manual posts so manual-only weeks appear in nav
$manual_dates = $wpdb->get_col(
    $wpdb->prepare(
        "SELECT DISTINCT scheduled_date FROM `{$wpdb->prefix}amai_scheduled_posts`
         WHERE tenant_id = %s AND channel = %s AND generation_batch LIKE 'manual-%'",
        'default',
        $channel ?? ''
    )
);
$all_batches_manual_weeks = [];
foreach ($manual_dates as $_md) {
    $_dto = new \DateTimeImmutable($_md, new \DateTimeZone('UTC'));
    $all_batches_manual_weeks[] = $_dto->format('o') . '-W' . $_dto->format('W');
}
$all_batches = array_values(array_unique(array_merge($all_batches_weekly, $all_batches_manual_weeks)));
usort($all_batches, static fn($a, $b) => strcmp($b, $a));

$batch_param   = sanitize_text_field((string) ($_GET['batch'] ?? ''));
$current_batch = '';
if ($batch_param !== '' && in_array($batch_param, $all_batches, true)) {
    $current_batch = $batch_param;
} elseif (!empty($all_batches)) {
    $current_batch = $all_batches[0];
}

// --------------------------------------------------
// Load posts for the selected batch
// --------------------------------------------------
$posts_raw  = [];
$week_label = '';

if ($current_batch !== '') {
    // Load weekly posts for this batch
    $weekly_posts = $wpdb->get_results(
        $wpdb->prepare(
            'SELECT id, post_type, scheduled_date, scheduled_time, status, post_content,
                    post_image_url, feeling, generation_batch,
                    unsplash_attachment_id, unsplash_credit,
                    stat_likes, stat_comments, stat_reach, stats_fetched_at,
                    failure_reason, posted_at
             FROM `' . $wpdb->prefix . 'amai_scheduled_posts`
             WHERE tenant_id = %s AND channel = %s AND generation_batch = %s
             ORDER BY scheduled_date ASC',
            'default',
            'facebook',
            $current_batch
        ),
        ARRAY_A
    );

    // Derive week date range from batch key (e.g. 2026-W17)
    if (!empty($weekly_posts)) {
        $week_start_str = $weekly_posts[0]['scheduled_date'];
        $week_end_str   = $weekly_posts[count($weekly_posts) - 1]['scheduled_date'];
    } else {
        // Parse ISO week to Mon-Fri date range
        [$iso_year, $iso_week] = explode('-W', $current_batch);
        $week_start_obj = new \DateTimeImmutable();
        $week_start_obj = $week_start_obj->setISODate((int) $iso_year, (int) $iso_week, 1);
        $week_start_str = $week_start_obj->format('Y-m-d');
        $week_end_str   = $week_start_obj->modify('+6 days')->format('Y-m-d');
    }

    // Load manual posts for the same date range
    $manual_posts = $wpdb->get_results(
        $wpdb->prepare(
            'SELECT id, post_type, scheduled_date, scheduled_time, status, post_content,
                    post_image_url, feeling, generation_batch,
                    unsplash_attachment_id, unsplash_credit,
                    stat_likes, stat_comments, stat_reach, stats_fetched_at,
                    failure_reason, posted_at
             FROM `' . $wpdb->prefix . 'amai_scheduled_posts`
             WHERE tenant_id = %s AND channel = %s
               AND generation_batch LIKE %s
               AND scheduled_date BETWEEN %s AND %s
             ORDER BY scheduled_date ASC',
            'default',
            'facebook',
            'manual-%',
            $week_start_str,
            $week_end_str
        ),
        ARRAY_A
    );

    $posts_raw = array_merge($weekly_posts, $manual_posts);

    if (!empty($weekly_posts)) {
        $first = new \DateTimeImmutable($weekly_posts[0]['scheduled_date'], new \DateTimeZone('UTC'));
        $last  = new \DateTimeImmutable($weekly_posts[count($weekly_posts) - 1]['scheduled_date'], new \DateTimeZone('UTC'));
        $week_label = $first->format('M j') . ' - ' . $last->format('M j, Y');
    } else {
        $week_label = $current_batch;
    }
}

$posts_by_type = [];
foreach ($posts_raw as $p) {
    if (!str_starts_with((string) ($p['generation_batch'] ?? ''), 'manual-')) {
        $posts_by_type[$p['post_type']] = $p;
    }
}

// --------------------------------------------------
// Build display rows in scheduled_date order
// --------------------------------------------------
$all_type_labels = [
    'educational'   => 'Educational',
    'product'       => 'Product',
    'feel_good'     => 'Feel-good',
    'behind_scenes' => 'Behind scenes',
    'engagement'    => 'Engagement',
    'quote'         => 'Quote',
    'humor'         => 'Humor',
    'myth_bust'     => 'Myth bust',
    'tip'           => 'Tip',
    'milestone'     => 'Milestone',
    'testimonial'   => 'Testimonial',
];

$day_types = [];
if (!empty($posts_by_type)) {
    foreach ($posts_by_type as $_pt => $_p) {
        $day_types[$_pt] = $all_type_labels[$_pt] ?? ucfirst(str_replace('_', ' ', $_pt));
    }
} else {
    $day_types = array_slice($all_type_labels, 0, 5, true);
}

$today_str = (new \DateTimeImmutable('today', new \DateTimeZone('UTC')))->format('Y-m-d');

// Build weekly feed rows
$feed_rows = [];
foreach (array_keys($day_types) as $type) {
    $post        = $posts_by_type[$type] ?? null;
    $date_str    = $post['scheduled_date'] ?? '';
    $date_obj    = $date_str !== '' ? new \DateTimeImmutable($date_str, new \DateTimeZone('UTC')) : null;
    $feed_rows[] = [
        'type'         => $type,
        'label'        => $day_types[$type],
        'dow'          => $date_obj !== null ? $date_obj->format('D') : '',
        'day_num'      => $date_obj !== null ? $date_obj->format('j') : '',
        'month_short'  => $date_obj !== null ? $date_obj->format('M') : '',
        'date_display' => $date_obj !== null ? $date_obj->format('M j') : '',
        'is_today'     => $date_str === $today_str,
        'is_manual'    => false,
        'post'         => $post,
    ];
}

// Insert manual posts interleaved by date
foreach ($posts_raw as $mp) {
    if (!str_starts_with((string) ($mp['generation_batch'] ?? ''), 'manual-')) {
        continue;
    }
    $date_str = $mp['scheduled_date'] ?? '';
    $date_obj = $date_str !== '' ? new \DateTimeImmutable($date_str, new \DateTimeZone('UTC')) : null;
    $feed_rows[] = [
        'type'         => $mp['post_type'],
        'label'        => $all_type_labels[$mp['post_type']] ?? ucfirst(str_replace('_', ' ', $mp['post_type'])),
        'dow'          => $date_obj !== null ? $date_obj->format('D') : '',
        'day_num'      => $date_obj !== null ? $date_obj->format('j') : '',
        'month_short'  => $date_obj !== null ? $date_obj->format('M') : '',
        'date_display' => $date_obj !== null ? $date_obj->format('M j') : '',
        'is_today'     => $date_str === $today_str,
        'is_manual'    => true,
        'post'         => $mp,
    ];
}

// Sort all rows by scheduled_date ASC
usort($feed_rows, static function (array $a, array $b): int {
    $da = $a['post']['scheduled_date'] ?? '';
    $db = $b['post']['scheduled_date'] ?? '';
    return strcmp($da, $db);
});
// Batch nav — prev/next in the sorted list
// --------------------------------------------------
$base_url      = admin_url('admin.php?page=automarketer-ai-social&channel=facebook');
$batch_index   = array_search($current_batch, $all_batches, true);
$prev_batch    = ($batch_index !== false && isset($all_batches[$batch_index + 1])) ? $all_batches[$batch_index + 1] : null;
$next_batch    = ($batch_index !== false && $batch_index > 0) ? $all_batches[$batch_index - 1] : null;
$prev_url      = $prev_batch !== null ? esc_url($base_url . '&batch=' . rawurlencode($prev_batch)) : '';
$next_url      = $next_batch !== null ? esc_url($base_url . '&batch=' . rawurlencode($next_batch)) : '';

$action_nonce   = wp_create_nonce('amai_post_action');
$save_nonce     = wp_create_nonce('amai_post_save');
$regen_nonce    = wp_create_nonce('amai_post_regenerate');
$post_now_nonce = wp_create_nonce('amai_post_now');
$upload_nonce   = wp_create_nonce('amai_image_upload');
$feeling_labels = [
    'HAPPY'        => '😊 Happy',
    'EXCITED'      => '🤩 Excited',
    'GRATEFUL'     => '🙏 Grateful',
    'BLESSED'      => '✨ Blessed',
    'MOTIVATED'    => '💪 Motivated',
    'PROUD'        => '🦁 Proud',
    'THANKFUL'     => '💛 Thankful',
    'INSPIRED'     => '💡 Inspired',
    'HOPEFUL'      => '🌱 Hopeful',
    'DETERMINED'   => '🎯 Determined',
    'OPTIMISTIC'   => '☀️ Optimistic',
    'CONFIDENT'    => '💼 Confident',
    'LOVED'        => '❤️ Loved',
    'ACCOMPLISHED' => '🏆 Accomplished',
    'ENERGIZED'    => '⚡ Energized',
    'FOCUSED'      => '🔍 Focused',
    'JOYFUL'       => '🎉 Joyful',
    'CELEBRATED'   => '🥂 Celebrated',
    'AMBITIOUS'    => '🚀 Ambitious',
    'REFRESHED'    => '🌿 Refreshed',
    'FANTASTIC'    => '🌟 Fantastic',
    'WONDERFUL'    => '🦋 Wonderful',
    'POSITIVE'     => '👍 Positive',
    'STRONG'       => '💥 Strong',
    'THRILLED'     => '🎊 Thrilled',
];

// Determine whether this is the most recent batch (used for action visibility)
$is_latest_batch = ($batch_index === 0 || $batch_index === false);

// --------------------------------------------------
// Bio writer — pre-fill URL from business profile
// --------------------------------------------------
$bio_profile     = new \AutoMarketerAI\BusinessProfile();
$bio_profile_row = $bio_profile->get();
$bio_website_url = esc_attr((string) ($bio_profile_row['website_url'] ?? ''));
$bio_nonce       = wp_create_nonce('amai_generate_fb_bio');
$bio_saved_text  = trim((string) ($bio_profile_row['facebook_bio'] ?? ''));
$bio_has_saved   = $bio_saved_text !== '';
?>
<?php
// Token expiry warning — show banner if token expires within 30 days
$_amai_token_expires_at  = (string) ($fb['token_expires_at'] ?? '');
$_amai_show_token_warning = false;
$_amai_token_days_left    = null;
if ($_amai_token_expires_at !== '') {
    $_amai_expires_ts        = strtotime($_amai_token_expires_at);
    $_amai_days_left_raw     = $_amai_expires_ts !== false ? (int) ceil(($_amai_expires_ts - time()) / DAY_IN_SECONDS) : 0;
    $_amai_token_days_left   = $_amai_days_left_raw;
    if ($_amai_days_left_raw <= 30 && $_amai_days_left_raw > 0) {
        $_amai_show_token_warning = true;
    }
}
$_amai_gen_failed        = get_option('amai_generation_failed', []);
$_amai_gen_failed_fb     = is_array($_amai_gen_failed) && ($_amai_gen_failed['channel'] ?? '') === 'facebook';
$_amai_regen_nonce       = wp_create_nonce('amai_regenerate_week');
?>
<?php if ($_amai_show_token_warning) : ?>
<div class="amai-fbdash-notice amai-fbdash-notice--info" id="amai-token-expiry-warning">
    <svg width="15" height="15" viewBox="0 0 15 15" fill="none" aria-hidden="true" style="flex-shrink:0;margin-top:1px;"><circle cx="7.5" cy="7.5" r="6" stroke="#1877F2" stroke-width="1.4"/><path d="M7.5 5v.5M7.5 7v3.5" stroke="#1877F2" stroke-width="1.4" stroke-linecap="round"/></svg>
    <span>Your Facebook connection renews automatically - no action needed. It's valid for <?php echo (int) $_amai_token_days_left; ?> more day<?php echo $_amai_token_days_left === 1 ? '' : 's'; ?>. <a href="<?php echo esc_url(FacebookAuth::getAuthUrl(false)); ?>" class="amai-token-reauth-link">Refresh manually</a> if you prefer.</span>
</div>
<?php endif; ?>
<?php if ($_amai_gen_failed_fb) : ?>
<div class="amai-fbdash-notice amai-fbdash-notice--warn" id="amai-gen-failed-notice">
    <svg width="15" height="15" viewBox="0 0 15 15" fill="none" aria-hidden="true" style="flex-shrink:0;margin-top:1px;"><circle cx="7.5" cy="7.5" r="6" stroke="#D97757" stroke-width="1.4"/><path d="M7.5 4.5v4M7.5 10v1" stroke="#D97757" stroke-width="1.4" stroke-linecap="round"/></svg>
    <span>We had trouble generating this week's posts. <button type="button" class="amai-regen-week-btn" data-nonce="<?php echo esc_attr($_amai_regen_nonce); ?>" data-channel="facebook">Try again</button></span>
</div>
<?php endif; ?>
<div class="amai-fb-tabs">
    <a href="<?php echo esc_url(admin_url('admin.php?page=automarketer-ai-social&channel=facebook')); ?>"
       class="amai-fb-tab<?php echo $active_tab === 'dashboard' ? ' amai-fb-tab--active' : ''; ?>">
        Dashboard
    </a>
    <a href="<?php echo esc_url(admin_url('admin.php?page=automarketer-ai-social&channel=facebook&tab=compose')); ?>"
       class="amai-fb-tab<?php echo $active_tab === 'compose' ? ' amai-fb-tab--active' : ''; ?>">
        Compose Post
    </a>
</div>
<div class="amai-fbdash" data-approval-mode="<?php echo esc_attr($approval_mode); ?>">

    <?php if (isset($_GET['connected'])) : ?>
    <div class="amai-fbdash-notice amai-fbdash-notice--success">
        You're connected! We'll start getting to know your business so we can write posts that actually sound like you.
    </div>
    <?php endif; ?>

    <?php if ($show_autopilot_nudge) : ?>
    <div class="amai-fbdash-notice amai-fbdash-notice--nudge" id="amai-autopilot-nudge">
        <div class="amai-nudge-body">
            <div class="amai-nudge-text">
                <strong>You're on a roll.</strong> You've approved your last <?php echo (int) get_option('amai_autopilot_nudge_threshold', 20); ?> posts without a single change - your content is dialled in. Let Autopilot take it from here.
            </div>
            <div class="amai-nudge-actions">
                <button type="button" class="amai-nudge-btn-primary" id="amai-nudge-enable-autopilot"
                    data-nonce="<?php echo esc_attr($nudge_nonce); ?>">
                    Switch to Autopilot
                </button>
                <button type="button" class="amai-nudge-btn-dismiss" id="amai-nudge-dismiss"
                    data-nonce="<?php echo esc_attr($nudge_dismiss_nonce); ?>">
                    Not yet
                </button>
            </div>
        </div>
    </div>
    <script>
    (function () {
        var nudge        = document.getElementById('amai-autopilot-nudge');
        var btnEnable    = document.getElementById('amai-nudge-enable-autopilot');
        var btnDismiss   = document.getElementById('amai-nudge-dismiss');
        var approvalNonce = <?php echo wp_json_encode($nudge_nonce); ?>;
        var dismissNonce  = <?php echo wp_json_encode($nudge_dismiss_nonce); ?>;

        function hideNudge() {
            if (nudge) { nudge.style.display = 'none'; }
        }

        if (btnEnable) {
            btnEnable.addEventListener('click', function () {
                btnEnable.disabled = true;
                btnEnable.textContent = 'Switching…';
                var fd = new FormData();
                fd.append('action', 'amai_save_approval_mode');
                fd.append('_wpnonce', approvalNonce);
                fd.append('mode', 'autopilot');
                fetch(window.ajaxurl || '/wp-admin/admin-ajax.php', {
                    method: 'POST', credentials: 'same-origin', body: fd,
                })
                .then(function (r) { return r.json(); })
                .then(function (data) {
                    if (data && data.success) {
                        // Sync the segmented control in the approval bar
                        var dash = document.querySelector('.amai-fbdash');
                        if (dash) { dash.dataset.approvalMode = 'autopilot'; }
                        var seg = document.getElementById('amai-approval-seg');
                        if (seg) {
                            seg.querySelectorAll('.amai-approval-seg-btn').forEach(function (b) {
                                b.classList.toggle('active', b.dataset.mode === 'autopilot');
                            });
                        }
                        var hint = document.getElementById('amai-approval-hint');
                        if (hint) { hint.textContent = 'Posts go out automatically at their scheduled time. Click any post to read it.'; }
                        hideNudge();
                    } else {
                        btnEnable.disabled = false;
                        btnEnable.textContent = 'Switch to Autopilot';
                    }
                })
                .catch(function () {
                    btnEnable.disabled = false;
                    btnEnable.textContent = 'Switch to Autopilot';
                });
            });
        }

        if (btnDismiss) {
            btnDismiss.addEventListener('click', function () {
                var fd = new FormData();
                fd.append('action', 'amai_autopilot_nudge_dismiss');
                fd.append('_wpnonce', dismissNonce);
                fetch(window.ajaxurl || '/wp-admin/admin-ajax.php', {
                    method: 'POST', credentials: 'same-origin', body: fd,
                }).catch(function () {});
                hideNudge();
            });
        }
    }());
    </script>
    <?php endif; ?>

    <div class="amai-fbdash-page-card">
        <div class="amai-fbdash-page-identity">
            <div class="amai-fbdash-page-avatar">
                <?php if ($page_pic !== '') : ?>
                    <img src="<?php echo $page_pic; ?>" alt="<?php echo $page_name; ?>" width="56" height="56"/>
                <?php else : ?>
                    <div class="amai-fbdash-page-initials"><?php echo esc_html($initials); ?></div>
                <?php endif; ?>
                <span class="amai-fbdash-status-dot" title="Connected"></span>
            </div>
            <div class="amai-fbdash-page-meta">
                <div class="amai-fbdash-page-name"><?php echo $page_name; ?></div>
                <div class="amai-fbdash-page-sub">
                    <?php if ($page_category !== '') : ?>
                        <span><?php echo $page_category; ?></span>
                        <?php if ($follows_raw >= 100) : ?><span class="amai-fbdash-dot">·</span><?php endif; ?>
                    <?php endif; ?>
                    <?php if ($follows_raw >= 100) : ?>
                    <span><?php echo esc_html($page_follows); ?></span>
                    <?php endif; ?>

                </div>
            </div>
        </div>
        <button type="button" class="amai-fbdash-disconnect-btn" id="amai-fb-disconnect-trigger">Disconnect</button>
    </div>

    <div class="amai-bio-card" id="amai-bio-card">
        <button type="button" class="amai-bio-card-toggle" id="amai-bio-card-toggle" aria-expanded="false">
            <span class="amai-bio-card-toggle-label">
                <svg width="15" height="15" viewBox="0 0 15 15" fill="none" aria-hidden="true"><path d="M2 4h11M2 7.5h7M2 11h5" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"/></svg>
                Write your Facebook bio
                <?php if ($bio_has_saved) : ?>
                <span class="amai-bio-status-badge amai-bio-status-done">&#10003; Bio saved</span>
                <?php else : ?>
                <span class="amai-bio-status-badge amai-bio-status-nudge">No bio yet</span>
                <?php endif; ?>
            </span>
            <svg class="amai-bio-chevron" width="14" height="14" viewBox="0 0 14 14" fill="none" aria-hidden="true"><path d="M3 5l4 4 4-4" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/></svg>
        </button>
        <div class="amai-bio-body" id="amai-bio-body" style="display:none;">
            <div class="amai-bio-hint">Paste your website URL and we'll write a ready-to-use Facebook page bio.</div>
            <div class="amai-bio-input-row">
                <input type="url" class="amai-bio-url-input" id="amai-bio-url-input"
                    placeholder="https://yourbusiness.com"
                    value="<?php echo $bio_website_url; ?>"
                    autocomplete="off"
                    spellcheck="false"/>
                <button type="button" class="amai-bio-generate-btn" id="amai-bio-generate-btn"
                    data-nonce="<?php echo esc_attr($bio_nonce); ?>">
                    Generate
                </button>
            </div>
            <div class="amai-bio-result" id="amai-bio-result"<?php echo $bio_has_saved ? '' : ' style="display:none;"'; ?>>
                <textarea class="amai-bio-textarea" id="amai-bio-textarea" rows="3"><?php echo esc_textarea($bio_saved_text); ?></textarea>
                <div class="amai-bio-result-actions">
                    <button type="button" class="amai-bio-copy-btn" id="amai-bio-copy-btn">Copy</button>
                    <button type="button" class="amai-bio-save-btn" id="amai-bio-save-btn"
                        data-save-nonce="<?php echo esc_attr(wp_create_nonce('amai_save_fb_bio')); ?>">Save</button>
                    <button type="button" class="amai-bio-regen-btn" id="amai-bio-regen-btn">Regenerate</button>
                </div>
            </div>
            <div class="amai-bio-error" id="amai-bio-error" style="display:none;"></div>
        </div>
    </div>
    <script>
    (function () {
        var toggle    = document.getElementById('amai-bio-card-toggle');
        var body      = document.getElementById('amai-bio-body');
        var chevron   = document.querySelector('.amai-bio-chevron');
        var urlInput  = document.getElementById('amai-bio-url-input');
        var genBtn    = document.getElementById('amai-bio-generate-btn');
        var result    = document.getElementById('amai-bio-result');
        var textarea  = document.getElementById('amai-bio-textarea');
        var copyBtn   = document.getElementById('amai-bio-copy-btn');
        var regenBtn  = document.getElementById('amai-bio-regen-btn');
        var saveBtn   = document.getElementById('amai-bio-save-btn');
        var errorEl   = document.getElementById('amai-bio-error');
        var nonce     = genBtn ? genBtn.dataset.nonce : '';

        if (toggle && body) {
            toggle.addEventListener('click', function () {
                var open = body.style.display !== 'none';
                body.style.display = open ? 'none' : 'block';
                toggle.setAttribute('aria-expanded', String(!open));
                if (chevron) { chevron.style.transform = open ? '' : 'rotate(180deg)'; }
            });
        }

        function setLoading(loading) {
            if (genBtn) { genBtn.disabled = loading; genBtn.textContent = loading ? 'Generating…' : 'Generate'; }
            if (regenBtn) { regenBtn.disabled = loading; }
            if (errorEl) { errorEl.style.display = 'none'; }
        }

        function showError(msg) {
            if (errorEl) { errorEl.textContent = msg; errorEl.style.display = 'block'; }
            if (result) { result.style.display = 'none'; }
        }

        function doGenerate() {
            var url = urlInput ? urlInput.value.trim() : '';
            setLoading(true);
            var fd = new FormData();
            fd.append('action', 'amai_generate_fb_bio');
            fd.append('_wpnonce', nonce);
            fd.append('website_url', url);
            fetch(window.ajaxurl || '/wp-admin/admin-ajax.php', {
                method: 'POST', credentials: 'same-origin', body: fd,
            })
            .then(function (r) { return r.json(); })
            .then(function (data) {
                setLoading(false);
                if (data && data.success && data.data && data.data.bio) {
                    if (textarea) { textarea.value = data.data.bio; }
                    if (result) { result.style.display = 'block'; }
                    if (copyBtn) { copyBtn.textContent = 'Copy'; }
                    var lbl = document.querySelector('.amai-bio-card-toggle-label');
                    if (lbl) {
                        var existingBadge = lbl.querySelector('.amai-bio-status-badge');
                        if (existingBadge) { existingBadge.remove(); }
                        var badge = document.createElement('span');
                        badge.className = 'amai-bio-status-badge amai-bio-status-done';
                        badge.textContent = '\u2713 Bio saved';
                        lbl.appendChild(badge);
                    }
                } else {
                    var msg = (data && data.data && data.data.message) ? data.data.message : 'Something went wrong. Please try again.';
                    showError(msg);
                }
            })
            .catch(function () {
                setLoading(false);
                showError('Network error. Please try again.');
            });
        }


        function doSave() {
            var text      = textarea ? textarea.value.trim() : '';
            var saveNonce = saveBtn ? saveBtn.dataset.saveNonce : '';
            if (!text) { return; }
            if (saveBtn) { saveBtn.disabled = true; saveBtn.textContent = 'Saving…'; }
            if (errorEl) { errorEl.style.display = 'none'; }
            var fd = new FormData();
            fd.append('action', 'amai_save_fb_bio');
            fd.append('_wpnonce', saveNonce);
            fd.append('bio_text', text);
            fetch(window.ajaxurl || '/wp-admin/admin-ajax.php', {
                method: 'POST', credentials: 'same-origin', body: fd,
            })
            .then(function (r) { return r.json(); })
            .then(function (data) {
                if (saveBtn) { saveBtn.disabled = false; saveBtn.textContent = 'Save'; }
                if (data && data.success) {
                    var lbl = document.querySelector('.amai-bio-card-toggle-label');
                    if (lbl) {
                        var existingBadge = lbl.querySelector('.amai-bio-status-badge');
                        if (existingBadge) { existingBadge.remove(); }
                        var badge = document.createElement('span');
                        badge.className = 'amai-bio-status-badge amai-bio-status-done';
                        badge.textContent = '✓ Bio saved';
                        lbl.appendChild(badge);
                    }
                    if (saveBtn) { saveBtn.textContent = 'Saved!'; setTimeout(function () { saveBtn.textContent = 'Save'; }, 2000); }
                } else {
                    var msg = (data && data.data && data.data.message) ? data.data.message : 'Save failed. Please try again.';
                    if (errorEl) { errorEl.textContent = msg; errorEl.style.display = 'block'; }
                    if (saveBtn) { saveBtn.disabled = false; saveBtn.textContent = 'Save'; }
                }
            })
            .catch(function () {
                if (saveBtn) { saveBtn.disabled = false; saveBtn.textContent = 'Save'; }
                if (errorEl) { errorEl.textContent = 'Network error. Please try again.'; errorEl.style.display = 'block'; }
            });
        }
        if (genBtn) { genBtn.addEventListener('click', doGenerate); }
        if (regenBtn) { regenBtn.addEventListener('click', doGenerate); }
        if (saveBtn) { saveBtn.addEventListener('click', doSave); }

        if (copyBtn && textarea) {
            copyBtn.addEventListener('click', function () {
                navigator.clipboard.writeText(textarea.value).then(function () {
                    copyBtn.textContent = 'Copied!';
                    setTimeout(function () { copyBtn.textContent = 'Copy'; }, 2000);
                }).catch(function () {
                    textarea.select();
                    document.execCommand('copy');
                    copyBtn.textContent = 'Copied!';
                    setTimeout(function () { copyBtn.textContent = 'Copy'; }, 2000);
                });
            });
        }
    }());
    </script>

    <div class="amai-approval-bar">
        <div class="amai-approval-bar-left">
            <div class="amai-approval-bar-label">Content Approval</div>
            <div class="amai-approval-bar-hint" id="amai-approval-hint">
                <?php if ($approval_mode === 'review') : ?>
                    Click any post to review it before it goes out.
                <?php else : ?>
                    Posts go out automatically at their scheduled time. Click any post to read it.
                <?php endif; ?>
            </div>
        </div>
        <div class="amai-approval-seg" id="amai-approval-seg" data-nonce="<?php echo esc_attr($approval_mode_nonce); ?>">
            <button type="button" class="amai-approval-seg-btn<?php echo $approval_mode === 'review' ? ' active' : ''; ?>" data-mode="review">Review each post</button>
            <button type="button" class="amai-approval-seg-btn<?php echo $approval_mode === 'autopilot' ? ' active' : ''; ?>" data-mode="autopilot">Autopilot</button>
        </div>
    </div>

    <div class="amai-feed">
        <div class="amai-feed-header">
            <?php if ($prev_url !== '') : ?>
                <a href="<?php echo $prev_url; ?>" class="amai-feed-nav-btn">← Older</a>
            <?php else : ?>
                <span class="amai-feed-nav-btn amai-feed-nav-btn--disabled">← Older</span>
            <?php endif; ?>

            <div class="amai-feed-week-label">
                <?php if (count($all_batches) > 1) : ?>
                <?php
                // Build human-readable labels for all batches
                $batch_labels = [];
                foreach ($all_batches as $_b) {
                    $_posts = $wpdb->get_results(
                        $wpdb->prepare(
                            'SELECT scheduled_date FROM `' . $wpdb->prefix . 'amai_scheduled_posts`
                             WHERE tenant_id = %s AND channel = \'facebook\' AND generation_batch = %s
                             ORDER BY scheduled_date ASC LIMIT 1',
                            'default', $_b
                        ),
                        ARRAY_A
                    );
                    if (!empty($_posts)) {
                        $_first = new \DateTimeImmutable($_posts[0]['scheduled_date'], new \DateTimeZone('UTC'));
                        $_last_row = $wpdb->get_row($wpdb->prepare('SELECT scheduled_date FROM `' . $wpdb->prefix . 'amai_scheduled_posts` WHERE tenant_id = %s AND channel = \'facebook\' AND generation_batch = %s ORDER BY scheduled_date DESC LIMIT 1', 'default', $_b), ARRAY_A);
                        $_last = $_last_row ? new \DateTimeImmutable($_last_row['scheduled_date'], new \DateTimeZone('UTC')) : $_first;
                        $batch_labels[$_b] = $_first->format('M j') . ' – ' . $_last->format('M j, Y');
                    } else {
                        $batch_labels[$_b] = $_b;
                    }
                }
                ?>
                <select class="amai-batch-select" onchange="window.location.href='<?php echo esc_js($base_url); ?>&batch=' + this.value">
                    <option value="<?php echo esc_attr($current_batch); ?>" selected disabled hidden><?php echo esc_html($week_label !== '' ? $week_label : $current_batch); ?></option>
                    <?php foreach ($all_batches as $b) : ?>
                    <?php if ($b === $current_batch) { continue; } ?>
                    <option value="<?php echo esc_attr($b); ?>"><?php echo esc_html($batch_labels[$b] ?? $b); ?></option>
                    <?php endforeach; ?>
                </select>
                <?php else : ?>
                <?php echo esc_html($week_label !== '' ? $week_label : 'No posts yet'); ?>
                <?php endif; ?>
            </div>

            <?php if ($next_url !== '') : ?>
                <a href="<?php echo $next_url; ?>" class="amai-feed-nav-btn">Newer →</a>
            <?php else : ?>
                <span class="amai-feed-nav-btn amai-feed-nav-btn--disabled">Newer →</span>
            <?php endif; ?>
        </div>

        <?php if ($current_batch === '' || empty($posts_raw)) : ?>
        <div class="amai-feed-empty-state">
            <div class="amai-feed-empty-icon">📅</div>
            <div class="amai-feed-empty-title">No posts yet</div>
            <div class="amai-feed-empty-body">Your first batch of posts will be generated automatically on Wednesday.</div>
        </div>
        <?php else : ?>
        <div class="amai-feed-list">
            <?php foreach ($feed_rows as $row) :
                $post        = $row['post'];
                $has_post    = $post !== null;
                $status      = $has_post ? $post['status'] : '';
                $post_type   = $row['label'];
                $raw_content = $has_post ? wp_unslash((string) $post['post_content']) : '';
                // Past batches are read-only — disable editing actions
                $row_readonly = !$is_latest_batch;
            ?>
            <div class="amai-feed-row<?php echo $row['is_today'] ? ' amai-feed-row--today' : ''; echo !$has_post ? ' amai-feed-row--empty' : ''; echo $row_readonly ? ' amai-feed-row--readonly' : ''; ?>"
                <?php if ($has_post) : ?>
                data-post-id="<?php echo (int) $post['id']; ?>"
                data-post-type="<?php echo esc_attr($post['post_type']); ?>"
                data-post-type-label="<?php echo esc_attr($post_type); ?>"
                data-post-status="<?php echo esc_attr($status); ?>"
                data-post-content="<?php echo esc_attr($raw_content); ?>"
                data-post-image-url="<?php echo esc_attr((string) ($post['post_image_url'] ?? '')); ?>"
                data-feeling="<?php echo esc_attr((string) ($post['feeling'] ?? '')); ?>"
                data-unsplash-attachment-id="<?php echo (int) ($post['unsplash_attachment_id'] ?? 0); ?>"
                data-unsplash-credit="<?php echo esc_attr((string) ($post['unsplash_credit'] ?? '')); ?>"
                data-generation-batch="<?php echo esc_attr((string) ($post['generation_batch'] ?? '')); ?>"
                                data-unsplash-url="<?php echo esc_attr((string) (($post['unsplash_attachment_id'] ?? 0) > 0 ? wp_get_attachment_image_url((int) $post['unsplash_attachment_id'], 'medium') : '')); ?>"
                data-scheduled-date="<?php echo esc_attr($row['date_display']); ?>"
                data-readonly="<?php echo $row_readonly ? '1' : '0'; ?>"
                data-stat-likes="<?php echo isset($post['stat_likes']) && $post['stat_likes'] !== null ? (int)$post['stat_likes'] : ''; ?>"
                data-stat-comments="<?php echo isset($post['stat_comments']) && $post['stat_comments'] !== null ? (int)$post['stat_comments'] : ''; ?>"
                data-stat-reach="<?php echo isset($post['stat_reach']) && $post['stat_reach'] !== null ? (int)$post['stat_reach'] : ''; ?>"
                data-stats-fetched="<?php echo !empty($post['stats_fetched_at']) ? '1' : '0'; ?>"
                data-action-nonce="<?php echo esc_attr($action_nonce); ?>"
                data-save-nonce="<?php echo esc_attr($save_nonce); ?>"
                data-regen-nonce="<?php echo esc_attr($regen_nonce); ?>"
                data-post-now-nonce="<?php echo esc_attr($post_now_nonce); ?>"
                data-upload-nonce="<?php echo esc_attr($upload_nonce); ?>"
                data-is-current-week="<?php echo $is_latest_batch ? '1' : '0'; ?>"
                role="button"
                tabindex="0"
                <?php endif; ?>>
                <div class="amai-feed-date">
                    <div class="amai-feed-dow"><?php echo esc_html($row['dow']); ?></div>
                    <div class="amai-feed-day-num"><?php echo esc_html($row['day_num']); ?></div>
                    <div class="amai-feed-month"><?php echo esc_html($row['month_short']); ?></div>
                </div>
                <div class="amai-feed-content">
                    <?php if ($has_post) : ?>
                        <div class="amai-feed-pills">
                            <span class="amai-feed-pill amai-feed-pill--<?php echo esc_attr($post['post_type']); ?>"><?php echo esc_html($post_type); ?></span>
                            <?php if (!empty($post['post_image_url'])) : ?>
                            <span class="amai-feed-pill amai-feed-pill--media">📷 Photo</span>
                            <?php if ($row['is_manual']) : ?>
                            <span class="amai-feed-pill amai-feed-pill--manual">Manual</span>
                            <?php endif; ?>
                            <?php endif; ?>
                            <?php if (!empty($post['feeling'])) : ?>
                            <span class="amai-feed-pill amai-feed-pill--feeling"><?php echo esc_html($feeling_labels[$post['feeling']] ?? $post['feeling']); ?></span>
                            <?php endif; ?>
                        </div>
                        <div class="amai-feed-preview"><?php echo esc_html($raw_content); ?></div>
                    <?php else : ?>
                        <div class="amai-feed-empty-label">No post scheduled</div>
                    <?php endif; ?>
                </div>
                <?php if ($has_post) : ?>
                <?php
                $unsplash_thumb = ($post['unsplash_attachment_id'] ?? 0) > 0
                    ? wp_get_attachment_image_url((int) $post['unsplash_attachment_id'], 'thumbnail')
                    : '';
                $feed_thumb = $unsplash_thumb !== '' ? $unsplash_thumb : esc_url((string) ($post['post_image_url'] ?? ''));
                ?>
                <div class="amai-feed-right-col">
                    <?php if ($feed_thumb !== '') : ?>
                    <div class="amai-feed-thumb">
                        <img src="<?php echo esc_url($feed_thumb); ?>" alt="" class="amai-feed-thumb-img"/>
                    </div>
                    <?php else : ?>
                    <div class="amai-feed-thumb amai-feed-thumb--empty">
                        <svg width="20" height="20" viewBox="0 0 20 20" fill="none" aria-hidden="true"><rect x="2" y="2" width="16" height="16" rx="3" stroke="#D0C8C2" stroke-width="1.4" stroke-dasharray="3 2"/><path d="M6 14l3-4 2.5 3 1.5-2 3 3" stroke="#D0C8C2" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/><circle cx="7.5" cy="7.5" r="1" fill="#D0C8C2"/></svg>
                    </div>
                    <?php endif; ?>
                    <div class="amai-feed-status">
                        <span class="amai-feed-status-dot amai-feed-status-dot--<?php echo esc_attr($status); ?>"></span>
                        <span class="amai-feed-status-label"><?php echo esc_html(ucfirst($status)); ?></span>
                    </div>
                    <?php
                    $stat_likes_val    = (int)($post['stat_likes']    ?? 0);
                    $stat_comments_val = (int)($post['stat_comments'] ?? 0);
                    $stat_reach_val    = (int)($post['stat_reach']    ?? 0);
                    $has_stats = !empty($post['stats_fetched_at']) && ($stat_likes_val > 0 || $stat_comments_val > 0 || $stat_reach_val > 0);
                    ?>
                    <?php if ($has_stats) : ?>
                    <div class="amai-feed-stats">
                        <span class="amai-feed-stat">&#128077; <?php echo esc_html((string)$stat_likes_val); ?></span>
                        <span class="amai-feed-stat">&#128172; <?php echo esc_html((string)$stat_comments_val); ?></span>
                    </div>
                    <?php endif; ?>
                </div>
                <?php endif; ?>
            </div>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>
    </div>

</div>

<?php if (isset($_GET['amai_onboarding'])) : ?>
<script>
(function () {
    var url = new URL(window.location.href);
    url.searchParams.delete('amai_onboarding');
    window.history.replaceState(null, '', url.toString());
}());
</script>
<?php endif; ?>

<!-- ══════════════════════════════════════════════════
     SLIDE-IN POST PANEL
══════════════════════════════════════════════════ -->
<div id="amai-post-panel" class="amai-post-panel" aria-hidden="true">
    <div class="amai-post-panel-backdrop" id="amai-post-panel-backdrop"></div>
    <div class="amai-post-panel-inner">

        <div class="amai-post-panel-header">
            <div>
                <div class="amai-post-panel-eyebrow" id="amai-panel-eyebrow"></div>
                <div class="amai-post-panel-title" id="amai-panel-title"></div>
            </div>
            <button type="button" class="amai-post-panel-close" id="amai-panel-close">&#10005;</button>
        </div>

        <div class="amai-post-panel-body">
            <div class="amai-post-panel-status-row">
                <span class="amai-post-panel-status" id="amai-panel-status"></span>
            </div>

            <!-- Read view -->
            <div class="amai-post-panel-content" id="amai-panel-content"></div>
            <!-- FB post preview -->
            <div class="amai-fb-preview-toggle" id="amai-fb-preview-toggle" style="display:none;">
                <button type="button" class="amai-fb-preview-btn" id="amai-fb-preview-btn">
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
                    Preview on Facebook
                </button>
            </div>
            <div class="amai-fb-post-preview" id="amai-fb-post-preview" style="display:none;">
                <div class="amai-fbp-card">
                    <div class="amai-fbp-header">
                        <img class="amai-fbp-avatar" id="amai-fbp-avatar" src="" alt="" />
                        <div class="amai-fbp-meta">
                            <div class="amai-fbp-name" id="amai-fbp-name"></div>
                            <div class="amai-fbp-time">Just now &middot; <svg width="10" height="10" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z"/></svg></div>
                        </div>
                    </div>
                    <div class="amai-fbp-copy" id="amai-fbp-copy"></div>
                    <div class="amai-fbp-image-wrap" id="amai-fbp-image-wrap" style="display:none;">
                        <img class="amai-fbp-image" id="amai-fbp-image" src="" alt="" />
                    </div>
                    <div class="amai-fbp-actions">
                        <span class="amai-fbp-action">&#128077; Like</span>
                        <span class="amai-fbp-action">&#128172; Comment</span>
                        <span class="amai-fbp-action">&#8634; Share</span>
                    </div>
                </div>
            </div>
            <div class="amai-panel-view-image" id="amai-panel-view-image" style="display:none;">
                <img id="amai-panel-view-img" src="" alt="Post image" class="amai-panel-view-img"/>
            </div>
            <div class="amai-panel-meta-summary" id="amai-panel-meta-summary"></div>

            <!-- Unsplash suggested image -->
            <div class="amai-unsplash-block" id="amai-unsplash-block" style="display:none;">
                <div class="amai-unsplash-label">Suggested photo</div>
                <div class="amai-unsplash-img-wrap">
                    <img id="amai-unsplash-img" src="" alt="Suggested photo" class="amai-unsplash-img"/>
                    <div class="amai-unsplash-credit" id="amai-unsplash-credit"></div>
                </div>
                <div class="amai-unsplash-actions" id="amai-unsplash-actions">
                    <button type="button" class="amai-unsplash-btn-accept" id="amai-unsplash-btn-accept">Use this photo</button>
                    <button type="button" class="amai-unsplash-btn-remove" id="amai-unsplash-btn-remove">Remove</button>
                </div>
                <div class="amai-unsplash-accepted" id="amai-unsplash-accepted" style="display:none;">
                    <span class="amai-unsplash-accepted-label">✓ Photo added to post</span>
                    <button type="button" class="amai-unsplash-btn-undo" id="amai-unsplash-btn-undo">Undo</button>
                </div>
            </div>
            <!-- Edit view -->
            <div class="amai-textarea-wrap" id="amai-textarea-wrap" style="display:none;">
                <textarea class="amai-post-panel-textarea" id="amai-panel-textarea" rows="8"></textarea>
                <button type="button" class="amai-emoji-corner-btn" id="amai-enrich-btn-emoji" title="Add emoji">
                    <svg width="18" height="18" viewBox="0 0 18 18" fill="none" aria-hidden="true"><circle cx="9" cy="9" r="7" stroke="currentColor" stroke-width="1.4"/><path d="M6 11.5s1 1.5 3 1.5 3-1.5 3-1.5" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"/><circle cx="6.5" cy="7" r="1" fill="currentColor"/><circle cx="11.5" cy="7" r="1" fill="currentColor"/></svg>
                </button>
                <div class="amai-emoji-dropdown" id="amai-emoji-dropdown" style="display:none;">
                    <div class="amai-emoji-sticky-cat" id="amai-emoji-sticky-cat"></div>
                    <div class="amai-emoji-scroll" id="amai-emoji-grid"></div>
                </div>
            </div>
            <div class="amai-post-panel-char-count" id="amai-panel-char-count" style="display:none;"></div>

            <!-- ── ENRICHMENT TOOLBAR ── -->
            <div class="amai-panel-enrichments" id="amai-panel-enrichments" style="display:none;">

                <div class="amai-enrich-toolbar">
                    <span class="amai-enrich-toolbar-label">Add</span>

                    <!-- Photo button -->
                    <button type="button" class="amai-enrich-btn amai-edit-img-trigger" id="amai-enrich-btn-img" title="Add photo">
                        <svg width="18" height="18" viewBox="0 0 18 18" fill="none" aria-hidden="true"><rect x="1.5" y="3" width="15" height="12" rx="2.5" stroke="currentColor" stroke-width="1.4"/><circle cx="6" cy="7.5" r="1.5" fill="currentColor"/><path d="M1.5 12l4-4 3 3 2.5-2.5 5 5" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/></svg>
                    </button>


                    <!-- Feeling button -->
                    <button type="button" class="amai-enrich-btn" id="amai-enrich-btn-feeling" title="Add feeling">
                        <svg width="18" height="18" viewBox="0 0 18 18" fill="none" aria-hidden="true"><circle cx="9" cy="9" r="7" stroke="#F0B429" stroke-width="1.4"/><path d="M6 11s1 2 3 2 3-2 3-2" stroke="#F0B429" stroke-width="1.4" stroke-linecap="round"/><circle cx="6.5" cy="7.5" r="1" fill="#F0B429"/><circle cx="11.5" cy="7.5" r="1" fill="#F0B429"/></svg>
                    </button>


                    <!-- Active chips -->
                    <span class="amai-enrich-chip" id="amai-img-chip" style="display:none;">📷 Photo<button type="button" class="amai-enrich-chip-remove" id="amai-img-chip-remove">&#10005;</button></span>
                    <span class="amai-enrich-chip" id="amai-feeling-chip" style="display:none;"><span class="amai-enrich-chip-label"></span><button type="button" class="amai-enrich-chip-remove" id="amai-feeling-chip-remove">&#10005;</button></span>
                </div>

                <!-- ── Edit-mode image block ── -->
                <div class="amai-edit-img-block" id="amai-edit-img-block" style="display:none;">

                    <!-- state: no image -->
                    <div class="amai-edit-img-state" id="amai-edit-img-none">
                        <div class="amai-edit-img-empty-label">No image added</div>
                        <div class="amai-edit-img-options">
                            <label class="amai-edit-img-opt" title="Upload from your computer">
                                <input type="file" id="amai-image-input" accept="image/jpeg,image/png,image/gif,image/webp" style="display:none;"/>
                                <svg width="15" height="15" viewBox="0 0 18 18" fill="none" aria-hidden="true"><rect x="1.5" y="3" width="15" height="12" rx="2.5" stroke="currentColor" stroke-width="1.4"/><circle cx="6" cy="7.5" r="1.5" fill="currentColor"/><path d="M1.5 12l4-4 3 3 2.5-2.5 5 5" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/></svg>
                                Upload
                            </label>
                            <button type="button" class="amai-edit-img-opt" id="amai-edit-img-unsplash-btn">
                                <svg width="15" height="15" viewBox="0 0 18 18" fill="none" aria-hidden="true"><circle cx="9" cy="9" r="7" stroke="currentColor" stroke-width="1.4"/><path d="M6 9l2.5 2.5L12 6" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/></svg>
                                Unsplash
                            </button>
                            <button type="button" class="amai-edit-img-opt" id="amai-edit-img-ai-btn">
                                <svg width="15" height="15" viewBox="0 0 18 18" fill="none" aria-hidden="true"><path d="M9 2v2M9 14v2M2 9h2M14 9h2M4.22 4.22l1.42 1.42M12.36 12.36l1.42 1.42M4.22 13.78l1.42-1.42M12.36 5.64l1.42-1.42" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"/><circle cx="9" cy="9" r="3" stroke="currentColor" stroke-width="1.4"/></svg>
                                Generate with AI
                            </button>
                        </div>
                    </div>

                    <!-- state: uploading -->
                    <div class="amai-edit-img-state" id="amai-edit-img-uploading" style="display:none;">
                        <div class="amai-edit-img-spinner-row">
                            <svg class="amai-regen-spin" width="13" height="13" viewBox="0 0 13 13" fill="none"><path d="M11 2.5A5.5 5.5 0 1 0 12 6.5" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"/><path d="M9 2.5h2V.5" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/></svg>
                            Uploading…
                        </div>
                    </div>

                    <!-- state: has image -->
                    <div class="amai-edit-img-state" id="amai-edit-img-has" style="display:none;">
                        <div class="amai-edit-img-preview-wrap">
                            <img id="amai-edit-img-preview" src="" alt="Post image" class="amai-edit-img-preview-img"/>
                            <button type="button" class="amai-edit-img-remove" id="amai-edit-img-remove" title="Remove image">&#10005;</button>
                        </div>
                        <div class="amai-edit-img-credit" id="amai-edit-img-credit" style="display:none;"></div>
                        <div class="amai-edit-img-replace-row">
                            <span class="amai-edit-img-replace-label">Replace:</span>
                            <label class="amai-edit-img-opt amai-edit-img-opt--sm" title="Upload from your computer">
                                <input type="file" id="amai-image-input-replace" accept="image/jpeg,image/png,image/gif,image/webp" style="display:none;"/>
                                <svg width="13" height="13" viewBox="0 0 18 18" fill="none" aria-hidden="true"><rect x="1.5" y="3" width="15" height="12" rx="2.5" stroke="currentColor" stroke-width="1.4"/><circle cx="6" cy="7.5" r="1.5" fill="currentColor"/><path d="M1.5 12l4-4 3 3 2.5-2.5 5 5" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/></svg>
                                Upload
                            </label>
                            <button type="button" class="amai-edit-img-opt amai-edit-img-opt--sm" id="amai-edit-img-unsplash-replace-btn">
                                <svg width="13" height="13" viewBox="0 0 18 18" fill="none" aria-hidden="true"><circle cx="9" cy="9" r="7" stroke="currentColor" stroke-width="1.4"/><path d="M6 9l2.5 2.5L12 6" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/></svg>
                                Unsplash
                            </button>
                            <button type="button" class="amai-edit-img-opt amai-edit-img-opt--sm" id="amai-edit-img-ai-replace-btn">
                                <svg width="13" height="13" viewBox="0 0 18 18" fill="none" aria-hidden="true"><path d="M9 2v2M9 14v2M2 9h2M14 9h2M4.22 4.22l1.42 1.42M12.36 12.36l1.42 1.42M4.22 13.78l1.42-1.42M12.36 5.64l1.42-1.42" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"/><circle cx="9" cy="9" r="3" stroke="currentColor" stroke-width="1.4"/></svg>
                                AI
                            </button>
                        </div>
                    </div>

                    <!-- state: Unsplash search -->
                    <div class="amai-edit-img-state" id="amai-edit-img-unsplash" style="display:none;">
                        <div class="amai-edit-img-unsplash-head">
                            <input type="text" class="amai-edit-img-unsplash-input" id="amai-edit-img-unsplash-input" placeholder="Search photos…" maxlength="80" autocomplete="off"/>
                            <button type="button" class="amai-edit-img-unsplash-search-btn" id="amai-edit-img-unsplash-search-btn">Search</button>
                            <button type="button" class="amai-edit-img-unsplash-cancel" id="amai-edit-img-unsplash-cancel">Cancel</button>
                        </div>
                        <div class="amai-edit-img-unsplash-status" id="amai-edit-img-unsplash-status" style="display:none;"></div>
                        <div class="amai-edit-img-unsplash-grid" id="amai-edit-img-unsplash-grid" style="display:none;"></div>
                    </div>

                    <!-- state: AI prompt -->
                    <div class="amai-edit-img-state" id="amai-edit-img-ai-prompt" style="display:none;">
                        <div class="amai-edit-img-ai-label">Describe the image you want</div>
                        <textarea class="amai-edit-img-ai-textarea" id="amai-edit-img-ai-textarea" rows="3" maxlength="400" placeholder="e.g. Cozy small business owner at a desk, warm lighting, minimal background"></textarea>
                        <div class="amai-edit-img-ai-row">
                            <button type="button" class="amai-edit-img-ai-cancel" id="amai-edit-img-ai-cancel">Cancel</button>
                            <button type="button" class="amai-edit-img-ai-generate" id="amai-edit-img-ai-generate">Generate</button>
                        </div>
                    </div>

                    <!-- state: AI generating -->
                    <div class="amai-edit-img-state" id="amai-edit-img-ai-generating" style="display:none;">
                        <div class="amai-edit-img-spinner-row">
                            <svg class="amai-regen-spin" width="13" height="13" viewBox="0 0 13 13" fill="none"><path d="M11 2.5A5.5 5.5 0 1 0 12 6.5" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"/><path d="M9 2.5h2V.5" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/></svg>
                            Generating image… this takes up to 30 seconds
                        </div>
                    </div>

                    <!-- state: AI preview -->
                    <div class="amai-edit-img-state" id="amai-edit-img-ai-preview" style="display:none;">
                        <div class="amai-edit-img-ai-preview-label">AI-generated image - looks good?</div>
                        <div class="amai-edit-img-preview-wrap">
                            <img id="amai-edit-img-ai-preview-img" src="" alt="AI generated image" class="amai-edit-img-preview-img"/>
                        </div>
                        <div class="amai-edit-img-ai-preview-row">
                            <button type="button" class="amai-edit-img-ai-discard" id="amai-edit-img-ai-discard">&#10005; Discard</button>
                            <button type="button" class="amai-edit-img-ai-accept" id="amai-edit-img-ai-accept">&#10003; Accept</button>
                        </div>
                    </div>

                    <!-- state: AI error -->
                    <div class="amai-edit-img-state" id="amai-edit-img-ai-error" style="display:none;">
                        <div class="amai-edit-img-error-row">
                            <span class="amai-edit-img-error-msg" id="amai-edit-img-ai-error-msg"></span>
                            <button type="button" class="amai-edit-img-error-retry" id="amai-edit-img-ai-retry">Try again</button>
                            <button type="button" class="amai-edit-img-unsplash-cancel" id="amai-edit-img-ai-error-cancel">Cancel</button>
                        </div>
                    </div>

                </div>
                <!-- ── End edit-mode image block ── -->

            </div>
            <!-- ── END ENRICHMENT TOOLBAR ── -->

        </div>

        <div class="amai-panel-stats" id="amai-panel-stats" style="display:none;">
            <div class="amai-panel-stat-item">
                <div class="amai-panel-stat-icon-wrap">
                    <svg width="14" height="14" viewBox="0 0 14 14" fill="none" aria-hidden="true"><path d="M7 1.5C4.5 1.5 2 3.5 2 6c0 1.2.5 2.2 1.3 3L7 12.5l3.7-3.5C11.5 8.2 12 7.2 12 6c0-2.5-2.5-4.5-5-4.5Z" stroke="currentColor" stroke-width="1.3" stroke-linejoin="round"/></svg>
                </div>
                <span class="amai-panel-stat-value" id="amai-stat-likes">&mdash;</span>
                <span class="amai-panel-stat-label">Likes</span>
            </div>
            <div class="amai-panel-stat-item">
                <div class="amai-panel-stat-icon-wrap">
                    <svg width="14" height="14" viewBox="0 0 14 14" fill="none" aria-hidden="true"><path d="M2 2.5h10a.5.5 0 0 1 .5.5v6a.5.5 0 0 1-.5.5H8l-2 2-2-2H2a.5.5 0 0 1-.5-.5V3a.5.5 0 0 1 .5-.5Z" stroke="currentColor" stroke-width="1.3" stroke-linejoin="round"/></svg>
                </div>
                <span class="amai-panel-stat-value" id="amai-stat-comments">&mdash;</span>
                <span class="amai-panel-stat-label">Comments</span>
            </div>
            <div class="amai-panel-stat-item">
                <div class="amai-panel-stat-icon-wrap">
                    <svg width="14" height="14" viewBox="0 0 14 14" fill="none" aria-hidden="true"><ellipse cx="7" cy="7" rx="5.5" ry="3.5" stroke="currentColor" stroke-width="1.3"/><circle cx="7" cy="7" r="1.5" fill="currentColor"/></svg>
                </div>
                <span class="amai-panel-stat-value" id="amai-stat-reach">&mdash;</span>
                <span class="amai-panel-stat-label">Reach</span>
            </div>
        </div>
        <div class="amai-post-panel-footer" id="amai-panel-footer">

            <div class="amai-panel-mode" id="amai-mode-draft" style="display:none;">
                <div class="amai-panel-mode-row">
                    <button type="button" class="amai-panel-btn amai-panel-btn--ghost" id="amai-panel-reject">Reject</button>
                    <button type="button" class="amai-panel-btn amai-panel-btn--clay" id="amai-panel-edit">Edit</button>
                    <button type="button" class="amai-panel-btn amai-panel-btn--green" id="amai-panel-approve">Approve</button>
                </div>
                <div class="amai-panel-regen-bar">
                    <span class="amai-panel-regen-label">Rewrite as</span>
                    <select id="amai-panel-regen-type" class="amai-panel-regen-select">
                        <option value="">Same type</option>
                        <option value="educational">Educational</option>
                        <option value="product">Product</option>
                        <option value="feel_good">Feel-good</option>
                        <option value="behind_scenes">Behind scenes</option>
                        <option value="engagement">Engagement</option>
                    </select>
                    <button type="button" class="amai-panel-btn-regen" id="amai-panel-regen">
                        <svg width="13" height="13" viewBox="0 0 13 13" fill="none" aria-hidden="true"><path d="M11 2.5A5.5 5.5 0 1 0 12 6.5" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"/><path d="M9 2.5h2V.5" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/></svg>
                        Regenerate
                    </button>
                </div>
            </div>

            <div class="amai-panel-mode" id="amai-mode-approved" style="display:none;">
                <div class="amai-panel-mode-row">
                    <button type="button" class="amai-panel-btn amai-panel-btn--ghost" id="amai-panel-unapprove-reject">Reject</button>
                    <button type="button" class="amai-panel-btn amai-panel-btn--clay" id="amai-panel-unapprove-edit">Edit</button>
                    <button type="button" class="amai-panel-btn amai-panel-btn--green" id="amai-panel-keep-approved">✓ Keep Approved</button>
                </div>
            </div>

            <div class="amai-panel-mode" id="amai-mode-rejected" style="display:none;">
                <div class="amai-panel-mode-row">
                    <button type="button" class="amai-panel-btn amai-panel-btn--ghost" id="amai-panel-keep-rejected">Keep Rejected</button>
                    <button type="button" class="amai-panel-btn amai-panel-btn--clay" id="amai-panel-restore-edit">Edit</button>
                    <button type="button" class="amai-panel-btn amai-panel-btn--green" id="amai-panel-approve-from-rejected">Approve</button>
                </div>
                <div class="amai-panel-mode-row">
                    <button type="button" class="amai-panel-btn amai-panel-btn--ghost amai-panel-btn--full" id="amai-panel-restore">↩ Put back in draft</button>
                </div>
            </div>

            <div class="amai-panel-mode" id="amai-mode-editing" style="display:none;">
                <div class="amai-panel-mode-row">
                    <button type="button" class="amai-panel-btn amai-panel-btn--ghost" id="amai-panel-edit-cancel">Cancel</button>
                    <button type="button" class="amai-panel-btn amai-panel-btn--clay" id="amai-panel-save">Save draft</button>
                    <button type="button" class="amai-panel-btn amai-panel-btn--green" id="amai-panel-save-approve">Save &amp; Approve</button>
                </div>
                <div class="amai-panel-regen-bar">
                    <span class="amai-panel-regen-label">Rewrite as</span>
                    <select id="amai-panel-regen-type-edit" class="amai-panel-regen-select">
                        <option value="">Same type</option>
                        <option value="educational">Educational</option>
                        <option value="product">Product</option>
                        <option value="feel_good">Feel-good</option>
                        <option value="behind_scenes">Behind scenes</option>
                        <option value="engagement">Engagement</option>
                    </select>
                    <button type="button" class="amai-panel-btn-regen" id="amai-panel-regen-edit">
                        <svg width="13" height="13" viewBox="0 0 13 13" fill="none" aria-hidden="true"><path d="M11 2.5A5.5 5.5 0 1 0 12 6.5" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"/><path d="M9 2.5h2V.5" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/></svg>
                        Regenerate
                    </button>
                </div>
            </div>

            <div class="amai-panel-mode" id="amai-mode-rejecting" style="display:none;">
                <div class="amai-post-panel-reason-label">What should change? <span class="amai-post-panel-reason-optional">(optional)</span></div>
                <input type="text" id="amai-panel-reason-input" class="amai-post-panel-reason-input" placeholder="e.g. Too salesy, wrong tone, needs more detail…" autocomplete="off" maxlength="255"/>
                <div class="amai-panel-mode-row" style="margin-top:8px;">
                    <button type="button" class="amai-panel-btn amai-panel-btn--ghost" id="amai-panel-reason-cancel">Cancel</button>
                    <button type="button" class="amai-panel-btn amai-panel-btn--ghost" id="amai-panel-reason-skip">Skip</button>
                    <button type="button" class="amai-panel-btn amai-panel-btn--red" id="amai-panel-reason-confirm">Reject</button>
                </div>
            </div>

            <div class="amai-panel-mode" id="amai-mode-regenerating" style="display:none;">
                <div class="amai-panel-regen-spinner">
                    <svg class="amai-regen-spin" width="15" height="15" viewBox="0 0 13 13" fill="none"><path d="M11 2.5A5.5 5.5 0 1 0 12 6.5" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"/><path d="M9 2.5h2V.5" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/></svg>
                    Writing a new post…
                </div>
            </div>

            <div class="amai-panel-mode" id="amai-mode-failed" style="display:none;">
                <div class="amai-panel-mode-row">
                    <button type="button" class="amai-panel-btn amai-panel-btn--ghost" id="amai-panel-failed-dismiss">Dismiss</button>
                    <button type="button" class="amai-panel-btn amai-panel-btn--clay" id="amai-panel-post-now">Post now</button>
                </div>
            </div>

            <div class="amai-panel-mode" id="amai-mode-posting" style="display:none;">
                <div class="amai-panel-regen-spinner">
                    <svg class="amai-regen-spin" width="15" height="15" viewBox="0 0 13 13" fill="none"><path d="M11 2.5A5.5 5.5 0 1 0 12 6.5" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"/><path d="M9 2.5h2V.5" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/></svg>
                    Posting to Facebook…
                </div>
            </div>

            <div class="amai-panel-mode" id="amai-mode-readonly" style="display:none;">
                <div class="amai-panel-readonly-nudge">
                    You're in Autopilot mode - posts go out automatically.
                    <button type="button" class="amai-panel-readonly-switch" id="amai-panel-switch-to-review">Switch to Review mode</button>
                    to make changes.
                </div>
            </div>

            <div class="amai-panel-mode" id="amai-mode-posted" style="display:none;">
                <div class="amai-panel-mode-row">
                    <button type="button" class="amai-panel-btn amai-panel-btn--clay" id="amai-panel-duplicate">Duplicate post</button>
                </div>
            </div>
            </div>

        </div>
    </div>
</div>

<!-- ══════════════════════════════════════════════════
     FEELING MODAL
══════════════════════════════════════════════════ -->
<div id="amai-feeling-modal" class="amai-feeling-modal">
    <div class="amai-feeling-modal-wrap">
        <div class="amai-feeling-modal-header">
            <div class="amai-feeling-modal-title">How are you feeling?</div>
            <button type="button" class="amai-feeling-modal-close" id="amai-feeling-modal-close">&#10005;</button>
        </div>
        <div class="amai-feeling-modal-grid" id="amai-feeling-modal-grid">
            <?php foreach ($feeling_labels as $value => $label) : ?>
            <button type="button" class="amai-feeling-option" data-feeling="<?php echo esc_attr($value); ?>"><?php echo esc_html($label); ?></button>
            <?php endforeach; ?>
        </div>
    </div>
</div>

<!-- ══════════════════════════════════════════════════
     DISCONNECT CONFIRMATION MODAL
══════════════════════════════════════════════════ -->
<div id="amai-disconnect-modal" class="amai-dc-modal">
    <div class="amai-dc-wrap">
        <div class="amai-dc-header">
            <div>
                <div class="amai-dc-eyebrow">Are you sure?</div>
                <div class="amai-dc-title">Disconnect <?php echo $page_name; ?>?</div>
            </div>
            <button type="button" class="amai-dc-close" id="amai-dc-close">&#10005;</button>
        </div>
        <div class="amai-dc-body">
            <p class="amai-dc-warning-text">
                Disconnecting will remove AutoMarketer AI's connection to this page. Your drafts, scheduled posts, and business profile will be cleared.
            </p>
            <div class="amai-dc-consequences">
                <div class="amai-dc-consequence">
                    <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M3 3l8 8M11 3l-8 8" stroke="#DC2626" stroke-width="1.5" stroke-linecap="round"/></svg>
                    Post history and drafts - deleted
                </div>
                <div class="amai-dc-consequence">
                    <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M3 3l8 8M11 3l-8 8" stroke="#DC2626" stroke-width="1.5" stroke-linecap="round"/></svg>
                    Scheduled posts - cancelled
                </div>
                <div class="amai-dc-consequence">
                    <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M3 3l8 8M11 3l-8 8" stroke="#DC2626" stroke-width="1.5" stroke-linecap="round"/></svg>
                    Business profile - cleared
                </div>
            </div>
            <p class="amai-dc-warning-sub">This can't be undone.</p>
        </div>
        <div class="amai-dc-footer">
            <button type="button" class="amai-dc-btn-cancel" id="amai-dc-cancel">Keep it connected</button>
            <button type="button" class="amai-dc-btn-disconnect" id="amai-dc-confirm-btn" data-nonce="<?php echo esc_attr($disconnect_nonce); ?>">Yes, disconnect</button>
        </div>
    </div>
</div>
</div>