<?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', 'المنتج'));
$agent = is_array($agent ?? null) ? $agent : [];
$workflow = is_array($workflow ?? null) ? $workflow : [];
$brief = is_array($workflow['brief'] ?? null) ? $workflow['brief'] : [];
$artifact = is_array($workflow['artifact'] ?? null) ? $workflow['artifact'] : [];
$stages = is_array($workflow['stages'] ?? null) ? $workflow['stages'] : [];
$history = is_array($workflow['history'] ?? null) ? array_reverse($workflow['history']) : [];
$workspace = is_array($agent['workspace'] ?? null) ? $agent['workspace'] : [];
$csrf = Csrf::token();
$destinationId = (string)($destination ?? 'landing_page');
$destinationTitle = (string)($workflow['title'] ?? __('landing.output_' . $destinationId, ucfirst(str_replace('_', ' ', $destinationId))));
$destinationGoal = (string)($workflow['goal'] ?? '');
$deliverables = is_array($workflow['deliverables'] ?? null) ? $workflow['deliverables'] : [];
$briefDeliverables = is_array($brief['deliverables'] ?? null) ? $brief['deliverables'] : [];
$primaryItems = is_array($artifact['primary_output']['items'] ?? null) ? $artifact['primary_output']['items'] : [];
$secondaryItems = is_array($artifact['secondary_output']['items'] ?? null) ? $artifact['secondary_output']['items'] : [];
$checklist = is_array($artifact['checklist'] ?? null) ? $artifact['checklist'] : [];
$sessionPages = is_array($productPages ?? null) ? $productPages : [];
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($destinationTitle . ' - ' . __('landing.destination_workflow_title', 'Destination Workflow'), 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') ?>;--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{display:flex;align-items:center;gap:14px;flex-wrap:wrap;padding:14px 24px;background:rgba(255,255,255,.86);backdrop-filter:blur(12px);border-bottom:1px solid var(--line)}
        .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(0,1.45fr) minmax(320px,.95fr);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:40px;line-height:1.15;font-weight:950;margin-top:12px}.muted{color:var(--muted);line-height:1.8}
        .status{display:flex;align-items:center;gap:8px;flex-wrap:wrap}.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.done{background:#ecfdf5;color:#166534;border-color:#bbf7d0}.chip.running{background:#eff6ff;color:#1d4ed8;border-color:#bfdbfe}.chip.ready{background:#fff7ed;color:#c2410c;border-color:#fed7aa}
        .grid2{display:grid;grid-template-columns:repeat(2,1fr);gap:14px}.stage-card,.card,.timeline-item,.metric,.session-card,.output-block{border:1px solid var(--line);border-radius:20px;background:#fff;padding:16px;display:grid;gap:10px}
        .stage-card.active{border-color:#fdba74;background:#fff7ed}.stage-card.done{border-color:#bbf7d0;background:#f0fdf4}.stage-card small{color:var(--muted)}
        .timeline{display:grid;gap:12px}.timeline-item{position:relative;padding-inline-start:18px}.timeline-item::before{content:"";position:absolute;inset-inline-start:8px;top:18px;bottom:-14px;width:2px;background:#e2e8f0}.timeline-item:last-child::before{display:none}
        .session-list{display:grid;gap:12px}.session-card{text-decoration:none;color:var(--text)}.session-card.active{border-color:#fdba74;background:#fff7ed}
        .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}
        @keyframes spin{to{transform:rotate(360deg)}}@media (max-width:1180px){.layout,.grid2{grid-template-columns:1fr}}
    </style>
</head>
<body>
<div class="shell">
    <div class="topbar">
        <div class="brand">
            <div class="brand-icon"><i class="bi bi-diagram-3"></i></div>
            <div>
                <div><?= __('landing.destination_workflow_title', 'Destination Workflow') ?></div>
                <small><?= __('landing.destination_workflow_subtitle', 'حوّل كل وجهة إلى خط إنتاج مستقل مع brief ومراحل ومخرجات محفوظة') ?></small>
            </div>
        </div>
        <div class="topbar-actions">
            <button type="button" class="btn-main" id="btn-run-workflow"><i class="bi bi-lightning-charge"></i><span><?= __('landing.run_workflow', 'تشغيل الـ Workflow') ?></span></button>
            <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">
        <div class="stack">
            <section class="panel hero">
                <div class="panel-inner">
                    <div class="eyebrow"><i class="bi bi-kanban"></i><?= htmlspecialchars($destinationTitle, ENT_QUOTES, 'UTF-8') ?></div>
                    <h1><?= htmlspecialchars($destinationTitle, ENT_QUOTES, 'UTF-8') ?></h1>
                    <p class="muted"><?= htmlspecialchars($destinationGoal !== '' ? $destinationGoal : __('landing.workflow_goal_fallback', 'هذا المسار يحوّل التحليل الحالي إلى مخرجات تنفيذية مستقلة قابلة للمراجعة والاعتماد.'), ENT_QUOTES, 'UTF-8') ?></p>
                    <div class="status">
                        <span class="chip <?= htmlspecialchars((string)($workflow['status'] ?? 'ready'), ENT_QUOTES, 'UTF-8') ?>" id="workflow-status-chip"><?= htmlspecialchars((string)($workflow['status'] ?? 'ready'), ENT_QUOTES, 'UTF-8') ?></span>
                        <span class="chip"><?= __('landing.workflow_current_stage', 'المرحلة الحالية') ?>: <strong style="margin-inline-start:6px"><?= htmlspecialchars((string)($workflow['current_stage'] ?? 'brief'), ENT_QUOTES, 'UTF-8') ?></strong></span>
                        <span class="chip"><?= __('landing.workflow_runs', 'عدد مرات التشغيل') ?>: <strong style="margin-inline-start:6px"><?= (int)($workflow['run_count'] ?? 0) ?></strong></span>
                    </div>
                    <div id="workflow-alert" class="alert-box<?= $success ? ' success show' : ($error ? ' error show' : '') ?>"><?= htmlspecialchars((string)($success ?: $error), ENT_QUOTES, 'UTF-8') ?></div>
                </div>
            </section>

            <section class="panel">
                <div class="panel-inner">
                    <div class="eyebrow"><i class="bi bi-signpost-split"></i><?= __('landing.workflow_stages', 'مراحل الـ Workflow') ?></div>
                    <div class="grid2">
                        <?php foreach ($stages as $stage): ?>
                            <?php $stageStatus = (string)($stage['status'] ?? 'todo'); ?>
                            <div class="stage-card <?= htmlspecialchars($stageStatus, ENT_QUOTES, 'UTF-8') ?><?= ($workflow['current_stage'] ?? '') === ($stage['id'] ?? '') ? ' active' : '' ?>">
                                <strong><?= htmlspecialchars((string)($stage['title'] ?? ''), ENT_QUOTES, 'UTF-8') ?></strong>
                                <small><?= htmlspecialchars((string)($stage['id'] ?? ''), ENT_QUOTES, 'UTF-8') ?></small>
                                <span class="chip <?= htmlspecialchars($stageStatus, ENT_QUOTES, 'UTF-8') ?>"><?= htmlspecialchars($stageStatus, 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"><i class="bi bi-file-earmark-richtext"></i><?= __('landing.workflow_brief', 'Brief الوجهة') ?></div>
                            <strong><?= htmlspecialchars((string)($brief['title'] ?? $destinationTitle), ENT_QUOTES, 'UTF-8') ?></strong>
                            <span class="muted"><?= htmlspecialchars((string)($brief['summary'] ?? $brief['objective'] ?? ''), ENT_QUOTES, 'UTF-8') ?></span>
                            <div class="output-block">
                                <strong><?= __('landing.prompt_label', 'البرومبت') ?></strong>
                                <span class="muted"><?= nl2br(htmlspecialchars((string)($brief['prompt'] ?? ''), ENT_QUOTES, 'UTF-8')) ?></span>
                            </div>
                            <div>
                                <?php foreach ($briefDeliverables as $item): ?>
                                    <span class="chip"><?= htmlspecialchars((string)$item, ENT_QUOTES, 'UTF-8') ?></span>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        <div class="card">
                            <div class="eyebrow"><i class="bi bi-box-seam"></i><?= __('landing.workflow_deliverables', 'المخرجات المطلوبة') ?></div>
                            <ul>
                                <?php foreach ($deliverables as $item): ?>
                                    <li><?= htmlspecialchars((string)$item, ENT_QUOTES, 'UTF-8') ?></li>
                                <?php endforeach; ?>
                            </ul>
                            <div class="output-block">
                                <strong><?= __('landing.workflow_checklist', 'قائمة التنفيذ') ?></strong>
                                <ul id="workflow-checklist">
                                    <?php foreach ($checklist as $item): ?>
                                        <li><?= htmlspecialchars((string)$item, ENT_QUOTES, 'UTF-8') ?></li>
                                    <?php endforeach; ?>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
            </section>

            <section class="panel">
                <div class="panel-inner">
                    <div class="eyebrow"><i class="bi bi-stars"></i><?= __('landing.workflow_artifact', 'المخرجات التنفيذية') ?></div>
                    <div class="grid2">
                        <div class="output-block" id="primary-output">
                            <strong><?= htmlspecialchars((string)($artifact['primary_output']['title'] ?? __('landing.workflow_primary_output', 'المخرج الرئيسي')), ENT_QUOTES, 'UTF-8') ?></strong>
                            <span class="muted"><?= htmlspecialchars((string)($artifact['summary'] ?? ''), ENT_QUOTES, 'UTF-8') ?></span>
                            <ul>
                                <?php foreach ($primaryItems as $item): ?>
                                    <li><?= htmlspecialchars((string)$item, ENT_QUOTES, 'UTF-8') ?></li>
                                <?php endforeach; ?>
                            </ul>
                        </div>
                        <div class="output-block" id="secondary-output">
                            <strong><?= htmlspecialchars((string)($artifact['secondary_output']['title'] ?? __('landing.workflow_secondary_output', 'المخرج الثانوي')), ENT_QUOTES, 'UTF-8') ?></strong>
                            <ul>
                                <?php foreach ($secondaryItems 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="eyebrow"><i class="bi bi-clock-history"></i><?= __('landing.workflow_history', 'سجل الـ Workflow') ?></div>
                    <div class="timeline">
                        <?php foreach ($history as $entry): ?>
                            <div class="timeline-item">
                                <strong><?= htmlspecialchars((string)($entry['title'] ?? ''), ENT_QUOTES, 'UTF-8') ?></strong>
                                <span class="muted"><?= htmlspecialchars((string)($entry['summary'] ?? ''), ENT_QUOTES, 'UTF-8') ?></span>
                                <small class="muted"><?= htmlspecialchars((string)($entry['stage'] ?? ''), ENT_QUOTES, 'UTF-8') ?> • <?= htmlspecialchars((string)($entry['at'] ?? ''), ENT_QUOTES, 'UTF-8') ?></small>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </section>
        </div>

        <aside class="stack">
            <section class="panel">
                <div class="panel-inner">
                    <div class="eyebrow"><i class="bi bi-info-circle"></i><?= __('landing.workflow_context', 'سياق التشغيل') ?></div>
                    <div class="grid2">
                        <div class="metric"><strong><?= htmlspecialchars($pageSlug, ENT_QUOTES, 'UTF-8') ?></strong><span><?= __('landing.page_slug', 'الرابط') ?></span></div>
                        <div class="metric"><strong><?= htmlspecialchars($pageStatus, ENT_QUOTES, 'UTF-8') ?></strong><span><?= __('landing.status', 'الحالة') ?></span></div>
                        <div class="metric"><strong><?= htmlspecialchars($productTitle, ENT_QUOTES, 'UTF-8') ?></strong><span><?= __('landing.workflow_product_context', 'المنتج') ?></span></div>
                        <div class="metric"><strong><?= htmlspecialchars((string)($workspace['selected_style'] ?? '—'), ENT_QUOTES, 'UTF-8') ?></strong><span><?= __('landing.style_system_title', 'نظام الـ Styles') ?></span></div>
                    </div>
                </div>
            </section>

            <section class="panel">
                <div class="panel-inner">
                    <div class="eyebrow"><i class="bi bi-collection"></i><?= __('landing.session_center_title', 'مركز الجلسات') ?></div>
                    <div class="session-list">
                        <?php foreach ($sessionPages as $sessionPage): ?>
                            <?php $active = (int)$sessionPage['id'] === $pageId; ?>
                            <a href="/admin/ai-landing-pages/destination/<?= (int)$sessionPage['id'] ?>/<?= urlencode($destinationId) ?>" class="session-card<?= $active ? ' active' : '' ?>">
                                <strong><?= htmlspecialchars((string)($sessionPage['name'] ?? ''), ENT_QUOTES, 'UTF-8') ?></strong>
                                <small class="muted"><?= htmlspecialchars((string)($sessionPage['slug'] ?? ''), ENT_QUOTES, 'UTF-8') ?></small>
                                <span class="chip <?= htmlspecialchars((string)($sessionPage['status'] ?? 'draft'), ENT_QUOTES, 'UTF-8') ?>"><?= htmlspecialchars((string)($sessionPage['status'] ?? 'draft'), ENT_QUOTES, 'UTF-8') ?></span>
                            </a>
                        <?php endforeach; ?>
                    </div>
                </div>
            </section>
        </aside>
    </div>
</div>
<script>
const PAGE_ID = <?= $pageId ?>;
const DESTINATION = <?= json_encode($destinationId, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
const CSRF = <?= json_encode($csrf, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
const I18N = {
    running: <?= json_encode(__('landing.workflow_running', 'يتم الآن تشغيل الـ Workflow وبناء المخرجات التنفيذية...'), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>,
    runSuccess: <?= json_encode(__('landing.workflow_run_success', 'تم تشغيل الـ Workflow وتحديث مخرجاته بنجاح.'), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>,
    runError: <?= json_encode(__('landing.workflow_run_error', 'تعذر تشغيل الـ Workflow.'), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>,
    runningLabel: <?= json_encode(__('landing.workflow_running_label', 'قيد التشغيل'), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>
};
function showAlert(type,text){const box=document.getElementById('workflow-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.runError);} if(!response.ok||data.success===false) throw new Error(data.error||I18N.runError); return data;}
document.getElementById('btn-run-workflow').addEventListener('click', async function(){
    const btn=this; const original=btn.innerHTML; btn.disabled=true; btn.innerHTML='<span class="spinner"></span><span>'+I18N.runningLabel+'</span>'; showAlert('info', I18N.running);
    try{const fd=new FormData(); fd.append('_csrf', CSRF); const res=await fetch('/admin/ai-landing-pages/destination-run/'+PAGE_ID+'/'+encodeURIComponent(DESTINATION), {method:'POST', body:fd}); await readJsonResponse(res); showAlert('success', I18N.runSuccess); setTimeout(()=>window.location.reload(), 600);}
    catch(err){showAlert('error', err.message||I18N.runError);}
    finally{btn.disabled=false; btn.innerHTML=original;}
});
</script>
</body>
</html>
