<?php
use Core\System\Csrf;

$pageId = (int)($page['id'] ?? 0);
$pageName = (string)($page['name'] ?? '');
$pageSlug = (string)($page['slug'] ?? '');
$pageStatus = (string)($page['status'] ?? 'draft');
$productTitle = (string)($product['title'] ?? $product['name'] ?? __('landing.product', 'المنتج'));
$report = is_array($report ?? null) ? $report : [];
$history = is_array($history ?? null) ? $history : [];
$agent = is_array($agent ?? null) ? $agent : [];
$scorecard = is_array($agent['scorecard'] ?? null) ? $agent['scorecard'] : [];
$ourScores = is_array($report['our_scorecard'] ?? null) ? $report['our_scorecard'] : [];
$competitorScores = is_array($report['competitor_scorecard'] ?? null) ? $report['competitor_scorecard'] : [];
$comparison = is_array($report['comparison'] ?? null) ? $report['comparison'] : [];
$summary = (string)($report['executive_summary'] ?? '');
$priorityActions = is_array($report['priority_actions'] ?? null) ? $report['priority_actions'] : [];
$quickWins = is_array($report['quick_wins'] ?? null) ? $report['quick_wins'] : [];
$strengths = is_array($report['strengths'] ?? null) ? $report['strengths'] : [];
$weaknesses = is_array($report['weaknesses'] ?? null) ? $report['weaknesses'] : [];
$gaps = is_array($report['gaps_we_can_exploit'] ?? null) ? $report['gaps_we_can_exploit'] : [];
$sections = is_array($report['recommended_sections'] ?? null) ? $report['recommended_sections'] : [];
$angles = is_array($report['recommended_angles'] ?? null) ? $report['recommended_angles'] : [];
$hooks = is_array($report['hooks_to_try'] ?? null) ? $report['hooks_to_try'] : [];
$cta = is_array($report['cta_opportunities'] ?? null) ? $report['cta_opportunities'] : [];
$trust = is_array($report['trust_opportunities'] ?? null) ? $report['trust_opportunities'] : [];
$ux = is_array($report['ux_observations'] ?? null) ? $report['ux_observations'] : [];
$offers = is_array($report['offer_observations'] ?? null) ? $report['offer_observations'] : [];
$executiveMetrics = is_array($report['executive_metrics'] ?? null) ? $report['executive_metrics'] : [];
$comparisonSummary = is_array($report['comparison_summary'] ?? null) ? $report['comparison_summary'] : [];
$csrf = Csrf::token();
require __DIR__ . '/_admin_theme_bridge.php';
?>
<!DOCTYPE html>
<html lang="<?= __('lang.code', 'ar') ?>" dir="<?= __('lang.direction', 'rtl') ?>">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?= htmlspecialchars(__('landing.competitor_workspace_title', 'Competitor Workspace') . ' - ' . $pageName, ENT_QUOTES, 'UTF-8') ?></title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
    <?php foreach ($lpThemeImports as $lpThemeCss): ?>
        <link rel="stylesheet" href="<?= htmlspecialchars($lpThemeCss, ENT_QUOTES, 'UTF-8') ?>">
    <?php endforeach; ?>
    <style>
        :root{--bg:<?= htmlspecialchars($lpThemeVars['bg'], ENT_QUOTES, 'UTF-8') ?>;--panel:<?= htmlspecialchars($lpThemeVars['panel'], ENT_QUOTES, 'UTF-8') ?>;--line:<?= htmlspecialchars($lpThemeVars['border'], ENT_QUOTES, 'UTF-8') ?>;--text:<?= htmlspecialchars($lpThemeVars['text'], ENT_QUOTES, 'UTF-8') ?>;--muted:<?= htmlspecialchars($lpThemeVars['muted'], ENT_QUOTES, 'UTF-8') ?>;--primary:<?= htmlspecialchars($lpThemeVars['primary'], ENT_QUOTES, 'UTF-8') ?>;--primary2:<?= htmlspecialchars($lpThemeVars['secondary'], ENT_QUOTES, 'UTF-8') ?>;--blue:<?= htmlspecialchars($lpThemeVars['accent'], ENT_QUOTES, 'UTF-8') ?>;--ok:<?= htmlspecialchars($lpThemeVars['success'], ENT_QUOTES, 'UTF-8') ?>;--bad:<?= htmlspecialchars($lpThemeVars['danger'], ENT_QUOTES, 'UTF-8') ?>;--shadow:0 18px 44px rgba(15,23,42,.08)}
        *{box-sizing:border-box}body{margin:0;background:radial-gradient(circle at top right,color-mix(in srgb, var(--primary) 14%, transparent),transparent 25%),radial-gradient(circle at top left,color-mix(in srgb, var(--blue) 12%, transparent),transparent 28%),var(--bg);color:var(--text);font-family:<?= $lpBodyFont ?>}
        h1,h2,h3,h4,h5,h6,.brand{font-family:<?= $lpHeadingFont ?>}
        .shell{min-height:100vh;display:grid;grid-template-rows:auto 1fr}.topbar{position:sticky;top:0;z-index:1000;display:flex;align-items:center;gap:14px;flex-wrap:wrap;padding:14px 24px;background:rgba(255,255,255,.98);backdrop-filter:blur(16px);border-bottom:1px solid var(--line);box-shadow:0 2px 16px rgba(15,23,42,.06)}
        .brand{display:flex;align-items:center;gap:12px;font-weight:900}.brand-icon{width:42px;height:42px;border-radius:14px;display:grid;place-items:center;color:#fff;background:linear-gradient(135deg,var(--primary),var(--primary2));box-shadow:0 14px 28px rgba(249,115,22,.22)}
        .brand small{display:block;color:var(--muted);font-size:11px;text-transform:uppercase;letter-spacing:.06em}.topbar-actions{margin-inline-start:auto;display:flex;gap:10px;flex-wrap:wrap}
        .btn-main,.btn-ghost{border:1px solid var(--line);background:#fff;color:var(--text);border-radius:14px;padding:11px 16px;font-size:13px;font-weight:800;display:inline-flex;align-items:center;justify-content:center;gap:8px;text-decoration:none;cursor:pointer;transition:.18s ease}
        .btn-main{background:linear-gradient(135deg,var(--primary),var(--primary2));border-color:transparent;color:#fff}.btn-main:hover,.btn-ghost:hover{transform:translateY(-1px)}
        .layout{display:grid;grid-template-columns:minmax(300px,.88fr) minmax(0,1.5fr) minmax(320px,.92fr);gap:18px;padding:18px}
        .stack{display:grid;gap:18px}.panel{background:rgba(255,255,255,.94);border:1px solid var(--line);border-radius:24px;box-shadow:var(--shadow)}.panel-inner{padding:20px;display:grid;gap:16px}
        .eyebrow{display:inline-flex;align-items:center;gap:8px;padding:8px 12px;border-radius:999px;background:rgba(37,99,235,.08);color:var(--blue);font-size:11px;font-weight:900;text-transform:uppercase;letter-spacing:.05em}
        h1,h2,h3,p{margin:0}.hero h1{font-size:36px;line-height:1.15;font-weight:950;margin-top:12px}.muted{color:var(--muted);line-height:1.8}
        .search{width:100%;border-radius:14px;border:1px solid var(--line);background:#f8fafc;padding:12px 14px;font-size:13px}
        .session-list,.cards,.timeline,.matrix{display:grid;gap:12px}.session-card,.card,.timeline-item,.metric,.matrix-row{border:1px solid var(--line);border-radius:20px;background:#fff;padding:16px;display:grid;gap:10px}
        .session-card{text-decoration:none;color:var(--text)}.session-card.active{border-color:#fdba74;background:#fff7ed}
        .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}.chip.win{background:#ecfdf5;color:#166534;border-color:#bbf7d0}.chip.lose{background:#fef2f2;color:#b91c1c;border-color:#fecaca}
        .grid2{display:grid;grid-template-columns:repeat(2,1fr);gap:14px}.grid3{display:grid;grid-template-columns:repeat(3,1fr);gap:14px}
        .alert-box{display:none;padding:14px 16px;border-radius:16px;border:1px solid var(--line)}.alert-box.show{display:block}.alert-box.error{background:#fef2f2;border-color:#fecaca}.alert-box.success{background:#f0fdf4;border-color:#bbf7d0}.alert-box.info{background:#eff6ff;border-color:#bfdbfe}
        .spinner{width:16px;height:16px;border:2px solid currentColor;border-top-color:transparent;border-radius:50%;display:inline-block;animation:spin .7s linear infinite}
        .matrix-row{grid-template-columns:1.1fr .6fr .6fr .6fr;align-items:center}
        .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}
        @keyframes spin{to{transform:rotate(360deg)}}@media (max-width:1240px){.layout,.grid2,.grid3,.matrix-row{grid-template-columns:1fr}}
        /* ── Enhanced Styles ── */
        .brand-icon{box-shadow:0 8px 24px rgba(249,115,22,.28)!important}
        .btn-ghost{transition:all .2s ease}
        .btn-ghost:hover{background:color-mix(in srgb,var(--primary) 8%,#fff);border-color:var(--primary);color:var(--primary);transform:translateY(-1px)}
        .btn-main:active,.btn-ghost:active{transform:translateY(0)}
        .session-card,.card{transition:box-shadow .22s,transform .22s}
        .session-card:hover{box-shadow:0 10px 28px rgba(15,23,42,.1)!important;transform:translateY(-2px)}
        .card:hover{box-shadow:0 8px 24px rgba(15,23,42,.09)!important;transform:translateY(-1px)}
        .panel{transition:box-shadow .22s}
        .eyebrow-o{background:rgba(249,115,22,.1)!important;color:var(--primary)!important}
        .eyebrow-g{background:rgba(22,163,74,.1)!important;color:var(--ok)!important}
        .eyebrow-p{background:rgba(139,92,246,.1)!important;color:#7c3aed!important}
        .eyebrow-r{background:rgba(220,38,38,.1)!important;color:var(--bad)!important}
        .eyebrow-a{background:rgba(217,119,6,.1)!important;color:var(--warning)!important}
        .eyebrow-t{background:rgba(14,165,233,.1)!important;color:var(--blue)!important}
        .metric{background:linear-gradient(135deg,#fff,#f8fafc);transition:box-shadow .2s}
        .metric:hover{box-shadow:0 6px 18px rgba(15,23,42,.08)!important}
        .metric strong{font-size:clamp(18px,2vw,26px);font-weight:900;color:var(--text)}
        .metric span{font-size:11px;text-transform:uppercase;letter-spacing:.05em;color:var(--muted);margin-top:2px}
        .matrix-row{border-radius:14px;background:linear-gradient(90deg,#fff,#f8fafc);transition:background .2s}
        .matrix-row:hover{background:linear-gradient(90deg,#fff7ed,#fff)}
        .chip.win{font-weight:900}.chip.lose{font-weight:900}
        .search:focus{outline:none;border-color:var(--primary);box-shadow:0 0 0 3px color-mix(in srgb,var(--primary) 15%,transparent)}
        .hero h1{background:linear-gradient(135deg,var(--text),var(--primary));-webkit-background-clip:text;-webkit-text-fill-color:transparent;background-clip:text}
        .topbar-actions{gap:8px!important}
        @media (max-width:768px){.topbar{padding:10px 16px}.brand-icon{width:36px!important;height:36px!important}}
    </style>
</head>
<body>
<div class="shell">
    <div class="topbar">
        <div class="brand">
            <div class="brand-icon"><i class="bi bi-binoculars"></i></div>
            <div>
                <div><?= __('landing.competitor_workspace_title', 'مساحة المنافسين') ?></div>
                <small><?= __('landing.competitor_workspace_text', 'تحليل أعمق، أرشيف، مقارنة مباشرة، وخطة تفوق عملية داخل نفس المنتج') ?></small>
            </div>
        </div>
        <div class="topbar-actions">
            <a href="/admin/ai-landing-pages/chat/<?= $pageId ?>" class="btn-ghost"><i class="bi bi-chat-square-text"></i><span><?= __('landing.chat_expert_title', '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/edit/<?= $pageId ?>" class="btn-ghost"><i class="bi bi-stars"></i><span><?= __('landing.open_studio', 'فتح الـ Studio') ?></span></a>
            <a href="/admin/ai-landing-pages" class="btn-ghost"><i class="bi bi-arrow-left"></i><span><?= __('common.back', 'رجوع') ?></span></a>
        </div>
    </div>

    <div class="layout">
        <aside class="stack">
            <section class="panel">
                <div class="panel-inner">
                    <div class="eyebrow eyebrow-t"><i class="bi bi-archive"></i><?= __('landing.competitor_archive_title', 'أرشيف المنافسين') ?></div>
                    <input type="search" id="archive-search" class="search" placeholder="<?= htmlspecialchars(__('landing.competitor_archive_search', 'ابحث عن منافس أو دومين'), ENT_QUOTES, 'UTF-8') ?>">
                    <div class="session-list" id="archive-list">
                        <?php foreach ($history as $entry): ?>
                            <?php $entryId = (string)($entry['id'] ?? ''); $active = ($selectedId !== '' ? $selectedId === $entryId : ($report['url'] ?? '') === ($entry['url'] ?? '')); ?>
                            <a href="/admin/ai-landing-pages/competitors/<?= $pageId ?>?entry=<?= urlencode($entryId) ?>" class="session-card<?= $active ? ' active' : '' ?>" data-search="<?= htmlspecialchars(mb_strtolower((string)($entry['domain'] ?? $entry['url'] ?? '')), ENT_QUOTES, 'UTF-8') ?>">
                                <strong><?= htmlspecialchars((string)($entry['domain'] ?? $entry['url'] ?? ''), ENT_QUOTES, 'UTF-8') ?></strong>
                                <small class="muted"><?= htmlspecialchars((string)($entry['at'] ?? ''), ENT_QUOTES, 'UTF-8') ?></small>
                                <span class="chip"><?= htmlspecialchars((string)(($entry['report']['global_score'] ?? '—')), ENT_QUOTES, 'UTF-8') ?></span>
                            </a>
                        <?php endforeach; ?>
                    </div>
                </div>
            </section>

            <section class="panel">
                <div class="panel-inner">
                    <div class="eyebrow eyebrow-o"><i class="bi bi-link-45deg"></i><?= __('landing.competitor_title', 'تحليل المنافس') ?></div>
                    <div id="competitor-alert" class="alert-box<?= $success ? ' success show' : ($error ? ' error show' : '') ?>"><?= htmlspecialchars((string)($success ?: $error), ENT_QUOTES, 'UTF-8') ?></div>
                    <input type="url" id="competitor-url" class="search" value="<?= htmlspecialchars((string)($report['url'] ?? ''), ENT_QUOTES, 'UTF-8') ?>" placeholder="<?= htmlspecialchars(__('landing.competitor_placeholder', 'https://competitor.com/landing-page'), ENT_QUOTES, 'UTF-8') ?>">
                    <button type="button" class="btn-main" id="btn-run-competitor"><i class="bi bi-search"></i><span><?= __('landing.analyze_competitor', 'تحليل المنافس') ?></span></button>
                </div>
            </section>
        </aside>

        <div class="stack">
            <section class="panel hero">
                <div class="panel-inner">
                    <div class="eyebrow eyebrow-o"><i class="bi bi-radar"></i><?= __('landing.competitor_report_title', 'تقرير المنافس') ?></div>
                    <h1><?= htmlspecialchars((string)($comparisonSummary['headline'] ?? __('landing.competitor_report_title', 'تقرير المنافس')), ENT_QUOTES, 'UTF-8') ?></h1>
                    <p class="muted"><?= htmlspecialchars($summary !== '' ? $summary : __('landing.competitor_summary_fallback', 'تم تحليل المنافس وتجهيز مقارنة تنفيذية مع صفحتنا الحالية.'), ENT_QUOTES, 'UTF-8') ?></p>
                    <div class="grid3">
                        <div class="metric"><strong><?= htmlspecialchars((string)($ourScores['global'] ?? ($scorecard['global_score'] ?? '—')), ENT_QUOTES, 'UTF-8') ?></strong><span><?= __('landing.our_score_label', 'تقييمنا') ?></span></div>
                        <div class="metric"><strong><?= htmlspecialchars((string)($competitorScores['global'] ?? ($report['global_score'] ?? '—')), ENT_QUOTES, 'UTF-8') ?></strong><span><?= __('landing.competitor_score_label', 'تقييم المنافس') ?></span></div>
                        <div class="metric"><strong><?= htmlspecialchars((string)($comparison['global_delta'] ?? '—'), ENT_QUOTES, 'UTF-8') ?></strong><span><?= __('landing.comparison_delta', 'الفارق') ?></span></div>
                    </div>
                </div>
            </section>

            <section class="panel">
                <div class="panel-inner">
                    <div class="eyebrow eyebrow-p"><i class="bi bi-bar-chart-line"></i><?= __('landing.competitor_comparison_title', 'لوحة المقارنة') ?></div>
                    <div class="matrix">
                        <?php
                        $rows = [
                            'copy' => __('landing.copy_axis', 'Copy'),
                            'design' => __('landing.design_axis', 'Design'),
                            'cta' => __('landing.cta_axis', 'CTA'),
                            'trust' => __('landing.trust_axis', 'Trust'),
                            'mobile' => __('landing.mobile_axis', 'Mobile'),
                        ];
                        foreach ($rows as $axis => $label):
                            $delta = (int)($comparison[$axis . '_delta'] ?? 0);
                            $lead = $delta >= 0 ? __('landing.comparison_ours', 'نحن') : __('landing.comparison_competitor', 'المنافس');
                        ?>
                        <div class="matrix-row">
                            <strong><?= htmlspecialchars($label, ENT_QUOTES, 'UTF-8') ?></strong>
                            <span><?= htmlspecialchars((string)($ourScores[$axis] ?? '—'), ENT_QUOTES, 'UTF-8') ?></span>
                            <span><?= htmlspecialchars((string)($competitorScores[$axis] ?? '—'), ENT_QUOTES, 'UTF-8') ?></span>
                            <span class="chip <?= $delta >= 0 ? 'win' : 'lose' ?>"><?= htmlspecialchars($lead . ' • ' . $delta, ENT_QUOTES, 'UTF-8') ?></span>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </section>

            <section class="panel">
                <div class="panel-inner">
                    <div class="grid2">
                        <div class="card">
                            <div class="eyebrow eyebrow-g"><i class="bi bi-stars"></i><?= __('landing.competitor_strengths', 'نقاط القوة') ?></div>
                            <ul><?php foreach ($strengths as $item): ?><li><?= htmlspecialchars((string)$item, ENT_QUOTES, 'UTF-8') ?></li><?php endforeach; ?></ul>
                        </div>
                        <div class="card">
                            <div class="eyebrow eyebrow-r"><i class="bi bi-exclamation-circle"></i><?= __('landing.competitor_weaknesses', 'نقاط الضعف') ?></div>
                            <ul><?php foreach ($weaknesses as $item): ?><li><?= htmlspecialchars((string)$item, ENT_QUOTES, 'UTF-8') ?></li><?php endforeach; ?></ul>
                        </div>
                        <div class="card">
                            <div class="eyebrow eyebrow-a"><i class="bi bi-lightning-charge"></i><?= __('landing.competitor_gaps', 'الثغرات التي يمكن استغلالها') ?></div>
                            <ul><?php foreach ($gaps as $item): ?><li><?= htmlspecialchars((string)$item, ENT_QUOTES, 'UTF-8') ?></li><?php endforeach; ?></ul>
                        </div>
                        <div class="card">
                            <div class="eyebrow eyebrow-t"><i class="bi bi-signpost"></i><?= __('landing.competitor_strategy', 'الاستراتيجية المقترحة') ?></div>
                            <span class="muted"><?= htmlspecialchars((string)($report['lp_strategy'] ?? ''), ENT_QUOTES, 'UTF-8') ?></span>
                            <ul><?php foreach ($priorityActions as $item): ?><li><?= htmlspecialchars((string)$item, ENT_QUOTES, 'UTF-8') ?></li><?php endforeach; ?></ul>
                        </div>
                    </div>
                </div>
            </section>

            <section class="panel">
                <div class="panel-inner">
                    <div class="grid2">
                        <div class="card">
                            <div class="eyebrow eyebrow-t"><i class="bi bi-layout-text-window"></i><?= __('landing.competitor_recommended_sections', 'الأقسام المقترحة') ?></div>
                            <ul><?php foreach ($sections as $item): ?><li><?= htmlspecialchars((string)$item, ENT_QUOTES, 'UTF-8') ?></li><?php endforeach; ?></ul>
                        </div>
                        <div class="card">
                            <div class="eyebrow eyebrow-p"><i class="bi bi-bullseye"></i><?= __('landing.competitor_recommended_angles', 'الزوايا المقترحة') ?></div>
                            <ul><?php foreach ($angles as $item): ?><li><?= htmlspecialchars((string)$item, ENT_QUOTES, 'UTF-8') ?></li><?php endforeach; ?></ul>
                        </div>
                        <div class="card">
                            <div class="eyebrow eyebrow-a"><i class="bi bi-chat-left-text"></i><?= __('landing.competitor_hooks_title', 'Hooks ونسخ مقترحة') ?></div>
                            <ul><?php foreach ($hooks as $item): ?><li><?= htmlspecialchars((string)$item, ENT_QUOTES, 'UTF-8') ?></li><?php endforeach; ?></ul>
                            <ul><?php foreach ($cta as $item): ?><li><?= htmlspecialchars((string)$item, ENT_QUOTES, 'UTF-8') ?></li><?php endforeach; ?></ul>
                        </div>
                        <div class="card">
                            <div class="eyebrow eyebrow-g"><i class="bi bi-shield-check"></i><?= __('landing.competitor_trust_title', 'الثقة والعرض وتجربة الاستخدام') ?></div>
                            <ul><?php foreach ($trust as $item): ?><li><?= htmlspecialchars((string)$item, ENT_QUOTES, 'UTF-8') ?></li><?php endforeach; ?></ul>
                            <ul><?php foreach ($ux as $item): ?><li><?= htmlspecialchars((string)$item, ENT_QUOTES, 'UTF-8') ?></li><?php endforeach; ?></ul>
                            <ul><?php foreach ($offers as $item): ?><li><?= htmlspecialchars((string)$item, ENT_QUOTES, 'UTF-8') ?></li><?php endforeach; ?></ul>
                        </div>
                    </div>
                </div>
            </section>
        </div>

        <aside class="stack">
            <section class="panel">
                <div class="panel-inner">
                    <div class="eyebrow eyebrow-o"><i class="bi bi-clipboard-data"></i><?= __('landing.competitor_priority_title', 'أولوية التنفيذ') ?></div>
                    <div class="cards">
                        <?php foreach ($priorityActions as $item): ?>
                            <div class="card"><strong><?= htmlspecialchars((string)$item, ENT_QUOTES, 'UTF-8') ?></strong></div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </section>

            <section class="panel">
                <div class="panel-inner">
                    <div class="eyebrow eyebrow-p"><i class="bi bi-graph-up-arrow"></i><?= __('landing.executive_metrics_title', 'مؤشرات تنفيذية') ?></div>
                    <div class="grid2">
                        <div class="metric"><strong><?= htmlspecialchars((string)($executiveMetrics['our_sections'] ?? '—'), ENT_QUOTES, 'UTF-8') ?></strong><span><?= __('landing.sections_detected', 'الأقسام المكتشفة') ?></span></div>
                        <div class="metric"><strong><?= htmlspecialchars((string)($executiveMetrics['concepts_ready'] ?? '—'), ENT_QUOTES, 'UTF-8') ?></strong><span><?= __('landing.concepts_ready', 'المفاهيم الجاهزة') ?></span></div>
                        <div class="metric"><strong><?= htmlspecialchars((string)($executiveMetrics['market'] ?? '—'), ENT_QUOTES, 'UTF-8') ?></strong><span><?= __('landing.market', 'السوق') ?></span></div>
                        <div class="metric"><strong><?= htmlspecialchars((string)($executiveMetrics['audience'] ?? '—'), ENT_QUOTES, 'UTF-8') ?></strong><span><?= __('landing.audience', 'الجمهور') ?></span></div>
                    </div>
                </div>
            </section>

            <section class="panel">
                <div class="panel-inner">
                    <div class="eyebrow eyebrow-a"><i class="bi bi-lightning"></i><?= __('landing.quick_wins', 'تحسينات سريعة') ?></div>
                    <div class="timeline">
                        <?php foreach ($quickWins as $item): ?>
                            <div class="timeline-item">
                                <strong><?= htmlspecialchars((string)$item, ENT_QUOTES, 'UTF-8') ?></strong>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </section>
        </aside>
    </div>
</div>

<script>
const PAGE_ID = <?= $pageId ?>;
const CSRF = <?= json_encode($csrf, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
const I18N = {
    running: <?= json_encode(__('landing.competitor_running', 'نجلب صفحة المنافس ونبني تقرير المقارنة الموسع الآن...'), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>,
    success: <?= json_encode(__('landing.competitor_analyzed', 'تحليل المنافس جاهز الآن.'), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>,
    error: <?= json_encode(__('landing.competitor_fetch_failed', 'تعذر جلب صفحة المنافس.'), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>,
    invalid: <?= json_encode(__('landing.competitor_invalid_url', 'يرجى إدخال رابط منافس صالح.'), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>
};
function showAlert(type,text){const box=document.getElementById('competitor-alert'); box.className='alert-box show '+type; box.textContent=text;}
async function readJsonResponse(response){const text=await response.text(); let data=null; try{data=text?JSON.parse(text):{};}catch(e){throw new Error(text||I18N.error);} if(!response.ok||data.success===false) throw new Error(data.error||I18N.error); return data;}
document.getElementById('btn-run-competitor').addEventListener('click', async function(){
    const url=(document.getElementById('competitor-url').value||'').trim();
    if(!url){showAlert('error', I18N.invalid); return;}
    const btn=this; const original=btn.innerHTML; btn.disabled=true; btn.innerHTML='<span class="spinner"></span><span>'+I18N.running+'</span>'; showAlert('info', I18N.running);
    try{
        const fd=new FormData(); fd.append('_csrf', CSRF); fd.append('url', url);
        const res=await fetch('/admin/ai-landing-pages/analyze-competitor/'+PAGE_ID, {method:'POST', body:fd});
        await readJsonResponse(res);
        showAlert('success', I18N.success);
        setTimeout(()=>window.location.reload(), 500);
    }catch(err){
        showAlert('error', err.message || I18N.error);
    }finally{
        btn.disabled=false; btn.innerHTML=original;
    }
});
document.getElementById('archive-search').addEventListener('input', function(){
    const q=(this.value||'').trim().toLowerCase();
    document.querySelectorAll('#archive-list .session-card').forEach(card=>{
        card.style.display = !q || (card.dataset.search||'').includes(q) ? '' : 'none';
    });
});
</script>
</body>
</html>
