<?php
/**
 * AI Landing Pages — Builder (Edit)
 * Full-screen builder: left chat panel + right live preview
 * Rendered standalone (not inside admin layout)
 */

use Core\App\Models\ThemeSettings;

$builderThemeSettings = [];
$builderFontImports   = [];
$builderBodyFont      = '';

try {
    $builderThemeSettings = (new ThemeSettings())->getAll();
} catch (\Throwable $e) {
    $builderThemeSettings = [];
}

$builderAdminTheme = $builderThemeSettings['admin_theme'] ?? [];
$builderAdminFonts = $builderAdminTheme['fonts'] ?? [];
$builderFontMap = [
    'ar_cairo' => [
        'family' => "'Cairo', sans-serif",
        'import' => '/public/assets/fonts/cairo/cairo.css',
    ],
    'ar_tajawal' => [
        'family' => "'Tajawal', sans-serif",
        'import' => '/public/assets/fonts/tajawal/tajawal.css',
    ],
    'ar_noto_kufi' => [
        'family' => "'Noto Kufi Arabic', sans-serif",
        'import' => '/public/assets/fonts/noto-kufi-arabic/noto-kufi-arabic.css',
    ],
    'en_poppins' => [
        'family' => "'Poppins', sans-serif",
        'import' => '/public/assets/fonts/poppins/poppins.css',
    ],
    'en_roboto' => [
        'family' => "'Roboto', sans-serif",
        'import' => '/public/assets/fonts/roboto/roboto.css',
    ],
];

$builderBodyKey = $builderAdminFonts['body'] ?? null;
if ($builderBodyKey && isset($builderFontMap[$builderBodyKey])) {
    $builderFontImports[$builderBodyKey] = $builderFontMap[$builderBodyKey]['import'];
    $builderBodyFont = $builderFontMap[$builderBodyKey]['family'];
}

