<?php
declare(strict_types=1);
// ==================================================
// Nuclear Fancy Pants Edition™ — NUCLEAR+++
// File: /templates/social/google-dashboard.php
// Description: Google Business Profile connected dashboard - feed layout - NUCLEAR+++
// Last Edited: 2026-05-22
// ==================================================

namespace AutoMarketerAI;

defined('ABSPATH') || exit;

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

$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;
}

$business_name    = esc_html((string) ($conn['business_name'] ?? ''));
$location_name    = esc_html((string) ($conn['location_name'] ?? ''));
$connected_at     = esc_html((string) ($conn['connected_at'] ?? ''));
$connected_ago    = $connected_at !== ''
    ? human_time_diff(strtotime($connected_at), current_time('timestamp', true)) . ' ago'
    : '';
$initials         = strtoupper(substr((string) ($conn['business_name'] ?? 'G'), 0, 2));
$disconnect_nonce = wp_create_nonce('amai_google_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
// --------------------------------------------------
$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 AND channel = 'google'
             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');
    }
}

// --------------------------------------------------
// Batch selection
// --------------------------------------------------
$channel = 'google';

$all_batches_raw = $wpdb->get_col(
    $wpdb->prepare(
        "SELECT DISTINCT generation_batch
         FROM `{$wpdb->prefix}amai_scheduled_posts`
         WHERE tenant_id = %s AND channel = 'google'
         ORDER BY generation_batch DESC",
        'default'
    )
);

$all_batches_weekly = array_values(array_filter($all_batches_raw, static fn($b) => (bool) preg_match('/^\d{4}-W\d{2}$/', (string) $b)));

$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 selected batch
// --------------------------------------------------
$posts_raw  = [];
$week_label = '';

if ($current_batch !== '') {
    $weekly_posts = $wpdb->get_results(
        $wpdb->prepare(
            'SELECT id, post_type, scheduled_date, scheduled_time, status, post_content,
                    post_image_url, generation_batch,
                    unsplash_attachment_id, unsplash_credit,
                    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',
            'google',
            $current_batch
        ),
        ARRAY_A
    );

    if (!empty($weekly_posts)) {
        $week_start_str = $weekly_posts[0]['scheduled_date'];
        $week_end_str   = $weekly_posts[count($weekly_posts) - 1]['scheduled_date'];
    } else {
        [$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');
    }

    $manual_posts = $wpdb->get_results(
        $wpdb->prepare(
            'SELECT id, post_type, scheduled_date, scheduled_time, status, post_content,
                    post_image_url, generation_batch,
                    unsplash_attachment_id, unsplash_credit,
                    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',
            'google',
            '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;
    }
}

// --------------------------------------------------
// GBP post type labels
// --------------------------------------------------
$all_type_labels = [
    'update'        => 'Update',
    'offer'         => 'Offer',
    'event'         => 'Event',
    'educational'   => 'Educational',
    'tip'           => 'Tip',
    'behind_scenes' => 'Behind the scenes',
];

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

$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') : '',
        'is_today'    => $date_str === $today_str,
        'is_manual'   => false,
        'post'        => $post,
    ];
}

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') : '',
        'is_today'    => $date_str === $today_str,
        'is_manual'   => true,
        'post'        => $mp,
    ];
}

usort($feed_rows, static function (array $a, array $b): int {
    $da = $a['post']['scheduled_date'] ?? '';
    $db = $b['post']['scheduled_date'] ?? '';
    return strcmp($da, $db);
});

$base_url    = admin_url('admin.php?page=automarketer-ai-social&channel=google');
$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');

$is_latest_batch = ($batch_index === 0 || $batch_index === false);

