<?php
$center = is_array($center ?? null) ? $center : [];
$hospitalName = $hospital['name'] ?? strtoupper((string)($hospitalCode ?? 'NJCH'));
$isAr = current_lang() === 'ar';
$txt = function (string $en, string $ar = '') use ($isAr): string { return $isAr && $ar !== '' ? $ar : $en; };
$getText = function (array $item, string $key, string $fallback = '') use ($isAr): string {
    $arKey = $key . '_ar';
    if ($isAr && isset($item[$arKey]) && (string)$item[$arKey] !== '') { return (string)$item[$arKey]; }
    return isset($item[$key]) && (string)$item[$key] !== '' ? (string)$item[$key] : $fallback;
};
$metric = function ($value): string {
    if ($value === null || $value === '') { return '—'; }
    return number_format((float)$value, 0);
};
$money = function ($value): string {
    if ($value === null || $value === '') { return '—'; }
    return 'SAR ' . compact_money((float)$value);
};
$pct = function ($value): string {
    if ($value === null || $value === '') { return '—'; }
    return number_format((float)$value, 0) . '%';
};
$actionUrl = function (array $item): string {
    $type = (string)($item['link_type'] ?? $item['type'] ?? 'page');
    $target = (string)($item['target'] ?? 'dashboard');
    if ($type === 'public') { return $target; }
    return url_to($target);
};
$shortText = function (string $text, int $limit = 110): string {
    $text = trim((string)preg_replace('/\s+/', ' ', $text));
    if ($text === '') { return ''; }
    if (function_exists('mb_strlen') && function_exists('mb_substr')) {
        return mb_strlen($text) > $limit ? mb_substr($text, 0, $limit) . '…' : $text;
    }
    return strlen($text) > $limit ? substr($text, 0, $limit) . '...' : $text;
};

$system = is_array($center['system'] ?? null) ? $center['system'] : ['tone' => 'good', 'status' => 'STABLE', 'status_ar' => 'مستقر', 'text' => 'No blocking executive actions.', 'text_ar' => 'لا توجد إجراءات مانعة.'];
$operational = is_array($center['operational'] ?? null) ? $center['operational'] : [];
$metrics = is_array($center['metrics'] ?? null) ? $center['metrics'] : [];
$actions = is_array($center['actions'] ?? null) ? $center['actions'] : [];
$counts = is_array($center['counts'] ?? null) ? $center['counts'] : [];
$reviewWorkflow = is_array($center['review_workflow'] ?? null) ? $center['review_workflow'] : [];
$governanceWorkflow = is_array($center['governance'] ?? null) ? $center['governance'] : [];
$governanceSummary = is_array($governanceWorkflow['summary'] ?? null) ? $governanceWorkflow['summary'] : [];
$governanceStorage = (string)($governanceWorkflow['storage'] ?? 'json_fallback');
$reviewCounts = is_array($reviewWorkflow['counts'] ?? null) ? $reviewWorkflow['counts'] : ['open' => 0, 'reviewed' => 0, 'deferred' => 0];
$reviewManagement = is_array($reviewWorkflow['management'] ?? null) ? $reviewWorkflow['management'] : [];
$lastReviewActivity = is_array($reviewManagement['last_activity'] ?? null) ? $reviewManagement['last_activity'] : [];

$reviewCompletion = max(0, min(100, (int)($reviewManagement['completion_percent'] ?? 0)));
$reviewTotalActions = (int)($reviewManagement['total_actions'] ?? count($actions));
$reviewOpenCount = (int)($reviewManagement['open'] ?? 0);
$reviewReviewedCount = (int)($reviewManagement['reviewed'] ?? 0);
$reviewDeferredCount = (int)($reviewManagement['deferred'] ?? 0);
$reviewPendingCount = (int)($reviewManagement['pending_attention'] ?? 0);
$reviewAuditCount = (int)($reviewManagement['lifetime_audit_count'] ?? 0);
$reviewActionTitles = [];
foreach ($actions as $actionForTitle) {
    if (!is_array($actionForTitle)) { continue; }
    $actionKeyForTitle = (string)($actionForTitle['rule_id'] ?? '');
    if ($actionKeyForTitle === '') { continue; }
    $reviewActionTitles[$actionKeyForTitle] = $getText($actionForTitle, 'title', $actionKeyForTitle);
}
$lastReviewActionKey = (string)($lastReviewActivity['action_key'] ?? '');
$lastReviewActionTitle = $reviewActionTitles[$lastReviewActionKey] ?? ($lastReviewActionKey !== '' ? ucwords(str_replace('_', ' ', $lastReviewActionKey)) : '');
$reviewFilter = strtolower(trim((string)($_GET['review_status'] ?? 'all')));
if (!in_array($reviewFilter, ['all', 'open', 'reviewed', 'deferred', 'critical'], true)) { $reviewFilter = 'all'; }
$reviewStorage = (string)($reviewWorkflow['storage'] ?? 'json_fallback');
$quickTools = is_array($center['quick_tools'] ?? null) ? $center['quick_tools'] : [];
$lastUpdated = (string)($center['last_updated'] ?? '—');
$operationalDate = (string)($operational['operational_date'] ?? '—');
$window = trim((string)($operational['window_start'] ?? '') . ' → ' . (string)($operational['window_end'] ?? ''), ' →');
$isRollover = !empty($operational['is_rollover']);
$summaryAvailable = !empty($center['summary_available']);
$isStale = !empty($center['is_stale']);
$systemTone = (string)($system['tone'] ?? 'good');

