
<?php
use Core\System\Csrf;

$pageId = (int)($page['id'] ?? 0);
$pageName = (string)($page['name'] ?? '');
$pageSlug = (string)($page['slug'] ?? '');
$pageStatus = (string)($page['status'] ?? 'draft');
$pageSourceImage = (string)($page['source_image'] ?? '');
$pageSourceMode = (string)($page['source_mode'] ?? 'manual');
$conversation = is_array($conversation ?? null) ? $conversation : [];
$productPages = is_array($productPages ?? null) ? $productPages : [];
$analysis = is_array($page['analysis_json'] ?? null) ? $page['analysis_json'] : [];
$structure = is_array($page['structure_json'] ?? null) ? $page['structure_json'] : [];
$agent = is_array($page['agent_trace'] ?? null) ? $page['agent_trace'] : [];
$variants = is_array($agent['variants'] ?? null) ? $agent['variants'] : [];
$competitor = is_array($agent['competitor_report'] ?? null) ? $agent['competitor_report'] : [];
$hasContent = !empty($page['html_content']);

$resolveMedia = static function ($value): string {
    if (!is_string($value)) {
        return '';
    }
    $value = trim($value);
    if ($value === '') {
        return '';
    }
    if (preg_match('/^(https?:)?\/\//i', $value) || strpos($value, 'data:') === 0) {
        return $value;
    }
    return '/' . ltrim($value, '/');
};

$productTitle = (string)($product['title'] ?? $product['name'] ?? '');
$productDescription = (string)($product['description'] ?? $product['short_description'] ?? '');
$productPrice = (string)($product['price'] ?? '');
$productImages = [];
foreach (['featured_image', 'image'] as $field) {
    if (!empty($product[$field]) && is_string($product[$field])) {
        $productImages[] = $resolveMedia($product[$field]);
    }
}
if (!empty($product['images']) && is_array($product['images'])) {
    foreach ($product['images'] as $item) {
        if (is_string($item) && trim($item) !== '') {
            $productImages[] = $resolveMedia($item);
            continue;
        }
        if (is_array($item)) {
            foreach (['url', 'path', 'image', 'src'] as $key) {
                if (!empty($item[$key]) && is_string($item[$key])) {
                    $productImages[] = $resolveMedia($item[$key]);
                    break;
                }
            }
        }
    }
}
if ($pageSourceImage !== '') {
    $productImages[] = $resolveMedia($pageSourceImage);
}
$productImages = array_values(array_filter(array_unique($productImages)));
$productImage = $productImages[0] ?? '';

