<?php
use Core\System\Csrf;

$pageId = (int)($page['id'] ?? 0);
$pageName = (string)($page['name'] ?? '');
$pageSlug = (string)($page['slug'] ?? '');
$pageStatus = (string)($page['status'] ?? 'draft');
$productTitle = (string)($product['title'] ?? $product['name'] ?? __('landing.product', 'المنتج'));
$workspace = is_array($workspace ?? null) ? $workspace : [];
$agent = is_array($agent ?? null) ? $agent : [];
$conversation = is_array($conversation ?? null) ? $conversation : [];
$sessionHistory = is_array($sessionHistory ?? null) ? $sessionHistory : [];
$tasks = is_array($tasks ?? null) ? $tasks : [];
$briefs = is_array($briefs ?? null) ? $briefs : [];
$styles = is_array($agent['styles'] ?? null) ? $agent['styles'] : [];
$destinations = is_array($agent['destinations'] ?? null) ? array_values($agent['destinations']) : [];
$score = is_array($agent['scorecard']['breakdown'] ?? null) ? $agent['scorecard']['breakdown'] : [];
$selectedDestinations = is_array($workspace['selected_destinations'] ?? null) ? $workspace['selected_destinations'] : [];
$currentStyle = (string)($workspace['selected_style'] ?? '');
$selectedLanguage = (string)($workspace['selected_language'] ?? 'ar');
$selectedDialect = (string)($workspace['selected_dialect'] ?? 'ar-dz');
$csrf = Csrf::token();
require __DIR__ . '/_admin_theme_bridge.php';
?>
<!DOCTYPE html>
<html lang="<?= __('lang.code', 'ar') ?>" dir="<?= __('lang.direction', 'rtl') ?>">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?= htmlspecialchars($pageName !== '' ? $pageName . ' - ' . __('landing.chat_expert_title', 'Chat Expert') : __('landing.chat_expert_title', 'Chat Expert'), ENT_QUOTES, 'UTF-8') ?></title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
    <?php foreach ($lpThemeImports as $lpThemeCss): ?>
        <link rel="stylesheet" href="<?= htmlspecialchars($lpThemeCss, ENT_QUOTES, 'UTF-8') ?>">
    <?php endforeach; ?>
    <style>
        :root{--bg:<?= htmlspecialchars($lpThemeVars['bg'], ENT_QUOTES, 'UTF-8') ?>;--panel:<?= htmlspecialchars($lpThemeVars['panel'], ENT_QUOTES, 'UTF-8') ?>;--line:<?= htmlspecialchars($lpThemeVars['border'], ENT_QUOTES, 'UTF-8') ?>;--text:<?= htmlspecialchars($lpThemeVars['text'], ENT_QUOTES, 'UTF-8') ?>;--muted:<?= htmlspecialchars($lpThemeVars['muted'], ENT_QUOTES, 'UTF-8') ?>;--primary:<?= htmlspecialchars($lpThemeVars['primary'], ENT_QUOTES, 'UTF-8') ?>;--primary2:<?= htmlspecialchars($lpThemeVars['secondary'], ENT_QUOTES, 'UTF-8') ?>;--blue:<?= htmlspecialchars($lpThemeVars['accent'], ENT_QUOTES, 'UTF-8') ?>;--ok:<?= htmlspecialchars($lpThemeVars['success'], ENT_QUOTES, 'UTF-8') ?>;--bad:<?= htmlspecialchars($lpThemeVars['danger'], ENT_QUOTES, 'UTF-8') ?>;--shadow:0 18px 44px rgba(15,23,42,.08)}
        *{box-sizing:border-box}body{margin:0;background:radial-gradient(circle at top right,color-mix(in srgb, var(--primary) 14%, transparent),transparent 25%),radial-gradient(circle at top left,color-mix(in srgb, var(--blue) 12%, transparent),transparent 28%),var(--bg);color:var(--text);font-family:<?= $lpBodyFont ?>}
        h1,h2,h3,h4,h5,h6,.brand{font-family:<?= $lpHeadingFont ?>}
        .shell{min-height:100vh;display:grid;grid-template-rows:auto 1fr}.topbar{position:sticky;top:0;z-index:1000;display:flex;align-items:center;gap:14px;flex-wrap:wrap;padding:14px 24px;background:rgba(255,255,255,.98);backdrop-filter:blur(16px);border-bottom:1px solid var(--line);box-shadow:0 2px 16px rgba(15,23,42,.06)}
        .brand{display:flex;align-items:center;gap:12px;font-weight:900}.brand-icon{width:42px;height:42px;border-radius:14px;display:grid;place-items:center;color:#fff;background:linear-gradient(135deg,var(--primary),var(--primary2));box-shadow:0 14px 28px rgba(249,115,22,.22)}
        .brand small{display:block;color:var(--muted);font-size:11px;text-transform:uppercase;letter-spacing:.06em}.topbar-actions{margin-inline-start:auto;display:flex;gap:10px;flex-wrap:wrap}
        .btn-main,.btn-ghost{border:1px solid var(--line);background:#fff;color:var(--text);border-radius:14px;padding:11px 16px;font-size:13px;font-weight:800;display:inline-flex;align-items:center;justify-content:center;gap:8px;text-decoration:none;cursor:pointer;transition:.18s ease}.btn-main{background:linear-gradient(135deg,var(--primary),var(--primary2));border-color:transparent;color:#fff}.btn-main:hover,.btn-ghost:hover{transform:translateY(-1px)}
        .layout{display:grid;grid-template-columns:minmax(290px,24vw) minmax(0,1fr) minmax(300px,23vw);gap:18px;padding:18px}.panel{background:rgba(255,255,255,.94);border:1px solid var(--line);border-radius:24px;box-shadow:var(--shadow)}.panel-inner{padding:18px;display:grid;gap:14px}
        .header-card{padding:18px 20px}.eyebrow{display:inline-flex;align-items:center;gap:8px;padding:8px 12px;border-radius:999px;background:rgba(37,99,235,.08);color:var(--blue);font-size:11px;font-weight:900;text-transform:uppercase;letter-spacing:.05em}
        h1,h2,h3,p{margin:0}.muted{color:var(--muted);line-height:1.8}.search{width:100%;border-radius:14px;border:1px solid var(--line);background:#f8fafc;padding:12px 14px;font-size:13px}
        .session-list,.timeline,.feed,.cards{display:grid;gap:12px}.session-item,.feed-item,.mini-card,.task-card,.brief-card,.timeline-item{border:1px solid var(--line);border-radius:18px;background:#fff;padding:14px;display:grid;gap:8px}
        .session-item{cursor:pointer;text-decoration:none;color:var(--text)}.session-item.active{border-color:#fdba74;background:linear-gradient(180deg,#fff7ed,#fff)}.session-meta{display:flex;justify-content:space-between;align-items:center;gap:8px;color:var(--muted);font-size:11px;font-weight:800}
        .badge-soft{display:inline-flex;align-items:center;justify-content:center;padding:4px 8px;border-radius:999px;background:#eff6ff;color:#1d4ed8}.badge-live{background:#dcfce7;color:#166534}.badge-draft{background:#fff7ed;color:#c2410c}
        .chat-shell{display:grid;grid-template-rows:auto minmax(0,1fr) auto;min-height:calc(100vh - 150px)}.feed{min-height:360px;max-height:calc(100vh - 360px);overflow:auto;background:linear-gradient(180deg,#f8fafc,#fff);border:1px solid var(--line);border-radius:20px;padding:14px}
        .feed-item.user{background:linear-gradient(135deg,var(--primary),var(--primary2));color:#fff;border:none}.feed-item.assistant,.feed-item.system{background:#fff}.feed-item .meta{font-size:10px;font-weight:900;text-transform:uppercase;letter-spacing:.06em;opacity:.72}
        .composer{display:grid;grid-template-columns:1fr auto;gap:12px}.composer textarea{width:100%;min-height:92px;resize:vertical;border-radius:16px;border:1px solid var(--line);background:#f8fafc;padding:14px;font-size:13px;line-height:1.9}
        .timeline-item{position:relative;padding-inline-start:18px}.timeline-item::before{content:"";position:absolute;inset-inline-start:8px;top:18px;bottom:-14px;width:2px;background:#e2e8f0}.timeline-item:last-child::before{display:none}
        .grid2{display:grid;grid-template-columns:repeat(2,1fr);gap:12px}.style-chip,.status-chip{display:inline-flex;align-items:center;justify-content:center;padding:6px 10px;border-radius:999px;font-size:11px;font-weight:900;background:#f1f5f9;color:#334155;border:1px solid #dbe5f0}.status-chip.done{background:#ecfdf5;color:#166534;border-color:#bbf7d0}
        .alert-box{display:none;padding:14px 16px;border-radius:16px;border:1px solid var(--line)}.alert-box.show{display:block}.alert-box.error{background:#fef2f2;border-color:#fecaca}.alert-box.success{background:#f0fdf4;border-color:#bbf7d0}
        .spinner{width:16px;height:16px;border:2px solid currentColor;border-top-color:transparent;border-radius:50%;display:inline-block;animation:spin .7s linear infinite}
        @keyframes spin{to{transform:rotate(360deg)}}@media (max-width:1200px){.layout{grid-template-columns:1fr}.grid2,.composer{grid-template-columns:1fr}.feed{max-height:none}}
        /* ── Enhanced Styles ── */
        .brand-icon{box-shadow:0 8px 24px rgba(249,115,22,.28)!important}
        .btn-ghost{transition:all .2s ease}
        .btn-ghost:hover{background:color-mix(in srgb,var(--primary) 8%,#fff);border-color:var(--primary);color:var(--primary);transform:translateY(-1px)}
        .btn-main:active,.btn-ghost:active{transform:translateY(0)}
        .session-item{transition:box-shadow .22s,transform .22s,background .18s}
        .session-item:hover{box-shadow:0 8px 22px rgba(15,23,42,.09)!important;transform:translateY(-1px)}
        .mini-card,.task-card,.brief-card,.timeline-item{transition:box-shadow .22s}
        .mini-card:hover,.task-card:hover{box-shadow:0 6px 18px rgba(15,23,42,.08)!important}
        .eyebrow-o{background:rgba(249,115,22,.1)!important;color:var(--primary)!important}
        .eyebrow-g{background:rgba(22,163,74,.1)!important;color:var(--ok)!important}
        .eyebrow-p{background:rgba(139,92,246,.1)!important;color:#7c3aed!important}
        .eyebrow-r{background:rgba(220,38,38,.1)!important;color:var(--bad)!important}
        .eyebrow-a{background:rgba(217,119,6,.1)!important;color:var(--warning)!important}
        .eyebrow-t{background:rgba(14,165,233,.1)!important;color:var(--blue)!important}
        .composer textarea:focus{outline:none;border-color:var(--primary);box-shadow:0 0 0 3px color-mix(in srgb,var(--primary) 15%,transparent)}
        .feed{scrollbar-width:thin;scrollbar-color:var(--line) transparent}
        .feed-item{border-radius:18px!important;transition:box-shadow .2s}
        .feed-item.user{border-radius:18px 18px 4px 18px!important}
        .feed-item.assistant{border-radius:18px 18px 18px 4px!important}
        .badge-soft{border-radius:999px;font-size:10px;font-weight:800;padding:3px 9px}
        .status-chip.done{font-weight:800}.status-chip.todo{font-weight:800}
        .btn-main{box-shadow:0 4px 14px color-mix(in srgb,var(--primary) 28%,transparent)}
        .btn-main:hover{box-shadow:0 6px 20px color-mix(in srgb,var(--primary) 35%,transparent)}
        @media (max-width:768px){.topbar{padding:10px 16px}.brand-icon{width:36px!important;height:36px!important}}
    </style>
</head>
<body>
<div class="shell">
    <div class="topbar">
        <div class="brand">
            <div class="brand-icon"><i class="bi bi-chat-square-text"></i></div>
            <div>
                <div><?= __('landing.chat_expert_title', 'Chat Expert') ?></div>
                <small><?= __('landing.chat_expert_subtitle', 'جلسات منظمة، محادثات محفوظة، وسير عمل تسويقي من مكان واحد') ?></small>
            </div>
        </div>
        <div class="topbar-actions">
            <a href="/admin/ai-landing-pages/edit/<?= $pageId ?>" class="btn-ghost"><i class="bi bi-stars"></i><span><?= __('landing.open_studio', 'فتح الـ Studio') ?></span></a>
            <a href="/admin/ai-landing-pages/production/<?= $pageId ?>" class="btn-ghost"><i class="bi bi-kanban"></i><span><?= __('landing.open_production_workspace', 'سير الإنتاج') ?></span></a>
            <a href="/admin/ai-landing-pages/competitors/<?= $pageId ?>" class="btn-ghost"><i class="bi bi-binoculars"></i><span><?= __('landing.open_competitor_workspace', 'مساحة المنافسين') ?></span></a>
            <a href="/admin/ai-landing-pages/preview/<?= $pageId ?>" target="_blank" class="btn-ghost"><i class="bi bi-eye"></i><span><?= __('landing.preview', 'معاينة') ?></span></a>
            <a href="/admin/ai-landing-pages" class="btn-ghost"><i class="bi bi-arrow-left"></i><span><?= __('common.back', 'رجوع') ?></span></a>
        </div>
    </div>

    <div class="layout">
        <aside class="panel">
            <div class="panel-inner">
                <div class="header-card">
                    <div class="eyebrow eyebrow-t"><i class="bi bi-collection"></i><?= __('landing.session_center_title', 'مركز الجلسات') ?></div>
                    <h2 style="margin-top:10px;font-size:24px;font-weight:900;"><?= htmlspecialchars($productTitle, ENT_QUOTES, 'UTF-8') ?></h2>
                    <p class="muted" style="margin-top:8px;"><?= __('landing.session_center_text', 'استعرض كل جلسات هذا المنتج، وابحث بينها، وأنشئ جلسة مستقلة جديدة عند الحاجة.') ?></p>
                </div>

                <?php if ($success): ?><div class="alert-box success show"><?= htmlspecialchars($success, ENT_QUOTES, 'UTF-8') ?></div><?php endif; ?>
                <?php if ($error): ?><div class="alert-box error show"><?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8') ?></div><?php endif; ?>

                <form method="post" action="/admin/ai-landing-pages/create-session/<?= $pageId ?>">
                    <?= Csrf::field() ?>
                    <button type="submit" class="btn-main" style="width:100%"><i class="bi bi-plus-circle"></i><span><?= __('landing.new_session', 'جلسة جديدة') ?></span></button>
                </form>

                <input type="search" id="session-search" class="search" placeholder="<?= htmlspecialchars(__('landing.session_search', 'ابحث باسم الجلسة أو الـ slug'), ENT_QUOTES, 'UTF-8') ?>">

                <div class="session-list" id="session-list">
                    <?php foreach ($productPages as $sessionPage): ?>
                        <?php
                        $isCurrent = (int)$sessionPage['id'] === $pageId;
                        $sessionName = (string)($sessionPage['name'] ?? '');
                        $sessionSlug = (string)($sessionPage['slug'] ?? '');
                        $sessionStatus = (string)($sessionPage['status'] ?? 'draft');
                        ?>
                        <a href="/admin/ai-landing-pages/chat/<?= (int)$sessionPage['id'] ?>" class="session-item<?= $isCurrent ? ' active' : '' ?>" data-search="<?= htmlspecialchars(mb_strtolower($sessionName . ' ' . $sessionSlug), ENT_QUOTES, 'UTF-8') ?>">
                            <strong><?= htmlspecialchars($sessionName, ENT_QUOTES, 'UTF-8') ?></strong>
                            <small class="muted"><?= htmlspecialchars($sessionSlug, ENT_QUOTES, 'UTF-8') ?></small>
                            <div class="session-meta">
                                <span class="badge-soft<?= $sessionStatus === 'published' ? ' badge-live' : ' badge-draft' ?>"><?= htmlspecialchars($sessionStatus, ENT_QUOTES, 'UTF-8') ?></span>
                                <span><?= htmlspecialchars((string)($sessionPage['updated_at'] ?? ''), ENT_QUOTES, 'UTF-8') ?></span>
                            </div>
                        </a>
                    <?php endforeach; ?>
                </div>
            </div>
        </aside>

        <section class="panel">
            <div class="panel-inner chat-shell">
                <div class="header-card">
                    <div class="eyebrow eyebrow-o"><i class="bi bi-chat-dots"></i><?= __('landing.conversation_title', 'المحادثة المحفوظة') ?></div>
                    <h2 style="margin-top:10px;font-size:24px;font-weight:900;"><?= htmlspecialchars($pageName, ENT_QUOTES, 'UTF-8') ?></h2>
                    <p class="muted" style="margin-top:8px;"><?= __('landing.conversation_text', 'هذه هي المحادثة الحقيقية الخاصة بهذه الجلسة. كل تعليمات جديدة تُحفظ وتبقى مرتبطة بهذه النسخة وحدها.') ?></p>
                </div>

                <div id="chat-status" class="alert-box"></div>

                <div id="chat-feed" class="feed">
                    <?php if (!$conversation): ?>
                        <div class="feed-item assistant">
                            <div class="meta"><?= __('landing.assistant_label', 'assistant') ?></div>
                            <div><?= __('landing.chat_empty', 'ابدأ بإرسال أول تعليماتك هنا. ستُحفظ كل الرسائل داخل هذه الجلسة.') ?></div>
                        </div>
                    <?php else: ?>
                        <?php foreach ($conversation as $message): ?>
                            <?php $role = (string)($message['role'] ?? 'assistant'); ?>
                            <div class="feed-item <?= htmlspecialchars(in_array($role, ['user','assistant','system'], true) ? $role : 'assistant', ENT_QUOTES, 'UTF-8') ?>">
                                <div class="meta"><?= htmlspecialchars($role, ENT_QUOTES, 'UTF-8') ?></div>
                                <div><?= nl2br(htmlspecialchars((string)($message['content'] ?? ''), ENT_QUOTES, 'UTF-8')) ?></div>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>

                <div class="composer">
                    <textarea id="chat-input" placeholder="<?= htmlspecialchars(__('landing.chat_input_placeholder', 'اكتب تعليماتك هنا: حسّن الصفحة، غيّر الـ CTA، ابنِ brief جديد، أو عدّل زاوية البيع...'), ENT_QUOTES, 'UTF-8') ?>"></textarea>
                    <button type="button" id="send-chat-message" class="btn-main"><i class="bi bi-send"></i><span><?= __('landing.send_request', 'إرسال') ?></span></button>
                </div>
            </div>
        </section>

        <aside class="panel">
            <div class="panel-inner">
                <div class="header-card">
                    <div class="eyebrow eyebrow-p"><i class="bi bi-kanban"></i><?= __('landing.workspace_summary_title', 'ملخص الجلسة') ?></div>
                    <h2 style="margin-top:10px;font-size:22px;font-weight:900;"><?= __('landing.workspace_summary_text', 'حالة العمل والإنتاج') ?></h2>
                </div>

                <div class="cards">
                    <div class="mini-card">
                        <strong><?= __('landing.session_title_label', 'عنوان الجلسة') ?></strong>
                        <span><?= htmlspecialchars((string)($workspace['session_title'] ?? $pageName), ENT_QUOTES, 'UTF-8') ?></span>
                        <span><?= htmlspecialchars((string)($workspace['current_objective'] ?? ''), ENT_QUOTES, 'UTF-8') ?></span>
                    </div>
                    <div class="grid2">
                        <div class="mini-card"><strong><?= __('landing.score_global', 'Score') ?></strong><span><?= htmlspecialchars((string)($score['global'] ?? $agent['scorecard']['global_score'] ?? '—'), ENT_QUOTES, 'UTF-8') ?></span></div>
                        <div class="mini-card"><strong><?= __('landing.output_landing_page', 'Landing Page') ?></strong><span><?= htmlspecialchars((string)$pageStatus, ENT_QUOTES, 'UTF-8') ?></span></div>
                    </div>
                    <div class="mini-card">
                        <strong><?= __('landing.style_system_title', 'نظام الـ Styles') ?></strong>
                        <span><?= htmlspecialchars($currentStyle, ENT_QUOTES, 'UTF-8') ?></span>
                        <span><?= htmlspecialchars($selectedLanguage . ' / ' . $selectedDialect, ENT_QUOTES, 'UTF-8') ?></span>
                    </div>
                    <div class="mini-card">
                        <strong><?= __('landing.destinations_title', 'وجهات الإنتاج') ?></strong>
                        <div>
                            <?php foreach ($destinations as $destination): ?>
                                <?php $destId = (string)($destination['id'] ?? ''); ?>
                                <a href="/admin/ai-landing-pages/destination/<?= $pageId ?>/<?= urlencode($destId) ?>" class="style-chip" style="text-decoration:none;margin:0 0 6px 6px;display:inline-flex;">
                                    <?= htmlspecialchars((string)($destination['title'] ?? $destId), ENT_QUOTES, 'UTF-8') ?><?= in_array($destId, $selectedDestinations, true) ? ' ✓' : '' ?>
                                </a>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>

                <div class="header-card" style="padding-top:0">
                    <div class="eyebrow eyebrow-a"><i class="bi bi-clock-history"></i><?= __('landing.session_history_title', 'تاريخ الجلسة') ?></div>
                </div>
                <div class="timeline">
                    <?php if (!$sessionHistory): ?>
                        <div class="timeline-item"><strong><?= __('landing.no_session_history', 'لا يوجد سجل جلسة بعد') ?></strong></div>
                    <?php else: ?>
                        <?php foreach (array_reverse($sessionHistory) as $snapshot): ?>
                            <div class="timeline-item">
                                <strong><?= htmlspecialchars((string)($snapshot['title'] ?? ''), ENT_QUOTES, 'UTF-8') ?></strong>
                                <span><?= htmlspecialchars((string)($snapshot['summary'] ?? ''), ENT_QUOTES, 'UTF-8') ?></span>
                                <span><?= htmlspecialchars((string)($snapshot['stage'] ?? ''), ENT_QUOTES, 'UTF-8') ?> • <?= htmlspecialchars((string)($snapshot['at'] ?? ''), ENT_QUOTES, 'UTF-8') ?></span>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>

                <div class="header-card" style="padding-top:0">
                    <div class="eyebrow eyebrow-g"><i class="bi bi-check2-square"></i><?= __('landing.tasks_title', 'المهام') ?></div>
                </div>
                <div class="cards">
                    <?php if (!$tasks): ?>
                        <div class="task-card"><strong><?= __('landing.no_tasks', 'لا توجد مهام بعد') ?></strong></div>
                    <?php else: ?>
                        <?php foreach ($tasks as $task): ?>
                            <div class="task-card">
                                <strong><?= htmlspecialchars((string)($task['title'] ?? ''), ENT_QUOTES, 'UTF-8') ?></strong>
                                <span><?= htmlspecialchars((string)($task['note'] ?? ''), ENT_QUOTES, 'UTF-8') ?></span>
                                <span class="status-chip <?= htmlspecialchars((string)($task['status'] ?? 'todo'), ENT_QUOTES, 'UTF-8') ?>"><?= htmlspecialchars((string)($task['status'] ?? 'todo'), ENT_QUOTES, 'UTF-8') ?></span>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>

                <div class="header-card" style="padding-top:0">
                    <div class="eyebrow eyebrow-r"><i class="bi bi-file-earmark-text"></i><?= __('landing.briefs_title', 'الـ Briefs') ?></div>
                </div>
                <div class="cards">
                    <?php if (!$briefs): ?>
                        <div class="brief-card"><strong><?= __('landing.no_briefs', 'لا توجد Briefs بعد') ?></strong></div>
                    <?php else: ?>
                        <?php foreach (array_slice(array_reverse($briefs), 0, 5) as $brief): ?>
                            <div class="brief-card">
                                <strong><?= htmlspecialchars((string)($brief['title'] ?? ''), ENT_QUOTES, 'UTF-8') ?></strong>
                                <span><?= htmlspecialchars((string)($brief['summary'] ?? $brief['objective'] ?? ''), ENT_QUOTES, 'UTF-8') ?></span>
                                <span><?= htmlspecialchars((string)($brief['destination_label'] ?? $brief['destination'] ?? ''), ENT_QUOTES, 'UTF-8') ?></span>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>
        </aside>
    </div>
</div>

<script>
const PAGE_ID = <?= $pageId ?>;
const CSRF = <?= json_encode($csrf, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
const I18N = {
    send: <?= json_encode(__('landing.send_request', 'إرسال'), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>,
    sending: <?= json_encode(__('landing.send_request_text', 'نرسل طلبك إلى الوكيل ونحفظه في الجلسة الحالية.'), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>,
    updated: <?= json_encode(__('landing.ai_updated', 'تم تحديث صفحة الهبوط بناءً على طلبك.'), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>,
    pipelineError: <?= json_encode(__('landing.pipeline_error', 'خطأ في المسار'), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>,
    userLabel: <?= json_encode(__('landing.user_label', 'user'), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>,
    assistantLabel: <?= json_encode(__('landing.assistant_label', 'assistant'), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>
};
function escapeHtml(value){return String(value ?? '').replace(/[&<>"']/g, function(m){return({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;'})[m];});}
function appendFeed(role, content){
    const feed = document.getElementById('chat-feed');
    const item = document.createElement('div');
    item.className = 'feed-item ' + (role === 'user' ? 'user' : 'assistant');
    item.innerHTML = '<div class="meta">'+escapeHtml(role === 'user' ? I18N.userLabel : I18N.assistantLabel)+'</div><div>'+escapeHtml(content).replace(/\n/g,'<br>')+'</div>';
    feed.appendChild(item);
    feed.scrollTop = feed.scrollHeight;
}
function setStatus(type, text){
    const box = document.getElementById('chat-status');
    box.className = 'alert-box show ' + (type || '');
    box.textContent = text;
}
async function sendMessage(){
    const input = document.getElementById('chat-input');
    const button = document.getElementById('send-chat-message');
    const message = input.value.trim();
    if(!message){return;}
    appendFeed('user', message);
    input.value = '';
    button.disabled = true;
    button.innerHTML = '<span class="spinner"></span><span>'+escapeHtml(I18N.sending)+'</span>';
    try{
        const fd = new FormData();
        fd.append('_csrf', CSRF);
        fd.append('message', message);
        const res = await fetch('/admin/ai-landing-pages/generate/' + PAGE_ID, {method:'POST', body:fd});
        const text = await res.text();
        let data = {};
        try{
            data = JSON.parse(text);
        }catch(err){
            throw new Error(text.slice(0, 220));
        }
        if(!data.success){
            throw new Error(data.error || I18N.pipelineError);
        }
        appendFeed('assistant', I18N.updated);
        setStatus('success', I18N.updated);
    }catch(err){
        setStatus('error', (err && err.message) ? err.message : I18N.pipelineError);
        appendFeed('assistant', '⚠️ ' + ((err && err.message) ? err.message : I18N.pipelineError));
    }finally{
        button.disabled = false;
        button.innerHTML = '<i class="bi bi-send"></i><span>'+escapeHtml(I18N.send)+'</span>';
    }
}
document.getElementById('send-chat-message').addEventListener('click', sendMessage);
document.getElementById('chat-input').addEventListener('keydown', function(e){
    if(e.key === 'Enter' && (e.ctrlKey || e.metaKey)){
        sendMessage();
    }
});
document.getElementById('session-search').addEventListener('input', function(){
    const q = this.value.toLowerCase().trim();
    document.querySelectorAll('#session-list .session-item').forEach(function(item){
        const hay = item.getAttribute('data-search') || '';
        item.style.display = !q || hay.indexOf(q) !== -1 ? '' : 'none';
    });
});
</script>
</body>
</html>