$pageId       = (int)$page['id'];
$pageName     = htmlspecialchars($page['name'] ?? '');
$pageSlug     = htmlspecialchars($page['slug'] ?? '');
$pageStatus   = $page['status'] ?? 'draft';
$htmlContent  = $page['html_content'] ?? '';
$conversation = $page['conversation'] ?? [];
$productTitle = htmlspecialchars($page['product_title'] ?? ($product['title'] ?? ''));
$hasContent   = trim($htmlContent) !== '';
$sourceImage  = $page['source_image'] ?? '';
$analysisJson = $page['analysis_json'] ?? [];
$structureJson = $page['structure_json'] ?? [];
$agentTrace   = $page['agent_trace'] ?? [];
$sourceMode   = $page['source_mode'] ?? 'manual';
?>
<!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><?= $pageName ?> — <?= __('landing.builder', 'AI Builder') ?></title>

    <!-- AdminLTE / Bootstrap already loaded by header, but we inline here for full-page mode -->
    <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 ($builderFontImports as $builderFontCss): ?>
        <link rel="stylesheet" href="<?= htmlspecialchars($builderFontCss, ENT_QUOTES, 'UTF-8') ?>">
    <?php endforeach; ?>

    <style>
        :root {
            --builder-bg:      #0f1117;
            --builder-panel:   #181c27;
            --builder-border:  #2a2f3f;
            --builder-accent:  #4f7eff;
            --builder-text:    #e4e8f0;
            --builder-muted:   #6b7592;
            --builder-success: #22c55e;
            --toolbar-h:       54px;
            --chat-w:          380px;
        }

        * { box-sizing: border-box; margin: 0; padding: 0; }

        body {
            background: var(--builder-bg);
            color: var(--builder-text);
            height: 100vh;
            overflow: hidden;
            display: flex;
            flex-direction: column;
        }

        <?php if ($builderBodyFont !== ''): ?>
        body,
        button,
        input,
        select,
        textarea {
            font-family: <?= $builderBodyFont ?> !important;
        }
        <?php endif; ?>


        /* ── Toolbar ───────────────────────── */
        #toolbar {
            height: var(--toolbar-h);
            background: var(--builder-panel);
            border-bottom: 1px solid var(--builder-border);
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 0 16px;
            flex-shrink: 0;
            z-index: 100;
        }
        #toolbar .brand { font-weight: 700; font-size: 15px; display: flex; align-items: center; gap: 8px; }
        #toolbar .brand i { color: var(--builder-accent); font-size: 20px; }
        #toolbar .page-info { font-size: 13px; color: var(--builder-muted); margin-inline-start: 8px; }
        #toolbar .page-info strong { color: var(--builder-text); }
        #toolbar .spacer { flex: 1; }
        #toolbar .btn-tool {
            background: rgba(255,255,255,.07);
            border: 1px solid var(--builder-border);
            color: var(--builder-text);
            border-radius: 8px;
            padding: 6px 14px;
            font-size: 13px;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 6px;
            transition: background .15s;
            text-decoration: none;
        }
        #toolbar .btn-tool:hover { background: rgba(255,255,255,.13); }
        #toolbar .btn-publish {
            background: var(--builder-accent);
            border-color: var(--builder-accent);
            color: #fff;
        }
        #toolbar .btn-publish:hover { background: #3a6de8; }
        #toolbar .btn-published {
            background: var(--builder-success);
            border-color: var(--builder-success);
            color: #fff;
        }

        /* ── Main Layout ────────────────────── */
        #builder-body {
            flex: 1;
            display: flex;
            overflow: hidden;
        }

        /* ── Chat Sidebar ───────────────────── */
        #chat-sidebar {
            width: var(--chat-w);
            min-width: 280px;
            max-width: 480px;
            background: var(--builder-panel);
            border-inline-end: 1px solid var(--builder-border);
            display: flex;
            flex-direction: column;
            flex-shrink: 0;
        }

        #chat-header {
            padding: 14px 16px 12px;
            border-bottom: 1px solid var(--builder-border);
            font-size: 13px;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        #chat-header i { color: var(--builder-accent); font-size: 16px; }

        .image-agent-panel {
            padding: 14px 16px;
            border-bottom: 1px solid var(--builder-border);
            display: grid;
            gap: 10px;
            background: linear-gradient(180deg, rgba(79,126,255,.07), rgba(255,255,255,.02));
        }
        .image-agent-title {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 10px;
            font-size: 12.5px;
            color: var(--builder-muted);
        }
        .image-agent-title strong {
            color: var(--builder-text);
            font-size: 13.5px;
        }
        .image-agent-card {
            border: 1px solid var(--builder-border);
            background: rgba(255,255,255,.05);
            border-radius: 12px;
            padding: 12px;
            display: grid;
            gap: 10px;
        }
        .image-agent-drop {
            border: 1px dashed rgba(255,255,255,.2);
            border-radius: 12px;
            padding: 12px;
            display: flex;
            align-items: center;
            gap: 10px;
            color: var(--builder-muted);
        }
        .image-agent-thumb {
            width: 72px;
            height: 72px;
            border-radius: 10px;
            object-fit: cover;
            border: 1px solid var(--builder-border);
            background: rgba(255,255,255,.04);
            display: none;
        }
        .image-agent-actions {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
        }
        .image-agent-btn {
            flex: 1;
            min-width: 140px;
            border-radius: 10px;
            border: 1px solid var(--builder-border);
            background: rgba(255,255,255,.06);
            color: var(--builder-text);
            padding: 9px 12px;
            font-size: 12.5px;
            font-weight: 600;
            cursor: pointer;
        }
        .image-agent-btn.primary {
            background: linear-gradient(135deg, #22c55e, #0ea5e9);
            border-color: transparent;
            color: #fff;
        }
        .analysis-grid {
            display: grid;
            grid-template-columns: repeat(2, minmax(0, 1fr));
            gap: 8px;
        }
        .analysis-stat {
            border-radius: 10px;
            border: 1px solid var(--builder-border);
            background: rgba(255,255,255,.04);
            padding: 10px;
        }
        .analysis-stat .k {
            color: var(--builder-muted);
            font-size: 11px;
            margin-bottom: 4px;
        }
        .analysis-stat .v {
            color: var(--builder-text);
            font-size: 12.5px;
            line-height: 1.5;
        }
        .analysis-list {
            display: flex;
            flex-wrap: wrap;
            gap: 6px;
        }
        .analysis-pill {
            border-radius: 999px;
            padding: 4px 10px;
            font-size: 11px;
            border: 1px solid var(--builder-border);
            background: rgba(255,255,255,.05);
            color: var(--builder-text);
        }
        .workbench-stack {
            display: grid;
            gap: 10px;
        }
        .workbench-card {
            border-radius: 12px;
            border: 1px solid var(--builder-border);
            background: rgba(255,255,255,.04);
            padding: 12px;
            display: grid;
            gap: 8px;
        }
        .workbench-card h4 {
            font-size: 12.5px;
            margin: 0;
            color: var(--builder-text);
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .workbench-card p {
            margin: 0;
            font-size: 12px;
            line-height: 1.55;
            color: var(--builder-muted);
        }
        .workbench-kv {
            display: grid;
            grid-template-columns: repeat(2, minmax(0, 1fr));
            gap: 8px;
        }
        .workbench-kv .item,
        .concept-card,
        .section-row,
        .score-row {
            border-radius: 10px;
            border: 1px solid var(--builder-border);
            background: rgba(255,255,255,.03);
            padding: 9px 10px;
        }
        .workbench-kv .label,
        .section-row .label,
        .score-row .label {
            font-size: 10.5px;
            color: var(--builder-muted);
            text-transform: uppercase;
            letter-spacing: .04em;
            margin-bottom: 4px;
        }
        .workbench-kv .value,
        .section-row .value,
        .score-row .value {
            font-size: 12.5px;
            color: var(--builder-text);
            line-height: 1.5;
        }
        .concepts-grid,
        .sections-stack,
        .score-stack,
        .destination-grid {
            display: grid;
            gap: 8px;
        }
        .concept-card .name {
            font-size: 12.5px;
            font-weight: 700;
            color: var(--builder-text);
            margin-bottom: 4px;
        }
        .concept-card .meta {
            font-size: 11px;
            color: var(--builder-muted);
            margin-bottom: 6px;
        }
        .concept-card .hook {
            font-size: 12px;
            color: var(--builder-text);
            line-height: 1.5;
        }
        .score-grid {
            display: grid;
            grid-template-columns: repeat(3, minmax(0, 1fr));
            gap: 8px;
        }
        .score-box {
            border-radius: 10px;
            border: 1px solid var(--builder-border);
            background: rgba(255,255,255,.03);
            padding: 10px;
            text-align: center;
        }
        .score-box .n {
            font-size: 18px;
            font-weight: 700;
            color: #fff;
        }
        .score-box .t {
            font-size: 10.5px;
            color: var(--builder-muted);
            margin-top: 4px;
            text-transform: uppercase;
            letter-spacing: .04em;
        }
        .assembler-card {
            border-radius: 12px;
            border: 1px solid var(--builder-border);
            background: rgba(255,255,255,.04);
            padding: 12px;
            display: grid;
            gap: 10px;
        }
        .assembler-card h4 {
            margin: 0;
            font-size: 12.5px;
            color: var(--builder-text);
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .assembler-toolbar {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
            align-items: center;
        }
        .assembler-toolbar select,
        .assembler-section input,
        .assembler-section textarea {
            width: 100%;
            background: rgba(255,255,255,.06);
            border: 1px solid var(--builder-border);
            border-radius: 8px;
            color: var(--builder-text);
            padding: 8px 10px;
            font-size: 12.5px;
            outline: none;
        }
        .assembler-toolbar select {
            max-width: 260px;
        }
        .assembler-btn {
            border-radius: 10px;
            border: 1px solid var(--builder-border);
            background: rgba(255,255,255,.06);
            color: var(--builder-text);
            padding: 9px 12px;
            font-size: 12.5px;
            font-weight: 600;
            cursor: pointer;
        }
        .assembler-btn.primary {
            background: linear-gradient(135deg, #f97316, #ef4444);
            border-color: transparent;
            color: #fff;
        }
        .assembler-stack {
            display: grid;
            gap: 8px;
        }
        .assembler-section {
            border-radius: 10px;
            border: 1px solid var(--builder-border);
            background: rgba(255,255,255,.03);
            padding: 10px;
            display: grid;
            gap: 8px;
        }
        .assembler-section-head {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 10px;
        }
        .assembler-section-title {
            font-size: 12.5px;
            font-weight: 700;
            color: var(--builder-text);
        }
        .assembler-checkbox {
            display: flex;
            align-items: center;
            gap: 6px;
            color: var(--builder-muted);
            font-size: 11.5px;
        }
        .assembler-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 8px;
        }
        .variants-card,
        .competitor-card {
            border-radius: 12px;
            border: 1px solid var(--builder-border);
            background: rgba(255,255,255,.04);
            padding: 12px;
            display: grid;
            gap: 10px;
        }
        .variants-grid {
            display: grid;
            gap: 8px;
        }
        .variant-card {
            border-radius: 10px;
            border: 1px solid var(--builder-border);
            background: rgba(255,255,255,.03);
            padding: 10px;
            display: grid;
            gap: 6px;
        }
        .variant-card .top {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 10px;
        }
        .variant-card .name {
            color: var(--builder-text);
            font-size: 12.5px;
            font-weight: 700;
        }
        .variant-card .meta {
            color: var(--builder-muted);
            font-size: 11px;
        }
        .mini-badge {
            border-radius: 999px;
            padding: 3px 8px;
            border: 1px solid var(--builder-border);
            background: rgba(255,255,255,.05);
            color: var(--builder-text);
            font-size: 10.5px;
        }
        .competitor-toolbar {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
        }
        .competitor-toolbar input {
            flex: 1;
            min-width: 260px;
            background: rgba(255,255,255,.06);
            border: 1px solid var(--builder-border);
            border-radius: 8px;
            color: var(--builder-text);
            padding: 8px 10px;
            font-size: 12.5px;
            outline: none;
        }

        #chat-messages {
            flex: 1;
            overflow-y: auto;
            padding: 12px;
            display: flex;
            flex-direction: column;
            gap: 10px;
        }

        .chat-msg {
            max-width: 92%;
            padding: 10px 14px;
            border-radius: 12px;
            font-size: 13.5px;
            line-height: 1.55;
            word-break: break-word;
        }
        .chat-msg.user {
            background: var(--builder-accent);
            color: #fff;
            align-self: flex-end;
            border-bottom-inline-end-radius: 4px;
        }
        .chat-msg.assistant {
            background: rgba(255,255,255,.07);
            color: var(--builder-text);
            align-self: flex-start;
            border-bottom-inline-start-radius: 4px;
        }
        .chat-msg.system-hint {
            background: transparent;
            border: 1px dashed var(--builder-border);
            color: var(--builder-muted);
            font-size: 12px;
            align-self: center;
            text-align: center;
        }

        #chat-input-area {
            padding: 12px;
            border-top: 1px solid var(--builder-border);
        }
        #chat-input {
            width: 100%;
            background: rgba(255,255,255,.06);
            border: 1px solid var(--builder-border);
            color: var(--builder-text);
            border-radius: 10px;
            padding: 10px 14px;
            font-size: 13.5px;
            resize: none;
            min-height: 80px;
            max-height: 180px;
            line-height: 1.5;
            outline: none;
            transition: border-color .15s;
        }
        #chat-input:focus { border-color: var(--builder-accent); }
        #chat-input::placeholder { color: var(--builder-muted); }

        .chat-actions {
            display: flex;
            gap: 8px;
            margin-top: 8px;
            align-items: center;
        }
        #btn-generate {
            flex: 1;
            background: linear-gradient(135deg, var(--builder-accent), #7c4fff);
            border: none;
            color: #fff;
            border-radius: 8px;
            padding: 9px 16px;
            font-size: 13.5px;
            font-weight: 600;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 7px;
            transition: opacity .15s;
        }
        #btn-generate:disabled { opacity: .55; cursor: not-allowed; }
        #btn-generate .spinner {
            width: 16px; height: 16px;
            border: 2px solid rgba(255,255,255,.35);
            border-top-color: #fff;
            border-radius: 50%;
            animation: spin .7s linear infinite;
            display: none;
        }
        #btn-generate.loading .spinner { display: inline-block; }
        #btn-generate.loading .label { display: none; }

        @keyframes spin { to { transform: rotate(360deg); } }

        .quick-prompts {
            display: flex;
            flex-wrap: wrap;
            gap: 5px;
            margin-top: 8px;
        }
        .quick-prompt-btn {
            background: rgba(255,255,255,.05);
            border: 1px solid var(--builder-border);
            color: var(--builder-muted);
            border-radius: 20px;
            padding: 3px 10px;
            font-size: 11.5px;
            cursor: pointer;
            transition: all .15s;
        }
        .quick-prompt-btn:hover {
            background: rgba(79,126,255,.15);
            border-color: var(--builder-accent);
            color: var(--builder-text);
        }

        /* ── Preview Area ───────────────────── */
        #preview-area {
            flex: 1;
            display: flex;
            flex-direction: column;
            overflow: hidden;
            background: #1a1d27;
        }
        #preview-toolbar {
            height: 40px;
            background: rgba(255,255,255,.04);
            border-bottom: 1px solid var(--builder-border);
            display: flex;
            align-items: center;
            padding: 0 12px;
            gap: 8px;
            font-size: 12px;
            color: var(--builder-muted);
            flex-shrink: 0;
        }
        #preview-toolbar .preview-url {
            flex: 1;
            background: rgba(255,255,255,.06);
            border: 1px solid var(--builder-border);
            border-radius: 6px;
            padding: 3px 10px;
            font-size: 12px;
            color: var(--builder-muted);
        }
        #preview-frame {
            flex: 1;
            border: none;
            background: #fff;
        }
        #preview-empty {
            flex: 1;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            color: var(--builder-muted);
            gap: 14px;
        }
        #preview-empty i { font-size: 3.5rem; opacity: .25; }
        #preview-empty p { font-size: 14px; }

        /* ── Meta Form (collapsible) ─────────── */
        #meta-form-wrap {
            background: var(--builder-panel);
            border-top: 1px solid var(--builder-border);
        }
        #meta-toggle-btn {
            width: 100%;
            background: none;
            border: none;
            color: var(--builder-muted);
            font-size: 12px;
            padding: 8px 16px;
            cursor: pointer;
            text-align: start;
            display: flex;
            align-items: center;
            gap: 6px;
        }
        #meta-toggle-btn:hover { color: var(--builder-text); }
        #meta-form {
            padding: 12px 16px 14px;
            border-top: 1px solid var(--builder-border);
            display: none;
        }
        #meta-form.open { display: block; }
        .meta-row { display: flex; gap: 8px; align-items: center; margin-bottom: 8px; }
        .meta-row label { font-size: 12px; color: var(--builder-muted); min-width: 70px; }
        .meta-row input,
        .meta-row select {
            flex: 1;
            background: rgba(255,255,255,.06);
            border: 1px solid var(--builder-border);
            color: var(--builder-text);
            border-radius: 6px;
            padding: 5px 10px;
            font-size: 12.5px;
            outline: none;
        }
        .meta-row input:focus, .meta-row select:focus { border-color: var(--builder-accent); }
        .meta-row select option { background: #1e2330; }

        /* ── Resize handle (chat width drag) ── */
        #resize-handle {
            width: 5px;
            background: transparent;
            cursor: col-resize;
            flex-shrink: 0;
            transition: background .15s;
            position: relative;
            z-index: 10;
        }
        #resize-handle:hover, #resize-handle.dragging { background: var(--builder-accent); }

        /* Flash */
        #flash-msg {
            position: fixed;
            bottom: 20px;
            inset-inline-end: 20px;
            background: var(--builder-success);
            color: #fff;
            border-radius: 8px;
            padding: 10px 18px;
            font-size: 13px;
            font-weight: 600;
            display: none;
            z-index: 9999;
            box-shadow: 0 4px 20px rgba(0,0,0,.4);
        }

        .command-center-hero {
            margin: 16px 16px 0;
            padding: 18px;
            border-radius: 18px;
            border: 1px solid rgba(255,255,255,.08);
            background:
                radial-gradient(circle at top left, rgba(34,197,94,.18), transparent 35%),
                radial-gradient(circle at top right, rgba(14,165,233,.18), transparent 32%),
                linear-gradient(145deg, rgba(15,23,42,.98), rgba(17,24,39,.92));
            display: grid;
            gap: 14px;
            box-shadow: 0 14px 42px rgba(2,6,23,.22);
        }
        .command-center-copy .eyebrow {
            font-size: 11px;
            letter-spacing: .08em;
            text-transform: uppercase;
            color: #7dd3fc;
            margin-bottom: 8px;
            font-weight: 700;
        }
        .command-center-copy h2 {
            margin: 0 0 8px;
            font-size: 24px;
            line-height: 1.45;
            color: #fff;
        }
        .command-center-copy p {
            margin: 0;
            color: rgba(255,255,255,.72);
            font-size: 13px;
            line-height: 1.8;
        }
        .command-center-steps {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
        }
        .command-center-steps span {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 8px 12px;
            border-radius: 999px;
            border: 1px solid rgba(255,255,255,.09);
            background: rgba(255,255,255,.06);
            color: #e5eefb;
            font-size: 12px;
            font-weight: 600;
        }
        .image-agent-panel {
            padding: 16px;
            gap: 14px;
            background: linear-gradient(180deg, rgba(248,250,252,.98), rgba(241,245,249,.94));
            border-bottom: 1px solid #e5e7eb;
        }
        .image-agent-title {
            padding: 0 2px;
            color: #475569;
        }
        .image-agent-title strong {
            color: #0f172a;
            font-size: 16px;
        }
        .image-agent-card {
            background: linear-gradient(180deg, #ffffff, #f8fafc);
            border: 1px solid #dbe3ef;
            border-radius: 18px;
            padding: 16px;
            box-shadow: 0 10px 30px rgba(15,23,42,.06);
            gap: 14px;
        }
        .image-agent-drop {
            border: 1px dashed #cbd5e1;
            background: #f8fafc;
            color: #475569;
            padding: 14px;
        }
        .image-agent-actions {
            display: grid;
            grid-template-columns: repeat(2, minmax(0, 1fr));
            gap: 10px;
        }
        .image-agent-btn {
            min-width: auto;
            flex: initial;
            border: 1px solid #d6deea;
            background: #fff;
            color: #0f172a;
            font-weight: 700;
            box-shadow: 0 8px 16px rgba(15,23,42,.04);
        }
        .image-agent-btn.primary {
            background: linear-gradient(135deg, #f97316, #ea580c);
            color: #fff;
            box-shadow: 0 14px 30px rgba(249,115,22,.28);
        }
        .pipeline-status {
            border-radius: 14px;
            border: 1px solid #dbeafe;
            background: linear-gradient(180deg, #eff6ff, #f8fbff);
            padding: 12px 14px;
            display: grid;
            gap: 6px;
        }
        .pipeline-status.success {
            border-color: #bbf7d0;
            background: linear-gradient(180deg, #f0fdf4, #f7fee7);
        }
        .pipeline-status.error {
            border-color: #fecaca;
            background: linear-gradient(180deg, #fef2f2, #fff7f7);
        }
        .pipeline-status .kicker {
            font-size: 11px;
            font-weight: 800;
            letter-spacing: .08em;
            text-transform: uppercase;
            color: #2563eb;
        }
        .pipeline-status.success .kicker { color: #15803d; }
        .pipeline-status.error .kicker { color: #dc2626; }
        .pipeline-status .message {
            font-size: 13px;
            line-height: 1.8;
            color: #0f172a;
        }
        .activity-header {
            display: flex;
            align-items: flex-start;
            justify-content: space-between;
            gap: 12px;
            padding: 16px 16px 10px;
            border-top: 1px solid #eef2f7;
            background: linear-gradient(180deg, #fff, #fcfdff);
        }
        .activity-header strong {
            display: block;
            margin-bottom: 4px;
            font-size: 15px;
            color: #0f172a;
        }
        .activity-header p {
            margin: 0;
            font-size: 12px;
            line-height: 1.7;
            color: #64748b;
        }
        .activity-badge {
            display: inline-flex;
            align-items: center;
            padding: 7px 10px;
            border-radius: 999px;
            background: #eff6ff;
            color: #1d4ed8;
            font-size: 11px;
            font-weight: 800;
            border: 1px solid #bfdbfe;
        }
        #chat-messages {
            min-height: 290px;
            max-height: 420px;
            background:
                linear-gradient(180deg, rgba(248,250,252,.95), rgba(255,255,255,.98));
            border-top: 1px solid #eef2f7;
            border-bottom: 1px solid #eef2f7;
            padding: 16px;
            gap: 12px;
        }
        .chat-msg {
            max-width: calc(100% - 16px);
            padding: 14px 16px;
            border-radius: 16px;
            font-size: 13px;
            line-height: 1.9;
            box-shadow: 0 10px 22px rgba(15,23,42,.05);
            white-space: pre-wrap;
        }
        .chat-msg.user {
            background: linear-gradient(135deg, #f97316, #fb923c);
            color: #fff;
            border-bottom-inline-end-radius: 6px;
        }
        .chat-msg.assistant {
            background: #ffffff;
            color: #0f172a;
            border: 1px solid #dbe3ef;
            border-bottom-inline-start-radius: 6px;
        }
        .chat-msg.system-hint {
            background: linear-gradient(180deg, #eff6ff, #f8fbff);
            border: 1px dashed #bfdbfe;
            color: #1e3a8a;
        }
        #chat-input-area {
            padding: 16px;
            background: #fff;
            border-top: 1px solid #eef2f7;
        }
        #chat-input {
            min-height: 110px;
            border-radius: 16px;
            border: 1px solid #dbe3ef;
            background: #f8fafc;
            color: #0f172a;
            line-height: 1.9;
            box-shadow: inset 0 1px 2px rgba(15,23,42,.03);
        }
        .quick-prompts {
            gap: 8px;
            padding-top: 8px;
        }
        .quick-prompt-btn {
            border-radius: 999px;
            border: 1px solid #dbe3ef;
            background: #fff;
            color: #334155;
            font-weight: 700;
        }
        .workbench-card,
        .assembler-card,
        .variants-card,
        .competitor-card {
            border-radius: 18px;
            border: 1px solid #dbe3ef;
            background: #fff;
            box-shadow: 0 10px 24px rgba(15,23,42,.05);
        }
        .analysis-grid,
        .workbench-grid,
        .assembler-grid,
        .variants-grid {
            gap: 12px;
        }
        #preview-area {
            background:
                radial-gradient(circle at top right, rgba(249,115,22,.08), transparent 24%),
                linear-gradient(180deg, #f8fafc, #eef2f7);
        }
        #preview-toolbar {
            background: rgba(255,255,255,.88);
            backdrop-filter: blur(10px);
            border-bottom: 1px solid #e5e7eb;
            color: #0f172a;
        }
        #preview-empty {
            background: linear-gradient(180deg, rgba(255,255,255,.92), rgba(248,250,252,.98));
            border: 1px dashed #cbd5e1;
            box-shadow: 0 18px 40px rgba(15,23,42,.07);
        }
        @media (max-width: 1200px) {
            .image-agent-actions {
                grid-template-columns: 1fr;
            }
            #chat-messages {
                max-height: none;
                min-height: 220px;
            }
        }
    </style>
</head>
<body>

<!-- ═══ TOOLBAR ═══════════════════════════════════════════════════════════ -->
<div id="toolbar">
    <div class="brand">
        <i class="bi bi-stars"></i>
        <?= __('landing.builder', 'AI Builder') ?>
    </div>
    <div class="page-info">
        <strong><?= $pageName ?></strong>
        <?php if ($productTitle): ?>
        <span class="mx-1">·</span>
        <span><?= $productTitle ?></span>
        <?php endif; ?>
    </div>
    <div class="spacer"></div>

    <a href="/admin/ai-landing-pages/preview/<?= $pageId ?>"
       target="_blank"
       class="btn-tool"
       id="btn-preview-new-tab">
        <i class="bi bi-eye"></i>
        <?= __('landing.preview', 'Preview') ?>
    </a>

    <button class="btn-tool <?= $pageStatus === 'published' ? 'btn-published' : 'btn-publish' ?>"
            id="btn-toggle-status"
            data-status="<?= $pageStatus ?>"
            data-id="<?= $pageId ?>">
        <i class="bi bi-<?= $pageStatus === 'published' ? 'globe2' : 'send' ?>"></i>
        <span id="status-label">
            <?= $pageStatus === 'published' ? __('landing.published', 'Published') : __('landing.publish', 'Publish') ?>
        </span>
    </button>

    <a href="/admin/ai-landing-pages" class="btn-tool">
        <i class="bi bi-arrow-left"></i>
        <?= __('actions.back', 'Back') ?>
    </a>
</div>

<!-- ═══ MAIN BODY ═════════════════════════════════════════════════════════ -->
<div id="builder-body">

    <!-- ── Chat Sidebar ─── -->
    <div id="chat-sidebar">

        <!-- Chat header -->
        <div id="chat-header">
            <i class="bi bi-chat-dots-fill"></i>
            <?= __('landing.ai_chat', 'AI Conversation') ?>
        </div>

        <div class="command-center-hero">
            <div class="command-center-copy">
                <div class="eyebrow"><?= __('landing.command_center_eyebrow', 'AI Landing Command Center') ?></div>
                <h2><?= __('landing.command_center_title', 'حوّل الصورة إلى صفحة هبوط احترافية قابلة للنشر') ?></h2>
                <p><?= __('landing.command_center_subtitle', 'ابدأ بتحليل الصورة، ثم راجع المفاهيم والأقسام والنسخ البديلة من شاشة واحدة واضحة وراقية.') ?></p>
            </div>
            <div class="command-center-steps">
                <span><?= __('landing.pipeline_analyze', '1. Analyze') ?></span>
                <span><?= __('landing.pipeline_structure', '2. Structure') ?></span>
                <span><?= __('landing.pipeline_assemble', '3. Assemble') ?></span>
                <span><?= __('landing.pipeline_variants', '4. Variants') ?></span>
                <span><?= __('landing.pipeline_publish', '5. Publish') ?></span>
            </div>
        </div>

        <div class="image-agent-panel">
            <div class="image-agent-title">
                <strong><?= __('landing.image_agent_title', 'AI Image-to-Landing Agent') ?></strong>
                <span><?= __('landing.image_agent_subtitle', 'Plan → Generate → Evaluate → Improve') ?></span>
            </div>
            <div class="image-agent-card">
                <div class="image-agent-drop">
                    <img id="source-image-thumb" class="image-agent-thumb" alt="Source image preview">
                    <div style="flex:1">
                        <div class="fw-semibold mb-1"><?= __('landing.image_agent_upload', 'Upload screenshot or design') ?></div>
                        <div class="small"><?= __('landing.image_agent_hint', 'The AI agent will extract layout, sections, CTA, colors, then generate a full landing page.') ?></div>
                    </div>
                    <label class="btn-tool" style="cursor:pointer">
                        <i class="bi bi-upload"></i>
                        <?= __('landing.choose_image', 'Choose Image') ?>
                        <input type="file" id="source-image-input" accept="image/*" style="display:none">
                    </label>
                </div>
                <div class="image-agent-actions">
                    <button type="button" class="image-agent-btn primary" id="btn-build-from-image">
                        <i class="bi bi-stars me-1"></i><?= __('landing.build_from_image', 'Build From Image') ?>
                    </button>
                    <button type="button" class="image-agent-btn" id="btn-regenerate-structure">
                        <i class="bi bi-arrow-repeat me-1"></i><?= __('landing.regenerate_from_structure', 'Regenerate') ?>
                    </button>
                </div>
                <div id="pipeline-status" class="pipeline-status" style="display:none"></div>
                <div id="analysis-summary"></div>
                <div id="agent-workbench" class="workbench-stack"></div>
                <div id="agent-assembler" class="assembler-card" style="display:none"></div>
                <div id="agent-variants" class="variants-card" style="display:none"></div>
                <div id="competitor-analysis-card" class="competitor-card"></div>
            </div>
        </div>

        <!-- Chat messages -->
        <div class="activity-header">
            <div>
                <strong><?= __('landing.activity_title', 'AI Activity & Reports') ?></strong>
                <p><?= __('landing.activity_subtitle', 'هنا ستظهر رسائل التحليل، الأخطاء، التحديثات، ونتائج الذكاء الاصطناعي بوضوح.') ?></p>
            </div>
            <span class="activity-badge"><?= __('landing.live_feed', 'Live Feed') ?></span>
        </div>
        <div id="chat-messages">
            <?php if (empty($conversation)): ?>
            <div class="chat-msg system-hint">
                <?= __('landing.chat_hint', 'Describe what you want. The AI will build or update the landing page.') ?>
            </div>
            <?php else: ?>
                <?php foreach ($conversation as $msg): ?>
                    <?php
                    $role    = $msg['role'] ?? 'user';
                    $content = htmlspecialchars($msg['content'] ?? '');
                    ?>
                    <div class="chat-msg <?= $role === 'user' ? 'user' : 'assistant' ?>">
                        <?= nl2br($content) ?>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>

        <!-- Meta form (collapsible) -->
        <div id="meta-form-wrap">
            <button id="meta-toggle-btn" onclick="toggleMetaForm()">
                <i class="bi bi-sliders"></i>
                <?= __('landing.page_settings', 'Page Settings') ?>
                <i class="bi bi-chevron-down ms-auto" id="meta-chevron"></i>
            </button>
            <div id="meta-form">
                <form id="form-meta" method="post" action="/admin/ai-landing-pages/update/<?= $pageId ?>">
                    <?= \Core\System\Csrf::field() ?>
                    <input type="hidden" name="product_id" value="<?= (int)$page['product_id'] ?>">

                    <div class="meta-row">
                        <label><?= __('landing.name', 'Name') ?></label>
                        <input type="text" name="name" value="<?= $pageName ?>">
                    </div>
                    <div class="meta-row">
                        <label><?= __('landing.slug', 'Slug') ?></label>
                        <input type="text" name="slug" value="<?= $pageSlug ?>">
                    </div>
                    <div class="meta-row">
                        <label><?= __('landing.status', 'Status') ?></label>
                        <select name="status" id="meta-status">
                            <option value="draft"     <?= $pageStatus === 'draft'     ? 'selected' : '' ?>>Draft</option>
                            <option value="published" <?= $pageStatus === 'published' ? 'selected' : '' ?>>Published</option>
                        </select>
                    </div>
                    <button type="submit" class="btn-tool mt-2" style="font-size:12px;padding:6px 12px">
                        <i class="bi bi-check2"></i>
                        <?= __('actions.save', 'Save Settings') ?>
                    </button>
                </form>
            </div>
        </div>

        <!-- Chat input -->
        <div id="chat-input-area">

            <!-- Image upload preview strip -->
            <div id="img-preview-strip" style="display:none;gap:6px;flex-wrap:wrap;padding:6px 0 4px;border-bottom:1px solid var(--builder-border);margin-bottom:6px;"></div>

            <textarea id="chat-input"
                      placeholder="<?= __('landing.chat_placeholder', "Describe what you want...\ne.g. Add a testimonials section with 3 reviews") ?>"></textarea>

            <div class="chat-actions">
                <!-- Image upload button (like claude.ai) -->
                <label for="img-upload-input"
                       class="btn-tool"
                       style="padding:7px 10px;cursor:pointer;"
                       title="<?= __('landing.upload_image', 'Attach image') ?>">
                    <i class="bi bi-image"></i>
                    <input type="file" id="img-upload-input" accept="image/*" multiple
                           style="display:none" onchange="handleImageUpload(this)">
                </label>

                <!-- Import HTML from URL -->
                <button onclick="showImportPanel()" class="btn-tool" style="padding:7px 10px;"
                        title="<?= __('landing.import_html', 'Import HTML') ?>">
                    <i class="bi bi-box-arrow-in-down"></i>
                </button>

                <button id="btn-generate" onclick="sendMessage()">
                    <span class="spinner"></span>
                    <span class="label">
                        <i class="bi bi-stars"></i>
                        <?= __('landing.generate', 'Generate') ?>
                    </span>
                </button>
            </div>

            <!-- HTML Import Panel -->
            <div id="import-panel" style="display:none;background:rgba(255,255,255,.05);border:1px solid var(--builder-border);border-radius:8px;padding:10px;margin-top:8px;">
                <div style="font-size:12px;color:var(--builder-muted);margin-bottom:6px;">
                    <i class="bi bi-info-circle me-1"></i>
                    <?= __('landing.import_hint', 'Paste a URL (e.g. from just.ad) or paste HTML directly') ?>
                </div>
                <input type="text" id="import-url-input"
                       placeholder="https://just.ad/... <?= __('landing.or', 'or paste URL') ?>"
                       style="width:100%;background:rgba(255,255,255,.08);border:1px solid var(--builder-border);color:var(--builder-text);border-radius:6px;padding:6px 10px;font-size:12px;margin-bottom:6px;">
                <textarea id="import-html-input"
                          placeholder="<?= __('landing.paste_html', 'Or paste HTML directly here...') ?>"
                          rows="3"
                          style="width:100%;background:rgba(255,255,255,.08);border:1px solid var(--builder-border);color:var(--builder-text);border-radius:6px;padding:6px 10px;font-size:12px;resize:vertical;margin-bottom:6px;"></textarea>
                <div style="display:flex;gap:6px;">
                    <button onclick="doImportHtml()" class="btn-tool" style="flex:1;justify-content:center;font-size:12px;">
                        <i class="bi bi-download me-1"></i><?= __('landing.import', 'Import') ?>
                    </button>
                    <button onclick="document.getElementById('import-panel').style.display='none'" class="btn-tool" style="font-size:12px;">
                        <?= __('actions.cancel', 'Cancel') ?>
                    </button>
                </div>
            </div>

            <!-- Quick prompts -->
            <div class="quick-prompts">
                <button class="quick-prompt-btn" onclick="setPrompt('Generate a complete high-converting landing page for this product')">
                    <?= __('landing.qp_generate', '✨ Generate Full Page') ?>
                </button>
                <button class="quick-prompt-btn" onclick="setPrompt('Make the hero section more powerful with a strong headline and clear value proposition')">
                    <?= __('landing.qp_hero', '🚀 Strengthen Hero') ?>
                </button>
                <button class="quick-prompt-btn" onclick="setPrompt('Add a FAQ section with 5 common questions and answers about this product')">
                    <?= __('landing.qp_faq', '❓ Add FAQ') ?>
                </button>
                <button class="quick-prompt-btn" onclick="setPrompt('Add testimonials section with 3 customer reviews with names and ratings')">
                    <?= __('landing.qp_testimonials', '⭐ Add Testimonials') ?>
                </button>
                <button class="quick-prompt-btn" onclick="setPrompt('Add a product features and benefits section with icons')">
                    <?= __('landing.qp_features', '✅ Add Features') ?>
                </button>
                <button class="quick-prompt-btn" onclick="setPrompt('Add urgency elements: countdown timer, limited stock badge, and a strong CTA button')">
                    <?= __('landing.qp_urgency', '⏰ Add Urgency') ?>
                </button>
                <button class="quick-prompt-btn" onclick="setPrompt('Improve the copy to be more persuasive and conversion-focused')">
                    <?= __('landing.qp_copy', '✍️ Improve Copy') ?>
                </button>
                <button class="quick-prompt-btn" onclick="setPrompt('Make the design more modern and professional with better typography and spacing')">
                    <?= __('landing.qp_design', '🎨 Improve Design') ?>
                </button>
                <button class="quick-prompt-btn" onclick="setPrompt('Add a complete order form box (صندوق الطلب) connected to the store — embed it using the iframe with real order form. Match the colors and theme of the current page design.')">
                    <?= __('landing.qp_orderbox', '🛒 Add Order Box') ?>
                </button>
                <button class="quick-prompt-btn" onclick="showImportPanel()">
                    <?= __('landing.qp_import', '📥 Import HTML') ?>
                </button>
            </div>
        </div>
    </div>

    <!-- ── Resize Handle ─── -->
    <div id="resize-handle"></div>

    <!-- ── Preview Area ─── -->
    <div id="preview-area">
        <div id="preview-toolbar">
            <i class="bi bi-display"></i>
            <span><?= __('landing.live_preview', 'Live Preview') ?></span>
            <div class="spacer"></div>
            <?php if ($hasContent): ?>
            <span class="preview-url">/lp/<?= $pageSlug ?></span>
            <?php endif; ?>
        </div>

        <?php if ($hasContent): ?>
        <iframe id="preview-frame"
                src="/admin/ai-landing-pages/preview/<?= $pageId ?>"
                title="Landing Page Preview"
                sandbox="allow-scripts allow-forms allow-popups">
        </iframe>
        <?php else: ?>
        <div id="preview-empty">
            <i class="bi bi-layout-text-sidebar-reverse"></i>
            <p><?= __('landing.preview_empty', 'Start a conversation to generate your landing page') ?></p>
            <button class="btn-tool" onclick="document.getElementById('chat-input').focus()">
                <i class="bi bi-chat-dots"></i>
                <?= __('landing.start_chat', 'Start Building') ?>
            </button>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- Flash message -->
<div id="flash-msg"></div>

<script>
const PAGE_ID      = <?= $pageId ?>;
const CSRF_TOKEN   = '<?= htmlspecialchars(\Core\System\Csrf::token()) ?>';
const INITIAL_SOURCE_IMAGE = <?= json_encode($sourceImage) ?>;
const INITIAL_ANALYSIS = <?= json_encode($analysisJson, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
const INITIAL_STRUCTURE = <?= json_encode($structureJson, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
const INITIAL_AGENT = <?= json_encode($agentTrace, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
const INITIAL_SOURCE_MODE = <?= json_encode($sourceMode) ?>;
let selectedSourceImage = null;
let workbenchState = {
    analysis: INITIAL_ANALYSIS || {},
    structure: INITIAL_STRUCTURE || {},
    agent: INITIAL_AGENT || {},
    variants: Array.isArray(INITIAL_AGENT?.variants) ? INITIAL_AGENT.variants : [],
    competitor: INITIAL_AGENT?.competitor_analysis || {},
};

function setPipelineStatus(type, message, kicker) {
    const box = document.getElementById('pipeline-status');
    if (!box) return;
    if (!message) {
        box.style.display = 'none';
        box.innerHTML = '';
        return;
    }
    box.className = 'pipeline-status ' + (type || 'info');
    box.style.display = 'grid';
    box.innerHTML = `
        <div class="kicker">${escapeHtml(kicker || 'Status')}</div>
        <div class="message">${escapeHtml(message)}</div>
    `;
}

function syncPipelineStatusFromState() {
    const sections = Array.isArray(workbenchState?.structure?.sections) ? workbenchState.structure.sections : [];
    const fallbackUsed = Array.isArray(workbenchState?.analysis?.conversion_notes)
        && workbenchState.analysis.conversion_notes.some(note => String(note).toLowerCase().indexOf('fallback analysis used') !== -1);

    if (sections.length) {
        setPipelineStatus(
            fallbackUsed ? 'info' : 'success',
            fallbackUsed
                ? '<?= __('landing.pipeline_status_fallback', 'تم توليد structure احتياطي صالح ويمكنك الآن تحسينه أو إعادة التوليد من نفس الصورة.') ?>'
                : '<?= __('landing.pipeline_status_ready', 'تم تحليل الصورة وبناء الـ structure بنجاح. يمكنك الآن التجميع أو التوليد أو إنشاء variants.') ?>',
            fallbackUsed
                ? '<?= __('landing.pipeline_status_fallback_label', 'Fallback Ready') ?>'
                : '<?= __('landing.pipeline_status_ready_label', 'Structure Ready') ?>'
        );
        return;
    }

    if (INITIAL_SOURCE_MODE === 'image' || INITIAL_SOURCE_IMAGE) {
        setPipelineStatus(
            'info',
            '<?= __('landing.pipeline_status_waiting', 'الصورة محفوظة، لكن لم يتم بناء structure بعد. اضغط "Build From Image" لبدء التحليل.') ?>',
            '<?= __('landing.pipeline_status_waiting_label', 'Waiting For Analysis') ?>'
        );
        return;
    }

    setPipelineStatus(
        'info',
        '<?= __('landing.pipeline_status_upload', 'ابدأ باختيار منتج وصورة مرجعية أو Screenshot لصفحة منافس، ثم شغّل التحليل من هنا.') ?>',
        '<?= __('landing.pipeline_status_upload_label', 'Upload A Source') ?>'
    );
}

/* ── Send message to AI ──────────────────────────────────────── */
async function sendMessage() {
    const input   = document.getElementById('chat-input');
    const message = input.value.trim();
    if (!message && !uploadedImages.length) return;

    const btn = document.getElementById('btn-generate');
    btn.disabled = true;
    btn.classList.add('loading');

    // Build display message with image indicators
    let displayMsg = message;
    if (uploadedImages.length) {
        displayMsg += (displayMsg ? '\n' : '') + uploadedImages.map(i => `🖼️ ${i.name}`).join('\n');
    }
    appendMessage('user', displayMsg);
    input.value = '';

    // Build full message with image URLs for AI context
    let fullMessage = message;
    if (uploadedImages.length) {
        fullMessage += '\n\n[Images attached for reference — use these URLs in the landing page HTML:]\n';
        fullMessage += uploadedImages.map(i => i.fullUrl).join('\n');
    }

    try {
        const fd = new FormData();
        fd.append('_csrf',   CSRF_TOKEN);
        fd.append('message', fullMessage);

        const res  = await fetch(`/admin/ai-landing-pages/generate/${PAGE_ID}`, {
            method: 'POST',
            body:   fd,
        });
        const data = await res.json();

        if (data.success) {
            appendMessage('assistant', '<?= __('landing.ai_updated', 'I\'ve updated the landing page based on your request.') ?>');
            updatePreview(data.html);
            showFlash('<?= __('landing.generated', 'Page updated!') ?>');
            // Clear uploaded images after sending
            uploadedImages.length = 0;
            document.getElementById('img-preview-strip').style.display = 'none';
            document.getElementById('img-preview-strip').innerHTML = '';
        } else {
            appendMessage('assistant', '⚠️ ' + (data.error || 'Unknown error'));
        }
    } catch (e) {
        appendMessage('assistant', '⚠️ Network error: ' + e.message);
    } finally {
        btn.disabled = false;
        btn.classList.remove('loading');
    }
}

/* ── Append chat bubble ──────────────────────────────────────── */
function appendMessage(role, content) {
    const msgs = document.getElementById('chat-messages');
    // Remove hint if present
    const hint = msgs.querySelector('.system-hint');
    if (hint) hint.remove();

    const div = document.createElement('div');
    div.className = 'chat-msg ' + role;
    const meta = document.createElement('div');
    meta.style.fontSize = '10px';
    meta.style.fontWeight = '800';
    meta.style.marginBottom = '6px';
    meta.style.opacity = '.72';
    meta.textContent = role === 'user'
        ? '<?= __('landing.message_user', 'You') ?>'
        : '<?= __('landing.message_ai', 'AI Agent') ?>';

    const body = document.createElement('div');
    body.textContent = content;

    div.appendChild(meta);
    div.appendChild(body);
    msgs.appendChild(div);
    msgs.scrollTop = msgs.scrollHeight;
}

/* ── Update iframe preview ───────────────────────────────────── */
// Load preview from server endpoint to avoid allow-same-origin in sandbox
function updatePreview(html) {
    const emptyDiv = document.getElementById('preview-empty');
    if (emptyDiv) emptyDiv.remove();

    let frame = document.getElementById('preview-frame');
    if (!frame) {
        frame = document.createElement('iframe');
        frame.id        = 'preview-frame';
        frame.title     = 'Landing Page Preview';
        // allow-same-origin removed — iframe loaded via src from server
        frame.sandbox   = 'allow-scripts allow-forms allow-popups';
        frame.style.cssText = 'flex:1;border:none;background:#fff;';
        document.getElementById('preview-area').appendChild(frame);
    }

    // Reload from server preview endpoint (which serves the sanitized, styled page)
    frame.src = '/admin/ai-landing-pages/preview/' + PAGE_ID + '?v=' + Date.now();
}

/* ── Quick prompt ────────────────────────────────────────────── */
function setPrompt(text) {
    document.getElementById('chat-input').value = text;
    document.getElementById('chat-input').focus();
}

/* ── Toggle status ───────────────────────────────────────────── */
document.getElementById('btn-toggle-status').addEventListener('click', async function () {
    const current   = this.dataset.status;
    const newStatus = current === 'published' ? 'draft' : 'published';

    const fd = new FormData();
    fd.append('_csrf',      CSRF_TOKEN);
    fd.append('product_id', '<?= (int)$page['product_id'] ?>');
    fd.append('name',       '<?= addslashes($pageName) ?>');
    fd.append('slug',       '<?= addslashes($pageSlug) ?>');
    fd.append('status',     newStatus);

    try {
        await fetch(`/admin/ai-landing-pages/update/${PAGE_ID}`, {
            method: 'POST',
            body:   fd,
        });
        this.dataset.status = newStatus;
        document.getElementById('status-label').textContent =
            newStatus === 'published' ? '<?= __('landing.published', 'Published') ?>' : '<?= __('landing.publish', 'Publish') ?>';
        this.classList.toggle('btn-publish',    newStatus === 'draft');
        this.classList.toggle('btn-published',  newStatus === 'published');
        document.querySelector('#meta-status').value = newStatus;
        showFlash(newStatus === 'published' ? '<?= __('landing.now_live', 'Page is now live!') ?>' : '<?= __('landing.now_draft', 'Page set to Draft') ?>');
    } catch (e) {}
});

/* ── Flash message ───────────────────────────────────────────── */
function showFlash(msg) {
    const el = document.getElementById('flash-msg');
    el.textContent = msg;
    el.style.display = 'block';
    setTimeout(() => { el.style.display = 'none'; }, 2800);
}

/* ── Meta form toggle ────────────────────────────────────────── */
function toggleMetaForm() {
    const form    = document.getElementById('meta-form');
    const chevron = document.getElementById('meta-chevron');
    form.classList.toggle('open');
    chevron.className = form.classList.contains('open')
        ? 'bi bi-chevron-up ms-auto'
        : 'bi bi-chevron-down ms-auto';
}

/* ── Resize handle ───────────────────────────────────────────── */
(function() {
    const handle  = document.getElementById('resize-handle');
    const sidebar = document.getElementById('chat-sidebar');
    let dragging  = false, startX = 0, startW = 0;
    const isRtl   = document.documentElement.dir === 'rtl';

    handle.addEventListener('mousedown', e => {
        dragging = true;
        startX   = e.clientX;
        startW   = sidebar.offsetWidth;
        handle.classList.add('dragging');
        document.body.style.cursor = 'col-resize';
        document.body.style.userSelect = 'none';
    });

    document.addEventListener('mousemove', e => {
        if (!dragging) return;
        const delta = isRtl ? (startX - e.clientX) : (e.clientX - startX);
        const newW  = Math.min(Math.max(240, startW + delta), 600);
        sidebar.style.width = newW + 'px';
    });

    document.addEventListener('mouseup', () => {
        dragging = false;
        handle.classList.remove('dragging');
        document.body.style.cursor = '';
        document.body.style.userSelect = '';
    });
})();

/* ── Enter key sends message ─────────────────────────────────── */
document.getElementById('chat-input').addEventListener('keydown', function (e) {
    if (e.key === 'Enter' && !e.shiftKey) {
        e.preventDefault();
        sendMessage();
    }
});

/* ── Image Upload (like claude.ai) ─────────────────── */
const uploadedImages = []; // stores {url, name}

async function handleImageUpload(input) {
    const files = Array.from(input.files);
    if (!files.length) return;

    const strip = document.getElementById('img-preview-strip');
    strip.style.display = 'flex';

    for (const file of files) {
        const fd = new FormData();
        fd.append('image', file);
        fd.append('_csrf', '<?= \Core\System\Csrf::token() ?>');

        try {
            const res  = await fetch(`/admin/ai-landing-pages/upload-image/${PAGE_ID}`, {
                method: 'POST', body: fd, credentials: 'same-origin'
            });
            const data = await res.json();

            if (data.success) {
                uploadedImages.push({ url: data.url, fullUrl: data.fullUrl, name: file.name });

                // Thumbnail preview
                const thumb = document.createElement('div');
                thumb.style.cssText = 'position:relative;';
                thumb.innerHTML = `
                    <img src="${data.url}" style="width:52px;height:52px;object-fit:cover;border-radius:6px;border:1px solid var(--builder-border);">
                    <button onclick="removeUploadedImage(this,'${data.url}')"
                            style="position:absolute;top:-4px;right:-4px;background:var(--builder-bg);border:none;color:var(--builder-muted);border-radius:50%;width:16px;height:16px;font-size:11px;line-height:16px;text-align:center;cursor:pointer;">×</button>`;
                strip.appendChild(thumb);
            }
        } catch(e) {}
    }
    input.value = ''; // reset so same file can be selected again
}

function removeUploadedImage(btn, url) {
    const idx = uploadedImages.findIndex(i => i.url === url);
    if (idx !== -1) uploadedImages.splice(idx, 1);
    btn.closest('div').remove();
    if (!uploadedImages.length) document.getElementById('img-preview-strip').style.display = 'none';
}

/* ── HTML Import from URL ───────────────────────────── */
function showImportPanel() {
    const panel = document.getElementById('import-panel');
    panel.style.display = panel.style.display === 'none' ? 'block' : 'none';
}

async function doImportHtml() {
    const url  = document.getElementById('import-url-input').value.trim();
    const html = document.getElementById('import-html-input').value.trim();

    if (!url && !html) { showFlash('<?= __('landing.import_empty', 'Enter URL or paste HTML') ?>'); return; }

    const fd = new FormData();
    fd.append('_csrf', '<?= \Core\System\Csrf::token() ?>');
    if (url)  fd.append('url',  url);
    if (html) fd.append('html', html);

    const btn = document.querySelector('#import-panel button');
    if (btn) btn.disabled = true;

    try {
        const res  = await fetch(`/admin/ai-landing-pages/import-html/${PAGE_ID}`, {
            method: 'POST', body: fd, credentials: 'same-origin'
        });
        const data = await res.json();

        if (data.success) {
            updatePreview(data.html);
            document.getElementById('import-panel').style.display = 'none';
            document.getElementById('import-url-input').value = '';
            document.getElementById('import-html-input').value = '';
            appendMessage('assistant', '<?= __('landing.imported', 'HTML imported! You can now edit it with AI.') ?>');
            showFlash('<?= __('landing.imported_ok', 'HTML imported successfully!') ?>');
        } else {
            showFlash('❌ ' + (data.error || 'Import failed'));
        }
    } catch(e) {
        showFlash('❌ ' + e.message);
    } finally {
        if (btn) btn.disabled = false;
    }
}

<?php if ($success): ?>
showFlash(<?= json_encode($success) ?>);
<?php endif; ?>
<?php if (!empty($error ?? null)): ?>
showFlash(<?= json_encode($error) ?>);
<?php endif; ?>

function renderSourceImageThumb(url) {
    const thumb = document.getElementById('source-image-thumb');
    if (!url) {
        thumb.style.display = 'none';
        thumb.removeAttribute('src');
        return;
    }
    thumb.src = url;
    thumb.style.display = 'block';
}

function renderAnalysisSummary(analysis, structure, agent) {
    workbenchState = {
        analysis: analysis || {},
        structure: structure || {},
        agent: agent || {},
        variants: Array.isArray(agent?.variants) ? agent.variants : (workbenchState.variants || []),
        competitor: agent?.competitor_analysis || workbenchState.competitor || {},
    };
    const root = document.getElementById('analysis-summary');
    const sections = Array.isArray(structure?.sections) ? structure.sections : [];
    const visual = structure?.visual_system || analysis?.visual_system || {};
    const ctas = Array.isArray(analysis?.cta_candidates) ? analysis.cta_candidates : [];
    const plan = agent?.plan || {};
    const finalEval = agent?.final_evaluation || {};

    if (!sections.length && !ctas.length && !Object.keys(visual).length) {
        root.innerHTML = '';
        syncPipelineStatusFromState();
        return;
    }

    root.innerHTML = `
        <div class="analysis-grid">
            <div class="analysis-stat">
                <div class="k"><?= __('landing.analysis_sections', 'Sections') ?></div>
                <div class="v">${sections.map(s => s.type).join(' • ') || '—'}</div>
            </div>
            <div class="analysis-stat">
                <div class="k"><?= __('landing.analysis_palette', 'Palette') ?></div>
                <div class="v">${[visual.primary_color, visual.secondary_color, visual.accent_color].filter(Boolean).join(' / ') || '—'}</div>
            </div>
            <div class="analysis-stat">
                <div class="k"><?= __('landing.analysis_plan', 'Plan') ?></div>
                <div class="v">${(Array.isArray(plan.section_order) ? plan.section_order.join(' → ') : '') || '—'}</div>
            </div>
            <div class="analysis-stat">
                <div class="k"><?= __('landing.analysis_score', 'Score') ?></div>
                <div class="v">${finalEval.score || '—'}</div>
            </div>
        </div>
        <div class="analysis-list" style="margin-top:8px">
            ${(ctas.length ? ctas : ['<?= __('landing.analysis_no_cta', 'No CTA detected yet') ?>']).map(item => `<span class="analysis-pill">${item}</span>`).join('')}
        </div>
    `;

    renderWorkbench(analysis, structure, agent);
    renderAssembler(structure, agent);
    renderVariants(workbenchState.variants);
    renderCompetitorCard(workbenchState.competitor);
    syncPipelineStatusFromState();
}

function renderWorkbench(analysis, structure, agent) {
    const root = document.getElementById('agent-workbench');
    const productCard = agent?.product_card || {};
    const destinations = agent?.destinations || {};
    const concepts = Array.isArray(agent?.concepts) ? agent.concepts : [];
    const blueprint = agent?.section_blueprint || {};
    const blueprintSections = Array.isArray(blueprint.sections) ? blueprint.sections : [];
    const score = agent?.scorecard || {};

    const hasAnything = Object.keys(productCard).length || Object.keys(destinations).length || concepts.length || blueprintSections.length || Object.keys(score).length;
    if (!hasAnything) {
        root.innerHTML = '';
        return;
    }

    const destinationCards = Object.entries(destinations).map(([key, value]) => `
        <div class="item">
            <div class="label">${key.replace('_', ' ')}</div>
            <div class="value">${escapeHtml(value?.title || '—')}</div>
            <p>${escapeHtml((value?.notes || []).join(' • '))}</p>
        </div>
    `).join('');

    const conceptCards = concepts.map((concept, index) => `
        <div class="concept-card">
            <div class="name">${index + 1}. ${escapeHtml(concept.name || 'Concept')}</div>
            <div class="meta">${escapeHtml(concept.angle || '')} ${concept.fit ? '• ' + escapeHtml(concept.fit) : ''}</div>
            <div class="hook">${escapeHtml(concept.hook || concept.promise || '')}</div>
        </div>
    `).join('');

    const sectionCards = blueprintSections.map((section, index) => `
        <div class="section-row">
            <div class="label">${index + 1}. ${escapeHtml(section.type || 'section')} ${section.priority ? '• ' + escapeHtml(section.priority) : ''}</div>
            <div class="value">${escapeHtml(section.headline || section.goal || '')}</div>
        </div>
    `).join('');

    const scoreBoxes = [
        ['<?= __('landing.score_global', 'Global') ?>', score.global_score],
        ['<?= __('landing.score_copy', 'Copy') ?>', score.copy_score],
        ['<?= __('landing.score_cta', 'CTA') ?>', score.cta_score],
        ['<?= __('landing.score_visual', 'Visual') ?>', score.visual_score],
        ['<?= __('landing.score_mobile', 'Mobile') ?>', score.mobile_score],
        ['<?= __('landing.score_market_fit', 'Market Fit') ?>', score.market_fit_score],
    ].map(([label, value]) => `
        <div class="score-box">
            <div class="n">${value ?? '—'}</div>
            <div class="t">${label}</div>
        </div>
    `).join('');

    root.innerHTML = `
        <div class="workbench-card">
            <h4><i class="bi bi-box-seam"></i><?= __('landing.workbench_product_card', 'Product Analysis Card') ?></h4>
            <div class="workbench-kv">
                <div class="item"><div class="label"><?= __('landing.workbench_product_name', 'Product') ?></div><div class="value">${escapeHtml(productCard.product_name || '—')}</div></div>
                <div class="item"><div class="label"><?= __('landing.workbench_brand', 'Brand') ?></div><div class="value">${escapeHtml(productCard.brand || '—')}</div></div>
                <div class="item"><div class="label"><?= __('landing.workbench_category', 'Category') ?></div><div class="value">${escapeHtml(productCard.category || '—')}</div></div>
                <div class="item"><div class="label"><?= __('landing.workbench_audience', 'Audience') ?></div><div class="value">${escapeHtml(productCard.audience || '—')}</div></div>
            </div>
            <p>${escapeHtml(productCard.positioning || '')}</p>
        </div>

        <div class="workbench-card">
            <h4><i class="bi bi-signpost-2"></i><?= __('landing.workbench_destinations', 'Destination Engine') ?></h4>
            <div class="destination-grid">${destinationCards || '<p>—</p>'}</div>
        </div>

        <div class="workbench-card">
            <h4><i class="bi bi-lightbulb"></i><?= __('landing.workbench_concepts', 'Concept Generator') ?></h4>
            <div class="concepts-grid">${conceptCards || '<p>—</p>'}</div>
        </div>

        <div class="workbench-card">
            <h4><i class="bi bi-diagram-3"></i><?= __('landing.workbench_sections', 'Section Planner') ?></h4>
            <p>${escapeHtml(blueprint.selected_concept || '')}</p>
            <div class="sections-stack">${sectionCards || '<p>—</p>'}</div>
        </div>

        <div class="workbench-card">
            <h4><i class="bi bi-speedometer2"></i><?= __('landing.workbench_scorecard', 'Scorecard') ?></h4>
            <div class="score-grid">${scoreBoxes}</div>
            <div class="score-stack">
                <div class="score-row">
                    <div class="label"><?= __('landing.workbench_strengths', 'Strengths') ?></div>
                    <div class="value">${escapeHtml((score.strengths || []).join(' • '))}</div>
                </div>
                <div class="score-row">
                    <div class="label"><?= __('landing.workbench_quick_wins', 'Quick Wins') ?></div>
                    <div class="value">${escapeHtml((score.quick_wins || []).join(' • '))}</div>
                </div>
            </div>
        </div>
    `;
}

function renderAssembler(structure, agent) {
    const root = document.getElementById('agent-assembler');
    const sections = Array.isArray(structure?.sections) ? structure.sections : [];
    const concepts = Array.isArray(agent?.concepts) ? agent.concepts : [];
    const selectedConcept = agent?.selected_concept || agent?.section_blueprint?.selected_concept || '';

    if (!sections.length) {
        root.style.display = 'none';
        root.innerHTML = '';
        return;
    }

    root.style.display = 'grid';
    const options = ['<option value=""><?= __('landing.assembler_auto_concept', 'Auto-select strongest concept') ?></option>']
        .concat(concepts.map(concept => `<option value="${escapeAttr(concept.name || '')}" ${selectedConcept === concept.name ? 'selected' : ''}>${escapeHtml(concept.name || 'Concept')}</option>`))
        .join('');

    root.innerHTML = `
        <h4><i class="bi bi-ui-checks-grid"></i><?= __('landing.assembler_title', 'Section Editor & Assembler') ?></h4>
        <div class="assembler-toolbar">
            <select id="assembler-concept">${options}</select>
            <button type="button" class="assembler-btn primary" id="btn-assemble-page">
                <i class="bi bi-layers me-1"></i><?= __('landing.assemble_page', 'Assemble Landing Page') ?>
            </button>
        </div>
        <div class="assembler-stack" id="assembler-stack">
            ${sections.map((section, index) => `
                <div class="assembler-section" data-index="${index}">
                    <div class="assembler-section-head">
                        <div class="assembler-section-title">${index + 1}. ${escapeHtml(section.type || 'section')}</div>
                        <div style="display:flex;gap:12px;align-items:center;">
                            <label class="assembler-checkbox">
                                <input type="checkbox" class="assembler-enabled" ${section.enabled === false ? '' : 'checked'}>
                                <?= __('landing.assembler_include', 'Include') ?>
                            </label>
                            <label class="assembler-checkbox">
                                <input type="checkbox" class="assembler-locked" ${section.locked ? 'checked' : ''}>
                                <?= __('landing.assembler_lock', 'Lock') ?>
                            </label>
                        </div>
                    </div>
                    <div class="assembler-grid">
                        <div>
                            <div class="label" style="font-size:10.5px;color:var(--builder-muted);margin-bottom:4px;"><?= __('landing.assembler_headline', 'Headline') ?></div>
                            <input type="text" class="assembler-headline" value="${escapeAttr(section.headline || '')}">
                        </div>
                        <div>
                            <div class="label" style="font-size:10.5px;color:var(--builder-muted);margin-bottom:4px;"><?= __('landing.assembler_label', 'Label') ?></div>
                            <input type="text" class="assembler-label" value="${escapeAttr(section.label || '')}">
                        </div>
                    </div>
                    <div>
                        <div class="label" style="font-size:10.5px;color:var(--builder-muted);margin-bottom:4px;"><?= __('landing.assembler_goal', 'Goal / Note') ?></div>
                        <textarea rows="2" class="assembler-goal">${escapeHtml(section.purpose || section.subheadline || '')}</textarea>
                    </div>
                </div>
            `).join('')}
        </div>
    `;

    document.getElementById('btn-assemble-page').addEventListener('click', assembleLandingPage);
}

function renderVariants(variants) {
    const root = document.getElementById('agent-variants');
    const items = Array.isArray(variants) ? variants : [];

    if (!items.length) {
        root.style.display = 'grid';
        root.innerHTML = `
            <h4 style="margin:0;font-size:12.5px;color:var(--builder-text);display:flex;align-items:center;gap:8px;">
                <i class="bi bi-grid-1x2"></i><?= __('landing.variants_title', 'Smart Variants') ?>
            </h4>
            <div class="assembler-toolbar">
                <button type="button" class="assembler-btn primary" id="btn-generate-variants">
                    <i class="bi bi-stars me-1"></i><?= __('landing.generate_variants', 'Generate 3 Variants') ?>
                </button>
            </div>
            <p><?= __('landing.variants_hint', 'Generate three alternative landing pages from the same image using different marketing concepts.') ?></p>
        `;
        document.getElementById('btn-generate-variants').addEventListener('click', generateVariants);
        return;
    }

    root.style.display = 'grid';
    root.innerHTML = `
        <h4 style="margin:0;font-size:12.5px;color:var(--builder-text);display:flex;align-items:center;gap:8px;">
            <i class="bi bi-grid-1x2"></i><?= __('landing.variants_title', 'Smart Variants') ?>
        </h4>
        <div class="assembler-toolbar">
            <button type="button" class="assembler-btn primary" id="btn-generate-variants">
                <i class="bi bi-arrow-repeat me-1"></i><?= __('landing.refresh_variants', 'Refresh Variants') ?>
            </button>
        </div>
        <div class="variants-grid">
            ${items.map((variant, index) => `
                <div class="variant-card">
                    <div class="top">
                        <div>
                            <div class="name">${index + 1}. ${escapeHtml(variant.name || 'Variant')}</div>
                            <div class="meta">${escapeHtml(variant.angle || '')}</div>
                        </div>
                        <span class="mini-badge"><?= __('landing.analysis_score', 'Score') ?>: ${variant.score ?? '—'}</span>
                    </div>
                    <div class="meta">${escapeHtml(variant.hook || '')}</div>
                    <div class="assembler-toolbar">
                        <button type="button" class="assembler-btn" onclick="previewVariant(${index})">
                            <i class="bi bi-eye me-1"></i><?= __('landing.preview_variant', 'Preview') ?>
                        </button>
                        <button type="button" class="assembler-btn primary" onclick="applyVariant(${index})">
                            <i class="bi bi-check2-circle me-1"></i><?= __('landing.apply_variant', 'Apply Variant') ?>
                        </button>
                    </div>
                </div>
            `).join('')}
        </div>
    `;
    document.getElementById('btn-generate-variants').addEventListener('click', generateVariants);
}

function renderCompetitorCard(report) {
    const root = document.getElementById('competitor-analysis-card');
    const hasReport = report && Object.keys(report).length;

    root.innerHTML = `
        <h4 style="margin:0;font-size:12.5px;color:var(--builder-text);display:flex;align-items:center;gap:8px;">
            <i class="bi bi-binoculars"></i><?= __('landing.competitor_title', 'Competitor Analysis') ?>
        </h4>
        <div class="competitor-toolbar">
            <input type="url" id="competitor-url" placeholder="<?= __('landing.competitor_placeholder', 'https://competitor.com/landing-page') ?>">
            <button type="button" class="assembler-btn primary" id="btn-analyze-competitor">
                <i class="bi bi-search me-1"></i><?= __('landing.analyze_competitor', 'Analyze Competitor') ?>
            </button>
        </div>
        ${hasReport ? `
            <div class="score-grid">
                <div class="score-box">
                    <div class="n">${report.global_score ?? '—'}</div>
                    <div class="t"><?= __('landing.score_global', 'Global') ?></div>
                </div>
            </div>
            <div class="score-stack">
                <div class="score-row"><div class="label"><?= __('landing.competitor_strengths', 'Strengths') ?></div><div class="value">${escapeHtml((report.strengths || []).join(' • '))}</div></div>
                <div class="score-row"><div class="label"><?= __('landing.competitor_weaknesses', 'Weaknesses') ?></div><div class="value">${escapeHtml((report.weaknesses || []).join(' • '))}</div></div>
                <div class="score-row"><div class="label"><?= __('landing.competitor_gaps', 'Gaps We Can Exploit') ?></div><div class="value">${escapeHtml((report.gaps_we_can_exploit || []).join(' • '))}</div></div>
                <div class="score-row"><div class="label"><?= __('landing.competitor_strategy', 'Recommended Strategy') ?></div><div class="value">${escapeHtml(report.lp_strategy || '')}</div></div>
            </div>
        ` : `<p><?= __('landing.competitor_hint', 'Analyze a competitor URL to discover weaknesses, angles, and section opportunities we can outperform.') ?></p>`}
    `;
    document.getElementById('btn-analyze-competitor').addEventListener('click', analyzeCompetitor);
}

function escapeHtml(value) {
    return String(value ?? '')
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;');
}

function escapeAttr(value) {
    return escapeHtml(value).replace(/`/g, '&#096;');
}

function collectAssemblerStructure() {
    const source = JSON.parse(JSON.stringify(workbenchState.structure || {}));
    const stack = document.getElementById('assembler-stack');
    if (!stack) return source;

    const sections = [];
    stack.querySelectorAll('.assembler-section').forEach(sectionEl => {
        const index = Number(sectionEl.dataset.index);
        const original = (source.sections || [])[index] || {};
        sections.push({
            ...original,
            enabled: !!sectionEl.querySelector('.assembler-enabled')?.checked,
            locked: !!sectionEl.querySelector('.assembler-locked')?.checked,
            headline: sectionEl.querySelector('.assembler-headline')?.value?.trim() || '',
            label: sectionEl.querySelector('.assembler-label')?.value?.trim() || '',
            purpose: sectionEl.querySelector('.assembler-goal')?.value?.trim() || '',
            subheadline: sectionEl.querySelector('.assembler-goal')?.value?.trim() || original.subheadline || '',
        });
    });

    source.sections = sections;
    return source;
}

async function assembleLandingPage() {
    const btn = document.getElementById('btn-assemble-page');
    btn.disabled = true;
    try {
        const structure = collectAssemblerStructure();
        const selectedConcept = document.getElementById('assembler-concept')?.value || '';
        const fd = new FormData();
        fd.append('_csrf', CSRF_TOKEN);
        fd.append('selected_concept', selectedConcept);
        fd.append('structure_json', JSON.stringify(structure));

        const res = await fetch(`/admin/ai-landing-pages/assemble/${PAGE_ID}`, {
            method: 'POST',
            body: fd,
        });
        const data = await res.json();
        if (!data.success) {
            throw new Error(data.error || 'Assembly failed');
        }

        appendMessage('assistant', '<?= __('landing.assembled_note', 'The landing page was assembled from your selected concept and edited sections.') ?>');
        updatePreview(data.html);
        renderAnalysisSummary(workbenchState.analysis, data.structure, data.agent);
        showFlash('<?= __('landing.assembled', 'The landing page was assembled successfully.') ?>');
    } catch (e) {
        appendMessage('assistant', '⚠️ ' + e.message);
    } finally {
        btn.disabled = false;
    }
}

async function generateVariants() {
    const btn = document.getElementById('btn-generate-variants');
    if (btn) btn.disabled = true;
    try {
        const fd = new FormData();
        fd.append('_csrf', CSRF_TOKEN);
        const res = await fetch(`/admin/ai-landing-pages/generate-variants/${PAGE_ID}`, {
            method: 'POST',
            body: fd,
        });
        const data = await res.json();
        if (!data.success) {
            throw new Error(data.error || 'Variant generation failed');
        }
        workbenchState.variants = Array.isArray(data.variants) ? data.variants : [];
        renderVariants(workbenchState.variants);
        showFlash('<?= __('landing.variants_generated', 'Three variants were generated successfully.') ?>');
    } catch (e) {
        appendMessage('assistant', '⚠️ ' + e.message);
    } finally {
        if (btn) btn.disabled = false;
    }
}

function previewVariant(index) {
    const variant = (workbenchState.variants || [])[index];
    if (!variant) return;
    updatePreview(variant.html || '');
    showFlash('<?= __('landing.variant_previewed', 'Variant preview loaded.') ?>');
}

async function applyVariant(index) {
    const variant = (workbenchState.variants || [])[index];
    if (!variant) return;

    try {
        const fd = new FormData();
        fd.append('_csrf', CSRF_TOKEN);
        fd.append('html', variant.html || '');
        const res = await fetch(`/admin/ai-landing-pages/save-html/${PAGE_ID}`, {
            method: 'POST',
            body: fd,
        });
        const data = await res.json();
        if (!data.success) {
            throw new Error(data.error || 'Save failed');
        }
        updatePreview(variant.html || '');
        showFlash('<?= __('landing.variant_applied', 'Variant applied successfully.') ?>');
    } catch (e) {
        appendMessage('assistant', '⚠️ ' + e.message);
    }
}

async function analyzeCompetitor() {
    const url = document.getElementById('competitor-url')?.value?.trim() || '';
    if (!url) {
        showFlash('<?= __('landing.competitor_invalid_url', 'Please enter a valid competitor URL.') ?>');
        return;
    }

    const btn = document.getElementById('btn-analyze-competitor');
    if (btn) btn.disabled = true;
    try {
        const fd = new FormData();
        fd.append('_csrf', CSRF_TOKEN);
        fd.append('url', url);
        const res = await fetch(`/admin/ai-landing-pages/analyze-competitor/${PAGE_ID}`, {
            method: 'POST',
            body: fd,
        });
        const data = await res.json();
        if (!data.success) {
            throw new Error(data.error || 'Competitor analysis failed');
        }
        workbenchState.competitor = data.report || {};
        renderCompetitorCard(workbenchState.competitor);
        const input = document.getElementById('competitor-url');
        if (input) input.value = url;
        showFlash('<?= __('landing.competitor_analyzed', 'Competitor analysis is ready.') ?>');
    } catch (e) {
        appendMessage('assistant', '⚠️ ' + e.message);
    } finally {
        if (btn) btn.disabled = false;
    }
}

document.getElementById('source-image-input').addEventListener('change', function () {
    const file = this.files[0];
    if (!file) return;
    selectedSourceImage = file;
    renderSourceImageThumb(URL.createObjectURL(file));
});

async function buildFromSourceImage() {
    if (!selectedSourceImage && !INITIAL_SOURCE_IMAGE) {
        showFlash('<?= __('landing.source_image_required', 'Please upload a screenshot or landing page design first.') ?>');
        return;
    }

    const btn = document.getElementById('btn-build-from-image');
    btn.disabled = true;

    try {
        const fd = new FormData();
        fd.append('_csrf', CSRF_TOKEN);
        if (selectedSourceImage) {
            fd.append('source_image', selectedSourceImage);
        }

        const res = await fetch(`/admin/ai-landing-pages/generate-from-image/${PAGE_ID}`, {
            method: 'POST',
            body: fd,
        });
        const data = await res.json();

        if (!data.success) {
            throw new Error(data.error || 'Build failed');
        }

        workbenchState.analysis = data.analysis || {};
        workbenchState.structure = data.structure || {};
        workbenchState.agent = data.agent || {};
        appendMessage('assistant', '<?= __('landing.image_pipeline_note', 'The AI agent analyzed the uploaded image, planned the layout, generated the page, and improved it automatically.') ?>');
        updatePreview(data.html);
        renderSourceImageThumb(data.sourceImage);
        renderAnalysisSummary(data.analysis, data.structure, data.agent);
        setPipelineStatus('success', '<?= __('landing.pipeline_status_ready', 'تم تحليل الصورة وبناء الـ structure بنجاح. يمكنك الآن التجميع أو التوليد أو إنشاء variants.') ?>', '<?= __('landing.pipeline_status_ready_label', 'Structure Ready') ?>');
        showFlash('<?= __('landing.image_pipeline_ready', 'The landing page was generated from the uploaded image.') ?>');
    } catch (e) {
        setPipelineStatus('error', e.message, '<?= __('landing.pipeline_status_error_label', 'Pipeline Error') ?>');
        appendMessage('assistant', '⚠️ ' + e.message);
    } finally {
        btn.disabled = false;
    }
}

async function regenerateFromStructure() {
    const btn = document.getElementById('btn-regenerate-structure');
    btn.disabled = true;
    try {
        const fd = new FormData();
        fd.append('_csrf', CSRF_TOKEN);
        const res = await fetch(`/admin/ai-landing-pages/regenerate/${PAGE_ID}`, {
            method: 'POST',
            body: fd,
        });
        const data = await res.json();
        if (!data.success) {
            throw new Error(data.error || 'Regeneration failed');
        }
        appendMessage('assistant', '<?= __('landing.regenerated_note', 'The AI agent regenerated and improved the landing page from the saved image structure.') ?>');
        updatePreview(data.html);
        renderAnalysisSummary(workbenchState.analysis || INITIAL_ANALYSIS, data.structure, data.agent);
        setPipelineStatus('success', '<?= __('landing.pipeline_status_regenerated', 'تمت إعادة التوليد بنجاح من الـ structure المحفوظ.') ?>', '<?= __('landing.pipeline_status_regenerated_label', 'Regenerated') ?>');
        showFlash('<?= __('landing.regenerated', 'The page was regenerated successfully.') ?>');
    } catch (e) {
        setPipelineStatus('error', e.message, '<?= __('landing.pipeline_status_error_label', 'Pipeline Error') ?>');
        appendMessage('assistant', '⚠️ ' + e.message);
    } finally {
        btn.disabled = false;
    }
}

document.getElementById('btn-build-from-image').addEventListener('click', buildFromSourceImage);
document.getElementById('btn-regenerate-structure').addEventListener('click', regenerateFromStructure);
renderSourceImageThumb(INITIAL_SOURCE_IMAGE);
renderAnalysisSummary(INITIAL_ANALYSIS, INITIAL_STRUCTURE, INITIAL_AGENT);
syncPipelineStatusFromState();

if (INITIAL_SOURCE_MODE === 'image' && INITIAL_SOURCE_IMAGE && !<?= $hasContent ? 'true' : 'false' ?> && !Array.isArray(INITIAL_STRUCTURE.sections)) {
    setTimeout(function () {
        buildFromSourceImage();
    }, 400);
}
</script>
</body>
</html>
