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

namespace AutoMarketerAI;

defined('ABSPATH') || exit;

$instagram_account_id = FacebookAuth::getInstagramAccountId();
if ($instagram_account_id === null) {
    include AMAI_PLUGIN_DIR . 'templates/social/instagram-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;
}

$approval_mode       = (get_option('amai_approval_mode', 'review') === 'autopilot') ? 'autopilot' : 'review';
$approval_mode_nonce   = wp_create_nonce('amai_save_approval_mode');
$ig_disconnect_nonce = wp_create_nonce('amai_ig_disconnect');
$page_pic            = esc_url((string) (FacebookAuth::getConnection()['page_picture_url'] ?? ''));

$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');
global $wpdb;

// --------------------------------------------------
// --------------------------------------------------
// Generation failure notice
// --------------------------------------------------
$_amai_gen_failed        = get_option('amai_generation_failed', []);
$_amai_show_gen_failed   = !empty($_amai_gen_failed) && ($_amai_gen_failed['channel'] ?? '') === 'instagram';
$_amai_regen_nonce       = wp_create_nonce('amai_regenerate_week');

// 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);
    $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++;
    }
    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 = 'instagram';
// 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 = 'instagram'
         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',
            'instagram',
            $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',
            'instagram',
            'manual-%',
            $week_start_str,
            $week_end_str
        ),
        ARRAY_A
    );

    $posts_raw = array_merge($weekly_posts, $manual_posts);
usort($posts_raw, static function (array $a, array $b): int {
    return strcmp((string) ($a['scheduled_date'] ?? ''), (string) ($b['scheduled_date'] ?? ''));
});

    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 navigation
// --------------------------------------------------
$batch_index = array_search($current_batch, $all_batches, true);
$prev_batch  = ($batch_index !== false && $batch_index < count($all_batches) - 1) ? $all_batches[$batch_index + 1] : null;
$next_batch  = ($batch_index !== false && $batch_index > 0) ? $all_batches[$batch_index - 1] : null;
$base_url    = admin_url('admin.php?page=automarketer-ai-social&channel=instagram');
$prev_url    = $prev_batch !== null ? $base_url . '&batch=' . urlencode($prev_batch) : '';
$next_url    = $next_batch !== null ? $base_url . '&batch=' . urlencode($next_batch) : '';

// --------------------------------------------------
// Labels
// --------------------------------------------------
$type_labels = [
    'educational'   => 'Educational',
    'product'       => 'Product',
    'feel_good'     => 'Feel Good',
    'behind_scenes' => 'Behind the Scenes',
    'engagement'    => 'Engagement',
];

$status_labels = [
    'draft'    => 'Draft',
    'approved' => 'Approved',
    'rejected' => 'Rejected',
    'posted'   => 'Posted',
    'failed'   => 'Failed',
];

$feeling_labels = [
    'accomplished' => 'Accomplished',
    'grateful'     => 'Grateful',
    'motivated'    => 'Motivated',
    'excited'      => 'Excited',
    'inspired'     => 'Inspired',
    'optimistic'   => 'Optimistic',
    'proud'        => 'Proud',
    'thankful'     => 'Thankful',
    'determined'   => 'Determined',
    'happy'        => 'Happy',
    'hopeful'      => 'Hopeful',
    'focused'      => 'Focused',
];

?>