$severityMeta = [
    'critical' => ['label' => $txt('Critical', 'حرج'), 'hint' => $txt('Immediate executive attention', 'انتباه تنفيذي فوري'), 'rank' => 1],
    'watch' => ['label' => $txt('Watch', 'متابعة'), 'hint' => $txt('Monitor and review today', 'متابعة ومراجعة اليوم'), 'rank' => 2],
    'routine' => ['label' => $txt('Routine', 'روتيني'), 'hint' => $txt('Standard review actions', 'إجراءات مراجعة قياسية'), 'rank' => 3],
    'opportunity' => ['label' => $txt('Opportunity', 'فرصة'), 'hint' => $txt('Improve flow and utilization', 'تحسين التدفق والاستفادة'), 'rank' => 4],
];

$priorityActions = [];
foreach ($actions as $idx => $action) {
    if (!is_array($action)) { continue; }
    $review = is_array($action['review'] ?? null) ? $action['review'] : [];
    $actionReviewStatus = strtolower((string)($review['status'] ?? 'open'));
    if (!in_array($actionReviewStatus, ['open', 'reviewed', 'deferred'], true)) { $actionReviewStatus = 'open'; }
    $sev = (string)($action['severity'] ?? 'routine');
    if (!isset($severityMeta[$sev])) { $sev = 'routine'; }
    if ($reviewFilter === 'critical' && $sev !== 'critical') { continue; }
    if (!in_array($reviewFilter, ['all', 'critical'], true) && $actionReviewStatus !== $reviewFilter) { continue; }
    $action['_severity'] = $sev;
    $action['_rank'] = (int)$severityMeta[$sev]['rank'];
    $action['_original_index'] = (int)$idx;
    $priorityActions[] = $action;
}
usort($priorityActions, function ($a, $b) {
    $ra = (int)($a['_rank'] ?? 99);
    $rb = (int)($b['_rank'] ?? 99);
    if ($ra === $rb) {
        return ((int)($a['sort'] ?? $a['priority'] ?? $a['_original_index'] ?? 0)) <=> ((int)($b['sort'] ?? $b['priority'] ?? $b['_original_index'] ?? 0));
    }
    return $ra <=> $rb;
});