$_amai_gen_failed       = get_option('amai_generation_failed', []);
$_amai_gen_failed_google = is_array($_amai_gen_failed) && ($_amai_gen_failed['channel'] ?? '') === 'google';
$_amai_regen_nonce      = wp_create_nonce('amai_regenerate_week');
?>
<?php if ($_amai_gen_failed_google) : ?>
<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="google">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=google')); ?>"
       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=google&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['amai_google_connected'])) : ?>
    <div class="amai-fbdash-notice amai-fbdash-notice--success">
        You're connected! AutoMarketer AI will start publishing updates to your Google Business Profile automatically.
    </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. 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');
        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', btnEnable.dataset.nonce);
                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) {
                        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', btnDismiss.dataset.nonce);
                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">
                <div class="amai-fbdash-page-initials"><?php echo esc_html($initials); ?></div>
                <span class="amai-fbdash-status-dot" title="Connected"></span>
            </div>
            <div class="amai-fbdash-page-meta">
                <div class="amai-fbdash-page-name"><?php echo $business_name; ?></div>
                <div class="amai-fbdash-page-sub">
                    <span>Google Business Profile</span>
                    <?php if ($connected_ago !== '') : ?>
                    <span class="amai-fbdash-dot">·</span>
                    <span>Connected <?php echo esc_html($connected_ago); ?></span>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <button type="button" class="amai-fbdash-disconnect-btn" id="amai-google-disconnect-trigger">Disconnect</button>
    </div>

    <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
                $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 = \'google\' 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 = \'google\' 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 Google Business Profile updates 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']) : '';
                $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-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['dow'] . ' ' . $row['day_num'] . ' ' . $row['month_short']); ?>"
                data-readonly="<?php echo $row_readonly ? '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 endif; ?>
                            <?php if ($row['is_manual']) : ?>
                            <span class="amai-feed-pill amai-feed-pill--manual">Manual</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>
                </div>
                <?php endif; ?>
            </div>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>
    </div>

</div>

<!-- 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>

            <div class="amai-post-panel-content" id="amai-panel-content"></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>

            <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">&#10003; Photo added to post</span>
                    <button type="button" class="amai-unsplash-btn-undo" id="amai-unsplash-btn-undo">Undo</button>
                </div>
            </div>

            <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>

            <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>
                    <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>
                    <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>
                </div>

                <div class="amai-edit-img-block" id="amai-edit-img-block" style="display:none;">
                    <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>
                    <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>
                    <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>
                    <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>
                    <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 storefront, 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>
                    <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>
                    <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>
                    <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>
            </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="update">Update</option>
                        <option value="offer">Offer</option>
                        <option value="event">Event</option>
                        <option value="educational">Educational</option>
                        <option value="tip">Tip</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">&#8617; 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="update">Update</option>
                        <option value="offer">Offer</option>
                        <option value="event">Event</option>
                        <option value="educational">Educational</option>
                        <option value="tip">Tip</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 Google Business Profile...
                </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>

<!-- 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 $business_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 access to this Google Business Profile. Scheduled posts will be cancelled.
            </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>
            <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>
            <form method="post">
                <?php wp_nonce_field('amai_google_disconnect', '_wpnonce'); ?>
                <button type="submit" name="amai_google_disconnect" value="1" class="amai-dc-btn-disconnect">Yes, disconnect</button>
            </form>
        </div>
    </div>
</div>
<script>
(function () {
    var trigger = document.getElementById('amai-google-disconnect-trigger');
    var modal   = document.getElementById('amai-disconnect-modal');
    var close   = document.getElementById('amai-dc-close');
    var cancel  = document.getElementById('amai-dc-cancel');
    function openModal()  { if (modal) modal.classList.add('is-open'); }
    function closeModal() { if (modal) modal.classList.remove('is-open'); }
    if (trigger) trigger.addEventListener('click', openModal);
    if (close)   close.addEventListener('click', closeModal);
    if (cancel)  cancel.addEventListener('click', closeModal);
    if (modal)   modal.addEventListener('click', function (e) { if (e.target === modal) closeModal(); });
}());
</script>