<?php // ── Tab row ───────────────────────────────────────────── ?>
<div class="amai-fb-tabs">
    <a href="<?php echo esc_url($base_url . '&tab=dashboard'); ?>"
       class="amai-fb-tab<?php echo $active_tab === 'dashboard' ? ' amai-fb-tab--active' : ''; ?>">
        Dashboard
    </a>
    <a href="<?php echo esc_url($base_url . '&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); ?>" data-channel="instagram">

    <?php // ── Page card ────────────────────────────────────────── ?>
    <div class="amai-fbdash-page-card">
        <div class="amai-fbdash-page-identity">
            <div class="amai-fbdash-page-avatar">
                <img src="<?php echo $page_pic; ?>" alt="AutoMarketer AI" class="amai-fbdash-page-initials" style="object-fit:cover;border-radius:50%;" />
                <span class="amai-fbdash-status-dot" title="Connected"></span>
            </div>
            <div class="amai-fbdash-page-meta">
                <div class="amai-fbdash-page-name">@automarketerai</div>
                <div class="amai-fbdash-page-sub">
                    <span>Instagram Business Account</span>
                </div>
            </div>
        </div>
        <button type="button" class="amai-fbdash-disconnect-btn" id="amai-ig-disconnect-trigger">Disconnect</button>
    </div>

    <?php // ── Approval bar ─────────────────────────────────────── ?>
    <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') : ?>
                    Posts need your sign-off before they go out. Click any post to review it.
                <?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>

    <?php if ($_amai_show_gen_failed) : ?>
    <div class="amai-fbdash-notice amai-fbdash-notice--warn" id="amai-gen-failed-notice">
        <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="instagram">Try again</button></span>
    </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');
        if (!nudge || !btnEnable || !btnDismiss) return;
        btnEnable.addEventListener('click', function () {
            var nonce = this.dataset.nonce;
            var xhr = new XMLHttpRequest();
            xhr.open('POST', window.ajaxurl || '/wp-admin/admin-ajax.php');
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.onload = function () { location.reload(); };
            xhr.send('action=amai_save_approval_mode&mode=autopilot&_ajax_nonce=' + encodeURIComponent(nonce));
        });
        btnDismiss.addEventListener('click', function () {
            var nonce = this.dataset.nonce;
            var xhr = new XMLHttpRequest();
            xhr.open('POST', window.ajaxurl || '/wp-admin/admin-ajax.php');
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.onload = function () { nudge.style.display = 'none'; };
            xhr.send('action=amai_autopilot_nudge_dismiss&_ajax_nonce=' + encodeURIComponent(nonce));
        });
    }());
    </script>
    <?php endif; ?>
    </div>

    <?php if (empty($all_batches)) : ?>
    <?php // ── Empty state ─────────────────────────────────────── ?>
    <div class="amai-fbdash-empty">
        <div class="amai-fbdash-empty-icon">
            <svg width="40" height="40" viewBox="0 0 28 28" fill="none" xmlns="http://www.w3.org/2000/svg">
                <rect x="5" y="5" width="18" height="18" rx="5" stroke="#C4B5AD" stroke-width="1.8" fill="none"/>
                <circle cx="14" cy="14" r="4.5" stroke="#C4B5AD" stroke-width="1.8" fill="none"/>
                <circle cx="19.5" cy="8.5" r="1.2" fill="#C4B5AD"/>
            </svg>
        </div>
        <div class="amai-fbdash-empty-title">No Instagram posts yet</div>
        <div class="amai-fbdash-empty-body">
            Instagram captions are generated every Wednesday alongside your Facebook posts.
            Check back after the next generation run.
        </div>
    </div>
    <?php else : ?>

    <?php // ── Feed ────────────────────────────────────────────── ?>
    <div class="amai-feed">
        <div class="amai-feed-header">
            <?php if ($prev_url !== '') : ?>
                <a href="<?php echo esc_url($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) : ?>
                <div class="amai-feed-week-dropdown" id="amai-feed-week-dropdown">
                    <button type="button" class="amai-feed-week-btn" id="amai-feed-week-btn">
                        <?php echo esc_html($week_label !== '' ? $week_label : $current_batch); ?>
                        <svg width="10" height="10" viewBox="0 0 10 10" fill="none"><path d="M2 4l3 3 3-3" stroke="currentColor" stroke-width="1.3" stroke-linecap="round" stroke-linejoin="round"/></svg>
                    </button>
                    <div class="amai-feed-week-menu" id="amai-feed-week-menu" style="display:none;">
                        <?php
                        foreach ($all_batches as $_ib) {
                            $_ib_posts = $wpdb->get_results(
                                $wpdb->prepare(
                                    'SELECT scheduled_date FROM `' . $wpdb->prefix . 'amai_scheduled_posts`
                                     WHERE tenant_id = %s AND channel = \'instagram\' AND generation_batch = %s
                                     ORDER BY scheduled_date ASC LIMIT 1',
                                    'default', $_ib
                                ),
                                ARRAY_A
                            );
                            if (!empty($_ib_posts)) {
                                $_ib_first = new \DateTimeImmutable($_ib_posts[0]['scheduled_date'], new \DateTimeZone('UTC'));
                                $_ib_last_row = $wpdb->get_row($wpdb->prepare('SELECT scheduled_date FROM `' . $wpdb->prefix . 'amai_scheduled_posts` WHERE tenant_id = %s AND channel = \'instagram\' AND generation_batch = %s ORDER BY scheduled_date DESC LIMIT 1', 'default', $_ib), ARRAY_A);
                                $_ib_last = $_ib_last_row ? new \DateTimeImmutable($_ib_last_row['scheduled_date'], new \DateTimeZone('UTC')) : $_ib_first;
                                $_ib_label = $_ib_first->format('M j') . ' – ' . $_ib_last->format('M j, Y');
                            } else {
                                $_ib_label = $_ib;
                            }
                            $active_class = $_ib === $current_batch ? ' amai-feed-week-option--active' : '';
                            echo '<a href="' . esc_url($base_url . '&batch=' . urlencode($_ib)) . '" class="amai-feed-week-option' . $active_class . '">' . esc_html($_ib_label) . '</a>';
                        }
                        ?>
                    </div>
                </div>
                <?php else : ?>
                    <?php echo esc_html($week_label !== '' ? $week_label : 'No posts yet'); ?>
                <?php endif; ?>
            </div>
            <?php if ($next_url !== '') : ?>
                <a href="<?php echo esc_url($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 (empty($posts_raw)) : ?>
        <div class="amai-fbdash-empty">
            <div class="amai-fbdash-empty-title">No posts for this week</div>
            <div class="amai-fbdash-empty-body">Navigate to another week or wait for the next generation run.</div>
        </div>
        <?php else : ?>
        <?php foreach ($posts_raw as $post) :
            $post_id      = (int) $post['id'];
            $status       = $post['status'];
            $post_type    = $post['post_type'];
            $content      = $post['post_content'];
            $sched_date   = $post['scheduled_date'];
            $gen_batch    = $post['generation_batch'];
            $dt           = new \DateTimeImmutable($sched_date);
            $dow          = $dt->format('D');
            $day_num      = $dt->format('j');
            $month        = $dt->format('M');
            $status_label = $status_labels[$status] ?? ucfirst($status);
            $type_label   = $type_labels[$post_type] ?? ucfirst(str_replace('_', ' ', $post_type));
            $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-row"
             data-post-id="<?php echo (int) $post_id; ?>"
             data-post-type="<?php echo esc_attr($post_type); ?>"
             data-post-type-label="<?php echo esc_attr($type_label); ?>"
             data-post-status="<?php echo esc_attr($status); ?>"
             data-post-content="<?php echo esc_attr(wp_unslash((string) $content)); ?>"
             data-post-image-url="<?php echo esc_attr((string) ($post['post_image_url'] ?? '')); ?>"
             data-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-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-generation-batch="<?php echo esc_attr($gen_batch); ?>"
             data-scheduled-date="<?php echo esc_attr($dt->format('M j, Y')); ?>"
             data-readonly="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-is-current-week="1"
             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-channel="instagram"
             role="button"
             tabindex="0">
            <div class="amai-feed-date">
                <div class="amai-feed-dow"><?php echo esc_html($dow); ?></div>
                <div class="amai-feed-day-num"><?php echo esc_html($day_num); ?></div>
                <div class="amai-feed-month"><?php echo esc_html($month); ?></div>
            </div>
            <div class="amai-feed-content">
                <div class="amai-feed-pills">
                    <span class="amai-feed-pill amai-feed-pill--<?php echo esc_attr($post['post_type']); ?>"><?php echo esc_html($type_label); ?></span>
                            <?php if (str_starts_with((string) ($gen_batch ?? ''), 'manual-')) : ?>
                            <span class="amai-feed-pill amai-feed-pill--manual">Manual</span>
                            <?php endif; ?>
                    <?php if ($feed_thumb !== '') : ?>
                    <span class="amai-feed-pill amai-feed-pill--img">📷 Photo</span>
                    <?php endif; ?>
                </div>
                <div class="amai-feed-copy"><?php echo esc_html($content); ?></div>
            </div>
            <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 if (!empty($post['stats_fetched_at'])) : ?>
                <div class="amai-feed-stats">
                    <span class="amai-feed-stat">&#128077; <?php echo isset($post['stat_likes']) && $post['stat_likes'] !== null ? (int)$post['stat_likes'] : 0; ?></span>
                    <span class="amai-feed-stat">&#128172; <?php echo isset($post['stat_comments']) && $post['stat_comments'] !== null ? (int)$post['stat_comments'] : 0; ?></span>
                </div>
                <?php endif; ?>
            </div>
        </div>
        <?php endforeach; ?>
        <?php endif; ?>
    </div>

    <?php endif; ?>

    <?php // ── 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-status-row">
                <span class="amai-post-panel-status" id="amai-panel-status"></span>
            </div>

            <div class="amai-post-panel-body">
                <div class="amai-post-panel-content" id="amai-panel-content" contenteditable="false"></div>
                <!-- IG post preview -->
                <div class="amai-ig-preview-toggle" id="amai-ig-preview-toggle" style="display:none;">
                    <button type="button" class="amai-ig-preview-btn" id="amai-ig-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 Instagram
                    </button>
                </div>
                <div class="amai-ig-post-preview" id="amai-ig-post-preview" style="display:none;">
                    <div class="amai-igp-card">
                        <div class="amai-igp-header">
                            <img class="amai-igp-avatar" id="amai-igp-avatar" src="" alt="" />
                            <div class="amai-igp-meta">
                                <div class="amai-igp-username" id="amai-igp-username"></div>
                            </div>
                            <svg class="amai-igp-more" width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><circle cx="5" cy="12" r="2"/><circle cx="12" cy="12" r="2"/><circle cx="19" cy="12" r="2"/></svg>
                        </div>
                        <div class="amai-igp-image-wrap" id="amai-igp-image-wrap" style="display:none;">
                            <img class="amai-igp-image" id="amai-igp-image" src="" alt="" />
                        </div>
                        <div class="amai-igp-actions">
                            <div class="amai-igp-actions-left">
                                <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/></svg>
                                <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>
                                <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg>
                            </div>
                            <svg class="amai-igp-bookmark" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z"/></svg>
                        </div>
                        <div class="amai-igp-caption" id="amai-igp-caption"></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>
                <!-- 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" maxlength="2200"></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>

                <!-- ── 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 <span class="amai-edit-img-required">(required for Instagram)</span></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>

            <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">&#10003; 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">&#8629; 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 caption…
                    </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 Instagram…
                    </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>

<?php // ── 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><!-- ── IG Disconnect modal ── -->
<div id="amai-ig-disconnect-modal" class="amai-dc-modal" style="display:none;">
    <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 Instagram?</div>
            </div>
            <button type="button" class="amai-dc-close" id="amai-ig-dc-close">&#10005;</button>
        </div>
        <div class="amai-dc-body">
            <p class="amai-dc-warning-text">
                Disconnecting Instagram will stop all scheduled Instagram posts from going out.
                Your Facebook connection will remain active.
            </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>
                    Scheduled Instagram 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>
                    Instagram drafts and history - cleared
                </div>
            </div>
            <p class="amai-dc-warning-sub">You can reconnect Instagram at any time from the Social Media page.</p>
        </div>
        <div class="amai-dc-footer">
            <button type="button" class="amai-dc-btn-cancel" id="amai-ig-dc-cancel">Keep it connected</button>
            <button type="button" class="amai-dc-btn-disconnect" id="amai-ig-dc-confirm-btn" data-nonce="<?php echo esc_attr($ig_disconnect_nonce); ?>">Yes, disconnect</button>
        </div>
    </div>
</div>