$renderWorklistCard = function (array $action, int $number) use ($txt, $getText, $actionUrl, $shortText, $severityMeta) {
    $severity = (string)($action['_severity'] ?? $action['severity'] ?? 'routine');
    if (!isset($severityMeta[$severity])) { $severity = 'routine'; }
    $whyText = $getText($action, 'why', '');
    $recText = $getText($action, 'recommendation', '');
    $confidenceText = $getText($action, 'confidence', '');
    $reviewSource = $getText($action, 'review_source', '');
    $review = is_array($action['review'] ?? null) ? $action['review'] : [];
    $governance = is_array($action['governance'] ?? null) ? $action['governance'] : [];
    $governanceStatus = strtolower((string)($governance['accountability_status'] ?? 'unassigned'));
    $governanceLabels = [
        'unassigned' => $txt('Unassigned', 'غير مسند'),
        'assigned' => $txt('Assigned', 'مسند'),
        'due_soon' => $txt('Due soon', 'استحقاق قريب'),
        'follow_up_due' => $txt('Follow-up due', 'متابعة مستحقة'),
        'overdue' => $txt('Overdue', 'متأخر'),
        'escalated' => $txt('Escalated', 'مصعّد'),
        'resolved' => $txt('Resolved', 'مغلق'),
        'on_track' => $txt('On track', 'على المسار'),
    ];
    $governanceLabel = $governanceLabels[$governanceStatus] ?? ucwords(str_replace('_', ' ', $governanceStatus));
    $governanceSaved = (int)($governance['update_count'] ?? 0) > 0;
    $reviewStatus = strtolower((string)($review['status'] ?? 'open'));
    if (!in_array($reviewStatus, ['open', 'reviewed', 'deferred'], true)) { $reviewStatus = 'open'; }
    $reviewLabel = $reviewStatus === 'reviewed' ? $txt('Reviewed', 'تمت المراجعة') : ($reviewStatus === 'deferred' ? $txt('Deferred', 'مؤجل') : $txt('Open', 'مفتوح'));
    $previousReview = is_array($action['previous_review'] ?? null) ? $action['previous_review'] : [];
    $displayReview = (int)($review['review_count'] ?? 0) > 0 ? $review : $previousReview;
    $hasReviewHistory = !empty($displayReview);
    $reviewUrl = 'index.php?page=action-review&action=' . rawurlencode((string)($action['rule_id'] ?? '')) . '&lang=' . current_lang();
    ?>
    <article class="worklist-item worklist-<?= e($severity) ?>">
        <div class="worklist-rank"><b><?= e((string)$number) ?></b><span><?= e($severityMeta[$severity]['label']) ?></span></div>
        <div class="worklist-body">
            <div class="worklist-topline">
                <span><?= e(strtoupper((string)($action['category'] ?? 'action'))) ?></span>
                <?php if (!empty($action['metric'])): ?><em><?= e((string)$action['metric']) ?></em><?php endif; ?>
                <i class="review-state review-state-<?= e($reviewStatus) ?>"><?= e($reviewLabel) ?></i>
            </div>
            <h3><?= e($getText($action, 'title', 'Action')) ?></h3>
            <p><?= e($getText($action, 'text', '')) ?></p>
            <?php if ($hasReviewHistory): ?>
                <div class="worklist-review-meta">
                    <span><b><?= e($txt('Last review', 'آخر مراجعة')) ?></b><?= e((string)($displayReview['updated_at'] ?? '—')) ?></span>
                    <span><b><?= e($txt('By', 'بواسطة')) ?></b><?= e((string)($displayReview['updated_by'] ?? '—')) ?></span>
                    <?php if (!empty($displayReview['operational_date']) && (string)$displayReview['operational_date'] !== (string)($review['operational_date'] ?? '')): ?>
                        <em><?= e($txt('Previous operational day', 'من يوم تشغيلي سابق')) ?>: <?= e((string)$displayReview['operational_date']) ?></em>
                    <?php endif; ?>
                    <?php if (!empty($displayReview['note'])): ?><small><?= e($shortText((string)$displayReview['note'], 140)) ?></small><?php endif; ?>
                </div>
            <?php endif; ?>
            <?php if ($governanceSaved): ?>
                <div class="worklist-governance-meta governance-status-<?= e($governanceStatus) ?>">
                    <span><b><?= e($txt('Owner', 'المسؤول')) ?></b><?= e((string)($governance['owner_name'] ?? '') ?: '—') ?></span>
                    <span><b><?= e($txt('Assigned', 'المنفذ')) ?></b><?= e((string)($governance['assigned_to'] ?? '') ?: '—') ?></span>
                    <span><b><?= e($txt('Due', 'الاستحقاق')) ?></b><?= e((string)($governance['due_date'] ?? '') ?: '—') ?></span>
                    <em><?= e($governanceLabel) ?></em>
                </div>
            <?php endif; ?>
            <?php if ($whyText !== '' || $recText !== ''): ?>
                <div class="worklist-explain-mini">
                    <?php if ($whyText !== ''): ?><span><b><?= e($txt('Why', 'السبب')) ?></b><?= e($shortText($whyText, 96)) ?></span><?php endif; ?>
                    <?php if ($recText !== ''): ?><span><b><?= e($txt('Next', 'التالي')) ?></b><?= e($shortText($recText, 96)) ?></span><?php endif; ?>
                </div>
                <details class="exec-action-details worklist-details">
                    <summary><?= e($txt('Details', 'التفاصيل')) ?></summary>
                    <div class="exec-action-details-body">
                        <?php if ($confidenceText !== '' || $reviewSource !== ''): ?>
                            <div class="exec-detail-pills">
                                <?php if ($confidenceText !== ''): ?><span><?= e($confidenceText) ?></span><?php endif; ?>
                                <?php if ($reviewSource !== ''): ?><em><?= e($reviewSource) ?></em><?php endif; ?>
                            </div>
                        <?php endif; ?>
                        <?php if ($whyText !== ''): ?><div><b><?= e($txt('Why', 'السبب')) ?></b><span><?= e($whyText) ?></span></div><?php endif; ?>
                        <?php if ($recText !== ''): ?><div><b><?= e($txt('Next', 'التالي')) ?></b><span><?= e($recText) ?></span></div><?php endif; ?>
                        <?php if (!empty($action['observed']) || !empty($action['threshold'])): ?>
                            <div><b><?= e($txt('Rule', 'القاعدة')) ?></b><span><?= e((string)($action['observed'] ?? '')) ?><?= !empty($action['threshold']) ? ' / ' . e((string)$action['threshold']) : '' ?></span></div>
                        <?php endif; ?>
                    </div>
                </details>
            <?php endif; ?>
            <div class="worklist-actions"><a href="<?= e($actionUrl($action)) ?>"><?= e($getText($action, 'link_label', $txt('Review', 'مراجعة'))) ?> →</a><a class="review-workflow-link" href="<?= e($reviewUrl) ?>"><?= e($txt('Review workflow', 'سير المراجعة')) ?> →</a></div>
        </div>
    </article>
    <?php
};
?>

