<?php
$center = is_array($center ?? null) ? $center : [];
$analytics = is_array($analytics ?? null) ? $analytics : [];
$isAr = current_lang() === 'ar';
$txt = function (string $en, string $ar = '') use ($isAr): string { return $isAr && $ar !== '' ? $ar : $en; };
$getTitle = function (array $item) use ($isAr): string {
    if ($isAr && !empty($item['title_ar'])) { return (string)$item['title_ar']; }
    return (string)($item['title'] ?? $item['action_key'] ?? 'Action');
};
$humanStatus = function (string $status) use ($txt): string {
    $status = strtolower(trim($status));
    if ($status === 'reviewed') { return $txt('Reviewed', 'تمت المراجعة'); }
    if ($status === 'deferred') { return $txt('Deferred', 'مؤجل'); }
    return $txt('Open', 'مفتوح');
};
$humanSeverity = function (string $severity) use ($txt): string {
    $map = [
        'critical' => $txt('Critical', 'حرج'),
        'watch' => $txt('Watch', 'متابعة'),
        'routine' => $txt('Routine', 'روتيني'),
        'opportunity' => $txt('Opportunity', 'فرصة'),
    ];
    $severity = strtolower(trim($severity));
    return $map[$severity] ?? $map['routine'];
};
$short = function (string $value, int $limit = 120): string {
    $value = trim((string)preg_replace('/\s+/', ' ', $value));
    if ($value === '') { return ''; }
    if (function_exists('mb_strlen') && function_exists('mb_substr')) {
        return mb_strlen($value) > $limit ? mb_substr($value, 0, $limit) . '…' : $value;
    }
    return strlen($value) > $limit ? substr($value, 0, $limit) . '...' : $value;
};
$current = is_array($analytics['current'] ?? null) ? $analytics['current'] : [];
$window = is_array($analytics['window'] ?? null) ? $analytics['window'] : [];
$trend = is_array($analytics['trend'] ?? null) ? $analytics['trend'] : [];
$severityMatrix = is_array($analytics['severity_matrix'] ?? null) ? $analytics['severity_matrix'] : [];
$attentionQueue = is_array($analytics['attention_queue'] ?? null) ? $analytics['attention_queue'] : [];
$topActions = is_array($analytics['top_actions'] ?? null) ? $analytics['top_actions'] : [];
$reviewers = is_array($analytics['reviewers'] ?? null) ? $analytics['reviewers'] : [];
$recentActivity = is_array($analytics['recent_activity'] ?? null) ? $analytics['recent_activity'] : [];
$purity = is_array($analytics['purity'] ?? null) ? $analytics['purity'] : [];
$includeQaActivity = !empty($includeQaActivity) || !empty($purity['include_qa_activity']);
$qaRowsDetected = (int)($purity['qa_rows_detected'] ?? 0);
$qaRowsExcluded = (int)($purity['excluded_qa_count'] ?? 0);
$periodDays = (int)($analytics['period_days'] ?? ($days ?? 30));
$completion = (int)($current['completion_percent'] ?? 0);
$pending = (int)($current['pending_attention'] ?? 0);
$riskLevel = (string)($current['risk_level'] ?? 'watch');
$trendMax = 1;
foreach ($trend as $row) { $trendMax = max($trendMax, (int)($row['audit_count'] ?? 0)); }
$trendDisplay = $trend;
if (count($trendDisplay) > 30) { $trendDisplay = array_slice($trendDisplay, -30); }
$velocity = (int)($window['velocity_trend_percent'] ?? 0);
$hospitalName = $hospital['name'] ?? strtoupper((string)($hospitalCode ?? 'NJCH'));
$operational = is_array($center['operational'] ?? null) ? $center['operational'] : [];
$operationalDate = (string)($operational['operational_date'] ?? ($analytics['period_end'] ?? date('Y-m-d')));
$lastUpdated = (string)($center['last_updated'] ?? '');
$severityOrder = ['critical', 'watch', 'routine', 'opportunity'];
?>