$initialState = [
    'analysis' => $analysis,
    'structure' => $structure,
    'agent' => $agent,
    'variants' => $variants,
    'competitor' => $competitor,
    'conversation' => $conversation,
];

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 : 'AI Landing Studio', 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') ?>;--panel-soft:<?= htmlspecialchars($lpThemeVars['panel_soft'], 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') ?>;--warn:<?= htmlspecialchars($lpThemeVars['warning'], 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:80;display:flex;align-items:center;gap:14px;flex-wrap:wrap;padding:14px 24px;background:rgba(255,255,255,.92);backdrop-filter:blur(16px);border-bottom:1px solid var(--line);box-shadow:0 10px 26px 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)}.btn-main[disabled],.btn-ghost[disabled],.btn-main.is-loading,.btn-ghost.is-loading{pointer-events:none;opacity:.78}
        .btn-loading-spinner{width:14px;height:14px;border-radius:50%;border:2px solid currentColor;border-top-color:transparent;display:inline-block;animation:spin .7s linear infinite}
        .layout{display:grid;direction:ltr;grid-template-columns:minmax(320px,360px) minmax(0,1fr) 96px;grid-template-areas:"preview workspace rail";gap:20px;padding:20px;align-items:start}
        .rail,.workspace,.preview{direction:rtl;min-width:0}
        .rail{grid-area:rail}
        .workspace{grid-area:workspace}
        .preview{grid-area:preview}
        .rail{position:sticky;top:20px;align-self:start}
        .panel{background:color-mix(in srgb, var(--panel) 96%, transparent);border:1px solid color-mix(in srgb, var(--line) 88%, white);border-radius:24px;box-shadow:var(--shadow);overflow:hidden}
        .rail-box{padding:16px 10px;display:grid;gap:12px;justify-items:center}
        .rail-step{text-decoration:none;display:grid;justify-items:center;gap:8px;color:var(--muted);font-size:11px;font-weight:800;text-align:center}
        .rail-step .icon{width:48px;height:48px;border-radius:18px;border:1px solid var(--line);display:grid;place-items:center;background:var(--panel);color:var(--blue)}
        .rail-step.active{color:var(--text)}
        .rail-step.active .icon{background:linear-gradient(135deg,var(--primary),var(--primary2));border-color:transparent;color:#fff}
        .stack{display:grid;gap:18px;min-width:0}
        .card{padding:26px;min-width:0}
        .hero{display:grid;grid-template-columns:minmax(0,1.35fr) minmax(300px,.85fr);gap:20px;align-items:start}
        .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;margin-bottom:12px}
        h1{margin:0 0 10px;font-size:clamp(30px,3vw,44px);line-height:1.35;font-weight:900}
        .muted{color:var(--muted);line-height:1.85;overflow-wrap:anywhere}
        .metrics{display:grid;grid-template-columns:repeat(4,minmax(100px,1fr));gap:12px;margin-bottom:12px}
        .metric{background:#fff;border:1px solid var(--line);border-radius:20px;padding:16px;text-align:center;min-width:0;box-shadow:0 10px 24px rgba(15,23,42,.03)}
        .metric strong{display:block;font-size:22px}
        .snapshot{display:grid;grid-template-columns:88px minmax(0,1fr);gap:14px;align-items:center;padding:16px;border-radius:20px;background:linear-gradient(180deg,#fff,#f8fafc);border:1px solid var(--line);min-width:0}
        .snapshot img,.snap-ph{width:88px;height:88px;border-radius:18px;object-fit:cover;border:1px solid var(--line);background:#eef2f7}
        .snap-ph{display:grid;place-items:center;color:var(--muted);font-size:28px}
        .stage-head h3{margin:0 0 6px;font-size:20px;font-weight:900}.kicker{font-size:11px;font-weight:900;color:var(--blue);text-transform:uppercase;letter-spacing:.06em;display:inline-flex;align-items:center;gap:8px}.toolbar,.grid2,.grid3,.sections{display:grid;gap:12px}.toolbar{display:flex;flex-wrap:wrap;align-items:center}.grid2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid3{grid-template-columns:repeat(3,minmax(0,1fr))}
        .source-box{display:grid;grid-template-columns:110px minmax(0,1fr);gap:16px;align-items:start;padding:18px;border:1px dashed #cbd5e1;border-radius:22px;background:linear-gradient(180deg,#fff,#f8fafc)}
        .source-box .toolbar{grid-column:1/-1;justify-content:flex-start}
        .source-thumb,.source-placeholder{width:110px;height:110px;border-radius:20px;border:1px solid var(--line);background:#eef2f7;object-fit:cover}
        .source-placeholder{display:grid;place-items:center;color:var(--muted);font-size:28px}
        .status{display:none;gap:6px;border-radius:18px;padding:14px 16px;background:linear-gradient(180deg,#eff6ff,#f8fbff);border:1px solid #bfdbfe}.status.success{background:linear-gradient(180deg,#f0fdf4,#f7fee7);border-color:#bbf7d0}.status.error{background:linear-gradient(180deg,#fef2f2,#fff7f7);border-color:#fecaca}.status .meta{font-size:11px;font-weight:900;color:var(--blue);text-transform:uppercase;letter-spacing:.06em}
        .mini-card,.concept-card,.variant-card,.section-card,.output-card,.timeline-item{border:1px solid var(--line);border-radius:20px;background:#fff;padding:16px;display:grid;gap:8px;min-width:0;overflow:hidden;overflow-wrap:anywhere;word-break:break-word;box-shadow:0 12px 28px rgba(15,23,42,.035)}
        .mini-card span,.concept-card span,.variant-card span,.output-card span,.timeline-item span{font-size:12px;color:var(--muted);line-height:1.8}
        .section-head{display:flex;justify-content:space-between;gap:12px;align-items:center}
        .section-head h4{margin:0;font-size:15px;font-weight:900}
        .flags{display:flex;gap:14px;flex-wrap:wrap;color:var(--muted);font-size:12px}
        .field-label{color:var(--muted);font-size:11px;font-weight:900;text-transform:uppercase;letter-spacing:.05em;margin-bottom:6px}.input,.select,.textarea{width:100%;border-radius:14px;border:1px solid var(--line);background:#f8fafc;color:var(--text);padding:12px 14px;font-size:13px;outline:none}.textarea{min-height:94px;resize:vertical;line-height:1.9}
        .style-chip,.status-chip,.priority-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}.status-chip.doing{background:#eff6ff;color:#1d4ed8;border-color:#bfdbfe}.status-chip.todo{background:#fff7ed;color:#c2410c;border-color:#fed7aa}.priority-chip{background:#fff7ed;color:#9a3412;border-color:#fed7aa}
        .workflow-board{display:grid;gap:14px}
        .workflow-hero{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:14px}
        .timeline-stack,.production-board,.outputs-grid{display:grid;gap:12px}
        .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}
        .timeline-item strong{font-size:14px}
        .output-card header{display:flex;justify-content:space-between;gap:10px;align-items:flex-start}
        .output-card header strong{font-size:14px}
        .output-card .toolbar{margin-top:4px}
        .assembler-shell{display:grid;grid-template-columns:minmax(0,1.15fr) minmax(320px,.85fr);gap:16px}
        .assembler-lane{display:grid;gap:12px;min-width:0}
        .assembler-summary{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:12px}
        .assembler-metric{border:1px solid var(--line);border-radius:18px;padding:14px;background:linear-gradient(180deg,#fff,#f8fafc);text-align:center}
        .assembler-metric strong{display:block;font-size:22px}
        .assembler-board{display:grid;gap:12px}
        .section-actions{display:flex;flex-wrap:wrap;gap:8px}
        .section-actions button{padding:8px 10px;font-size:12px}
        .assembler-rail{display:grid;gap:12px;align-self:start;position:sticky;top:18px}.assembler-outline{display:grid;gap:10px}.outline-item{display:grid;gap:6px;padding:12px;border:1px solid var(--line);border-radius:16px;background:#fff}.outline-item.active{border-color:#fdba74;box-shadow:0 12px 28px rgba(249,115,22,.12)}.outline-item small{color:var(--muted)}
        .side-panel{display:grid;gap:14px;padding-inline-end:4px}
        .feed-log{min-height:220px;max-height:360px;overflow:auto;background:linear-gradient(180deg,#f8fafc,#fff);border:1px solid var(--line);border-radius:18px;padding:14px;display:grid;gap:12px}
        .feed-item{border-radius:16px;padding:12px 14px;display:grid;gap:6px;box-shadow:0 10px 20px rgba(15,23,42,.04)}
        .feed-item.user{background:linear-gradient(135deg,var(--primary),var(--primary2));color:#fff}
        .feed-item.assistant,.feed-item.system{background:#fff;color:var(--text);border:1px solid var(--line)}
        .feed-item .meta{font-size:10px;font-weight:900;text-transform:uppercase;letter-spacing:.06em;opacity:.72}
        .preview{display:grid;grid-template-rows:auto auto auto;gap:14px;position:sticky;top:92px;align-self:start;padding-inline-end:4px}
        .preview-card{overflow:hidden;min-height:420px}
        .preview-head{display:flex;justify-content:space-between;align-items:flex-start;gap:12px;padding:18px 18px 0;flex-wrap:wrap}
        .preview-wrap{padding:18px;max-height:520px;overflow:auto}
        .frame,.empty{width:100%;min-height:420px;border-radius:22px;border:1px solid var(--line);background:#fff}
        .empty{display:grid;place-items:center;padding:28px;text-align:center;color:var(--muted);background:linear-gradient(180deg,#fff,#f8fafc)}
        .publish{padding:20px;display:grid;gap:12px}
        .session-cluster{display:grid;gap:10px;max-height:280px;overflow:auto;padding-inline-end:4px}
        .session-link{display:grid;gap:6px;padding:12px 14px;border-radius:18px;border:1px solid var(--line);background:#fff;text-decoration:none;color:var(--text);transition:.18s ease}
        .session-link:hover{transform:translateY(-1px);border-color:#cbd5e1}
        .session-link.active{border-color:#fdba74;background:linear-gradient(180deg,#fff7ed,#fff)}
        .session-link strong{font-size:13px;font-weight:900}
        .session-link small{color:var(--muted);line-height:1.7}
        .session-meta{display:flex;justify-content:space-between;align-items:center;gap:8px;color:var(--muted);font-size:11px;font-weight:800}
        .session-badge{padding:4px 8px;border-radius:999px;background:#eff6ff;color:#1d4ed8}
        .session-badge.live{background:#dcfce7;color:#166534}
        .busy-overlay{position:fixed;inset:0;background:rgba(15,23,42,.42);backdrop-filter:blur(6px);display:none;place-items:center;z-index:1000;padding:20px}.busy-card{width:min(460px,92vw);background:#fff;border:1px solid var(--line);border-radius:28px;box-shadow:0 22px 60px rgba(15,23,42,.25);padding:28px;display:grid;gap:14px;text-align:center}.busy-spinner{width:56px;height:56px;border-radius:50%;border:4px solid #e2e8f0;border-top-color:var(--primary);margin:0 auto;animation:spin .9s linear infinite}.busy-title{font-size:20px;font-weight:900}.busy-text{color:var(--muted);line-height:1.9}
        @keyframes spin{to{transform:rotate(360deg)}}
        @media (max-width:1400px){
            .layout{grid-template-columns:300px minmax(0,1fr) 86px}
            .hero{grid-template-columns:1fr}
            .metrics{grid-template-columns:repeat(2,minmax(0,1fr))}
            .workflow-hero,.assembler-shell{grid-template-columns:1fr}
            .assembler-rail{position:static}
        }
        @media (max-width:1200px){
            .layout{grid-template-columns:1fr}
            .preview,.rail{position:static;max-height:none;overflow:visible}
            .layout{grid-template-areas:"rail" "workspace" "preview"}
            .preview-wrap,.session-cluster{max-height:none}
            .rail-box{grid-template-columns:repeat(5,minmax(0,1fr));justify-items:stretch}
            .hero,.grid2,.grid3,.metrics,.source-box,.workflow-hero,.assembler-shell,.assembler-summary{grid-template-columns:1fr}
        }
    </style>
</head>
<body>
<div class="shell">
    <div class="topbar">
        <div class="brand">
            <div class="brand-icon"><i class="bi bi-stars"></i></div>
            <div>
                <div><?= __('landing.studio_title', 'AI Landing Studio') ?></div>
                <small><?= __('landing.studio_subtitle', 'Image-driven strategy, structure, variants, and publishing in one workspace') ?></small>
            </div>
        </div>
        <div class="topbar-actions">
            <a href="/admin/ai-landing-pages" class="btn-ghost"><i class="bi bi-arrow-left"></i><span><?= __('common.back', 'رجوع') ?></span></a>
            <a href="/admin/ai-landing-pages/chat/<?= $pageId ?>" class="btn-ghost"><i class="bi bi-chat-square-text"></i><span><?= __('landing.open_chat_expert', 'Chat Expert') ?></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>
            <?php if ($pageStatus === 'published'): ?>
                <a href="/lp/<?= urlencode($pageSlug) ?>" target="_blank" class="btn-ghost"><i class="bi bi-box-arrow-up-right"></i><span><?= __('landing.view_live', 'عرض مباشر') ?></span></a>
            <?php endif; ?>
        </div>
    </div>

    <div class="layout">
        <aside class="rail">
            <div class="panel rail-box">
                <a href="#stage-intake" class="rail-step active"><div class="icon"><i class="bi bi-upload"></i></div><span><?= __('landing.stage_analysis_short', '1. Analysis') ?></span></a>
                <a href="#stage-analysis" class="rail-step"><div class="icon"><i class="bi bi-grid-3x3-gap"></i></div><span><?= __('landing.stage_structure_short', '2. Structure') ?></span></a>
                <a href="#stage-sections" class="rail-step"><div class="icon"><i class="bi bi-ui-checks-grid"></i></div><span><?= __('landing.stage_assemble_short', '3. Assembly') ?></span></a>
                <a href="#stage-variants" class="rail-step"><div class="icon"><i class="bi bi-layers"></i></div><span><?= __('landing.stage_variants_short', '4. Variants') ?></span></a>
                <a href="#stage-publish" class="rail-step"><div class="icon"><i class="bi bi-send-check"></i></div><span><?= __('landing.stage_publish_short', '5. Publish') ?></span></a>
            </div>
        </aside>

        <main class="workspace">
            <div class="stack">
                <section class="panel card hero">
                    <div>
                        <div class="eyebrow"><i class="bi bi-lightning-charge-fill"></i><?= __('landing.command_center_eyebrow', 'مركز قيادة صفحات الهبوط') ?></div>
                        <h1><?= __('landing.studio_hero_title', 'ابدأ من صورة أو صفحة منافس، ثم حوّلها إلى Landing Page قابلة للنشر') ?></h1>
                        <p class="muted"><?= __('landing.studio_hero_subtitle', 'المنصة تعمل كوكيل ذكاء اصطناعي متعدد المراحل: تحلل، تبني strategy، تقترح concepts، تنظم sections، تولد variants، ثم تجهز الصفحة للنشر النهائي.') ?></p>
                    </div>
                    <div>
                        <div class="metrics">
                            <div class="metric"><strong id="metric-sections">0</strong><span><?= __('landing.sections_detected', 'الأقسام المكتشفة') ?></span></div>
                            <div class="metric"><strong id="metric-concepts">0</strong><span><?= __('landing.concepts_ready', 'المفاهيم الجاهزة') ?></span></div>
                            <div class="metric"><strong id="metric-variants">0</strong><span><?= __('landing.variants_ready', 'النسخ المولدة') ?></span></div>
                            <div class="metric"><strong id="metric-briefs">0</strong><span><?= __('landing.briefs_ready', 'الـ Briefs') ?></span></div>
                        </div>
                        <div class="snapshot">
                            <?php if ($productImage): ?>
                                <img src="<?= htmlspecialchars($productImage, ENT_QUOTES, 'UTF-8') ?>" alt="">
                            <?php else: ?>
                                <div class="snap-ph"><i class="bi bi-box-seam"></i></div>
                            <?php endif; ?>
                            <div>
                                <strong style="display:block;font-size:15px;margin-bottom:6px;"><?= htmlspecialchars($productTitle !== '' ? $productTitle : __('landing.product', 'المنتج'), ENT_QUOTES, 'UTF-8') ?></strong>
                                <?php if ($productPrice !== ''): ?><div class="muted" style="font-size:12px;margin-bottom:6px;"><?= __('landing.price_label', 'السعر') ?>: <?= htmlspecialchars($productPrice, ENT_QUOTES, 'UTF-8') ?></div><?php endif; ?>
                                <div class="muted" style="font-size:12px;"><?= htmlspecialchars(mb_strimwidth($productDescription, 0, 140, '...'), ENT_QUOTES, 'UTF-8') ?></div>
                            </div>
                        </div>
                    </div>
                </section>

                <section class="panel card" id="stage-intake">
                    <div class="stage-head">
                        <div class="kicker"><i class="bi bi-upload"></i><?= __('landing.stage_analysis_short', '1. التحليل') ?></div>
                        <h3><?= __('landing.source_stage_title', 'رفع المرجع وتشغيل الوكيل') ?></h3>
                        <p class="muted"><?= __('landing.source_stage_text', 'Upload a full screenshot, design, or visual reference, then let the agent analyze the layout and extract sections, colors, and messaging.') ?></p>
                    </div>
                    <div class="source-box">
                        <img id="source-image-thumb" class="source-thumb" src="<?= htmlspecialchars($pageSourceImage, ENT_QUOTES, 'UTF-8') ?>" alt="" style="<?= $pageSourceImage !== '' ? '' : 'display:none' ?>">
                        <div id="source-image-placeholder" class="source-placeholder" style="<?= $pageSourceImage !== '' ? 'display:none' : '' ?>"><i class="bi bi-image"></i></div>
                        <div>
                            <div class="field-label"><?= __('landing.source_image', 'Reference image') ?></div>
                            <div style="font-size:14px;font-weight:900;margin-bottom:6px;"><?= __('landing.image_agent_upload', 'Upload screenshot or design') ?></div>
                            <div class="muted" style="font-size:12px;"><?= __('landing.source_image_best_result', 'For best results, select the correct product from the store and upload a full screenshot of the reference page — not just the product image alone.') ?></div>
                        </div>
                        <div class="toolbar">
                            <label class="btn-ghost" style="cursor:pointer">
                                <i class="bi bi-upload"></i><span><?= __('landing.choose_image', 'Choose image') ?></span>
                                <input type="file" id="source-image-input" accept="image/*" style="display:none">
                            </label>
                            <button type="button" class="btn-main" id="btn-build-from-image"><i class="bi bi-stars"></i><span><?= __('landing.build_from_image', 'Build from image') ?></span></button>
                            <button type="button" class="btn-ghost" id="btn-regenerate-structure"><i class="bi bi-arrow-repeat"></i><span><?= __('landing.regenerate_from_structure', 'Regenerate') ?></span></button>
                        </div>
                    </div>
                    <div id="pipeline-status" class="status"></div>
                </section>

                <section class="panel card" id="stage-analysis">
                    <div class="stage-head">
                        <div class="kicker"><i class="bi bi-grid-3x3-gap"></i><?= __('landing.stage_structure_short', '2. Structure') ?></div>
                        <h3><?= __('landing.stage_analysis_title', 'Analysis Result & Strategy') ?></h3>
                        <p class="muted"><?= __('landing.stage_analysis_description', 'The analysis card, colors, CTA, suggested concepts, and initial score appear here before assembly.') ?></p>
                    </div>
                    <div id="analysis-summary"></div>
                    <div id="agent-workbench"></div>
                </section>

                <section class="panel card" id="stage-sections">
                    <div class="stage-head">
                        <div class="kicker"><i class="bi bi-ui-checks-grid"></i><?= __('landing.stage_assemble_short', '3. Assembly') ?></div>
                        <h3><?= __('landing.stage_assemble_title', 'Section Editor & Assembler') ?></h3>
                        <p class="muted"><?= __('landing.stage_assemble_description', 'Review sections, disable or lock any section, then assemble the best final version before publishing.') ?></p>
                    </div>
                    <div id="agent-assembler"></div>
                </section>

                <section class="panel card" id="stage-variants">
                    <div class="stage-head">
                        <div class="kicker"><i class="bi bi-layers"></i><?= __('landing.stage_variants_short', '4. Variants') ?></div>
                        <h3><?= __('landing.stage_variants_title', 'Smart Variants') ?></h3>
                        <p class="muted"><?= __('landing.stage_variants_description', 'Generate multiple versions from the same structure with different angles and messages, then preview and adopt the best one.') ?></p>
                    </div>
                    <div id="agent-variants"></div>
                    <div id="competitor-analysis-card" style="margin-top:14px"></div>
                </section>

                <section class="panel card">
                    <div class="stage-head">
                        <div class="kicker"><i class="bi bi-chat-square-text"></i><?= __('landing.activity_kicker', 'Execution Activity') ?></div>
                        <h3><?= __('landing.activity_title', 'AI Activity & Reports') ?></h3>
                        <p class="muted"><?= __('landing.activity_subtitle', 'Analysis messages, errors, updates, and AI results will appear here clearly.') ?></p>
                    </div>
                    <div id="activity-log" class="feed-log"></div>
                    <div>
                        <div id="chat-image-preview" style="display:none;margin-bottom:8px;align-items:center;gap:8px;">
                            <img id="chat-image-thumb" style="max-height:72px;border-radius:10px;border:1px solid var(--line);object-fit:cover;" alt="">
                            <div style="display:grid;gap:4px;">
                                <span style="font-size:11px;font-weight:900;color:var(--muted);text-transform:uppercase;"><?= __('landing.chat_image_attached', 'Image attached') ?></span>
                                <button type="button" id="btn-remove-chat-image" class="btn-ghost" style="padding:4px 10px;font-size:11px;"><i class="bi bi-x"></i> <?= __('landing.chat_image_remove', 'Remove') ?></button>
                            </div>
                        </div>
                        <textarea id="chat-input" class="textarea" placeholder="<?= htmlspecialchars(__('landing.chat_input_placeholder', 'Write your instruction here: improve the page, change the CTA, build a new brief, or shift the sales angle...'), ENT_QUOTES, 'UTF-8') ?>"></textarea>
                        <div class="toolbar" style="margin-top:10px;">
                            <button type="button" class="btn-main" id="btn-send-message"><i class="bi bi-magic"></i><span><?= __('landing.execute_label', 'Execute') ?></span></button>
                            <label id="btn-chat-image-label" title="<?= htmlspecialchars(__('landing.chat_image_attach', 'Attach image'), ENT_QUOTES, 'UTF-8') ?>" style="cursor:pointer;width:40px;height:40px;border-radius:12px;border:1px solid var(--line);background:#fff;display:inline-flex;align-items:center;justify-content:center;color:var(--muted);font-size:17px;transition:.18s ease;flex-shrink:0;" onmouseover="this.style.color='var(--primary)';this.style.borderColor='var(--primary)'" onmouseout="this.style.color='var(--muted)';this.style.borderColor='var(--line)'">
                                <i class="bi bi-paperclip"></i>
                                <input type="file" id="chat-image-input" accept="image/*" style="display:none">
                            </label>
                            <button type="button" class="btn-ghost" id="btn-prompt-hero"><i class="bi bi-lightning"></i><span><?= __('landing.prompt_upgrade_hero', 'Strengthen Hero') ?></span></button>
                            <button type="button" class="btn-ghost" id="btn-prompt-cta"><i class="bi bi-bullseye"></i><span><?= __('landing.prompt_boost_cta', 'Improve Copy') ?></span></button>
                            <button type="button" class="btn-ghost" id="btn-prompt-order"><i class="bi bi-bag-check"></i><span><?= __('landing.prompt_order_box', 'Add Order Box') ?></span></button>
                        </div>
                    </div>
                </section>
            </div>
        </main>

        <aside class="preview">
            <div class="panel preview-card">
                <div class="preview-head">
                    <div>
                        <h3 style="margin:0;font-size:18px;font-weight:900;"><?= __('landing.live_preview_title', 'معاينة مباشرة') ?></h3>
                        <div class="muted" style="font-size:12px;"><?= __('landing.live_preview_text', 'المعاينة الحية تتحدث كلما غيّرت الصفحة أو اعتمدت نسخة جديدة.') ?></div>
                    </div>
                    <code>/lp/<?= htmlspecialchars($pageSlug, ENT_QUOTES, 'UTF-8') ?></code>
                </div>
                <div class="preview-wrap">
                    <?php if ($hasContent): ?>
                        <iframe id="preview-frame" class="frame" src="/admin/ai-landing-pages/preview/<?= $pageId ?>" title="Preview" sandbox="allow-scripts allow-forms allow-popups"></iframe>
                    <?php else: ?>
                        <div id="preview-empty" class="empty">
                            <div>
                                <i class="bi bi-window-stack" style="font-size:42px;display:block;margin-bottom:12px;"></i>
                                <strong style="display:block;font-size:17px;margin-bottom:8px;"><?= __('landing.preview_empty_title', 'ابدأ من الصورة لتظهر أول نسخة هنا') ?></strong>
                                <div class="muted"><?= __('landing.preview_empty_text', 'بمجرد انتهاء التحليل والتجميع ستظهر النسخة المباشرة هنا.') ?></div>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <section class="panel card side-panel">
                <div class="stage-head">
                    <div class="kicker"><i class="bi bi-collection"></i><?= __('landing.sessions_center', 'مركز الجلسات') ?></div>
                    <h3><?= __('landing.sessions_center_title', 'جلسات المنتج الحالية') ?></h3>
                    <p class="muted"><?= __('landing.sessions_center_text', 'تنقل بين جلسات نفس المنتج بسرعة، وواصل البناء من أي نسخة بدل العمل على جلسة واحدة فقط.') ?></p>
                </div>
                <div class="session-cluster">
                    <?php foreach ($productPages as $sessionPage): ?>
                        <?php
                        $sessionId = (int)($sessionPage['id'] ?? 0);
                        $sessionName = (string)($sessionPage['name'] ?? ('#' . $sessionId));
                        $sessionStatus = (string)($sessionPage['status'] ?? 'draft');
                        $sessionUpdated = !empty($sessionPage['updated_at']) ? date('d/m/Y H:i', strtotime((string)$sessionPage['updated_at'])) : '';
                        $isCurrentSession = $sessionId === $pageId;
                        ?>
                        <a href="/admin/ai-landing-pages/edit/<?= $sessionId ?>" class="session-link<?= $isCurrentSession ? ' active' : '' ?>">
                            <div class="session-meta">
                                <span class="session-badge<?= $sessionStatus === 'published' ? ' live' : '' ?>">
                                    <?= $sessionStatus === 'published' ? __('landing.published', 'Published') : __('landing.draft', 'Draft') ?>
                                </span>
                                <span><?= htmlspecialchars($sessionUpdated, ENT_QUOTES, 'UTF-8') ?></span>
                            </div>
                            <strong><?= htmlspecialchars($sessionName, ENT_QUOTES, 'UTF-8') ?></strong>
                            <small><?= htmlspecialchars($productTitle !== '' ? $productTitle : __('landing.product_session_fallback', 'جلسة مرتبطة بنفس المنتج'), ENT_QUOTES, 'UTF-8') ?></small>
                            <?php if ($isCurrentSession): ?>
                                <small><?= __('landing.current_session', 'هذه هي الجلسة المفتوحة الآن.') ?></small>
                            <?php endif; ?>
                        </a>
                    <?php endforeach; ?>
                </div>
                <div class="toolbar" style="margin-bottom:16px">
                    <a href="/admin/ai-landing-pages/create?mode=image" class="btn-main" style="width:100%">
                        <i class="bi bi-plus-circle"></i>
                        <span><?= __('landing.new_session_same_product', 'إنشاء جلسة جديدة') ?></span>
                    </a>
                </div>
                <div style="margin-bottom:16px">
                    <h3 style="margin:0 0 8px;font-size:16px;font-weight:900;"><?= __('landing.chat_history_title', 'سجل المحادثة') ?></h3>
                    <p class="muted" style="margin-bottom:10px;"><?= __('landing.chat_history_text', 'تابع آخر رسائل الجلسة الحالية بسرعة من الشريط الجانبي.') ?></p>
                    <div id="session-chat-sidebar" class="feed-log" style="min-height:180px;max-height:280px"></div>
                </div>
                <div class="stage-head">
                    <div class="kicker"><i class="bi bi-diagram-3"></i><?= __('landing.session_outputs_kicker', 'Session + Outputs') ?></div>
                    <h3><?= __('landing.session_outputs_title', 'لوحة الجلسة والإنتاج') ?></h3>
                    <p class="muted"><?= __('landing.session_outputs_subtitle', 'تابع ملخص الجلسة، المخرجات الجاهزة، والخط الزمني من مكان واحد بدون تشتت.') ?></p>
                </div>
                <div id="workspace-overview"></div>
                <div id="session-timeline"></div>
            </section>

            <form method="post" action="/admin/ai-landing-pages/update/<?= $pageId ?>" class="panel publish" id="stage-publish">
                <?= Csrf::field() ?>
                <input type="hidden" name="product_id" value="<?= (int)($page['product_id'] ?? 0) ?>">
                <div class="stage-head">
                    <div class="kicker"><i class="bi bi-send-check"></i><?= __('landing.stage_publish_short', '5. النشر') ?></div>
                    <h3><?= __('landing.publish_title', 'الاعتماد والنشر') ?></h3>
                    <p class="muted"><?= __('landing.publish_stage_text', 'حرر اسم الصفحة والـ slug، ثم انشرها عندما تصبح النسخة جاهزة تجاريًا.') ?></p>
                </div>
                <div>
                    <div class="field-label"><?= __('landing.name_label', 'الاسم') ?></div>
                    <input type="text" name="name" class="input" value="<?= htmlspecialchars($pageName, ENT_QUOTES, 'UTF-8') ?>">
                </div>
                <div>
                    <div class="field-label"><?= __('landing.slug_label', 'الرابط') ?></div>
                    <input type="text" name="slug" class="input" value="<?= htmlspecialchars($pageSlug, ENT_QUOTES, 'UTF-8') ?>">
                </div>
                <div>
                    <div class="field-label"><?= __('landing.status_label', 'الحالة') ?></div>
                    <select name="status" class="select">
                        <option value="draft" <?= $pageStatus === 'draft' ? 'selected' : '' ?>>مسودة</option>
                        <option value="published" <?= $pageStatus === 'published' ? 'selected' : '' ?>>منشورة</option>
                    </select>
                </div>
                <div class="toolbar">
                    <button type="submit" class="btn-main"><i class="bi bi-save"></i><span>حفظ</span></button>
                    <a href="/admin/ai-landing-pages/preview/<?= $pageId ?>" target="_blank" class="btn-ghost"><i class="bi bi-display"></i><span><?= __('landing.open_preview', 'فتح المعاينة') ?></span></a>
                </div>
            </form>
        </aside>
    </div>
</div>

<div class="busy-overlay" id="busy-overlay">
    <div class="busy-card">
        <div class="busy-spinner"></div>
        <div class="busy-title" id="busy-title"><?= __('landing.busy_title', 'جاري التنفيذ') ?></div>
        <div class="busy-text" id="busy-text"><?= __('landing.busy_text', 'يرجى الانتظار بينما ينفذ الوكيل الخطوة المطلوبة.') ?></div>
    </div>
</div>

<script>
/* ── Global error safety net (separate block so it survives any syntax error below) ── */
window.__studioErrorShown = false;
window.onerror = function(msg, src, line, col, err){
    if(window.__studioErrorShown) return;
    window.__studioErrorShown = true;
    var feed = document.getElementById('activity-log');
    if(feed){
        var item = document.createElement('div');
        item.className = 'feed-item system';
        item.style.cssText = 'border-right:3px solid #dc2626;background:#fef2f2;';
        item.innerHTML = '<div class="meta" style="color:#dc2626">خطأ في JavaScript</div>'
            + '<div style="direction:ltr;font-family:monospace;font-size:.8rem">'
            + (msg||'').replace(/[<>]/g,'') + ' — line ' + (line||'?')
            + '</div>';
        feed.appendChild(item);
        feed.scrollTop = feed.scrollHeight;
    }
    var box = document.getElementById('pipeline-status');
    if(box){
        box.className = 'status error';
        box.style.display = 'grid';
        box.innerHTML = '<div class="meta">خطأ في التهيئة</div>'
            + '<div>حدث خطأ أثناء تحميل الصفحة. راجع سجل النشاط للتفاصيل.</div>';
    }
};
</script>

<script>
const PAGE_ID = <?= $pageId ?>;
const CSRF_TOKEN = '<?= addslashes(Csrf::token()) ?>';
const INITIAL_SOURCE_IMAGE = <?= json_encode($pageSourceImage, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_SUBSTITUTE) ?: '""' ?>;
const INITIAL_SOURCE_MODE = <?= json_encode($pageSourceMode, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_SUBSTITUTE) ?: '"manual"' ?>;
const I18N = <?= json_encode([
    'busy_title' => __('landing.busy_title', 'جاري التنفيذ'),
    'busy_text' => __('landing.busy_text', 'يرجى الانتظار بينما ينفذ الوكيل الخطوة المطلوبة.'),
    'busy_default' => __('landing.busy_default', 'يرجى الانتظار...'),
    'busy_running' => __('landing.busy_running', 'جاري التنفيذ'),
    'activity_user' => __('landing.message_user', 'أنت'),
    'activity_ai' => __('landing.message_ai', 'وكيل الذكاء الاصطناعي'),
    'feed_empty' => __('landing.feed_empty', 'ابدأ برفع صورة ثم شغّل التحليل. بعد ذلك يمكنك إرسال تعليمات مثل: غيّر الخط، أضف صور المنتج، أضف صندوق الطلب، أو حسّن النصوص لسوق COD الجزائري.'),
    'status_ready_label' => __('landing.pipeline_status_ready_label', 'جاهز للعمل'),
    'status_ready_text' => __('landing.pipeline_status_ready', 'تم تجهيز الهيكل ويمكنك الآن التجميع أو توليد النسخ أو إرسال تعليمات إضافية.'),
    'status_waiting_label' => __('landing.pipeline_status_waiting_label', 'بانتظار التحليل'),
    'status_waiting_text' => __('landing.pipeline_status_waiting', 'الصورة محفوظة، اضغط إنشاء من الصورة لبدء التحليل والتوليد.'),
    'status_upload_label' => __('landing.pipeline_status_upload_label', 'أضف صورة أولًا'),
    'status_upload_text' => __('landing.pipeline_status_upload', 'ابدأ باختيار Screenshot أو Design ثم شغّل الوكيل من هنا.'),
    'select_image_ready' => __('landing.image_selected_ready', 'تم اختيار الصورة'),
    'select_image_ready_text' => __('landing.image_selected_ready_text', 'الصورة جاهزة. اضغط الآن على إنشاء من الصورة لتشغيل الوكيل.'),
    'build_missing_image' => __('landing.source_image_required', 'يرجى رفع Screenshot أو تصميم الصفحة أولاً.'),
    'pipeline_error' => __('landing.pipeline_status_error_label', 'خطأ في المسار'),
    'save_analysis' => __('landing.save_analysis', 'حفظ التحليل'),
    'save_analysis_text' => __('landing.save_analysis_text', 'نحفظ Product Analysis Form داخل مساحة العمل.'),
    'analysis_saved' => __('landing.analysis_saved', 'تم حفظ تحليل المنتج.'),
    'save_workspace' => __('landing.save_workspace', 'حفظ مساحة العمل'),
    'save_workspace_text' => __('landing.save_workspace_text', 'نحفظ الـ style الحالي والمهام والوجهات داخل الجلسة.'),
    'workspace_saved' => __('landing.workspace_saved', 'تم حفظ مساحة العمل.'),
    'generate_brief' => __('landing.generate_brief', 'توليد brief'),
    'generate_brief_text' => __('landing.generate_brief_text', 'نحوّل التحليل الحالي إلى brief جديد لهذه الوجهة.'),
    'brief_generated' => __('landing.brief_generated', 'تم توليد brief جديد لهذه الوجهة.'),
    'send_request' => __('landing.send_request', 'جاري تنفيذ التعليمات'),
    'send_request_text' => __('landing.send_request_text', 'نرسل طلبك إلى الوكيل لتحسين الصفحة الحالية.'),
    'ai_updated' => __('landing.ai_updated', 'تم تحديث صفحة الهبوط بناءً على طلبك.'),
    'build_success' => __('landing.image_pipeline_ready', 'تم إنشاء صفحة الهبوط انطلاقًا من الصورة المرفوعة.'),
    'regenerate_text' => __('landing.regenerate_text', 'نعيد بناء الصفحة من الـ Structure المحفوظ.'),
    'assemble_text' => __('landing.assemble_text', 'نجمّع الأقسام المختارة ونبني النسخة النهائية للمعاينة.'),
    'variants_text' => __('landing.variants_text', 'نولد الآن عدة نسخ مختلفة من نفس الهيكل التسويقي.'),
    'competitor_text' => __('landing.competitor_text', 'نجلب الصفحة المنافسة ونستخرج نقاط القوة والضعف الآن.'),
    'competitor_ready' => __('landing.competitor_analyzed', 'تحليل المنافس جاهز الآن.'),
    'variant_applied' => __('landing.variant_applied', 'تم اعتماد النسخة بنجاح.'),
    'assembler_missing' => __('landing.structure_missing', 'لا يوجد Structure محفوظ مشتق من الصورة لهذه الصفحة.'),
    'composer' => __('landing.composer_label', 'Composer'),
    'session_timeline' => __('landing.session_timeline', 'الخط الزمني للجلسة'),
    'session_timeline_text' => __('landing.session_timeline_text', 'آخر التحولات التي مر بها الوكيل داخل هذه الصفحة.'),
    'workspace_summary' => __('landing.workspace_summary', 'ملخص التشغيل'),
    'workspace_outputs' => __('landing.workspace_outputs', 'مخرجات الإنتاج'),
    'session_saved' => __('landing.session_saved', 'تم حفظ إعدادات الجلسة.'),
    'latest_brief' => __('landing.latest_brief', 'آخر Brief'),
    'brief_queue' => __('landing.brief_queue', 'طابور الـ Briefs'),
    'brief_queue_text' => __('landing.brief_queue_text', 'فعّل وجهة أو أكثر ثم اضغط توليد brief لبدء الإنتاج.'),
    'no_session_history' => __('landing.no_session_history', 'لا يوجد سجل بعد'),
    'no_session_history_text' => __('landing.no_session_history_text', 'ابدأ التحليل أو أنشئ brief جديدًا ليظهر التاريخ هنا.'),
    'variants_generate' => __('landing.generate_variants', 'توليد 3 Variants'),
    'variants_generate_help' => __('landing.variants_generate_help', 'أنشئ ثلاث نسخ مختلفة من نفس الصفحة بزوايا تسويقية مختلفة.'),
    'variants_refresh' => __('landing.refresh_variants', 'تحديث النسخ البديلة'),
    'variants_score' => __('landing.variants_score', 'Score'),
    'preview_label' => __('landing.preview', 'معاينة'),
    'apply_variant_label' => __('landing.apply_variant', 'اعتماد النسخة'),
    'competitor_title' => __('landing.competitor_title', 'تحليل المنافس'),
    'competitor_subtitle' => __('landing.competitor_subtitle', 'أدخل رابط منافس لتحليل نقاط القوة والثغرات والزوايا التي يمكننا التفوق بها.'),
    'competitor_placeholder' => __('landing.competitor_placeholder', 'https://competitor.com/landing-page'),
    'competitor_global' => __('landing.competitor_global', 'التقييم العام'),
    'competitor_strategy' => __('landing.competitor_strategy', 'الاستراتيجية المقترحة'),
    'competitor_strengths' => __('landing.competitor_strengths', 'نقاط القوة'),
    'competitor_gaps' => __('landing.competitor_gaps', 'الثغرات التي يمكن استغلالها'),
    'chat_prompt_hero' => __('landing.chat_prompt_hero', 'Strengthen the hero section with a stronger offer, clearer value proposition, and sharper CTA.'),
    'chat_prompt_cta' => __('landing.chat_prompt_cta', 'Improve the copy to be more persuasive and conversion-focused for the Algerian COD market.'),
    'chat_prompt_order' => __('landing.chat_prompt_order', 'أضف صندوق الطلب بخلفية إسلامية مع CTA واضح وثقة أعلى لسوق الجزائر.'),
    'chat_image_attach' => __('landing.chat_image_attach', 'Attach image'),
    'chat_image_attached' => __('landing.chat_image_attached', 'Image attached'),
    'chat_image_remove' => __('landing.chat_image_remove', 'Remove'),
    'chat_image_uploading' => __('landing.chat_image_uploading', 'Uploading image…'),
    'chat_image_uploaded' => __('landing.chat_image_uploaded', 'Image uploaded — mention what to do with it in your message.'),
    'chat_image_upload_failed' => __('landing.chat_image_upload_failed', 'Failed to upload image'),
    'chat_image_ref' => __('landing.chat_image_ref', 'Reference image'),
    'execute_label' => __('landing.execute_label', 'Execute'),
    'activity_kicker' => __('landing.activity_kicker', 'Execution Activity'),
    'stage_analysis_title' => __('landing.stage_analysis_title', 'Analysis Result & Strategy'),
    'stage_assemble_title' => __('landing.stage_assemble_title', 'Section Editor & Assembler'),
    'stage_variants_title' => __('landing.stage_variants_title', 'Smart Variants'),
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_SUBSTITUTE) ?: '{}' ?>;
let studioState = <?= json_encode($initialState, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_SUBSTITUTE) ?: '{}' ?> || {};
let selectedSourceImage = null;
let chatAttachedImageUrl = null;
let chatAttachedImageFile = null;

function e(value){return String(value ?? '').replace(/[&<>"']/g, s => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[s]));}
function textOf(value){if(Array.isArray(value)){return value.map(textOf).filter(Boolean).join(' • ');} if(value && typeof value==='object'){for(const key of ['text','label','title','value','name']){if(value[key]) return textOf(value[key]);} return Object.values(value).map(textOf).filter(Boolean).join(' • ');} return String(value ?? '').trim();}
function ensureArray(value){return Array.isArray(value) ? value : [];}
function t(key,fallback){return Object.prototype.hasOwnProperty.call(I18N,key) ? I18N[key] : fallback;}
function setStatus(type,kicker,message){const box=document.getElementById('pipeline-status'); box.className='status '+(type||''); box.style.display='grid'; box.innerHTML='<div class=\"meta\">'+e(kicker)+'</div><div>'+e(message)+'</div>'; if(type==='error'||type==='success'){try{box.scrollIntoView({behavior:'smooth',block:'nearest'});}catch(e){}}}
function setButtonLoading(target,active,label){const button=typeof target==='string'?document.getElementById(target):target; if(!button) return; if(active){if(!button.dataset.originalHtml) button.dataset.originalHtml=button.innerHTML; button.disabled=true; button.classList.add('is-loading'); button.innerHTML='<span class=\"btn-loading-spinner\"></span><span>'+e(label||t('busy_running','جاري التنفيذ'))+'</span>'; return;} button.disabled=false; button.classList.remove('is-loading'); if(button.dataset.originalHtml) button.innerHTML=button.dataset.originalHtml;}
function setBusy(active,title,message,target){const overlay=document.getElementById('busy-overlay'); const busyTitle=document.getElementById('busy-title'); const busyText=document.getElementById('busy-text'); if(busyTitle) busyTitle.textContent=title||t('busy_title','جاري التنفيذ'); if(busyText) busyText.textContent=message||t('busy_default','يرجى الانتظار...'); if(overlay) overlay.style.display=active?'grid':'none'; setButtonLoading(target,active,title||t('busy_running','جاري التنفيذ'));}
async function readJsonResponse(res){const text=await res.text(); let data=null; try{data=JSON.parse(text);}catch(err){const cleaned=(text||'').replace(/<style[\s\S]*?<\/style>/gi,' ').replace(/<script[\s\S]*?<\/script>/gi,' ').replace(/<[^>]+>/g,' ').replace(/\s+/g,' ').trim(); if(/request timeout|timed out/i.test(cleaned)){throw new Error('انتهت مهلة الخادم قبل اكتمال الطلب. حاول مجددًا أو نفّذ طلبًا أخف.');} throw new Error(cleaned?('الخادم أعاد صفحة خطأ بدل JSON: '+cleaned.slice(0,180)):'تعذر قراءة رد الخادم أثناء تنفيذ المسار.');} if(!res.ok){throw new Error((data&&data.error)?data.error:('فشل الطلب برمز '+res.status));} return data;}
function startPipelineProgress(target){const steps=[['رفع المرجع','تم استلام الصورة، نجهزها للتحليل الآن.'],['تحليل الصورة','نستخرج الأقسام والألوان والنصوص من المرجع.'],['بناء الهيكل','نحوّل التحليل إلى Structure داخلي قابل للتجميع.'],['توليد الصفحة','ننشىء نسخة أولية قابلة للمعاينة والنشر.']]; let index=0; setBusy(true,steps[0][0],steps[0][1],target); setStatus('',steps[0][0],steps[0][1]); appendFeed('system','⏳ '+steps[0][0]+' — '+steps[0][1]); const timer=setInterval(()=>{index=Math.min(index+1,steps.length-1); setBusy(true,steps[index][0],steps[index][1],target); setStatus('',steps[index][0],steps[index][1]); if(index>0 && index<steps.length) appendFeed('system','⏳ '+steps[index][0]+' — '+steps[index][1]);},2200); return ()=>{clearInterval(timer); setBusy(false,'','',target);};}
function appendFeed(role,content){const root=document.getElementById('activity-log'); const item=document.createElement('div'); item.className='feed-item '+(role==='user'?'user':(role==='assistant'?'assistant':'system')); item.innerHTML='<div class=\"meta\">'+(role==='user'?t('activity_user','أنت'):t('activity_ai','وكيل الذكاء الاصطناعي'))+'</div><div>'+e(content).replace(/\n/g,'<br>')+'</div>'; root.appendChild(item); root.scrollTop=root.scrollHeight;}
function renderFeed(){const root=document.getElementById('activity-log'); const items=ensureArray(studioState.conversation); root.innerHTML=''; if(!items.length){appendFeed('system',t('feed_empty','ابدأ برفع صورة ثم شغّل التحليل. بعد ذلك يمكنك إرسال تعليمات مثل: غيّر الخط، أضف صور المنتج، أضف صندوق الطلب، أو حسّن النصوص لسوق COD الجزائري.')); renderChatSidebar(); return;} items.forEach(msg=>appendFeed(msg.role||'assistant', textOf(msg.content||''))); renderChatSidebar();}
function renderChatSidebar(){const root=document.getElementById('session-chat-sidebar'); if(!root) return; const items=ensureArray(studioState.conversation).slice(-8); if(!items.length){root.innerHTML='<div class=\"muted\">'+t('feed_empty','ابدأ برفع صورة ثم شغّل التحليل. بعد ذلك يمكنك إرسال تعليمات دقيقة للوكيل هنا.')+'</div>'; return;} root.innerHTML=items.map(item=>'<div class=\"feed-item '+(item.role==='user'?'user':(item.role==='assistant'?'assistant':'system'))+'\"><div class=\"meta\">'+e(item.role||'assistant')+'</div><div>'+e(textOf(item.content||'')).replace(/\\n/g,'<br>')+'</div></div>').join(''); root.scrollTop=root.scrollHeight;}
function renderSource(image){const thumb=document.getElementById('source-image-thumb'); const ph=document.getElementById('source-image-placeholder'); if(image){thumb.src=image; thumb.style.display='block'; ph.style.display='none';} else {thumb.style.display='none'; ph.style.display='grid';}}
function syncStatus(){const sections=ensureArray((studioState.structure||{}).sections); const concepts=ensureArray((studioState.agent||{}).concepts); const variants=ensureArray(studioState.variants); const briefs=ensureArray((studioState.agent||{}).brief_history).length?ensureArray((studioState.agent||{}).brief_history):ensureArray((studioState.agent||{}).briefs); document.getElementById('metric-sections').textContent=sections.length; document.getElementById('metric-concepts').textContent=concepts.length; document.getElementById('metric-variants').textContent=variants.length; const briefMetric=document.getElementById('metric-briefs'); if(briefMetric) briefMetric.textContent=briefs.length; if(sections.length){setStatus('success',t('status_ready_label','جاهز للعمل'),t('status_ready_text','تم تجهيز الهيكل ويمكنك الآن التجميع أو توليد النسخ أو إرسال تعليمات إضافية.')); return;} if(INITIAL_SOURCE_MODE==='image'||INITIAL_SOURCE_IMAGE){setStatus('',t('status_waiting_label','بانتظار التحليل'),t('status_waiting_text','الصورة محفوظة، اضغط إنشاء من الصورة لبدء التحليل والتوليد.')); return;} setStatus('',t('status_upload_label','أضف صورة أولًا'),t('status_upload_text','ابدأ باختيار Screenshot أو Design ثم شغّل الوكيل من هنا.'));}
function ensureWorkspace(){if(!studioState.agent||typeof studioState.agent!=='object') studioState.agent={}; if(!studioState.agent.workspace||typeof studioState.agent.workspace!=='object') studioState.agent.workspace={}; if(!Array.isArray(studioState.agent.workspace.selected_destinations)) studioState.agent.workspace.selected_destinations=['landing_page']; if(!Array.isArray(studioState.agent.workspace.tasks)) studioState.agent.workspace.tasks=[]; if(!studioState.agent.workspace.selected_style){const first=ensureArray(studioState.agent.styles)[0]; studioState.agent.workspace.selected_style=textOf((first||{}).id||(first||{}).name||'');} if(!studioState.agent.workspace.selected_language) studioState.agent.workspace.selected_language='ar'; if(!studioState.agent.workspace.selected_dialect) studioState.agent.workspace.selected_dialect='ar-dz'; return studioState.agent.workspace;}
function bindClick(target,handler){const el=typeof target==='string'?document.getElementById(target):target; if(!el) return; if(el.dataset.boundClick==='1') return; el.addEventListener('click',handler); el.dataset.boundClick='1';}
function bindChange(target,handler){const el=typeof target==='string'?document.getElementById(target):target; if(!el) return; if(el.dataset.boundChange==='1') return; el.addEventListener('change',handler); el.dataset.boundChange='1';}
function attachAnalysisHandlers(){
    bindClick('btn-save-analysis',saveAnalysisForm);
    bindClick('btn-save-workspace',()=>{const nextWorkspace=ensureWorkspace(); nextWorkspace.session_title=document.getElementById('workspace-session-title')?.value||nextWorkspace.session_title; nextWorkspace.current_objective=document.getElementById('workspace-objective')?.value||nextWorkspace.current_objective; saveWorkspaceState('btn-save-workspace');});
    document.querySelectorAll('[data-style-id]').forEach(btn=>{ if(btn.dataset.boundClick==='1') return; btn.addEventListener('click',()=>{ensureWorkspace().selected_style=btn.dataset.styleId||''; renderAnalysis(); saveWorkspaceState(btn);}); btn.dataset.boundClick='1'; });
    document.querySelectorAll('[data-destination-check]').forEach(input=>{ if(input.dataset.boundChange==='1') return; input.addEventListener('change',()=>{const nextWorkspace=ensureWorkspace(); const id=input.dataset.destinationCheck||''; let selected=ensureArray(nextWorkspace.selected_destinations); if(input.checked){if(!selected.includes(id)) selected.push(id);} else {selected=selected.filter(item=>item!==id);} nextWorkspace.selected_destinations=selected; saveWorkspaceState(input);}); input.dataset.boundChange='1'; });
    document.querySelectorAll('[data-generate-brief]').forEach(btn=>{ if(btn.dataset.boundClick==='1') return; btn.addEventListener('click',()=>generateBriefForDestination(btn.dataset.generateBrief||'', btn)); btn.dataset.boundClick='1'; });
    document.querySelectorAll('[data-create-task]').forEach(btn=>{ if(btn.dataset.boundClick==='1') return; btn.addEventListener('click',()=>createTaskFromBrief(btn.dataset.createTask||'')); btn.dataset.boundClick='1'; });
    document.querySelectorAll('[data-task-id]').forEach(btn=>{ if(btn.dataset.boundClick==='1') return; btn.addEventListener('click',()=>toggleTaskStatus(btn.dataset.taskId||'', btn.dataset.taskStatus||'todo')); btn.dataset.boundClick='1'; });
}
function collectAnalysisForm(){return {product_name:document.getElementById('analysis-product-name')?.value||'',brand:document.getElementById('analysis-brand')?.value||'',category:document.getElementById('analysis-category')?.value||'',product_type:document.getElementById('analysis-product-type')?.value||'',primary_benefit:document.getElementById('analysis-benefit')?.value||'',audience:document.getElementById('analysis-audience')?.value||'',pain_point:document.getElementById('analysis-pain')?.value||'',market:document.getElementById('analysis-market')?.value||'',selected_language:document.getElementById('analysis-language')?.value||'',selected_dialect:document.getElementById('analysis-dialect')?.value||'',palette:(document.getElementById('analysis-palette')?.value||'').split(',').map(s=>s.trim()).filter(Boolean)};}
async function saveAnalysisForm(){const fd=new FormData(); fd.append('_csrf',CSRF_TOKEN); fd.append('analysis_json',JSON.stringify(collectAnalysisForm())); setBusy(true,t('save_analysis','حفظ التحليل'),t('save_analysis_text','نحفظ Product Analysis Form داخل مساحة العمل.'),'btn-save-analysis'); try{const res=await fetch('/admin/ai-landing-pages/save-analysis/'+PAGE_ID,{method:'POST',body:fd}); const data=await readJsonResponse(res); studioState.agent=data.agent||studioState.agent; renderAnalysis(); appendFeed('assistant',data.message||t('analysis_saved','تم حفظ تحليل المنتج.'));}catch(err){setStatus('error',t('save_analysis','حفظ التحليل'),err.message); appendFeed('assistant','⚠️ '+err.message);}finally{setBusy(false,'','','btn-save-analysis');}}
async function saveWorkspaceState(target){const workspace=ensureWorkspace(); const fd=new FormData(); fd.append('_csrf',CSRF_TOKEN); fd.append('workspace_json',JSON.stringify(workspace)); setBusy(true,t('save_workspace','حفظ مساحة العمل'),t('save_workspace_text','نحفظ الـ style الحالي والمهام والوجهات داخل الجلسة.'),target||'btn-save-workspace'); try{const res=await fetch('/admin/ai-landing-pages/save-workspace/'+PAGE_ID,{method:'POST',body:fd}); const data=await readJsonResponse(res); studioState.agent=data.agent||studioState.agent; renderAnalysis(); appendFeed('assistant',data.message||t('workspace_saved','تم حفظ مساحة العمل.'));}catch(err){setStatus('error',t('save_workspace','حفظ مساحة العمل'),err.message); appendFeed('assistant','⚠️ '+err.message);}finally{setBusy(false,'','',target||'btn-save-workspace');}}
async function generateBriefForDestination(destination,target){const selectedConcept=document.getElementById('assembler-concept')?.value||textOf((ensureArray((studioState.agent||{}).concepts)[0]||{}).name||''); const fd=new FormData(); fd.append('_csrf',CSRF_TOKEN); fd.append('destination',destination); fd.append('concept',selectedConcept); setBusy(true,t('generate_brief','توليد brief'),t('generate_brief_text','نحوّل التحليل الحالي إلى brief جديد لهذه الوجهة.'),target); try{const res=await fetch('/admin/ai-landing-pages/generate-brief/'+PAGE_ID,{method:'POST',body:fd}); const data=await readJsonResponse(res); studioState.agent=data.agent||studioState.agent; studioState.conversation=data.conversation||studioState.conversation; renderAnalysis(); renderFeed(); appendFeed('assistant',t('brief_generated','تم توليد brief جديد لهذه الوجهة.'));}catch(err){setStatus('error',t('generate_brief','توليد brief'),err.message); appendFeed('assistant','⚠️ '+err.message);}finally{setBusy(false,'','',target);}}
function createTaskFromBrief(id){const workspace=ensureWorkspace(); const briefs=ensureArray((studioState.agent||{}).brief_history).concat(ensureArray((studioState.agent||{}).briefs)); const brief=briefs.find(item=>textOf(item.id)===id); if(!brief) return; workspace.tasks.unshift({id:'task_'+Date.now(),title:'تنفيذ '+textOf(brief.destination_label||brief.destination||brief.title),status:'todo',owner:'AI Agent',note:textOf(brief.summary||brief.objective||''),destination:textOf(brief.destination||''),priority:'high'}); renderAnalysis(); saveWorkspaceState();}
function toggleTaskStatus(taskId,status){const workspace=ensureWorkspace(); workspace.tasks=ensureArray(workspace.tasks).map(task=>textOf(task.id)===taskId?Object.assign({},task,{status:status}):task); renderAnalysis(); saveWorkspaceState();}
function renderAnalysis(){const analysis=studioState.analysis||{}; const agent=studioState.agent||{}; const analysisForm=agent.analysis_form||{}; const workspace=ensureWorkspace(); const sessionHistory=ensureArray(workspace.session_history).slice().reverse().slice(0,6); const summary=document.getElementById('analysis-summary'); const colors=ensureArray(analysisForm.palette||analysis.colors).slice(0,4).map(textOf).filter(Boolean).join(' / ') || '—'; const quickWins=ensureArray((agent.scorecard||{}).quick_wins || analysis.conversion_notes).slice(0,4); const heroTitle=textOf((analysis.hero||{}).headline || analysis.product_name || analysisForm.product_name || '—'); const cta=textOf((analysis.hero||{}).cta || analysisForm.primary_cta || '—'); summary.innerHTML='<div class=\"grid2\"><div class=\"mini-card\"><strong>Hero</strong><span>'+e(heroTitle)+'</span></div><div class=\"mini-card\"><strong>Colors</strong><span>'+e(colors)+'</span></div><div class=\"mini-card\"><strong>CTA</strong><span>'+e(cta)+'</span></div><div class=\"mini-card\"><strong>الأقسام المكتشفة</strong><span>'+e(String(ensureArray((studioState.structure||{}).sections).length))+'</span></div></div>'+(quickWins.length?'<div class=\"concept-card\" style=\"margin-top:12px\"><strong>تحسينات سريعة</strong><span>'+e(quickWins.join(' • '))+'</span></div>':''); const workbench=document.getElementById('agent-workbench'); const concepts=ensureArray(agent.concepts); const styles=ensureArray(agent.styles); const briefHistory=ensureArray(agent.brief_history); const briefs=briefHistory.length?briefHistory:ensureArray(agent.briefs); const destinations=Object.values(agent.destinations||{}); const score=((agent.scorecard||{}).breakdown)||{}; const history=ensureArray(agent.history).slice().reverse().slice(0,8); const tasks=ensureArray(workspace.tasks); const competitorHistory=ensureArray(agent.competitor_history).slice().reverse().slice(0,4); workbench.innerHTML=''+
'<div class=\"grid2\">'+
'<div class=\"concept-card\"><strong>Product Analysis Form</strong><div class=\"grid2\"><div><div class=\"field-label\">اسم المنتج</div><input id=\"analysis-product-name\" class=\"input\" value=\"'+e(textOf(analysisForm.product_name||''))+'\"></div><div><div class=\"field-label\">العلامة</div><input id=\"analysis-brand\" class=\"input\" value=\"'+e(textOf(analysisForm.brand||''))+'\"></div><div><div class=\"field-label\">الفئة</div><input id=\"analysis-category\" class=\"input\" value=\"'+e(textOf(analysisForm.category||''))+'\"></div><div><div class=\"field-label\">النوع</div><input id=\"analysis-product-type\" class=\"input\" value=\"'+e(textOf(analysisForm.product_type||''))+'\"></div><div><div class=\"field-label\">الفائدة الأساسية</div><textarea id=\"analysis-benefit\" class=\"textarea\">'+e(textOf(analysisForm.primary_benefit||''))+'</textarea></div><div><div class=\"field-label\">الجمهور</div><textarea id=\"analysis-audience\" class=\"textarea\">'+e(textOf(analysisForm.audience||''))+'</textarea></div><div><div class=\"field-label\">المشكلة</div><textarea id=\"analysis-pain\" class=\"textarea\">'+e(textOf(analysisForm.pain_point||''))+'</textarea></div><div><div class=\"field-label\">Palette</div><input id=\"analysis-palette\" class=\"input\" value=\"'+e(ensureArray(analysisForm.palette).join(', '))+'\"></div><div><div class=\"field-label\">السوق</div><input id=\"analysis-market\" class=\"input\" value=\"'+e(textOf(analysisForm.market||''))+'\"></div><div><div class=\"field-label\">اللغة</div><select id=\"analysis-language\" class=\"select\"><option value=\"ar\" '+(textOf(analysisForm.selected_language||workspace.selected_language)==='ar'?'selected':'')+'>العربية</option><option value=\"ar-dz\" '+(textOf(analysisForm.selected_language||workspace.selected_language)==='ar-dz'?'selected':'')+'>الدارجة الجزائرية</option><option value=\"fr\" '+(textOf(analysisForm.selected_language||workspace.selected_language)==='fr'?'selected':'')+'>Français</option><option value=\"en\" '+(textOf(analysisForm.selected_language||workspace.selected_language)==='en'?'selected':'')+'>English</option></select></div><div><div class=\"field-label\">اللهجة</div><select id=\"analysis-dialect\" class=\"select\"><option value=\"ar-dz\" '+(textOf(analysisForm.selected_dialect||workspace.selected_dialect)==='ar-dz'?'selected':'')+'>الدارجة الجزائرية</option><option value=\"ar\" '+(textOf(analysisForm.selected_dialect||workspace.selected_dialect)==='ar'?'selected':'')+'>العربية الفصحى</option><option value=\"fr-dz\" '+(textOf(analysisForm.selected_dialect||workspace.selected_dialect)==='fr-dz'?'selected':'')+'>Français Algérie</option></select></div></div><div class=\"toolbar\"><button type=\"button\" class=\"btn-main\" id=\"btn-save-analysis\"><i class=\"bi bi-save\"></i><span>حفظ التحليل</span></button></div></div>'+
'<div class=\"concept-card\"><strong>Score + Workspace</strong><span>Global: '+e(String(score.global ?? (agent.scorecard||{}).global_score ?? '—'))+'</span><span>Copy: '+e(String(score.copy ?? '—'))+'</span><span>Design: '+e(String(score.design ?? '—'))+'</span><span>CTA: '+e(String(score.cta ?? '—'))+'</span><span>Trust: '+e(String(score.trust ?? '—'))+'</span><span>Mobile: '+e(String(score.mobile ?? '—'))+'</span><span>COD Fit: '+e(String(score.cod_fit ?? '—'))+'</span><div class=\"field-label\">عنوان الجلسة</div><input id=\"workspace-session-title\" class=\"input\" value=\"'+e(textOf(workspace.session_title||''))+'\"><div class=\"field-label\">هدف الجلسة</div><textarea id=\"workspace-objective\" class=\"textarea\">'+e(textOf(workspace.current_objective||''))+'</textarea><div class=\"toolbar\"><button type=\"button\" class=\"btn-ghost\" id=\"btn-save-workspace\"><i class=\"bi bi-save2\"></i><span>حفظ مساحة العمل</span></button></div></div>'+
'</div>'+
(styles.length?'<div class=\"grid3\" style=\"margin-top:12px\">'+styles.map(style=>{const id=textOf(style.id||style.name); const active=textOf(workspace.selected_style)===id; return '<div class=\"concept-card\" style=\"border-color:'+(active?'#fdba74':'')+'\"><strong>'+e(textOf(style.name||''))+'</strong><span>'+e(textOf(style.summary||''))+'</span><span>'+e(textOf(style.mood||style.direction||''))+'</span><span>'+e(ensureArray(style.chips).join(' • '))+'</span><div class=\"toolbar\"><button type=\"button\" class=\"'+(active?'btn-main':'btn-ghost')+'\" data-style-id=\"'+e(id)+'\"><i class=\"bi bi-palette\"></i><span>'+(active?'مفعّل':'اعتماد')+'</span></button></div></div>';}).join('')+'</div>':'')+
(destinations.length?'<div class=\"grid2\" style=\"margin-top:12px\">'+destinations.map(dest=>{const destId=textOf(dest.id||dest.title); const active=ensureArray(workspace.selected_destinations).includes(destId); return '<div class=\"mini-card\" style=\"border-color:'+(active?'#bfdbfe':'')+'\"><strong>'+e(textOf(dest.title||''))+'</strong><span>'+e(textOf(dest.goal||''))+'</span><span>'+e(ensureArray(dest.deliverables).join(' • '))+'</span><div>'+e(ensureArray(dest.notes).join(' • '))+'</div><div class=\"toolbar\"><label><input type=\"checkbox\" data-destination-check=\"'+e(destId)+'\" '+(active?'checked':'')+'> تفعيل</label><button type=\"button\" class=\"btn-main\" data-generate-brief=\"'+e(destId)+'\"><i class=\"bi bi-stars\"></i><span>Generate Brief</span></button></div></div>';}).join('')+'</div>':'')+
(briefs.length?'<div class=\"grid2\" style=\"margin-top:12px\">'+briefs.slice().reverse().map((brief,index)=>'<div class=\"concept-card\"><strong>'+(briefs.length-index)+'. '+e(textOf(brief.title||''))+'</strong><span>'+e(textOf(brief.summary||brief.objective||''))+'</span><span>'+e(textOf(brief.prompt||''))+'</span><div>'+ensureArray(brief.deliverables).map(item=>'<span class=\"style-chip\">'+e(textOf(item))+'</span>').join('')+'</div><div class=\"toolbar\"><button type=\"button\" class=\"btn-ghost\" data-create-task=\"'+e(textOf(brief.id||('brief_'+index)))+'\"><i class=\"bi bi-kanban\"></i><span>إضافة إلى المهام</span></button></div></div>').join('')+'</div>':'')+
(tasks.length?'<div class=\"grid2\" style=\"margin-top:12px\">'+tasks.map(task=>'<div class=\"concept-card\"><strong>'+e(textOf(task.title||''))+'</strong><span>'+e(textOf(task.note||''))+'</span><span>'+e(textOf(task.destination||''))+'</span><div class=\"toolbar\"><button type=\"button\" class=\"btn-ghost\" data-task-id=\"'+e(textOf(task.id||''))+'\" data-task-status=\"todo\"><span>Todo</span></button><button type=\"button\" class=\"btn-ghost\" data-task-id=\"'+e(textOf(task.id||''))+'\" data-task-status=\"doing\"><span>Doing</span></button><button type=\"button\" class=\"btn-main\" data-task-id=\"'+e(textOf(task.id||''))+'\" data-task-status=\"done\"><span>Done</span></button></div></div>').join('')+'</div>':'')+
(concepts.length?'<div class=\"grid3\" style=\"margin-top:12px\">'+concepts.map((concept,index)=>'<div class=\"concept-card\"><strong>'+(index+1)+'. '+e(textOf(concept.name||'Concept'))+'</strong><span>'+e(textOf(concept.angle||concept.hook||''))+'</span><span>'+e(textOf(concept.hook||''))+'</span></div>').join('')+'</div>':'')+
(sessionHistory.length?'<div class=\"grid2\" style=\"margin-top:12px\">'+sessionHistory.map(item=>'<div class=\"mini-card\"><strong>'+e(textOf(item.title||''))+'</strong><span>'+e(textOf(item.summary||''))+'</span><span>'+e(textOf(item.stage||''))+' • '+e(textOf(item.at||''))+'</span><span>'+e('Sections: '+textOf((item.metrics||{}).sections||0)+' • Briefs: '+textOf((item.metrics||{}).briefs||0)+' • Variants: '+textOf((item.metrics||{}).variants||0))+'</span></div>').join('')+'</div>':'')+
(history.length?'<div class=\"grid2\" style=\"margin-top:12px\">'+history.map(item=>'<div class=\"mini-card\"><strong>'+e(textOf(item.label||''))+'</strong><span>'+e(textOf(item.at||''))+'</span></div>').join('')+'</div>':'')+
(competitorHistory.length?'<div class=\"grid2\" style=\"margin-top:12px\">'+competitorHistory.map(entry=>'<div class=\"mini-card\"><strong>'+e(textOf(entry.domain||entry.url||''))+'</strong><span>'+e(textOf((entry.report||{}).lp_strategy||''))+'</span></div>').join('')+'</div>':'');
document.getElementById('btn-save-analysis')?.addEventListener('click',saveAnalysisForm);
document.getElementById('btn-save-workspace')?.addEventListener('click',()=>{const workspace=ensureWorkspace(); workspace.session_title=document.getElementById('workspace-session-title')?.value||workspace.session_title; workspace.current_objective=document.getElementById('workspace-objective')?.value||workspace.current_objective; saveWorkspaceState('btn-save-workspace');});
document.querySelectorAll('[data-style-id]').forEach(btn=>btn.addEventListener('click',()=>{ensureWorkspace().selected_style=btn.dataset.styleId||''; renderAnalysis(); saveWorkspaceState(btn);}));
document.querySelectorAll('[data-destination-check]').forEach(input=>input.addEventListener('change',()=>{const workspace=ensureWorkspace(); const id=input.dataset.destinationCheck||''; let selected=ensureArray(workspace.selected_destinations); if(input.checked){if(!selected.includes(id)) selected.push(id);} else {selected=selected.filter(item=>item!==id);} workspace.selected_destinations=selected; saveWorkspaceState(input);}));
document.querySelectorAll('[data-generate-brief]').forEach(btn=>btn.addEventListener('click',()=>generateBriefForDestination(btn.dataset.generateBrief||'', btn)));
document.querySelectorAll('[data-create-task]').forEach(btn=>btn.addEventListener('click',()=>createTaskFromBrief(btn.dataset.createTask||'')));
document.querySelectorAll('[data-task-id]').forEach(btn=>btn.addEventListener('click',()=>toggleTaskStatus(btn.dataset.taskId||'', btn.dataset.taskStatus||'todo')));
}
function collectStructure(){const structure=JSON.parse(JSON.stringify(studioState.structure||{})); structure.sections=[]; document.querySelectorAll('#assembler-stack .section-card').forEach((card,index)=>{structure.sections.push({type:card.dataset.type||'section',label:card.querySelector('.assembler-label')?.value||'',headline:card.querySelector('.assembler-headline')?.value||'',hook:card.querySelector('.assembler-hook')?.value||'',objective:card.querySelector('.assembler-objective')?.value||'',purpose:card.querySelector('.assembler-goal')?.value||'',copy_prompt:card.querySelector('.assembler-prompt')?.value||'',layout_notes:card.querySelector('.assembler-layout-notes')?.value||'',text_rules:(card.querySelector('.assembler-rules')?.value||'').split('\n').map(s=>s.trim()).filter(Boolean),palette:(card.querySelector('.assembler-palette')?.value||'').split(',').map(s=>s.trim()).filter(Boolean),enabled:!!card.querySelector('.assembler-enabled')?.checked,locked:!!card.querySelector('.assembler-locked')?.checked,order:index+1});}); return structure;}
function renderAssembler(){const root=document.getElementById('agent-assembler'); const sections=ensureArray((studioState.agent||{}).sections).length?ensureArray((studioState.agent||{}).sections):ensureArray((studioState.structure||{}).sections); const concepts=ensureArray((studioState.agent||{}).concepts); const selected=(studioState.agent||{}).selected_concept||''; if(!sections.length){root.innerHTML='<div class=\"muted\">لا يوجد Structure محفوظ مشتق من الصورة لهذه الصفحة.</div>'; return;} root.innerHTML='<div class=\"toolbar\"><select id=\"assembler-concept\" class=\"select\" style=\"max-width:320px;\"><option value=\"\">اختيار أقوى مفهوم تلقائيًا</option>'+concepts.map(c=>'<option value=\"'+e(textOf(c.name))+'\" '+(selected===textOf(c.name)?'selected':'')+'>'+e(textOf(c.name||'Concept'))+'</option>').join('')+'</select><button type=\"button\" class=\"btn-main\" id=\"btn-assemble-page\"><i class=\"bi bi-layers\"></i><span>تجميع صفحة الهبوط</span></button></div><div class=\"sections\" id=\"assembler-stack\">'+sections.map((section,index)=>'<div class=\"section-card\" data-index=\"'+index+'\" data-type=\"'+e(textOf(section.type||'section'))+'\"><div class=\"section-head\"><h4>'+(index+1)+'. '+e(textOf(section.type||'section'))+'</h4><div class=\"flags\"><label><input type=\"checkbox\" class=\"assembler-enabled\" '+(section.enabled===false?'':'checked')+'> إدراج</label><label><input type=\"checkbox\" class=\"assembler-locked\" '+(section.locked?'checked':'')+'> قفل</label></div></div><div class=\"muted\" style=\"font-size:12px;\">Layout: '+e(textOf(section.layout||''))+' • Difficulty: '+e(textOf(section.difficulty||''))+'</div><div class=\"grid2\"><div><div class=\"field-label\">الوسم</div><input type=\"text\" class=\"input assembler-label\" value=\"'+e(textOf(section.label||''))+'\"></div><div><div class=\"field-label\">العنوان</div><input type=\"text\" class=\"input assembler-headline\" value=\"'+e(textOf(section.headline||''))+'\"></div><div><div class=\"field-label\">Hook</div><input type=\"text\" class=\"input assembler-hook\" value=\"'+e(textOf(section.hook||section.headline||''))+'\"></div><div><div class=\"field-label\">Objective</div><textarea class=\"textarea assembler-objective\">'+e(textOf(section.objective||section.purpose||''))+'</textarea></div><div><div class=\"field-label\">الهدف / الملاحظة</div><textarea class=\"textarea assembler-goal\">'+e(textOf(section.purpose||section.subheadline||''))+'</textarea></div><div><div class=\"field-label\">Prompt</div><textarea class=\"textarea assembler-prompt\">'+e(textOf(section.copy_prompt||''))+'</textarea></div><div><div class=\"field-label\">Layout Notes</div><textarea class=\"textarea assembler-layout-notes\">'+e(textOf(section.layout_notes||''))+'</textarea></div><div><div class=\"field-label\">Palette</div><input type=\"text\" class=\"input assembler-palette\" value=\"'+e(ensureArray(section.palette).join(', '))+'\"></div><div><div class=\"field-label\">Text Rules</div><textarea class=\"textarea assembler-rules\">'+e(ensureArray(section.text_rules).join('\n'))+'</textarea></div></div></div>').join('')+'</div>'; document.getElementById('btn-assemble-page').addEventListener('click', assembleLandingPage);}
function renderVariants(){const root=document.getElementById('agent-variants'); const variants=ensureArray(studioState.variants); if(!variants.length){root.innerHTML='<div class=\"toolbar\"><button type=\"button\" class=\"btn-main\" id=\"btn-generate-variants\"><i class=\"bi bi-grid-1x2\"></i><span>'+t('variants_generate','توليد 3 Variants')+'</span></button></div><div class=\"muted\">'+t('variants_generate_help','أنشئ ثلاث نسخ مختلفة من نفس الصفحة بزوايا تسويقية مختلفة.')+'</div>'; document.getElementById('btn-generate-variants').addEventListener('click', generateVariants); return;} root.innerHTML='<div class=\"stage-head\"><div class=\"kicker\"><i class=\"bi bi-layers\"></i>'+t('variants_workspace_title','مساحة النسخ البديلة')+'</div><h3>'+t('variants_workspace_title','مساحة النسخ البديلة')+'</h3><p class=\"muted\">'+t('variants_workspace_text','قارن بين الزوايا المختلفة بسرعة، ثم اعتمد النسخة الأقرب للتحويل.')+'</p></div><div class=\"toolbar\"><button type=\"button\" class=\"btn-main\" id=\"btn-generate-variants\"><i class=\"bi bi-arrow-repeat\"></i><span>'+t('variants_refresh','تحديث النسخ البديلة')+'</span></button></div><div class=\"grid2\">'+variants.map((variant,index)=>'<div class=\"variant-card\"><strong>'+(index+1)+'. '+e(textOf(variant.name||'Variant'))+'</strong><span>'+e(textOf(variant.angle||variant.hook||''))+'</span><span>'+t('variants_score','Score')+': '+e(String(variant.score ?? '—'))+'</span><span>'+t('variant_hook','Hook')+': '+e(textOf(variant.hook||''))+'</span><div class=\"toolbar\"><button type=\"button\" class=\"btn-ghost\" data-action=\"preview-variant\" data-index=\"'+index+'\"><i class=\"bi bi-eye\"></i><span>'+t('preview_label','معاينة')+'</span></button><button type=\"button\" class=\"btn-main\" data-action=\"apply-variant\" data-index=\"'+index+'\"><i class=\"bi bi-check2-circle\"></i><span>'+t('apply_variant_label','اعتماد النسخة')+'</span></button></div></div>').join('')+'</div>'; document.getElementById('btn-generate-variants').addEventListener('click', generateVariants); root.querySelectorAll('[data-action=\"preview-variant\"]').forEach(btn=>btn.addEventListener('click',()=>previewVariant(Number(btn.dataset.index)))); root.querySelectorAll('[data-action=\"apply-variant\"]').forEach(btn=>btn.addEventListener('click',()=>applyVariant(Number(btn.dataset.index), btn)));}
function renderCompetitor(){const root=document.getElementById('competitor-analysis-card'); const report=studioState.competitor||{}; const history=ensureArray((studioState.agent||{}).competitor_history).slice().reverse().slice(0,6); const localScore=textOf(((studioState.agent||{}).scorecard||{}).global_score||((studioState.agent||{}).scorecard||{}).breakdown?.global||'—'); const competitorScore=textOf(report.global_score||'—'); const compareDelta=(localScore!=='—' && competitorScore!=='—') ? (Number(localScore)-Number(competitorScore)) : null; const has=Object.keys(report).length>0; root.innerHTML='<div class=\"stage-head\"><div class=\"kicker\"><i class=\"bi bi-binoculars\"></i>'+t('competitor_workspace_title','مساحة المنافسين')+'</div><h3>'+t('competitor_title','تحليل المنافس')+'</h3><p class=\"muted\">'+t('competitor_subtitle','أدخل رابط منافس لتحليل نقاط القوة والثغرات والزوايا التي يمكننا التفوق بها.')+'</p></div><div class=\"toolbar\"><input type=\"url\" id=\"competitor-url\" class=\"input\" style=\"flex:1;min-width:220px;\" placeholder=\"'+t('competitor_placeholder','https://competitor.com/landing-page')+'\"><button type=\"button\" class=\"btn-main\" id=\"btn-analyze-competitor\"><i class=\"bi bi-search\"></i><span>'+t('competitor_title','تحليل المنافس')+'</span></button><a href=\"/admin/ai-landing-pages/competitors/'+PAGE_ID+'\" class=\"btn-ghost\"><i class=\"bi bi-window\"></i><span>'+t('open_competitor_workspace','مساحة المنافسين')+'</span></a></div>'+(has?'<div class=\"workflow-board\" style=\"margin-top:12px;\"><div class=\"workflow-hero\"><div class=\"output-card\"><header><strong>'+t('competitor_global','التقييم العام')+'</strong><span class=\"priority-chip\">Score</span></header><span>'+t('our_score_label','تقييمنا')+': '+e(String(localScore))+'</span><span>'+t('competitor_score_label','تقييم المنافس')+': '+e(String(competitorScore))+'</span><span>'+(compareDelta===null?t('comparison_pending','المقارنة ستظهر بعد توفر التقييمين.'):t('comparison_delta','الفارق')+': '+e(String(compareDelta)))+'</span></div><div class=\"output-card\"><header><strong>'+t('competitor_report_title','تقرير المنافس')+'</strong><span class=\"priority-chip\">Intel</span></header><span>'+t('competitor_strategy','الاستراتيجية المقترحة')+': '+e(textOf(report.lp_strategy || ''))+'</span><span>'+t('competitor_strengths','نقاط القوة')+': '+e(ensureArray(report.strengths).join(' • '))+'</span><span>'+t('competitor_gaps','الثغرات التي يمكن استغلالها')+': '+e(ensureArray(report.gaps_we_can_exploit).join(' • '))+'</span></div></div>'+(ensureArray(report.suggested_sections).length?'<div class=\"grid2\">'+ensureArray(report.suggested_sections).map(item=>'<div class=\"mini-card\"><strong>'+e(textOf(item))+'</strong><span>'+t('competitor_section_hint','قسم مقترح يمكن استغلاله أو تحسينه في نسختنا.')+'</span></div>').join('')+'</div>':'')+'</div>':'')+(history.length?'<div class=\"production-board\" style=\"margin-top:12px;\"><div class=\"stage-head\"><div class=\"kicker\"><i class=\"bi bi-clock-history\"></i>'+t('competitor_archive_title','أرشيف المنافسين')+'</div><h3>'+t('competitor_archive_title','أرشيف المنافسين')+'</h3><p class=\"muted\">'+t('competitor_archive_text','نتائج التحليل الأخيرة تبقى محفوظة داخل هذه الجلسة للمقارنة السريعة.')+'</p></div><div class=\"grid2\">'+history.map(entry=>'<div class=\"mini-card\"><strong>'+e(textOf(entry.domain||entry.url||''))+'</strong><span>'+e(textOf(entry.at||''))+'</span><span>'+e(textOf((entry.report||{}).lp_strategy||''))+'</span></div>').join('')+'</div></div>':''); document.getElementById('btn-analyze-competitor').addEventListener('click', analyzeCompetitor);}
function renderWorkspacePanels(workspace, briefs, tasks, sessionHistory){
    const selectedDestinations=ensureArray(workspace.selected_destinations);
    const overview=document.getElementById('workspace-overview');
    const timeline=document.getElementById('session-timeline');
    if(overview){
        const outputs = [
            {id:'landing_page', title:t('output_landing_page','Landing Page'), ready:selectedDestinations.includes('landing_page')},
            {id:'static_ads', title:t('output_static_ads','Static Ads'), ready:selectedDestinations.includes('static_ads')},
            {id:'video_brief', title:t('output_video_brief','Video Brief'), ready:selectedDestinations.includes('video_brief')},
            {id:'ad_copies', title:t('output_ad_copies','Ad Copies'), ready:selectedDestinations.includes('ad_copies')},
            {id:'nextify', title:t('output_nextify','Nextify'), ready:selectedDestinations.includes('nextify')}
        ];
        overview.innerHTML='<div class=\"workflow-board\">'
            +'<div class=\"workflow-hero\">'
                +'<div class=\"output-card\"><header><strong>'+t('workspace_summary','ملخص التشغيل')+'</strong><span class=\"status-chip '+(tasks.some(task=>textOf(task.status)==='doing')?'doing':'todo')+'\">'+(tasks.some(task=>textOf(task.status)==='doing')?t('busy_running','جاري التنفيذ'):t('status_ready_label','جاهز للعمل'))+'</span></header><span><?= addslashes(__('landing.style_label', 'Style')) ?>: '+e(textOf(workspace.selected_style||'—'))+'</span><span><?= addslashes(__('landing.destinations_label', 'Destinations')) ?>: '+e(selectedDestinations.join(' • ')||'—')+'</span><span><?= addslashes(__('landing.briefs_ready_label', 'Briefs جاهزة')) ?>: '+e(String(briefs.length))+'</span><span><?= addslashes(__('landing.tasks_label', 'Tasks')) ?>: '+e(String(tasks.length))+'</span></div>'
                +'<div class=\"output-card\"><header><strong>'+t('workspace_outputs','مخرجات الإنتاج')+'</strong><span class=\"priority-chip\">Pipeline</span></header>'+outputs.map(output=>'<span>'+e(output.title)+': '+e(output.ready?t('active_label','مفعّلة'):t('inactive_label','غير مفعلة'))+'</span>').join('')+'</div>'
            +'</div>'
            +'<div class=\"grid3\">'+outputs.map(output=>'<div class=\"mini-card\"><strong>'+e(output.title)+'</strong><span>'+e(output.ready?t('output_ready_text','هذه الوجهة جاهزة داخل مساحة العمل الحالية.'):t('output_not_ready_text','فعّل هذه الوجهة لتبدأ إنتاجها من نفس التحليل.'))+'</span></div>').join('')+'</div>'
            +'<div class=\"outputs-grid grid2\">'
                +(briefs.length
                    ? briefs.slice().reverse().slice(0,4).map(brief=>'<div class=\"output-card\"><header><strong>'+e(textOf(brief.title||''))+'</strong><span class=\"status-chip done\">'+t('status_ready_label','جاهز للعمل')+'</span></header><span>'+e(textOf(brief.summary||brief.objective||''))+'</span><span>'+e(textOf(brief.destination_label||brief.destination||''))+'</span></div>').join('')
                    : '<div class=\"mini-card\"><strong>'+t('brief_queue','طابور الـ Briefs')+'</strong><span>'+t('brief_queue_text','فعّل وجهة أو أكثر ثم اضغط توليد brief لبدء الإنتاج.')+'</span></div>')
            +'</div>'
        +'</div>';
    }
    if(timeline){
        timeline.innerHTML='<div class=\"stage-head\"><div class=\"kicker\"><i class=\"bi bi-clock-history\"></i>'+t('session_timeline','الخط الزمني للجلسة')+'</div><h3>'+t('session_timeline','الخط الزمني للجلسة')+'</h3><p class=\"muted\">'+t('session_timeline_text','آخر التحولات التي مر بها الوكيل داخل هذه الصفحة.')+'</p></div><div class=\"timeline-stack\">'
            +(sessionHistory.length
                ? sessionHistory.map(item=>'<div class=\"timeline-item\"><strong>'+e(textOf(item.title||''))+'</strong><span>'+e(textOf(item.summary||''))+'</span><span>'+e(textOf(item.stage||''))+' • '+e(textOf(item.at||''))+'</span><span>'+e('Sections: '+textOf((item.metrics||{}).sections||0)+' • Briefs: '+textOf((item.metrics||{}).briefs||0)+' • Variants: '+textOf((item.metrics||{}).variants||0))+'</span></div>').join('')
                : '<div class=\"mini-card\"><strong>'+t('no_session_history','لا يوجد سجل بعد')+'</strong><span>'+t('no_session_history_text','ابدأ التحليل أو أنشئ brief جديدًا ليظهر التاريخ هنا.')+'</span></div>')
            +'</div>';
    }
}
function renderAnalysis(){
    const analysis=studioState.analysis||{};
    const agent=studioState.agent||{};
    const analysisForm=agent.analysis_form||{};
    const workspace=ensureWorkspace();
    const sessionHistory=ensureArray(workspace.session_history).slice().reverse().slice(0,6);
    const summary=document.getElementById('analysis-summary');
    const colors=ensureArray(analysisForm.palette||analysis.colors).slice(0,4).map(textOf).filter(Boolean).join(' / ') || '—';
    const quickWins=ensureArray((agent.scorecard||{}).quick_wins || analysis.conversion_notes).slice(0,4);
    const heroTitle=textOf((analysis.hero||{}).headline || analysis.product_name || analysisForm.product_name || '—');
    const cta=textOf((analysis.hero||{}).cta || analysisForm.primary_cta || '—');
    const workbench=document.getElementById('agent-workbench');
    const concepts=ensureArray(agent.concepts);
    const styles=ensureArray(agent.styles);
    const briefHistory=ensureArray(agent.brief_history);
    const briefs=briefHistory.length?briefHistory:ensureArray(agent.briefs);
    const destinations=Object.values(agent.destinations||{});
    const score=((agent.scorecard||{}).breakdown)||{};
    const history=ensureArray(agent.history).slice().reverse().slice(0,8);
    const tasks=ensureArray(workspace.tasks);
    const competitorHistory=ensureArray(agent.competitor_history).slice().reverse().slice(0,4);
    summary.innerHTML='<div class=\"grid2\">'
        +'<div class=\"mini-card\"><strong>Hero</strong><span>'+e(heroTitle)+'</span></div>'
        +'<div class=\"mini-card\"><strong>Colors</strong><span>'+e(colors)+'</span></div>'
        +'<div class=\"mini-card\"><strong>CTA</strong><span>'+e(cta)+'</span></div>'
        +'<div class=\"mini-card\"><strong>'+t('sections_detected','الأقسام المكتشفة')+'</strong><span>'+e(String(ensureArray((studioState.structure||{}).sections).length))+'</span></div>'
        +'</div>'
        +(quickWins.length?'<div class=\"concept-card\" style=\"margin-top:12px\"><strong>'+t('quick_wins','تحسينات سريعة')+'</strong><span>'+e(quickWins.join(' • '))+'</span></div>':'');
    workbench.innerHTML='<div class=\"workflow-board\">'
        +'<div class=\"workflow-hero\">'
            +'<div class=\"concept-card\"><strong>'+t('analysis_form_title','نموذج تحليل المنتج')+'</strong><span>'+t('analysis_form_help','حرر فهم المنتج والسوق واللغة قبل أي توليد إضافي.')+'</span><div class=\"grid2\">'
                +'<div><div class=\"field-label\">'+t('product_name','اسم المنتج')+'</div><input id=\"analysis-product-name\" class=\"input\" value=\"'+e(textOf(analysisForm.product_name||''))+'\"></div>'
                +'<div><div class=\"field-label\">'+t('brand','العلامة')+'</div><input id=\"analysis-brand\" class=\"input\" value=\"'+e(textOf(analysisForm.brand||''))+'\"></div>'
                +'<div><div class=\"field-label\">'+t('category','الفئة')+'</div><input id=\"analysis-category\" class=\"input\" value=\"'+e(textOf(analysisForm.category||''))+'\"></div>'
                +'<div><div class=\"field-label\">'+t('type','النوع')+'</div><input id=\"analysis-product-type\" class=\"input\" value=\"'+e(textOf(analysisForm.product_type||''))+'\"></div>'
                +'<div><div class=\"field-label\">'+t('primary_benefit','الفائدة الأساسية')+'</div><textarea id=\"analysis-benefit\" class=\"textarea\">'+e(textOf(analysisForm.primary_benefit||''))+'</textarea></div>'
                +'<div><div class=\"field-label\">'+t('audience','الجمهور')+'</div><textarea id=\"analysis-audience\" class=\"textarea\">'+e(textOf(analysisForm.audience||''))+'</textarea></div>'
                +'<div><div class=\"field-label\">'+t('problem','المشكلة')+'</div><textarea id=\"analysis-pain\" class=\"textarea\">'+e(textOf(analysisForm.pain_point||''))+'</textarea></div>'
                +'<div><div class=\"field-label\">Palette</div><input id=\"analysis-palette\" class=\"input\" value=\"'+e(ensureArray(analysisForm.palette).join(', '))+'\"></div>'
                +'<div><div class=\"field-label\">'+t('market','السوق')+'</div><input id=\"analysis-market\" class=\"input\" value=\"'+e(textOf(analysisForm.market||''))+'\"></div>'
                +'<div><div class=\"field-label\">'+t('language_label','اللغة')+'</div><select id=\"analysis-language\" class=\"select\"><option value=\"ar\" '+(textOf(analysisForm.selected_language||workspace.selected_language)==='ar'?'selected':'')+'>'+t('lang_ar','العربية')+'</option><option value=\"ar-dz\" '+(textOf(analysisForm.selected_language||workspace.selected_language)==='ar-dz'?'selected':'')+'>'+t('lang_ar_dz','الدارجة الجزائرية')+'</option><option value=\"fr\" '+(textOf(analysisForm.selected_language||workspace.selected_language)==='fr'?'selected':'')+'>'+t('lang_fr','Français')+'</option><option value=\"en\" '+(textOf(analysisForm.selected_language||workspace.selected_language)==='en'?'selected':'')+'>'+t('lang_en','English')+'</option></select></div>'
                +'<div><div class=\"field-label\">'+t('dialect_label','اللهجة')+'</div><select id=\"analysis-dialect\" class=\"select\"><option value=\"ar-dz\" '+(textOf(analysisForm.selected_dialect||workspace.selected_dialect)==='ar-dz'?'selected':'')+'>'+t('lang_ar_dz','الدارجة الجزائرية')+'</option><option value=\"ar\" '+(textOf(analysisForm.selected_dialect||workspace.selected_dialect)==='ar'?'selected':'')+'>'+t('lang_ar_fusha','العربية الفصحى')+'</option><option value=\"fr-dz\" '+(textOf(analysisForm.selected_dialect||workspace.selected_dialect)==='fr-dz'?'selected':'')+'>'+t('lang_fr_dz','Français Algérie')+'</option></select></div>'
            +'</div><div class=\"toolbar\"><button type=\"button\" class=\"btn-main\" id=\"btn-save-analysis\"><i class=\"bi bi-save\"></i><span>'+t('save_analysis','حفظ التحليل')+'</span></button></div></div>'
            +'<div class=\"concept-card\"><strong>'+t('strategy_cockpit','لوحة الاستراتيجية')+'</strong><span>'+t('strategy_cockpit_help','اضبط هوية الجلسة والاتجاه الحالي قبل إنتاج الـ briefs والنسخ.')+'</span><div class=\"assembler-summary\">'
                +'<div class=\"assembler-metric\"><strong>'+e(String(score.global ?? (agent.scorecard||{}).global_score ?? '—'))+'</strong><span>Global</span></div>'
                +'<div class=\"assembler-metric\"><strong>'+e(String(score.copy ?? '—'))+'</strong><span>Copy</span></div>'
                +'<div class=\"assembler-metric\"><strong>'+e(String(score.design ?? '—'))+'</strong><span>Design</span></div>'
                +'<div class=\"assembler-metric\"><strong>'+e(String(score.cta ?? '—'))+'</strong><span>CTA</span></div>'
            +'</div><div class=\"grid2\"><div><div class=\"field-label\">'+t('session_title_label','عنوان الجلسة')+'</div><input id=\"workspace-session-title\" class=\"input\" value=\"'+e(textOf(workspace.session_title||''))+'\"></div><div><div class=\"field-label\">'+t('session_goal_label','هدف الجلسة')+'</div><textarea id=\"workspace-objective\" class=\"textarea\">'+e(textOf(workspace.current_objective||''))+'</textarea></div></div><div class=\"toolbar\"><button type=\"button\" class=\"btn-ghost\" id=\"btn-save-workspace\"><i class=\"bi bi-save2\"></i><span>'+t('save_workspace','حفظ مساحة العمل')+'</span></button></div></div>'
        +'</div>'
        +(styles.length?'<div class=\"production-board\"><div class=\"stage-head\"><div class=\"kicker\"><i class=\"bi bi-palette\"></i>Style System</div><h3>'+t('style_system_title','الاتجاهات البصرية الجاهزة')+'</h3><p class=\"muted\">'+t('style_system_text','اختر mood بصريًا واضحًا بدل الاعتماد على prompt عشوائي.')+'</p></div><div class=\"grid3\">'+styles.map(style=>{const id=textOf(style.id||style.name); const active=textOf(workspace.selected_style)===id; return '<div class=\"concept-card\" style=\"border-color:'+(active?'#fdba74':'')+'\"><strong>'+e(textOf(style.name||''))+'</strong><span>'+e(textOf(style.summary||''))+'</span><span>'+e(textOf(style.mood||style.direction||''))+'</span><div>'+ensureArray(style.chips).map(item=>'<span class=\"style-chip\">'+e(textOf(item))+'</span>').join('')+'</div><div class=\"toolbar\"><button type=\"button\" class=\"'+(active?'btn-main':'btn-ghost')+'\" data-style-id=\"'+e(id)+'\"><i class=\"bi bi-palette\"></i><span>'+(active?t('active','مفعّل'):t('apply','اعتماد'))+'</span></button></div></div>';}).join('')+'</div></div>':'')
        +(destinations.length?'<div class=\"production-board\"><div class=\"stage-head\"><div class=\"kicker\"><i class=\"bi bi-diagram-2\"></i>Destination Engine</div><h3>'+t('destinations_title','وجهات الإنتاج')+'</h3><p class=\"muted\">'+t('destinations_text','نفس التحليل يمكن أن يغذي صفحة هبوط، static ads، video brief، وNextify.')+'</p></div><div class=\"grid2\">'+destinations.map(dest=>{const destId=textOf(dest.id||dest.title); const active=ensureArray(workspace.selected_destinations).includes(destId); return '<div class=\"output-card\" style=\"border-color:'+(active?'#bfdbfe':'')+'\"><header><strong>'+e(textOf(dest.title||''))+'</strong><span class=\"status-chip '+(active?'doing':'todo')+'\">'+(active?t('enabled_state','مفعلة'):t('optional_state','اختيارية'))+'</span></header><span>'+e(textOf(dest.goal||''))+'</span><span>'+e(ensureArray(dest.deliverables).join(' • '))+'</span><div>'+e(ensureArray(dest.notes).join(' • '))+'</div><div class=\"toolbar\"><label><input type=\"checkbox\" data-destination-check=\"'+e(destId)+'\" '+(active?'checked':'')+'> '+t('enable','تفعيل')+'</label><button type=\"button\" class=\"btn-main\" data-generate-brief=\"'+e(destId)+'\"><i class=\"bi bi-stars\"></i><span>'+t('generate_brief_button','Generate Brief')+'</span></button></div></div>';}).join('')+'</div></div>':'')
        +((briefs.length||tasks.length)?'<div class=\"production-board\"><div class=\"stage-head\"><div class=\"kicker\"><i class=\"bi bi-kanban\"></i>Production Workflow</div><h3>'+t('production_workflow_title','الـ Briefs والمهام')+'</h3><p class=\"muted\">'+t('production_workflow_text','حوّل المخرجات إلى عناصر تنفيذ فعلية داخل نفس الجلسة.')+'</p></div><div class=\"grid2\">'+(briefs.length?briefs.slice().reverse().map((brief,index)=>'<div class=\"output-card\"><header><strong>'+(briefs.length-index)+'. '+e(textOf(brief.title||''))+'</strong><span class=\"status-chip done\">Brief</span></header><span>'+e(textOf(brief.summary||brief.objective||''))+'</span><span>'+e(textOf(brief.prompt||''))+'</span><div>'+ensureArray(brief.deliverables).map(item=>'<span class=\"style-chip\">'+e(textOf(item))+'</span>').join('')+'</div><div class=\"toolbar\"><button type=\"button\" class=\"btn-ghost\" data-create-task=\"'+e(textOf(brief.id||('brief_'+index)))+'\"><i class=\"bi bi-kanban\"></i><span>'+t('add_to_tasks','إضافة إلى المهام')+'</span></button></div></div>').join(''):'<div class=\"mini-card\"><strong>'+t('no_briefs','لا توجد briefs')+'</strong><span>'+t('no_briefs_text','فعّل destinations ثم ابدأ التوليد.')+'</span></div>')+(tasks.length?tasks.map(task=>'<div class=\"output-card\"><header><strong>'+e(textOf(task.title||''))+'</strong><span class=\"status-chip '+e(textOf(task.status||'todo'))+'\">'+e(textOf(task.status||'todo'))+'</span></header><span>'+e(textOf(task.note||''))+'</span><span>'+e(textOf(task.destination||''))+'</span><div class=\"toolbar\"><button type=\"button\" class=\"btn-ghost\" data-task-id=\"'+e(textOf(task.id||''))+'\" data-task-status=\"todo\"><span>Todo</span></button><button type=\"button\" class=\"btn-ghost\" data-task-id=\"'+e(textOf(task.id||''))+'\" data-task-status=\"doing\"><span>Doing</span></button><button type=\"button\" class=\"btn-main\" data-task-id=\"'+e(textOf(task.id||''))+'\" data-task-status=\"done\"><span>Done</span></button></div></div>').join(''):'<div class=\"mini-card\"><strong>'+t('no_tasks','لا توجد tasks')+'</strong><span>'+t('no_tasks_text','حوّل أي brief إلى task لتبدأ إدارة التنفيذ من هنا.')+'</span></div>')+'</div></div>':'')
        +(concepts.length?'<div class=\"production-board\"><div class=\"stage-head\"><div class=\"kicker\"><i class=\"bi bi-lightbulb\"></i>Concept Engine</div><h3>'+t('concept_engine_title','المفاهيم والزوايا')+'</h3><p class=\"muted\">'+t('concept_engine_text','كل concept هنا يمثل زاوية بيع مختلفة يمكن دفعها نحو section أو brief أو variant.')+'</p></div><div class=\"grid3\">'+concepts.map((concept,index)=>'<div class=\"concept-card\"><strong>'+(index+1)+'. '+e(textOf(concept.name||'Concept'))+'</strong><span>'+e(textOf(concept.angle||concept.hook||''))+'</span><span>'+e(textOf(concept.hook||''))+'</span></div>').join('')+'</div></div>':'')
        +(history.length?'<div class=\"production-board\"><div class=\"stage-head\"><div class=\"kicker\"><i class=\"bi bi-list-task\"></i>'+t('agent_actions_title','آثار التشغيل')+'</div><h3>'+t('agent_actions_title','آثار التشغيل')+'</h3><p class=\"muted\">'+t('agent_actions_text','هذه آخر الأفعال التي سجلها الوكيل أثناء العمل على الصفحة.')+'</p></div><div class=\"grid2\">'+history.map(item=>'<div class=\"mini-card\"><strong>'+e(textOf(item.label||''))+'</strong><span>'+e(textOf(item.at||''))+'</span></div>').join('')+'</div></div>':'')
        +(competitorHistory.length?'<div class=\"production-board\"><div class=\"stage-head\"><div class=\"kicker\"><i class=\"bi bi-binoculars\"></i>'+t('competitor_memory_title','ذاكرة المنافسين')+'</div><h3>'+t('competitor_memory_title','ذاكرة المنافسين')+'</h3><p class=\"muted\">'+t('competitor_memory_text','آخر المنافسين الذين جرى تحليلهم داخل هذه الجلسة.')+'</p></div><div class=\"grid2\">'+competitorHistory.map(entry=>'<div class=\"mini-card\"><strong>'+e(textOf(entry.domain||entry.url||''))+'</strong><span>'+e(textOf((entry.report||{}).lp_strategy||''))+'</span></div>').join('')+'</div></div>':'')
    +'</div>';
    renderWorkspacePanels(workspace, briefs, tasks, sessionHistory);
    document.getElementById('btn-save-analysis')?.addEventListener('click',saveAnalysisForm);
    document.getElementById('btn-save-workspace')?.addEventListener('click',()=>{const nextWorkspace=ensureWorkspace(); nextWorkspace.session_title=document.getElementById('workspace-session-title')?.value||nextWorkspace.session_title; nextWorkspace.current_objective=document.getElementById('workspace-objective')?.value||nextWorkspace.current_objective; saveWorkspaceState('btn-save-workspace');});
    document.querySelectorAll('[data-style-id]').forEach(btn=>btn.addEventListener('click',()=>{ensureWorkspace().selected_style=btn.dataset.styleId||''; renderAnalysis(); saveWorkspaceState(btn);}));
    document.querySelectorAll('[data-destination-check]').forEach(input=>input.addEventListener('change',()=>{const nextWorkspace=ensureWorkspace(); const id=input.dataset.destinationCheck||''; let selected=ensureArray(nextWorkspace.selected_destinations); if(input.checked){if(!selected.includes(id)) selected.push(id);} else {selected=selected.filter(item=>item!==id);} nextWorkspace.selected_destinations=selected; saveWorkspaceState(input);}));
    document.querySelectorAll('[data-generate-brief]').forEach(btn=>btn.addEventListener('click',()=>generateBriefForDestination(btn.dataset.generateBrief||'', btn)));
    document.querySelectorAll('[data-create-task]').forEach(btn=>btn.addEventListener('click',()=>createTaskFromBrief(btn.dataset.createTask||'')));
    document.querySelectorAll('[data-task-id]').forEach(btn=>btn.addEventListener('click',()=>toggleTaskStatus(btn.dataset.taskId||'', btn.dataset.taskStatus||'todo')));
}
function moveSection(index, delta){const next=index+delta; const sourceSections=ensureArray((studioState.agent||{}).sections).length?JSON.parse(JSON.stringify(ensureArray((studioState.agent||{}).sections))):JSON.parse(JSON.stringify(ensureArray((studioState.structure||{}).sections))); if(next<0||next>=sourceSections.length) return; const current=sourceSections[index]; sourceSections[index]=sourceSections[next]; sourceSections[next]=current; if(studioState.agent&&Array.isArray(studioState.agent.sections)) studioState.agent.sections=sourceSections; studioState.structure=Object.assign({}, studioState.structure||{}, {sections:sourceSections}); renderAssembler();}
function renderAssembler(){const root=document.getElementById('agent-assembler'); const sections=ensureArray((studioState.agent||{}).sections).length?ensureArray((studioState.agent||{}).sections):ensureArray((studioState.structure||{}).sections); const concepts=ensureArray((studioState.agent||{}).concepts); const selected=(studioState.agent||{}).selected_concept||''; if(!sections.length){root.innerHTML='<div class=\"muted\">'+t('assembler_empty','لا يوجد هيكل محفوظ مشتق من الصورة لهذه الصفحة.')+'</div>'; return;} const enabledCount=sections.filter(section=>section.enabled!==false).length; const lockedCount=sections.filter(section=>!!section.locked).length; const contentCount=sections.filter(section=>textOf(section.headline||section.hook||section.label)).length; root.innerHTML='<div class=\"assembler-shell\"><div class=\"assembler-lane\"><div class=\"toolbar\"><select id=\"assembler-concept\" class=\"select\" style=\"max-width:320px;\"><option value=\"\">'+t('assembler_auto_concept','اختيار أقوى مفهوم تلقائيًا')+'</option>'+concepts.map(c=>'<option value=\"'+e(textOf(c.name))+'\" '+(selected===textOf(c.name)?'selected':'')+'>'+e(textOf(c.name||'Concept'))+'</option>').join('')+'</select><button type=\"button\" class=\"btn-main\" id=\"btn-assemble-page\"><i class=\"bi bi-layers\"></i><span>'+t('assembler_run','تجميع صفحة الهبوط')+'</span></button></div><div class=\"assembler-summary\"><div class=\"assembler-metric\"><strong>'+e(String(sections.length))+'</strong><span>'+t('assembler_sections','الأقسام')+'</span></div><div class=\"assembler-metric\"><strong>'+e(String(enabledCount))+'</strong><span>'+t('assembler_enabled','مفعلة')+'</span></div><div class=\"assembler-metric\"><strong>'+e(String(lockedCount))+'</strong><span>'+t('assembler_locked','مقفلة')+'</span></div><div class=\"assembler-metric\"><strong>'+e(String(contentCount))+'</strong><span>'+t('assembler_ready','جاهزة بالنص')+'</span></div></div><div class=\"assembler-board sections\" id=\"assembler-stack\">'+sections.map((section,index)=>'<div class=\"section-card\" data-index=\"'+index+'\" data-type=\"'+e(textOf(section.type||'section'))+'\"><div class=\"section-head\"><h4>'+(index+1)+'. '+e(textOf(section.type||'section'))+'</h4><div class=\"flags\"><label><input type=\"checkbox\" class=\"assembler-enabled\" '+(section.enabled===false?'':'checked')+'> '+t('insert_label','إدراج')+'</label><label><input type=\"checkbox\" class=\"assembler-locked\" '+(section.locked?'checked':'')+'> '+t('lock_label','قفل')+'</label></div></div><div class=\"muted\" style=\"font-size:12px;\">Layout: '+e(textOf(section.layout||''))+' • Difficulty: '+e(textOf(section.difficulty||''))+'</div><div class=\"section-actions\"><button type=\"button\" class=\"btn-ghost assembler-move-up\" data-index=\"'+index+'\"><i class=\"bi bi-arrow-up\"></i><span>'+t('move_up','رفع')+'</span></button><button type=\"button\" class=\"btn-ghost assembler-move-down\" data-index=\"'+index+'\"><i class=\"bi bi-arrow-down\"></i><span>'+t('move_down','خفض')+'</span></button></div><div class=\"grid2\"><div><div class=\"field-label\">'+t('label_field','الوسم')+'</div><input type=\"text\" class=\"input assembler-label\" value=\"'+e(textOf(section.label||''))+'\"></div><div><div class=\"field-label\">'+t('headline_field','العنوان')+'</div><input type=\"text\" class=\"input assembler-headline\" value=\"'+e(textOf(section.headline||''))+'\"></div><div><div class=\"field-label\">Hook</div><input type=\"text\" class=\"input assembler-hook\" value=\"'+e(textOf(section.hook||section.headline||''))+'\"></div><div><div class=\"field-label\">Objective</div><textarea class=\"textarea assembler-objective\">'+e(textOf(section.objective||section.purpose||''))+'</textarea></div><div><div class=\"field-label\">'+t('goal_field','الهدف / الملاحظة')+'</div><textarea class=\"textarea assembler-goal\">'+e(textOf(section.purpose||section.subheadline||''))+'</textarea></div><div><div class=\"field-label\">Prompt</div><textarea class=\"textarea assembler-prompt\">'+e(textOf(section.copy_prompt||''))+'</textarea></div><div><div class=\"field-label\">Layout Notes</div><textarea class=\"textarea assembler-layout-notes\">'+e(textOf(section.layout_notes||''))+'</textarea></div><div><div class=\"field-label\">Palette</div><input type=\"text\" class=\"input assembler-palette\" value=\"'+e(ensureArray(section.palette).join(', '))+'\"></div><div><div class=\"field-label\">Text Rules</div><textarea class=\"textarea assembler-rules\">'+e(ensureArray(section.text_rules).join('\\n'))+'</textarea></div></div></div>').join('')+'</div></div><aside class=\"assembler-rail\"><div class=\"output-card\"><header><strong>'+t('roadmap_title','خريطة التجميع')+'</strong><span class=\"priority-chip\">Composer</span></header><span>'+t('roadmap_text','اختر concept مناسبًا ثم راجع ترتيب الأقسام قبل بناء النسخة النهائية.')+'</span></div><div class=\"output-card\"><header><strong>'+t('assembler_preview_title','معاينة التجميع')+'</strong><span class=\"priority-chip\">Preview</span></header><span>'+t('assembler_preview_text','هذه المعاينة الطويلة مخصصة للتجميع قبل اعتماد الصفحة النهائية.')+'</span><iframe id=\"assembler-preview-frame\" class=\"frame\" style=\"min-height:720px\" src=\"/admin/ai-landing-pages/preview/'+PAGE_ID+'?assembler=1&v='+(Date.now())+'\" title=\"Assembler Preview\" sandbox=\"allow-scripts allow-forms allow-popups\"></iframe></div><div class=\"assembler-outline\">'+sections.map((section,index)=>'<div class=\"outline-item '+(section.enabled===false?'':'active')+'\"><strong>'+(index+1)+'. '+e(textOf(section.type||'section'))+'</strong><small>'+e(textOf(section.headline||section.hook||section.label||''))+'</small><small>'+e(section.locked?t('locked_state','مقفل'):t('editable_state','قابل للتحرير'))+' • '+e(section.enabled===false?t('excluded_state','مستبعد'):t('included_state','داخل الصفحة'))+'</small></div>').join('')+'</div></aside></div>'; document.getElementById('btn-assemble-page').addEventListener('click', assembleLandingPage); root.querySelectorAll('.assembler-move-up').forEach(btn=>btn.addEventListener('click',()=>moveSection(Number(btn.dataset.index),-1))); root.querySelectorAll('.assembler-move-down').forEach(btn=>btn.addEventListener('click',()=>moveSection(Number(btn.dataset.index),1)));}
function renderAnalysis(){const analysis=studioState.analysis||{}; const agent=studioState.agent||{}; const analysisForm=agent.analysis_form||{}; const workspace=ensureWorkspace(); const summary=document.getElementById('analysis-summary'); const colors=ensureArray(analysisForm.palette||analysis.colors).slice(0,4).map(textOf).filter(Boolean).join(' / ') || '—'; const quickWins=ensureArray((agent.scorecard||{}).quick_wins || analysis.conversion_notes).slice(0,4); const heroTitle=textOf((analysis.hero||{}).headline || analysis.product_name || analysisForm.product_name || '—'); const cta=textOf((analysis.hero||{}).cta || analysisForm.primary_cta || '—'); summary.innerHTML='<div class=\"grid2\"><div class=\"mini-card\"><strong>Hero</strong><span>'+e(heroTitle)+'</span></div><div class=\"mini-card\"><strong>Colors</strong><span>'+e(colors)+'</span></div><div class=\"mini-card\"><strong>CTA</strong><span>'+e(cta)+'</span></div><div class=\"mini-card\"><strong>'+t('sections_detected','الأقسام المكتشفة')+'</strong><span>'+e(String(ensureArray((studioState.structure||{}).sections).length))+'</span></div></div>'+(quickWins.length?'<div class=\"concept-card\" style=\"margin-top:12px\"><strong>'+t('quick_wins','تحسينات سريعة')+'</strong><span>'+e(quickWins.join(' • '))+'</span></div>':''); const workbench=document.getElementById('agent-workbench'); const concepts=ensureArray(agent.concepts); const styles=ensureArray(agent.styles); const briefHistory=ensureArray(agent.brief_history); const briefs=briefHistory.length?briefHistory:ensureArray(agent.briefs); const destinations=Object.values(agent.destinations||{}); const score=((agent.scorecard||{}).breakdown)||{}; const history=ensureArray(agent.history).slice().reverse().slice(0,8); const tasks=ensureArray(workspace.tasks); const competitorHistory=ensureArray(agent.competitor_history).slice().reverse().slice(0,4); workbench.innerHTML=''+
'<div class=\"grid2\">'+
'<div class=\"concept-card\"><strong>'+t('analysis_form_title','نموذج تحليل المنتج')+'</strong><span>'+t('analysis_form_help','راجع البيانات المستخرجة من التحليل قبل تشغيل الـ briefs والنسخ.')+'</span><div class=\"grid2\"><div><div class=\"field-label\">'+t('product_name','اسم المنتج')+'</div><input id=\"analysis-product-name\" class=\"input\" value=\"'+e(textOf(analysisForm.product_name||''))+'\"></div><div><div class=\"field-label\">'+t('brand','العلامة')+'</div><input id=\"analysis-brand\" class=\"input\" value=\"'+e(textOf(analysisForm.brand||''))+'\"></div><div><div class=\"field-label\">'+t('category','الفئة')+'</div><input id=\"analysis-category\" class=\"input\" value=\"'+e(textOf(analysisForm.category||''))+'\"></div><div><div class=\"field-label\">'+t('type','النوع')+'</div><input id=\"analysis-product-type\" class=\"input\" value=\"'+e(textOf(analysisForm.product_type||''))+'\"></div><div><div class=\"field-label\">'+t('primary_benefit','الفائدة الأساسية')+'</div><textarea id=\"analysis-benefit\" class=\"textarea\">'+e(textOf(analysisForm.primary_benefit||''))+'</textarea></div><div><div class=\"field-label\">'+t('audience','الجمهور')+'</div><textarea id=\"analysis-audience\" class=\"textarea\">'+e(textOf(analysisForm.audience||''))+'</textarea></div><div><div class=\"field-label\">'+t('problem','المشكلة')+'</div><textarea id=\"analysis-pain\" class=\"textarea\">'+e(textOf(analysisForm.pain_point||''))+'</textarea></div><div><div class=\"field-label\">'+t('palette_label','لوحة الألوان')+'</div><input id=\"analysis-palette\" class=\"input\" value=\"'+e(ensureArray(analysisForm.palette).join(', '))+'\"></div><div><div class=\"field-label\">'+t('market','السوق')+'</div><input id=\"analysis-market\" class=\"input\" value=\"'+e(textOf(analysisForm.market||''))+'\"></div><div><div class=\"field-label\">'+t('language_label','اللغة')+'</div><select id=\"analysis-language\" class=\"select\"><option value=\"ar\" '+(textOf(analysisForm.selected_language||workspace.selected_language)==='ar'?'selected':'')+'>'+t('lang_ar','العربية')+'</option><option value=\"ar-dz\" '+(textOf(analysisForm.selected_language||workspace.selected_language)==='ar-dz'?'selected':'')+'>'+t('lang_ar_dz','الدارجة الجزائرية')+'</option><option value=\"fr\" '+(textOf(analysisForm.selected_language||workspace.selected_language)==='fr'?'selected':'')+'>'+t('lang_fr','Français')+'</option><option value=\"en\" '+(textOf(analysisForm.selected_language||workspace.selected_language)==='en'?'selected':'')+'>'+t('lang_en','English')+'</option></select></div><div><div class=\"field-label\">'+t('dialect_label','اللهجة')+'</div><select id=\"analysis-dialect\" class=\"select\"><option value=\"ar-dz\" '+(textOf(analysisForm.selected_dialect||workspace.selected_dialect)==='ar-dz'?'selected':'')+'>'+t('lang_ar_dz','الدارجة الجزائرية')+'</option><option value=\"ar\" '+(textOf(analysisForm.selected_dialect||workspace.selected_dialect)==='ar'?'selected':'')+'>'+t('lang_ar_fusha','العربية الفصحى')+'</option><option value=\"fr-dz\" '+(textOf(analysisForm.selected_dialect||workspace.selected_dialect)==='fr-dz'?'selected':'')+'>'+t('lang_fr_dz','Français Algérie')+'</option></select></div></div><div class=\"toolbar\"><button type=\"button\" class=\"btn-main\" id=\"btn-save-analysis\"><i class=\"bi bi-save\"></i><span>'+t('save_analysis','حفظ التحليل')+'</span></button></div></div>'+
'<div class=\"concept-card\"><strong>'+t('strategy_cockpit','غرفة الاستراتيجية')+'</strong><span>'+t('strategy_cockpit_help','تحكم في scorecard والجلسة والهدف قبل المرور إلى الوجهات والإنتاج.')+'</span><span>Global: '+e(String(score.global ?? (agent.scorecard||{}).global_score ?? '—'))+'</span><span>Copy: '+e(String(score.copy ?? '—'))+'</span><span>Design: '+e(String(score.design ?? '—'))+'</span><span>CTA: '+e(String(score.cta ?? '—'))+'</span><span>Trust: '+e(String(score.trust ?? '—'))+'</span><span>Mobile: '+e(String(score.mobile ?? '—'))+'</span><span>COD Fit: '+e(String(score.cod_fit ?? '—'))+'</span><div class=\"field-label\">'+t('session_title_label','عنوان الجلسة')+'</div><input id=\"workspace-session-title\" class=\"input\" value=\"'+e(textOf(workspace.session_title||''))+'\"><div class=\"field-label\">'+t('session_goal_label','هدف الجلسة')+'</div><textarea id=\"workspace-objective\" class=\"textarea\">'+e(textOf(workspace.current_objective||''))+'</textarea><div class=\"toolbar\"><button type=\"button\" class=\"btn-ghost\" id=\"btn-save-workspace\"><i class=\"bi bi-save2\"></i><span>'+t('save_workspace','حفظ مساحة العمل')+'</span></button></div></div>'+
'</div>'+
(styles.length?'<div class=\"production-board\" style=\"margin-top:12px\"><div class=\"stage-head\"><div class=\"kicker\"><i class=\"bi bi-palette\"></i>'+t('style_system_title','نظام الـ Styles')+'</div><h3>'+t('style_system_title','نظام الـ Styles')+'</h3><p class=\"muted\">'+t('style_system_text','اختر اتجاهًا بصريًا جاهزًا له mood واضح بدل الاعتماد على prompt حر فقط.')+'</p></div><div class=\"grid3\">'+styles.map(style=>{const id=textOf(style.id||style.name); const active=textOf(workspace.selected_style)===id; return '<div class=\"concept-card\" style=\"border-color:'+(active?'#fdba74':'')+'\"><strong>'+e(textOf(style.name||''))+'</strong><span>'+e(textOf(style.summary||''))+'</span><span>'+e(textOf(style.mood||style.direction||''))+'</span><span>'+e(ensureArray(style.chips).join(' • '))+'</span><div class=\"toolbar\"><button type=\"button\" class=\"'+(active?'btn-main':'btn-ghost')+'\" data-style-id=\"'+e(id)+'\"><i class=\"bi bi-palette\"></i><span>'+(active?t('active','مفعّل'):t('apply','اعتماد'))+'</span></button></div></div>';}).join('')+'</div></div>':'')+
(destinations.length?'<div class=\"production-board\" style=\"margin-top:12px\"><div class=\"stage-head\"><div class=\"kicker\"><i class=\"bi bi-diagram-3\"></i>'+t('destinations_title','وجهات الإنتاج')+'</div><h3>'+t('destinations_title','وجهات الإنتاج')+'</h3><p class=\"muted\">'+t('destinations_text','فعّل الوجهات التي تريد تشغيلها من نفس التحليل: LP أو Ads أو Video أو Nextify.')+'</p></div><div class=\"grid2\">'+destinations.map(dest=>{const destId=textOf(dest.id||dest.title); const active=ensureArray(workspace.selected_destinations).includes(destId); return '<div class=\"mini-card\" style=\"border-color:'+(active?'#bfdbfe':'')+'\"><strong>'+e(textOf(dest.title||''))+'</strong><span>'+e(textOf(dest.goal||''))+'</span><span>'+e(ensureArray(dest.deliverables).join(' • '))+'</span><div>'+e(ensureArray(dest.notes).join(' • '))+'</div><div class=\"toolbar\"><label><input type=\"checkbox\" data-destination-check=\"'+e(destId)+'\" '+(active?'checked':'')+'> '+(active?t('enabled_state','مفعّلة'):t('enable','تفعيل'))+'</label><button type=\"button\" class=\"btn-main\" data-generate-brief=\"'+e(destId)+'\"><i class=\"bi bi-stars\"></i><span>'+t('generate_brief_button','توليد Brief')+'</span></button><a class=\"btn-ghost\" href=\"/admin/ai-landing-pages/destination/'+PAGE_ID+'/'+encodeURIComponent(destId)+'\"><i class=\"bi bi-diagram-3\"></i><span>'+t('open_destination_workflow','فتح الـ Workflow')+'</span></a></div></div>';}).join('')+'</div></div>':'')+
'<div class=\"production-board\" style=\"margin-top:12px\"><div class=\"stage-head\"><div class=\"kicker\"><i class=\"bi bi-kanban\"></i>'+t('production_workflow_title','سير الإنتاج')+'</div><h3>'+t('production_workflow_title','سير الإنتاج')+'</h3><p class=\"muted\">'+t('production_workflow_text','حوّل الـ briefs إلى مهام متابعة داخل نفس مساحة العمل بدل بقائها نصوصًا معزولة.')+'</p></div>'+(briefs.length?'<div class=\"grid2\">'+briefs.slice().reverse().map((brief,index)=>'<div class=\"concept-card\"><strong>'+(briefs.length-index)+'. '+e(textOf(brief.title||''))+'</strong><span>'+e(textOf(brief.summary||brief.objective||''))+'</span><span>'+e(textOf(brief.prompt||''))+'</span><div>'+ensureArray(brief.deliverables).map(item=>'<span class=\"style-chip\">'+e(textOf(item))+'</span>').join('')+'</div><div class=\"toolbar\"><button type=\"button\" class=\"btn-ghost\" data-create-task=\"'+e(textOf(brief.id||('brief_'+index)))+'\"><i class=\"bi bi-kanban\"></i><span>'+t('add_to_tasks','إضافة إلى المهام')+'</span></button></div></div>').join('')+'</div>':'<div class=\"muted\">'+t('no_briefs_text','فعّل وجهة واحدة على الأقل ثم شغّل توليد brief لتظهر هذه الطبقة هنا.')+'</div>')+(tasks.length?'<div class=\"grid2\" style=\"margin-top:12px\">'+tasks.map(task=>'<div class=\"concept-card\"><strong>'+e(textOf(task.title||''))+'</strong><span>'+e(textOf(task.note||''))+'</span><span>'+e(textOf(task.destination||''))+'</span><div class=\"toolbar\"><button type=\"button\" class=\"btn-ghost\" data-task-status=\"doing\" data-task-id=\"'+e(textOf(task.id||''))+'\">Doing</button><button type=\"button\" class=\"btn-main\" data-task-status=\"done\" data-task-id=\"'+e(textOf(task.id||''))+'\">Done</button></div></div>').join('')+'</div>':'<div class=\"muted\" style=\"margin-top:12px\">'+t('no_tasks_text','لا توجد مهام بعد. حوّل أحد الـ briefs إلى task ليظهر هنا.')+'</div>')+'</div>'+
(concepts.length?'<div class=\"production-board\" style=\"margin-top:12px\"><div class=\"stage-head\"><div class=\"kicker\"><i class=\"bi bi-lightning-charge\"></i>'+t('concept_engine_title','محرك المفاهيم')+'</div><h3>'+t('concept_engine_title','محرك المفاهيم')+'</h3><p class=\"muted\">'+t('concept_engine_text','كل concept يمر من زاوية واضحة ويمكن أن يتحول مباشرة إلى brief ثم section ثم variant.')+'</p></div><div class=\"grid2\">'+concepts.map((concept,index)=>'<div class=\"concept-card\"><strong>'+(index+1)+'. '+e(textOf(concept.name||''))+'</strong><span>'+e(textOf(concept.angle||''))+'</span><span>'+e(textOf(concept.hook||''))+'</span><div>'+ensureArray(concept.suggestions).map(s=>'<span class=\"style-chip\">'+e(textOf(s))+'</span>').join('')+'</div></div>').join('')+'</div></div>':'')+
(history.length?'<div class=\"production-board\" style=\"margin-top:12px\"><div class=\"stage-head\"><div class=\"kicker\"><i class=\"bi bi-cpu\"></i>'+t('agent_actions_title','سجل الوكيل')+'</div><h3>'+t('agent_actions_title','سجل الوكيل')+'</h3><p class=\"muted\">'+t('agent_actions_text','آخر العمليات التي قام بها الوكيل أثناء التحليل والتوليد والتقييم.')+'</p></div><div class=\"feed-log\">'+history.map(item=>'<div class=\"feed-item system\"><div class=\"meta\">'+e(textOf(item.at||''))+'</div><div>'+e(textOf(item.label||''))+'</div></div>').join('')+'</div></div>':'')+
(competitorHistory.length?'<div class=\"production-board\" style=\"margin-top:12px\"><div class=\"stage-head\"><div class=\"kicker\"><i class=\"bi bi-globe\"></i>'+t('competitor_memory_title','ذاكرة المنافسين')+'</div><h3>'+t('competitor_memory_title','ذاكرة المنافسين')+'</h3><p class=\"muted\">'+t('competitor_memory_text','آخر المنافسين الذين تمت مقارنتهم في هذه الجلسة لسهولة الرجوع إليهم بسرعة.')+'</p></div><div class=\"grid2\">'+competitorHistory.map(entry=>'<div class=\"mini-card\"><strong>'+e(textOf(entry.domain||entry.url||''))+'</strong><span>'+e(textOf(entry.at||''))+'</span></div>').join('')+'</div></div>':'');
attachAnalysisHandlers();}
function renderAssembler(){const root=document.getElementById('agent-assembler'); const sections=ensureArray((studioState.agent||{}).sections).length?ensureArray((studioState.agent||{}).sections):ensureArray((studioState.structure||{}).sections); const concepts=ensureArray((studioState.agent||{}).concepts); const selected=(studioState.agent||{}).selected_concept||''; if(!sections.length){root.innerHTML='<div class=\"muted\">'+t('assembler_empty','لا يوجد هيكل محفوظ مشتق من الصورة لهذه الصفحة.')+'</div>'; return;} const enabledCount=sections.filter(section=>section.enabled!==false).length; const lockedCount=sections.filter(section=>!!section.locked).length; const contentCount=sections.filter(section=>textOf(section.headline||section.hook||section.label)).length; root.innerHTML='<div class=\"assembler-shell\"><div class=\"assembler-lane\"><div class=\"toolbar\"><select id=\"assembler-concept\" class=\"select\" style=\"max-width:320px;\"><option value=\"\">'+t('assembler_auto_concept','اختيار أقوى مفهوم تلقائيًا')+'</option>'+concepts.map(c=>'<option value=\"'+e(textOf(c.name))+'\" '+(selected===textOf(c.name)?'selected':'')+'>'+e(textOf(c.name||'Concept'))+'</option>').join('')+'</select><button type=\"button\" class=\"btn-main\" id=\"btn-assemble-page\"><i class=\"bi bi-layers\"></i><span>'+t('assembler_run','تجميع صفحة الهبوط')+'</span></button></div><div class=\"assembler-summary\"><div class=\"assembler-metric\"><strong>'+e(String(sections.length))+'</strong><span>'+t('assembler_sections','الأقسام')+'</span></div><div class=\"assembler-metric\"><strong>'+e(String(enabledCount))+'</strong><span>'+t('assembler_enabled','مفعلة')+'</span></div><div class=\"assembler-metric\"><strong>'+e(String(lockedCount))+'</strong><span>'+t('assembler_locked','مقفلة')+'</span></div><div class=\"assembler-metric\"><strong>'+e(String(contentCount))+'</strong><span>'+t('assembler_ready','جاهزة بالنص')+'</span></div></div><div class=\"assembler-board sections\" id=\"assembler-stack\">'+sections.map((section,index)=>'<div class=\"section-card\" data-index=\"'+index+'\" data-type=\"'+e(textOf(section.type||'section'))+'\"><div class=\"section-head\"><h4>'+(index+1)+'. '+e(textOf(section.type||'section'))+'</h4><div class=\"flags\"><label><input type=\"checkbox\" class=\"assembler-enabled\" '+(section.enabled===false?'':'checked')+'> '+t('insert_label','إدراج')+'</label><label><input type=\"checkbox\" class=\"assembler-locked\" '+(section.locked?'checked':'')+'> '+t('lock_label','قفل')+'</label></div></div><div class=\"muted\" style=\"font-size:12px;\">Layout: '+e(textOf(section.layout||''))+' • Difficulty: '+e(textOf(section.difficulty||''))+'</div><div class=\"section-actions\"><button type=\"button\" class=\"btn-ghost assembler-move-up\" data-index=\"'+index+'\"><i class=\"bi bi-arrow-up\"></i><span>'+t('move_up','رفع')+'</span></button><button type=\"button\" class=\"btn-ghost assembler-move-down\" data-index=\"'+index+'\"><i class=\"bi bi-arrow-down\"></i><span>'+t('move_down','خفض')+'</span></button></div><div class=\"grid2\"><div><div class=\"field-label\">'+t('label_field','الوسم')+'</div><input type=\"text\" class=\"input assembler-label\" value=\"'+e(textOf(section.label||''))+'\"></div><div><div class=\"field-label\">'+t('headline_field','العنوان')+'</div><input type=\"text\" class=\"input assembler-headline\" value=\"'+e(textOf(section.headline||''))+'\"></div><div><div class=\"field-label\">'+t('hook_label','الـ Hook')+'</div><input type=\"text\" class=\"input assembler-hook\" value=\"'+e(textOf(section.hook||section.headline||''))+'\"></div><div><div class=\"field-label\">'+t('objective_label','الهدف')+'</div><textarea class=\"textarea assembler-objective\">'+e(textOf(section.objective||section.purpose||''))+'</textarea></div><div><div class=\"field-label\">'+t('goal_field','الهدف / الملاحظة')+'</div><textarea class=\"textarea assembler-goal\">'+e(textOf(section.purpose||section.subheadline||''))+'</textarea></div><div><div class=\"field-label\">'+t('prompt_label','البرومبت')+'</div><textarea class=\"textarea assembler-prompt\">'+e(textOf(section.copy_prompt||''))+'</textarea></div><div><div class=\"field-label\">'+t('layout_notes_label','ملاحظات التخطيط')+'</div><textarea class=\"textarea assembler-layout-notes\">'+e(textOf(section.layout_notes||''))+'</textarea></div><div><div class=\"field-label\">'+t('palette_label','لوحة الألوان')+'</div><input type=\"text\" class=\"input assembler-palette\" value=\"'+e(ensureArray(section.palette).join(', '))+'\"></div><div><div class=\"field-label\">'+t('text_rules_label','قواعد النص')+'</div><textarea class=\"textarea assembler-rules\">'+e(ensureArray(section.text_rules).join('\\n'))+'</textarea></div></div></div>').join('')+'</div></div><aside class=\"assembler-rail\"><div class=\"output-card\"><header><strong>'+t('roadmap_title','خريطة التجميع')+'</strong><span class=\"priority-chip\">'+t('composer_label','Composer')+'</span></header><span>'+t('roadmap_text','اختر concept مناسبًا ثم راجع ترتيب الأقسام قبل بناء النسخة النهائية.')+'</span></div><div class=\"output-card\"><header><strong>'+t('assembler_preview_title','معاينة التجميع')+'</strong><span class=\"priority-chip\">'+t('preview_chip','Preview')+'</span></header><span>'+t('assembler_preview_text','هذه المعاينة الطويلة مخصصة للتجميع قبل اعتماد الصفحة النهائية.')+'</span><iframe id=\"assembler-preview-frame\" class=\"frame\" style=\"min-height:720px\" src=\"/admin/ai-landing-pages/preview/'+PAGE_ID+'?assembler=1&v='+(Date.now())+'\" title=\"Assembler Preview\" sandbox=\"allow-scripts allow-forms allow-popups\"></iframe></div><div class=\"assembler-outline\">'+sections.map((section,index)=>'<div class=\"outline-item '+(section.enabled===false?'':'active')+'\"><strong>'+(index+1)+'. '+e(textOf(section.type||'section'))+'</strong><small>'+e(textOf(section.headline||section.hook||section.label||''))+'</small><small>'+e(section.locked?t('locked_state','مقفل'):t('editable_state','قابل للتحرير'))+' • '+e(section.enabled===false?t('excluded_state','مستبعد'):t('included_state','داخل الصفحة'))+'</small></div>').join('')+'</div></aside></div>'; document.getElementById('btn-assemble-page').addEventListener('click', assembleLandingPage); root.querySelectorAll('.assembler-move-up').forEach(btn=>btn.addEventListener('click',()=>moveSection(Number(btn.dataset.index),-1))); root.querySelectorAll('.assembler-move-down').forEach(btn=>btn.addEventListener('click',()=>moveSection(Number(btn.dataset.index),1)));}
function updatePreview(){const previewUrl='/admin/ai-landing-pages/preview/'+PAGE_ID+'?v='+Date.now(); const frame=document.getElementById('preview-frame'); const assemblerFrame=document.getElementById('assembler-preview-frame'); if(frame){frame.src=previewUrl;} else {const empty=document.getElementById('preview-empty'); if(empty){empty.outerHTML='<iframe id=\"preview-frame\" class=\"frame\" src=\"'+previewUrl+'\" title=\"Preview\" sandbox=\"allow-scripts allow-forms allow-popups\"></iframe>';}} if(assemblerFrame){assemblerFrame.src='/admin/ai-landing-pages/preview/'+PAGE_ID+'?assembler=1&v='+Date.now();}}
function previewVariant(index){const variant=ensureArray(studioState.variants)[index]; if(!variant || !variant.html) return; const frame=document.getElementById('preview-frame'); const assemblerFrame=document.getElementById('assembler-preview-frame'); if(frame){frame.srcdoc=variant.html;} if(assemblerFrame){assemblerFrame.srcdoc=variant.html;}}

async function sendMessage(){
  const input=document.getElementById('chat-input');
  let message=input.value.trim();
  if(!message && !chatAttachedImageUrl){input.style.cssText+='outline:3px solid #f97316!important;'; setTimeout(()=>{input.style.outline='';},2000); input.focus(); return;}
  if(!message) message=t('chat_image_ref','Reference image');
  // Include attached image URL in message so the AI can use it
  let fullMessage=message;
  if(chatAttachedImageUrl) fullMessage+='\n\n['+t('chat_image_ref','Reference image')+': '+chatAttachedImageUrl+']';
  appendFeed('user',fullMessage);
  studioState.conversation=ensureArray(studioState.conversation);
  studioState.conversation.push({role:'user',content:fullMessage});
  input.value='';
  // Clear attached image
  const _imgUrl=chatAttachedImageUrl;
  chatAttachedImageUrl=null; chatAttachedImageFile=null;
  document.getElementById('chat-image-preview').style.display='none';
  document.getElementById('chat-image-thumb').src='';
  document.getElementById('chat-image-input').value='';
  const fd=new FormData();
  fd.append('_csrf',CSRF_TOKEN);
  fd.append('message',fullMessage);
  if(_imgUrl) fd.append('image_url',_imgUrl);
  setBusy(true,t('send_request','Sending instructions'),t('send_request_text','Sending your request to the agent to improve the page.'),'btn-send-message');
  try{
    const res=await fetch('/admin/ai-landing-pages/generate/'+PAGE_ID,{method:'POST',body:fd});
    const data=await readJsonResponse(res);
    if(!data.success) throw new Error(data.error||t('pipeline_error','Pipeline error'));
    appendFeed('assistant',t('ai_updated','Landing page updated based on your request.'));
    studioState.conversation.push({role:'assistant',content:t('ai_updated','Landing page updated based on your request.')});
    updatePreview();
  }catch(err){setStatus('error',t('pipeline_error','Pipeline error'),err.message); appendFeed('assistant','⚠️ '+err.message);}
  finally{setBusy(false,'','','btn-send-message');}
}
async function buildFromSourceImage(){if(!selectedSourceImage && !INITIAL_SOURCE_IMAGE){const msg=t('build_missing_image','يرجى رفع Screenshot أو تصميم الصفحة أولاً.'); setStatus('error',t('pipeline_error','خطأ'),msg); appendFeed('assistant','⚠️ '+msg); const uploadInput=document.getElementById('source-image-input'); if(uploadInput){const lbl=uploadInput.closest('label'); if(lbl){lbl.style.cssText+='outline:3px solid #dc2626!important;outline-offset:3px;'; setTimeout(()=>{lbl.style.outline='';lbl.style.outlineOffset='';},2500);}} return;} const stopProgress=startPipelineProgress('btn-build-from-image'); const fd=new FormData(); fd.append('_csrf',CSRF_TOKEN); if(selectedSourceImage) fd.append('source_image',selectedSourceImage); try{const res=await fetch('/admin/ai-landing-pages/generate-from-image/'+PAGE_ID,{method:'POST',body:fd}); const data=await readJsonResponse(res); if(!data.success) throw new Error(data.error||t('pipeline_error','خطأ في المسار')); studioState.analysis=data.analysis||{}; studioState.structure=data.structure||{}; studioState.agent=data.agent||data.agent_trace||{}; renderSource(data.sourceImage||data.source_image||INITIAL_SOURCE_IMAGE); renderAnalysis(); renderAssembler(); renderVariants(); renderCompetitor(); updatePreview(); appendFeed('assistant',t('build_success','تم إنشاء صفحة الهبوط انطلاقًا من الصورة المرفوعة.')); syncStatus();}catch(err){setStatus('error',t('pipeline_error','خطأ في المسار'),err.message); appendFeed('assistant','⚠️ '+err.message);}finally{stopProgress();}}
async function regenerateFromStructure(){const fd=new FormData(); fd.append('_csrf',CSRF_TOKEN); setBusy(true,'<?= addslashes(__('landing.regenerate_from_structure', 'إعادة التوليد')) ?>',t('regenerate_text','نعيد بناء الصفحة من الـ Structure المحفوظ.'),'btn-regenerate-structure'); try{const res=await fetch('/admin/ai-landing-pages/regenerate/'+PAGE_ID,{method:'POST',body:fd}); const data=await readJsonResponse(res); if(!data.success) throw new Error(data.error||t('pipeline_error','خطأ في المسار')); studioState.structure=data.structure||studioState.structure; studioState.agent=data.agent||studioState.agent; renderAnalysis(); renderAssembler(); updatePreview(); appendFeed('assistant','<?= addslashes(__('landing.regenerated', 'تمت إعادة توليد الصفحة بنجاح.')) ?>'); syncStatus();}catch(err){setStatus('error',t('pipeline_error','خطأ في المسار'),err.message); appendFeed('assistant','⚠️ '+err.message);}finally{setBusy(false,'','','btn-regenerate-structure');}}
async function assembleLandingPage(){const fd=new FormData(); fd.append('_csrf',CSRF_TOKEN); fd.append('selected_concept',document.getElementById('assembler-concept')?.value||''); fd.append('structure_json',JSON.stringify(collectStructure())); setBusy(true,'<?= addslashes(__('landing.assemble_page', 'تجميع صفحة الهبوط')) ?>',t('assemble_text','نجمّع الأقسام المختارة ونبني النسخة النهائية للمعاينة.'),'btn-assemble-page'); try{const res=await fetch('/admin/ai-landing-pages/assemble/'+PAGE_ID,{method:'POST',body:fd}); const data=await readJsonResponse(res); if(!data.success) throw new Error(data.error||t('pipeline_error','خطأ في المسار')); studioState.structure=data.structure||studioState.structure; studioState.agent=data.agent||studioState.agent; renderAnalysis(); renderAssembler(); updatePreview(); appendFeed('assistant','<?= addslashes(__('landing.assembled', 'تم تجميع صفحة الهبوط بنجاح.')) ?>');}catch(err){setStatus('error',t('pipeline_error','خطأ في المسار'),err.message); appendFeed('assistant','⚠️ '+err.message);}finally{setBusy(false,'','','btn-assemble-page');}}
async function generateVariants(){const fd=new FormData(); fd.append('_csrf',CSRF_TOKEN); setBusy(true,'<?= addslashes(__('landing.generate_variants', 'توليد 3 Variants')) ?>',t('variants_text','نولد الآن عدة نسخ مختلفة من نفس الهيكل التسويقي.'),'btn-generate-variants'); try{const res=await fetch('/admin/ai-landing-pages/generate-variants/'+PAGE_ID,{method:'POST',body:fd}); const data=await readJsonResponse(res); if(!data.success) throw new Error(data.error||t('pipeline_error','خطأ في المسار')); studioState.variants=ensureArray(data.variants); renderVariants(); syncStatus(); appendFeed('assistant','<?= addslashes(__('landing.variants_generated', 'تم توليد ثلاث نسخ بنجاح.')) ?>');}catch(err){setStatus('error',t('pipeline_error','خطأ في المسار'),err.message); appendFeed('assistant','⚠️ '+err.message);}finally{setBusy(false,'','','btn-generate-variants');}}
async function applyVariant(index,button){const variant=ensureArray(studioState.variants)[index]; if(!variant||!variant.html){appendFeed('assistant','⚠️ لا توجد نسخة صالحة لاعتمادها.'); return;} const fd=new FormData(); fd.append('_csrf',CSRF_TOKEN); fd.append('html',variant.html||''); setBusy(true,'<?= addslashes(__('landing.apply_variant', 'اعتماد النسخة')) ?>','<?= addslashes(__('landing.apply_variant', 'اعتماد النسخة')) ?>',button); try{const res=await fetch('/admin/ai-landing-pages/save-html/'+PAGE_ID,{method:'POST',body:fd}); const data=await readJsonResponse(res); if(!data.success) throw new Error(data.error||t('pipeline_error','خطأ في المسار')); updatePreview(); appendFeed('assistant',t('variant_applied','تم اعتماد النسخة بنجاح.'));}catch(err){setStatus('error',t('pipeline_error','خطأ في المسار'),err.message); appendFeed('assistant','⚠️ '+err.message);}finally{setBusy(false,'','',button);}}
async function analyzeCompetitor(){const url=document.getElementById('competitor-url')?.value?.trim()||''; if(!url){setStatus('error','تنبيه','يرجى إدخال رابط URL لصفحة المنافس قبل التحليل.'); appendFeed('assistant','⚠️ يرجى إدخال رابط URL لصفحة المنافس أولاً.'); const urlInput=document.getElementById('competitor-url'); if(urlInput){urlInput.style.cssText+='outline:3px solid #dc2626!important;'; setTimeout(()=>{urlInput.style.outline='';},2500); urlInput.focus();} return;} const fd=new FormData(); fd.append('_csrf',CSRF_TOKEN); fd.append('url',url); setBusy(true,'<?= addslashes(__('landing.analyze_competitor', 'تحليل المنافس')) ?>',t('competitor_text','نجلب الصفحة المنافسة ونستخرج نقاط القوة والضعف الآن.'),'btn-analyze-competitor'); try{const res=await fetch('/admin/ai-landing-pages/analyze-competitor/'+PAGE_ID,{method:'POST',body:fd}); const data=await readJsonResponse(res); if(!data.success) throw new Error(data.error||t('pipeline_error','خطأ في المسار')); studioState.competitor=data.report||{}; studioState.agent=data.agent||studioState.agent; renderCompetitor(); renderAnalysis(); appendFeed('assistant',t('competitor_ready','تحليل المنافس جاهز الآن.'));}catch(err){setStatus('error',t('pipeline_error','خطأ في المسار'),err.message); appendFeed('assistant','⚠️ '+err.message);}finally{setBusy(false,'','','btn-analyze-competitor');}}

function clearChatImage(){chatAttachedImageUrl=null; chatAttachedImageFile=null; document.getElementById('chat-image-preview').style.display='none'; document.getElementById('chat-image-thumb').src=''; document.getElementById('chat-image-input').value='';}
function boot(){renderFeed(); renderSource(INITIAL_SOURCE_IMAGE); renderAnalysis(); renderAssembler(); renderVariants(); renderCompetitor(); syncStatus();}
document.getElementById('source-image-input').addEventListener('change',function(){const file=this.files&&this.files[0]?this.files[0]:null; if(!file) return; selectedSourceImage=file; const reader=new FileReader(); reader.onload=ev=>renderSource(ev.target?.result||''); reader.readAsDataURL(file); setStatus('',t('select_image_ready','Image selected'),t('select_image_ready_text','Image ready. Click Build from image to run the agent.'));});
document.getElementById('btn-build-from-image').addEventListener('click',buildFromSourceImage);
document.getElementById('btn-regenerate-structure').addEventListener('click',regenerateFromStructure);
document.getElementById('btn-send-message').addEventListener('click',sendMessage);
document.getElementById('btn-remove-chat-image').addEventListener('click',clearChatImage);
document.getElementById('btn-prompt-hero').addEventListener('click',()=>{document.getElementById('chat-input').value=t('chat_prompt_hero','Strengthen the hero section with a stronger offer, clearer value proposition, and sharper CTA.');});
document.getElementById('btn-prompt-cta').addEventListener('click',()=>{document.getElementById('chat-input').value=t('chat_prompt_cta','Improve the copy to be more persuasive and conversion-focused for the Algerian COD market.');});
document.getElementById('btn-prompt-order').addEventListener('click',()=>{document.getElementById('chat-input').value=t('chat_prompt_order','أضف صندوق الطلب بخلفية إسلامية مع CTA واضح وثقة أعلى لسوق الجزائر.');});
// ── Chat image upload handler
document.getElementById('chat-image-input').addEventListener('change',async function(){
  const file=this.files&&this.files[0]?this.files[0]:null;
  if(!file) return;
  chatAttachedImageFile=file;
  // Show local preview immediately
  const reader=new FileReader();
  reader.onload=ev=>{
    document.getElementById('chat-image-thumb').src=ev.target?.result||'';
    document.getElementById('chat-image-preview').style.display='flex';
  };
  reader.readAsDataURL(file);
  appendFeed('system','⏳ '+t('chat_image_uploading','Uploading image…'));
  const fd=new FormData();
  fd.append('_csrf',CSRF_TOKEN);
  fd.append('image',file);
  try{
    const res=await fetch('/admin/ai-landing-pages/upload-image/'+PAGE_ID,{method:'POST',body:fd});
    const data=await readJsonResponse(res);
    if(!data.success) throw new Error(data.error||t('chat_image_upload_failed','Failed to upload image'));
    chatAttachedImageUrl=data.url||data.fullUrl||'';
    appendFeed('system','✅ '+t('chat_image_uploaded','Image uploaded — mention what to do with it in your message.'));
  }catch(err){
    chatAttachedImageFile=null;
    document.getElementById('chat-image-preview').style.display='none';
    appendFeed('assistant','⚠️ '+t('chat_image_upload_failed','Failed to upload image')+': '+err.message);
  }
});
boot();
</script>
</body>
</html>