<section class="action-center action-center-worklist-layout action-review-workflow-scroll-clean action-review-audit-trail action-tone-<?= e($systemTone) ?>">
    <?php if (!empty($centerError)): ?>
        <div class="action-error"><strong><?= e($txt('Action Center could not fully load.', 'تعذر تحميل مركز الإجراءات بالكامل.')) ?></strong><span><?= e((string)$centerError) ?></span></div>
    <?php endif; ?>

    <section class="action-hero">
        <div class="action-hero-copy">
            <span class="action-overline">Phase 10.6.6</span>
            <h2><?= e($txt('Executive Action Center', 'مركز الإجراءات التنفيذي')) ?></h2>
            <p><?= e($txt('Managed executive worklist with controlled review transitions, durable ownership, due dates, follow-up commitments, escalation, resolution evidence, and Oracle audit trails.', 'قائمة تنفيذية مُدارة بحالات مراجعة واضحة ومسؤوليات دائمة وتواريخ استحقاق ومتابعة وتصعيد وإثبات إغلاق وسجلات تدقيق على Oracle.')) ?></p>
            <div class="action-hero-tags">
                <span><?= e($txt('Branch', 'الفرع')) ?>: <b><?= e((string)$hospitalName) ?></b></span>
                <span><?= e($txt('Operational Day', 'اليوم التشغيلي')) ?>: <b><?= e($operationalDate) ?></b></span>
                <span><?= e($txt('Last Updated', 'آخر تحديث')) ?>: <b><?= e($lastUpdated ?: '—') ?></b></span>
                <?php if (!empty($center['engine']['name'])): ?>
                    <span class="action-engine-pill"><b><?= e($txt('Rules Engine', 'محرك القواعد')) ?></b>: <?= e($txt('Explainable', 'مفسر')) ?></span>
                <?php endif; ?>
                <span class="review-flow-pill"><b><?= e($txt('Review Workflow', 'سير المراجعة')) ?></b>: <?= e((string)($reviewCounts['open'] ?? 0)) ?> <?= e($txt('open', 'مفتوح')) ?> / <?= e((string)($reviewCounts['reviewed'] ?? 0)) ?> <?= e($txt('reviewed', 'تمت')) ?></span>
                <span class="review-flow-pill review-storage-pill"><b><?= e($txt('Audit Trail', 'سجل التدقيق')) ?></b>: <?= e($reviewStorage === 'oracle' ? $txt('Oracle', 'Oracle') : $txt('JSON fallback', 'JSON احتياطي')) ?></span>
                <span class="review-flow-pill governance-flow-pill"><b><?= e($txt('Governance', 'الحوكمة')) ?></b>: <?= e((string)($governanceSummary['overdue'] ?? 0)) ?> <?= e($txt('overdue', 'متأخر')) ?> / <?= e((string)($governanceSummary['unassigned'] ?? 0)) ?> <?= e($txt('unassigned', 'غير مسند')) ?> · <?= e($governanceStorage === 'oracle' ? 'Oracle' : 'JSON fallback') ?></span>
            </div>
        </div>
        <div class="action-status-card">
            <small><?= e($txt('Executive Status', 'الحالة التنفيذية')) ?></small>
            <strong><?= e($getText($system, 'status', 'STABLE')) ?></strong>
            <p><?= e($getText($system, 'text', 'No blocking executive actions.')) ?></p>
            <div class="action-status-grid">
                <span><b><?= e((string)($counts['critical'] ?? 0)) ?></b><?= e($txt('Critical', 'حرج')) ?></span>
                <span><b><?= e((string)($counts['watch'] ?? 0)) ?></b><?= e($txt('Watch', 'متابعة')) ?></span>
                <span><b><?= e((string)($counts['routine'] ?? 0)) ?></b><?= e($txt('Routine', 'روتيني')) ?></span>
            </div>
        </div>
    </section>

    <section class="action-priority-strip" aria-label="Action counts">
        <?php foreach ($severityMeta as $key => $meta): ?>
            <article class="priority-chip priority-<?= e($key) ?> <?= (int)($counts[$key] ?? 0) > 0 ? 'has-count' : 'is-clear' ?>">
                <span><?= e($meta['label']) ?></span>
                <b><?= e((string)($counts[$key] ?? 0)) ?></b>
                <em><?= e($meta['hint']) ?></em>
            </article>
        <?php endforeach; ?>
    </section>

    <section class="review-management-summary review-management-summary-v2" aria-label="Review management summary">
        <header class="review-management-head">
            <div class="review-management-heading">
                <small><?= e($txt('Review Management', 'إدارة المراجعات')) ?></small>
                <h3><?= e($txt('Leadership review progress', 'تقدم مراجعات القيادة')) ?></h3>
                <p><?= e($txt('Track completion, pending attention, and the latest accountable review activity.', 'متابعة الإنجاز والإجراءات المنتظرة وآخر نشاط مراجعة موثّق.')) ?></p>
            </div>
            <a class="review-dashboard-open-link" href="<?= e(url_to('action-review-dashboard')) ?>"><?= e($txt('Open Review Dashboard', 'فتح لوحة المراجعات')) ?> →</a>
            <div class="review-completion-panel" aria-label="Review completion">
                <span><?= e($txt('Completion', 'نسبة الإنجاز')) ?></span>
                <strong><b><?= e((string)$reviewCompletion) ?></b><small>%</small></strong>
            </div>
        </header>

        <div class="review-progress-block">
            <div class="review-progress-track" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="<?= e((string)$reviewCompletion) ?>">
                <span style="width: <?= e((string)$reviewCompletion) ?>%"></span>
            </div>
            <div class="review-progress-caption">
                <span><b><?= e((string)$reviewReviewedCount) ?></b> <?= e($txt('of', 'من')) ?> <b><?= e((string)$reviewTotalActions) ?></b> <?= e($txt('actions reviewed', 'إجراءات تمت مراجعتها')) ?></span>
                <em><?= e((string)$reviewPendingCount) ?> <?= e($txt('pending attention', 'بانتظار المتابعة')) ?></em>
            </div>
        </div>

        <div class="review-management-grid review-management-kpis">
            <article class="review-kpi review-kpi-total">
                <span class="review-kpi-icon" aria-hidden="true">Σ</span>
                <div><small><?= e($txt('Total actions', 'إجمالي الإجراءات')) ?></small><strong><?= e((string)$reviewTotalActions) ?></strong></div>
            </article>
            <article class="review-kpi review-kpi-open">
                <span class="review-kpi-icon" aria-hidden="true">○</span>
                <div><small><?= e($txt('Open', 'مفتوح')) ?></small><strong><?= e((string)$reviewOpenCount) ?></strong></div>
            </article>
            <article class="review-kpi review-kpi-reviewed">
                <span class="review-kpi-icon" aria-hidden="true">✓</span>
                <div><small><?= e($txt('Reviewed', 'تمت المراجعة')) ?></small><strong><?= e((string)$reviewReviewedCount) ?></strong></div>
            </article>
            <article class="review-kpi review-kpi-deferred">
                <span class="review-kpi-icon" aria-hidden="true">↷</span>
                <div><small><?= e($txt('Deferred', 'مؤجل')) ?></small><strong><?= e((string)$reviewDeferredCount) ?></strong></div>
            </article>
            <article class="review-kpi review-kpi-pending">
                <span class="review-kpi-icon" aria-hidden="true">!</span>
                <div><small><?= e($txt('Pending attention', 'بانتظار المتابعة')) ?></small><strong><?= e((string)$reviewPendingCount) ?></strong></div>
            </article>
            <article class="review-kpi review-kpi-audit">
                <span class="review-kpi-icon" aria-hidden="true">◎</span>
                <div><small><?= e($txt('Audit history', 'سجل التدقيق')) ?></small><strong><?= e((string)$reviewAuditCount) ?></strong></div>
            </article>
        </div>

        <div class="review-management-last-activity review-management-last-activity-v2 <?= $lastReviewActivity ? 'has-activity' : 'is-empty' ?>">
            <div class="review-activity-icon" aria-hidden="true">↻</div>
            <div class="review-activity-content">
                <small><?= e($txt('Latest review activity', 'آخر نشاط للمراجعة')) ?></small>
                <?php if ($lastReviewActivity): ?>
                    <?php
                    $lastActivityOldStatus = strtolower(trim((string)($lastReviewActivity['old_status'] ?? '')));
                    $lastActivityNewStatus = strtolower(trim((string)($lastReviewActivity['new_status'] ?? 'open')));
                    $lastActivityNewStatusLabel = $lastActivityNewStatus !== '' ? ucfirst($lastActivityNewStatus) : $txt('Updated', 'تم التحديث');
                    $lastActivityHasTransition = $lastActivityOldStatus !== '' && $lastActivityOldStatus !== $lastActivityNewStatus;
                    ?>
                    <strong><?= e($lastReviewActionTitle !== '' ? $lastReviewActionTitle : $txt('Review activity', 'نشاط مراجعة')) ?></strong>
                    <span>
                        <i class="review-state review-state-<?= e($lastActivityNewStatus !== '' ? $lastActivityNewStatus : 'open') ?>"><?= e($lastActivityNewStatusLabel) ?></i>
                        <?php if ($lastActivityHasTransition): ?>
                            <?= e(ucfirst($lastActivityOldStatus)) ?> → <?= e($lastActivityNewStatusLabel) ?>
                        <?php else: ?>
                            <?= e($txt('Status changed to', 'تم تغيير الحالة إلى')) ?> <?= e($lastActivityNewStatusLabel) ?>
                        <?php endif; ?>
                    </span>
                <?php else: ?>
                    <strong><?= e($txt('No saved review activity yet', 'لا يوجد نشاط مراجعة محفوظ حتى الآن')) ?></strong>
                    <span><?= e($txt('The first saved review will appear here automatically.', 'ستظهر أول مراجعة محفوظة هنا تلقائيًا.')) ?></span>
                <?php endif; ?>
            </div>
            <?php if ($lastReviewActivity): ?>
                <div class="review-activity-meta">
                    <span><?= e((string)($lastReviewActivity['changed_at'] ?? '—')) ?></span>
                    <em><?= e((string)($lastReviewActivity['changed_by'] ?? '—')) ?></em>
                </div>
            <?php endif; ?>
        </div>
    </section>

    <section class="governance-command-strip" aria-label="Executive governance summary">
        <header>
            <div>
                <small><?= e($txt('Governance & Accountability', 'الحوكمة والمساءلة')) ?></small>
                <h3><?= e($txt('Ownership, due dates and follow-up control', 'إدارة المسؤولية والاستحقاقات والمتابعة')) ?></h3>
            </div>
            <a href="index.php?page=action-governance-dashboard&lang=<?= e(current_lang()) ?>"><?= e($txt('Open Governance Dashboard', 'فتح لوحة الحوكمة')) ?> →</a>
        </header>
        <div class="governance-command-kpis">
            <span><b><?= e((string)($governanceSummary['assigned'] ?? 0)) ?></b><?= e($txt('Assigned', 'مسند')) ?></span>
            <span class="gov-alert"><b><?= e((string)($governanceSummary['unassigned'] ?? 0)) ?></b><?= e($txt('Unassigned', 'غير مسند')) ?></span>
            <span class="gov-danger"><b><?= e((string)($governanceSummary['overdue'] ?? 0)) ?></b><?= e($txt('Overdue', 'متأخر')) ?></span>
            <span><b><?= e((string)($governanceSummary['follow_up_due'] ?? 0)) ?></b><?= e($txt('Follow-up due', 'متابعة مستحقة')) ?></span>
            <span><b><?= e((string)($governanceSummary['escalated'] ?? 0)) ?></b><?= e($txt('Escalated', 'مصعّد')) ?></span>
            <span class="gov-good"><b><?= e((string)($governanceSummary['resolved'] ?? 0)) ?></b><?= e($txt('Resolved', 'مغلق')) ?></span>
        </div>
    </section>

    <section class="executive-workboard">
        <section class="priority-worklist-panel">
            <header class="workboard-title">
                <div>
                    <small><?= e($txt('Priority Worklist', 'قائمة الأولويات')) ?></small>
                    <h3><?= e($txt('Today’s executive actions', 'إجراءات ومراجعات اليوم التنفيذية')) ?></h3>
                </div>
                <div class="review-filter-toolbar">
                    <span><?= e((string)count($priorityActions)) ?> <?= e($txt('actions', 'إجراءات')) ?></span>
                    <?php foreach (['all' => $txt('All', 'الكل'), 'open' => $txt('Open', 'مفتوح'), 'reviewed' => $txt('Reviewed', 'تمت'), 'deferred' => $txt('Deferred', 'مؤجل'), 'critical' => $txt('Critical only', 'الحرج فقط')] as $rfValue => $rfLabel): ?>
                        <a class="<?= $reviewFilter === $rfValue ? 'active' : '' ?>" href="<?= e(current_url(['review_status' => $rfValue])) ?>"><?= e($rfLabel) ?></a>
                    <?php endforeach; ?>
                </div>
            </header>

            <?php if (!empty($priorityActions)): ?>
                <div class="priority-worklist">
                    <?php $i = 1; foreach ($priorityActions as $action): ?>
                        <?php $renderWorklistCard($action, $i++); ?>
                    <?php endforeach; ?>
                </div>
            <?php else: ?>
                <div class="worklist-empty-state">
                    <b><?= e($txt('All clear', 'كل شيء واضح')) ?></b>
                    <span><?= e($txt('There are no executive actions requiring review right now.', 'لا توجد إجراءات تنفيذية تحتاج مراجعة حاليًا.')) ?></span>
                </div>
            <?php endif; ?>
        </section>

        <aside class="executive-context-panel">
            <header class="workboard-title compact">
                <div>
                    <small><?= e($txt('Context Signals', 'إشارات داعمة')) ?></small>
                    <h3><?= e($txt('Decision context', 'سياق القرار')) ?></h3>
                </div>
            </header>
            <div class="context-signal-grid">
                <article><small><?= e($txt('Data Freshness', 'حداثة البيانات')) ?></small><strong><?= e($isStale ? $txt('Needs refresh', 'تحتاج تحديث') : $txt('Fresh', 'حديثة')) ?></strong><em><?= e($lastUpdated ?: '—') ?></em></article>
                <article><small><?= e($txt('Revenue Pace', 'وتيرة الإيراد')) ?></small><strong><?= e($txt('Time-aware', 'مرتبطة بالوقت')) ?></strong><em><?= e($txt('Grace and flow calibrated', 'مضبوطة حسب الوقت والتدفق')) ?></em></article>
                <article><small><?= e($txt('Capacity Signal', 'إشارة الطاقة')) ?></small><strong><?= e($pct($metrics['occupancy_rate'] ?? null)) ?></strong><em><?= e($metric($metrics['available_beds'] ?? null)) ?> <?= e($txt('available beds', 'سرير متاح')) ?></em></article>
                <article><small><?= e($txt('Scheduler Health', 'حالة المجدول')) ?></small><strong><?= e($summaryAvailable && !$isStale ? $txt('Healthy', 'سليم') : $txt('Review', 'مراجعة')) ?></strong><em><?= e($txt('Auto refresh watch', 'متابعة التحديث التلقائي')) ?></em></article>
                <article><small><?= e($txt('Operational Window', 'نافذة التشغيل')) ?></small><strong><?= e($operationalDate) ?></strong><em><?= e($isRollover ? $txt('Night rollover active', 'تدوير ليلي مفعل') : $txt('Calendar day active', 'اليوم التقويمي مفعل')) ?></em></article>
                <article><small><?= e($txt('Beds', 'الأسرة')) ?></small><strong><?= e($metric($metrics['occupied_beds'] ?? null)) ?> / <?= e($metric($metrics['total_beds'] ?? null)) ?></strong><em><?= e($txt('Occupied / Total', 'مشغول / إجمالي')) ?></em></article>
            </div>
        </aside>
    </section>

    <section class="action-kpis">
        <article><small><?= e($txt('Summary Layer', 'طبقة الملخص')) ?></small><strong><?= e($summaryAvailable ? $txt('Active', 'مفعلة') : $txt('Unavailable', 'غير متاحة')) ?></strong><em><?= e($isStale ? $txt('Stale', 'قديم') : $txt('Fresh', 'حديث')) ?></em></article>
        <article><small><?= e($txt('Patient Flow', 'تدفق المرضى')) ?></small><strong><?= e($metric(($metrics['opd'] ?? 0) + ($metrics['er'] ?? 0))) ?></strong><em><?= e($txt('OPD + ER', 'عيادات + طوارئ')) ?></em></article>
        <article><small><?= e($txt('Occupancy', 'الإشغال')) ?></small><strong><?= e($pct($metrics['occupancy_rate'] ?? null)) ?></strong><em><?= e($metric($metrics['available_beds'] ?? null)) ?> <?= e($txt('available beds', 'سرير متاح')) ?></em></article>
        <article><small><?= e($txt('Today Revenue', 'إيراد اليوم')) ?></small><strong><?= e($money($metrics['today_total'] ?? null)) ?></strong><em><?= e($txt('Operational finance day', 'اليوم المالي التشغيلي')) ?></em></article>
        <article><small><?= e($txt('Doctors', 'الأطباء')) ?></small><strong><?= e($metric($metrics['active_doctors'] ?? null)) ?></strong><em><?= e($txt('active doctors', 'طبيب نشط')) ?></em></article>
    </section>

    <section class="action-ops-strip">
        <div><span>◷</span><b><?= e($txt('Operational Window', 'نافذة التشغيل')) ?></b><strong><?= e($window ?: '—') ?></strong><em><?= e($isRollover ? $txt('Night rollover active', 'تدوير ليلي مفعل') : $txt('Calendar day active', 'اليوم التقويمي مفعل')) ?></em></div>
        <div><span>▱</span><b><?= e($txt('Beds', 'الأسرة')) ?></b><strong><?= e($metric($metrics['occupied_beds'] ?? null)) ?> / <?= e($metric($metrics['total_beds'] ?? null)) ?></strong><em><?= e($txt('Occupied / Total', 'مشغول / إجمالي')) ?></em></div>
        <div><span>▣</span><b><?= e($txt('Operations', 'العمليات')) ?></b><strong><?= e($metric($metrics['performed_operations'] ?? null)) ?> / <?= e($metric($metrics['scheduled_operations'] ?? null)) ?></strong><em><?= e($txt('Performed / Scheduled', 'منفذ / مجدول')) ?></em></div>
        <div><span>◈</span><b><?= e($txt('Month Revenue', 'إيراد الشهر')) ?></b><strong><?= e($money($metrics['month_total'] ?? null)) ?></strong><em><?= e($txt('Net', 'الصافي')) ?> <?= e($money($metrics['net'] ?? null)) ?></em></div>
    </section>

    <section class="action-tools">
        <strong><?= e($txt('Executive Tools', 'أدوات تنفيذية')) ?></strong>
        <?php foreach ($quickTools as $tool): ?>
            <a href="<?= e($actionUrl($tool)) ?>"><span><?= e((string)($tool['icon'] ?? '•')) ?></span><?= e($getText($tool, 'label', 'Tool')) ?></a>
        <?php endforeach; ?>
    </section>

    <section class="action-runbook compact-runbook">
        <article><span>1</span><h3><?= e($txt('Detect', 'اكتشاف')) ?></h3><p><?= e($txt('Read executive KPIs from the fast summary layer.', 'قراءة المؤشرات من طبقة الملخص التنفيذية السريعة.')) ?></p></article>
        <article><span>2</span><h3><?= e($txt('Prioritize', 'ترتيب الأولويات')) ?></h3><p><?= e($txt('Sort all actions into one worklist by executive urgency.', 'ترتيب كل الإجراءات في قائمة واحدة حسب الأولوية التنفيذية.')) ?></p></article>
        <article><span>3</span><h3><?= e($txt('Open source dashboard', 'فتح اللوحة المصدر')) ?></h3><p><?= e($txt('Open the right detailed dashboard or diagnostic page.', 'فتح لوحة التفاصيل أو صفحة التشخيص المناسبة.')) ?></p></article>
        <article><span>4</span><h3><?= e($txt('Act', 'تنفيذ')) ?></h3><p><?= e($txt('Use the worklist as the daily leadership huddle agenda.', 'استخدام قائمة الأعمال كأجندة اجتماع القيادة اليومي.')) ?></p></article>
    </section>
</section>