<section class="executive-review-dashboard executive-review-dashboard-v1065 executive-review-dashboard-v10651 risk-<?= e($riskLevel) ?>">
    <?php if (!empty($centerError)): ?>
        <div class="action-error"><strong><?= e($txt('Executive Review Dashboard could not fully load.', 'تعذر تحميل لوحة المراجعات التنفيذية بالكامل.')) ?></strong><span><?= e((string)$centerError) ?></span></div>
    <?php endif; ?>

    <section class="review-dashboard-hero">
        <div class="review-dashboard-hero-copy">
            <span class="action-overline">Phase 10.6.5.1</span>
            <h2><?= e($txt('Executive Review Dashboard', 'لوحة المراجعات التنفيذية')) ?></h2>
            <p><?= e($txt('Management summary of review completion, pending executive attention, audit activity, reviewer accountability, and cross-day trends.', 'ملخص إداري لتقدم المراجعات والإجراءات المنتظرة ونشاط التدقيق ومسؤولية المراجعين والاتجاهات عبر الأيام.')) ?></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>
                <span class="review-storage-pill"><b><?= e($txt('Audit Storage', 'تخزين التدقيق')) ?></b>: <?= e(strtoupper((string)($analytics['storage'] ?? 'oracle'))) ?></span>
                <span class="review-purity-pill <?= $includeQaActivity ? 'technical' : 'production' ?>"><b><?= e($txt('Analytics mode', 'وضع التحليلات')) ?></b>: <?= e($includeQaActivity ? $txt('Technical + QA', 'فني + QA') : $txt('Production only', 'إنتاج فقط')) ?></span>
            </div>
        </div>
        <div class="review-dashboard-hero-actions">
            <a class="review-dashboard-back" href="<?= e(url_to('action-center')) ?>">← <?= e($txt('Back to Action Center', 'العودة إلى مركز الإجراءات')) ?></a>
            <a class="review-dashboard-governance-link" href="<?= e(url_to('action-governance-dashboard')) ?>"><?= e($txt('Governance Dashboard', 'لوحة الحوكمة')) ?> →</a>
            <div class="review-period-selector" aria-label="Review dashboard period">
                <?php foreach ([7, 14, 30, 60] as $period): ?>
                    <a class="<?= $periodDays === $period ? 'active' : '' ?>" href="<?= e(url_to('action-review-dashboard', ['days' => $period, 'include_qa' => $includeQaActivity ? '1' : '0'])) ?>"><?= e((string)$period) ?> <?= e($txt('days', 'يوم')) ?></a>
                <?php endforeach; ?>
            </div>
            <a class="review-qa-activity-toggle <?= $includeQaActivity ? 'active' : '' ?>" href="<?= e(url_to('action-review-dashboard', ['days' => $periodDays, 'include_qa' => $includeQaActivity ? '0' : '1'])) ?>">
                <?= e($includeQaActivity ? $txt('Hide QA activity', 'إخفاء نشاط QA') : $txt('Include QA activity', 'تضمين نشاط QA')) ?>
            </a>
        </div>
    </section>

    <div class="review-analytics-purity-banner <?= $includeQaActivity ? 'technical' : 'production' ?>">
        <div>
            <strong><?= e($includeQaActivity ? $txt('Technical analytics view', 'عرض تحليلات فني') : $txt('Production analytics protected', 'التحليلات الإنتاجية محمية')) ?></strong>
            <span><?= e($includeQaActivity
                ? $txt('Automated QA activity is included for technical verification only.', 'تم تضمين نشاط الاختبارات الآلية لأغراض التحقق الفني فقط.')
                : $txt('Automated QA activity is excluded from management KPIs, reviewer accountability, velocity, rankings, and recent activity.', 'تم استبعاد نشاط الاختبارات الآلية من مؤشرات الإدارة ومسؤولية المراجعين والسرعة والترتيب وأحدث النشاطات.')) ?></span>
        </div>
        <div class="review-purity-counts">
            <span><b><?= e((string)($purity['management_audit_count'] ?? ($window['audit_count'] ?? 0))) ?></b><?= e($txt('management events', 'أحداث إدارية')) ?></span>
            <span><b><?= e((string)$qaRowsDetected) ?></b><?= e($txt('QA events detected', 'أحداث QA مكتشفة')) ?></span>
            <?php if (!$includeQaActivity): ?><span><b><?= e((string)$qaRowsExcluded) ?></b><?= e($txt('excluded', 'مستبعدة')) ?></span><?php endif; ?>
        </div>
    </div>

    <section class="review-dashboard-kpis">
        <article class="review-dashboard-kpi kpi-completion">
            <span class="review-dashboard-kpi-icon">✓</span>
            <div><small><?= e($txt('Current completion', 'الإنجاز الحالي')) ?></small><strong><?= e((string)$completion) ?>%</strong><em><?= e((string)($current['reviewed'] ?? 0)) ?> / <?= e((string)($current['total_actions'] ?? 0)) ?> <?= e($txt('actions reviewed', 'إجراءات تمت مراجعتها')) ?></em></div>
        </article>
        <article class="review-dashboard-kpi kpi-pending">
            <span class="review-dashboard-kpi-icon">!</span>
            <div><small><?= e($txt('Pending attention', 'بانتظار المتابعة')) ?></small><strong><?= e((string)$pending) ?></strong><em><?= e((string)($current['critical_pending'] ?? 0)) ?> <?= e($txt('critical pending', 'حرج قيد الانتظار')) ?></em></div>
        </article>
        <article class="review-dashboard-kpi kpi-activity">
            <span class="review-dashboard-kpi-icon">↻</span>
            <div><small><?= e($txt('7-day audit activity', 'نشاط التدقيق خلال 7 أيام')) ?></small><strong><?= e((string)($window['activity_7d'] ?? 0)) ?></strong><em class="velocity <?= $velocity >= 0 ? 'up' : 'down' ?>"><?= $velocity >= 0 ? '+' : '' ?><?= e((string)$velocity) ?>% <?= e($txt('vs previous 7 days', 'مقارنة بالسبعة أيام السابقة')) ?></em></div>
        </article>
        <article class="review-dashboard-kpi kpi-reviewers">
            <span class="review-dashboard-kpi-icon">◎</span>
            <div><small><?= e($txt('Active reviewers', 'المراجعون النشطون')) ?></small><strong><?= e((string)($window['active_reviewers'] ?? 0)) ?></strong><em><?= e((string)($window['audit_count'] ?? 0)) ?> <?= e($txt('audit events in selected window', 'حدث تدقيق في الفترة المحددة')) ?></em></div>
        </article>
    </section>

    <section class="review-dashboard-grid review-dashboard-grid-primary">
        <article class="review-dashboard-panel review-trend-panel">
            <header class="review-dashboard-panel-head">
                <div><small><?= e($txt('Cross-day trend', 'اتجاه عبر الأيام')) ?></small><h3><?= e($txt('Review activity over time', 'نشاط المراجعة عبر الزمن')) ?></h3></div>
                <span><?= e((string)$periodDays) ?> <?= e($txt('days', 'يوم')) ?></span>
            </header>
            <div class="review-trend-legend">
                <span class="reviewed"><?= e($txt('Reviewed', 'تمت المراجعة')) ?></span>
                <span class="deferred"><?= e($txt('Deferred', 'مؤجل')) ?></span>
                <span class="reopened"><?= e($txt('Reopened', 'أعيد فتحه')) ?></span>
            </div>
            <?php if ($trendDisplay): ?>
                <div class="review-trend-chart" aria-label="Daily review activity chart">
                    <?php foreach ($trendDisplay as $row): ?>
                        <?php
                        $count = (int)($row['audit_count'] ?? 0);
                        $height = max(4, (int)round(($count / $trendMax) * 100));
                        $dateLabel = substr((string)($row['date'] ?? ''), 5);
                        ?>
                        <div class="review-trend-day" title="<?= e((string)($row['date'] ?? '')) ?>: <?= e((string)$count) ?>">
                            <span class="review-trend-count"><?= e((string)$count) ?></span>
                            <div class="review-trend-bar-wrap"><i class="review-trend-bar" style="height: <?= e((string)$height) ?>%"></i></div>
                            <small><?= e($dateLabel) ?></small>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php else: ?>
                <div class="review-dashboard-empty"><?= e($txt('No audit activity exists in the selected period yet.', 'لا يوجد نشاط تدقيق في الفترة المحددة حتى الآن.')) ?></div>
            <?php endif; ?>
            <div class="review-trend-summary">
                <span><b><?= e((string)($window['reviewed'] ?? 0)) ?></b><?= e($txt('Reviewed transitions', 'انتقالات إلى تمت المراجعة')) ?></span>
                <span><b><?= e((string)($window['deferred'] ?? 0)) ?></b><?= e($txt('Deferrals', 'حالات تأجيل')) ?></span>
                <span><b><?= e((string)($window['reopened'] ?? 0)) ?></b><?= e($txt('Reopened', 'إعادة فتح')) ?></span>
            </div>
        </article>

        <article class="review-dashboard-panel review-status-panel">
            <header class="review-dashboard-panel-head">
                <div><small><?= e($txt('Current state', 'الحالة الحالية')) ?></small><h3><?= e($txt('Review status distribution', 'توزيع حالات المراجعة')) ?></h3></div>
            </header>
            <div class="review-status-donut-wrap">
                <div class="review-status-donut" style="--completion: <?= e((string)$completion) ?>%;"><span><b><?= e((string)$completion) ?>%</b><?= e($txt('complete', 'مكتمل')) ?></span></div>
                <div class="review-status-breakdown">
                    <span class="status-open"><i></i><b><?= e((string)($current['open'] ?? 0)) ?></b><?= e($txt('Open', 'مفتوح')) ?></span>
                    <span class="status-reviewed"><i></i><b><?= e((string)($current['reviewed'] ?? 0)) ?></b><?= e($txt('Reviewed', 'تمت المراجعة')) ?></span>
                    <span class="status-deferred"><i></i><b><?= e((string)($current['deferred'] ?? 0)) ?></b><?= e($txt('Deferred', 'مؤجل')) ?></span>
                </div>
            </div>
            <div class="review-risk-banner risk-<?= e($riskLevel) ?>">
                <small><?= e($txt('Management attention level', 'مستوى اهتمام الإدارة')) ?></small>
                <strong><?= e($riskLevel === 'high' ? $txt('HIGH', 'مرتفع') : ($riskLevel === 'good' ? $txt('CLEAR', 'واضح') : $txt('WATCH', 'متابعة'))) ?></strong>
                <span><?= e((string)($current['oldest_pending_days'] ?? 0)) ?> <?= e($txt('days oldest pending action', 'يوم لأقدم إجراء منتظر')) ?></span>
            </div>
        </article>
    </section>

    <section class="review-dashboard-grid review-dashboard-grid-secondary">
        <article class="review-dashboard-panel review-severity-panel">
            <header class="review-dashboard-panel-head">
                <div><small><?= e($txt('Priority matrix', 'مصفوفة الأولويات')) ?></small><h3><?= e($txt('Actions by severity and review status', 'الإجراءات حسب الأولوية وحالة المراجعة')) ?></h3></div>
            </header>
            <div class="review-severity-matrix">
                <div class="review-severity-row review-severity-head"><span><?= e($txt('Severity', 'الأولوية')) ?></span><b><?= e($txt('Open', 'مفتوح')) ?></b><b><?= e($txt('Reviewed', 'تمت')) ?></b><b><?= e($txt('Deferred', 'مؤجل')) ?></b><b><?= e($txt('Total', 'الإجمالي')) ?></b></div>
                <?php foreach ($severityOrder as $severity): ?>
                    <?php $row = is_array($severityMatrix[$severity] ?? null) ? $severityMatrix[$severity] : []; ?>
                    <div class="review-severity-row severity-<?= e($severity) ?>"><span><i></i><?= e($humanSeverity($severity)) ?></span><b><?= e((string)($row['open'] ?? 0)) ?></b><b><?= e((string)($row['reviewed'] ?? 0)) ?></b><b><?= e((string)($row['deferred'] ?? 0)) ?></b><b><?= e((string)($row['total'] ?? 0)) ?></b></div>
                <?php endforeach; ?>
            </div>
        </article>

        <article class="review-dashboard-panel review-attention-panel">
            <header class="review-dashboard-panel-head">
                <div><small><?= e($txt('Attention queue', 'قائمة المتابعة')) ?></small><h3><?= e($txt('Unresolved executive actions', 'الإجراءات التنفيذية غير المحسومة')) ?></h3></div>
                <span><?= e((string)$pending) ?> <?= e($txt('pending', 'منتظر')) ?></span>
            </header>
            <?php if ($attentionQueue): ?>
                <div class="review-attention-list">
                    <?php foreach (array_slice($attentionQueue, 0, 6) as $item): ?>
                        <a href="<?= e(url_to('action-review', ['action' => (string)($item['action_key'] ?? '')])) ?>" class="review-attention-item severity-<?= e((string)($item['severity'] ?? 'routine')) ?>">
                            <span class="review-attention-severity"><?= e($humanSeverity((string)($item['severity'] ?? 'routine'))) ?></span>
                            <strong><?= e($getTitle($item)) ?></strong>
                            <em class="review-state review-state-<?= e((string)($item['status'] ?? 'open')) ?>"><?= e($humanStatus((string)($item['status'] ?? 'open'))) ?></em>
                            <small><?= e((string)($item['waiting_days'] ?? 0)) ?> <?= e($txt('days waiting', 'يوم انتظار')) ?></small>
                        </a>
                    <?php endforeach; ?>
                </div>
            <?php else: ?>
                <div class="review-dashboard-empty success"><?= e($txt('All current actions are reviewed.', 'تمت مراجعة جميع الإجراءات الحالية.')) ?></div>
            <?php endif; ?>
        </article>
    </section>

    <section class="review-dashboard-grid review-dashboard-grid-tertiary">
        <article class="review-dashboard-panel review-top-actions-panel">
            <header class="review-dashboard-panel-head">
                <div><small><?= e($txt('Audit concentration', 'تركيز نشاط التدقيق')) ?></small><h3><?= e($txt('Most reviewed actions', 'أكثر الإجراءات مراجعة')) ?></h3></div>
            </header>
            <?php if ($topActions): ?>
                <div class="review-ranking-list">
                    <?php $maxActionActivity = max(1, max(array_map(function ($item) { return (int)($item['activity_count'] ?? 0); }, $topActions))); ?>
                    <?php foreach (array_slice($topActions, 0, 6) as $index => $item): ?>
                        <?php $activity = (int)($item['activity_count'] ?? 0); $bar = max(4, (int)round(($activity / $maxActionActivity) * 100)); ?>
                        <div class="review-ranking-row">
                            <b class="review-rank-number"><?= e((string)($index + 1)) ?></b>
                            <div class="review-rank-main"><strong><?= e($getTitle($item)) ?></strong><span><i style="width: <?= e((string)$bar) ?>%"></i></span><small><?= e((string)$activity) ?> <?= e($txt('audit events', 'أحداث تدقيق')) ?> · <?= e((string)($item['reviewed'] ?? 0)) ?> <?= e($txt('reviewed', 'تمت')) ?></small></div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php else: ?>
                <div class="review-dashboard-empty"><?= e($txt('No review history exists in this period.', 'لا يوجد تاريخ مراجعات في هذه الفترة.')) ?></div>
            <?php endif; ?>
        </article>

        <article class="review-dashboard-panel review-reviewers-panel">
            <header class="review-dashboard-panel-head">
                <div><small><?= e($txt('Accountability', 'المسؤولية')) ?></small><h3><?= e($txt('Reviewer activity', 'نشاط المراجعين')) ?></h3></div>
            </header>
            <?php if ($reviewers): ?>
                <div class="review-reviewer-list">
                    <?php foreach (array_slice($reviewers, 0, 6) as $reviewer): ?>
                        <div class="review-reviewer-row">
                            <span class="review-reviewer-avatar"><?= e(strtoupper(substr((string)($reviewer['reviewer'] ?? '?'), 0, 1))) ?></span>
                            <div><strong><?= e((string)($reviewer['reviewer'] ?? 'system')) ?></strong><small><?= e((string)($reviewer['last_activity'] ?? '—')) ?></small></div>
                            <b><?= e((string)($reviewer['activity_count'] ?? 0)) ?></b>
                            <em><?= e((string)($reviewer['reviewed'] ?? 0)) ?> ✓</em>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php else: ?>
                <div class="review-dashboard-empty"><?= e($txt('No reviewer activity exists in this period.', 'لا يوجد نشاط مراجعين في هذه الفترة.')) ?></div>
            <?php endif; ?>
        </article>
    </section>

    <section class="review-dashboard-panel review-recent-panel">
        <header class="review-dashboard-panel-head">
            <div><small><?= e($txt('Oracle audit timeline', 'الخط الزمني لتدقيق Oracle')) ?></small><h3><?= e($txt('Recent review activity', 'أحدث نشاط للمراجعات')) ?></h3></div>
            <span><?= e((string)($analytics['period_start'] ?? '')) ?> → <?= e((string)($analytics['period_end'] ?? '')) ?></span>
        </header>
        <?php if ($recentActivity): ?>
            <div class="review-recent-timeline">
                <?php foreach ($recentActivity as $item): ?>
                    <?php
                    $oldStatus = strtolower((string)($item['old_status'] ?? ''));
                    $newStatus = strtolower((string)($item['new_status'] ?? 'open'));
                    $transition = $oldStatus !== '' && $oldStatus !== $newStatus
                        ? $humanStatus($oldStatus) . ' → ' . $humanStatus($newStatus)
                        : $txt('Status changed to', 'تم تغيير الحالة إلى') . ' ' . $humanStatus($newStatus);
                    ?>
                    <a class="review-recent-event status-<?= e($newStatus) ?>" href="<?= e(url_to('action-review', ['action' => (string)($item['action_key'] ?? '')])) ?>">
                        <span class="review-recent-dot"></span>
                        <div class="review-recent-main"><strong><?= e($getTitle($item)) ?></strong><small><?= e($transition) ?></small></div>
                        <div class="review-recent-meta"><b><?= e((string)($item['changed_by'] ?? 'system')) ?></b><span><?= e((string)($item['changed_at'] ?? '—')) ?></span></div>
                    </a>
                <?php endforeach; ?>
            </div>
        <?php else: ?>
            <div class="review-dashboard-empty"><?= e($txt('No audit events exist in the selected period yet.', 'لا توجد أحداث تدقيق في الفترة المحددة حتى الآن.')) ?></div>
        <?php endif; ?>
    </section>
</section>
