<?php
$executive = is_array($executive ?? null) ? $executive : [];
$hospitalName = (string)($hospital['name'] ?? 'New Jeddah');
$isAr = current_lang() === 'ar';

$txt = static function (string $en, string $ar = '') use ($isAr): string {
    return $isAr && $ar !== '' ? $ar : $en;
};
$num = static function ($value): string {
    return number_format((float)$value, 0);
};
$money = static function ($value): string {
    return 'SAR ' . compact_money((float)$value);
};
$get = static function (array $arr, string $key) {
    return array_key_exists($key, $arr) ? $arr[$key] : null;
};

$flow = is_array($executive['flow'] ?? null) ? $executive['flow'] : [];
$finance = is_array($executive['finance'] ?? null) ? $executive['finance'] : [];
$capacity = is_array($executive['capacity'] ?? null) ? $executive['capacity'] : [];
$clinical = is_array($executive['clinical'] ?? null) ? $executive['clinical'] : [];
$status = is_array($executive['status'] ?? null) ? $executive['status'] : [
    'status' => 'STABLE',
    'tone' => 'good',
    'text' => '',
];
$alerts = is_array($executive['alerts'] ?? null) ? $executive['alerts'] : [];
$actions = is_array($executive['actions'] ?? null) ? $executive['actions'] : [];
$isFastMode = !empty($executive['is_fast_mode']);
$isSummaryMode = ((string)($executive['mode'] ?? '') === 'summary');

$operational = is_array($executive['operational'] ?? null) ? $executive['operational'] : [];
$operationalDate = (string)($operational['operational_date'] ?? ($executive['today'] ?? date('Y-m-d')));
$operationalWindow = trim(
    (string)($operational['window_start'] ?? '') . ' → ' . (string)($operational['window_end'] ?? ''),
    ' →'
);
$lastUpdated = (string)($executive['last_updated'] ?? date('Y-m-d H:i'));

$smartCount = static function ($value, bool $trusted = true) use ($isFastMode, $num): string {
    if ($value === null || $value === '') return '—';
    if ($isFastMode && !$trusted && (float)$value == 0.0) return '—';
    return $num($value);
};
$smartMoney = static function ($value, bool $trusted = true) use ($isFastMode, $money): string {
    if ($value === null || $value === '') return '—';
    if ($isFastMode && !$trusted && (float)$value == 0.0) return '—';
    return $money($value);
};
$smartPct = static function ($value, bool $trusted = true, int $decimals = 0) use ($isFastMode): string {
    if ($value === null || $value === '') return '—';
    if ($isFastMode && !$trusted && (float)$value == 0.0) return '—';
    return number_format((float)$value, $decimals) . '%';
};

$occupancyRate = $capacity['occupancy_rate'] ?? null;
$monthRevenue = $get($finance, 'month_total');
$availableBeds = $get($capacity, 'available_beds');
$totalBeds = $get($capacity, 'total_beds');
$occupiedBeds = ($totalBeds !== null && $availableBeds !== null)
    ? max(0, (float)$totalBeds - (float)$availableBeds)
    : null;
$admissions = $get($flow, 'admissions');
$discharges = $get($flow, 'discharges');
$expectedDischarges = $get($capacity, 'expected_discharges');
$er = (int)($get($flow, 'er') ?? 0);
$opd = $get($flow, 'opd');
$followUp = $get($flow, 'follow_up');
$firstVisits = $get($flow, 'first_visits');
$activeDoctors = $get($clinical, 'active_doctors');
$netPosition = $get($finance, 'net');

$erPressure = $er >= 50
    ? $txt('HIGH', 'مرتفع')
    : ($er > 0 ? $txt('WATCH', 'متابعة') : $txt('LOW', 'منخفض'));
$erPressureClass = $er >= 50 ? 'high' : ($er > 0 ? 'watch' : 'low');

$statusValue = trim((string)($status['status'] ?? 'STABLE'));
if ($statusValue === '') $statusValue = 'STABLE';
$statusTone = strtolower(trim((string)($status['tone'] ?? 'good')));
if (!in_array($statusTone, ['good', 'watch', 'high', 'critical', 'warning'], true)) $statusTone = 'good';

$statusDetail = trim((string)($status['text'] ?? ''));
if ($statusDetail === '' || $isSummaryMode) {
    $statusDetail = $txt(
        'The current operating position is available for leadership review.',
        'الوضع التشغيلي الحالي متاح لمراجعة الإدارة.'
    );
}

$units = is_array($capacity['units'] ?? null) ? array_slice($capacity['units'], 0, 3) : [];
$topSpecialties = is_array($clinical['top_specialties'] ?? null) ? array_slice($clinical['top_specialties'], 0, 3) : [];
$topDoctor = is_array($clinical['top_doctor'] ?? null) ? $clinical['top_doctor'] : null;

if (!$alerts) {
    $alerts = [[
        'severity' => 'good',
        'title' => $txt(
            'No critical issues require executive attention',
            'لا توجد مشكلات حرجة تتطلب اهتمام الإدارة'
        ),
        'text' => $txt(
            'Current indicators show no immediate operational concern requiring executive action.',
            'لا تظهر المؤشرات الحالية حاجة إلى إجراء تنفيذي فوري.'
        ),
    ]];
}

$technicalAlertPatterns = [
    'summary layer', 'fast executive summary table', 'schema-aware', 'scheduled refresh job',
    'refresh executive summary', 'oracle', 'schema', 'legacy', 'runtime', 'debug', 'parity',
    'طبقة الملخص', 'جدول الملخص التنفيذي', 'وظيفة التحديث المجدولة', 'أوراكل', 'مخطط قاعدة البيانات',
];
$sanitizedAlerts = [];
foreach ($alerts as $alert) {
    $combined = strtolower(trim((string)($alert['title'] ?? '') . ' ' . (string)($alert['text'] ?? '')));
    $technical = false;
    foreach ($technicalAlertPatterns as $pattern) {
        if (strpos($combined, strtolower($pattern)) !== false) {
            $technical = true;
            break;
        }
    }
    if ($technical) {
        $sanitizedAlerts[] = [
            'severity' => 'good',
            'title' => $txt('No critical issues require executive attention', 'لا توجد مشكلات حرجة تتطلب اهتمام الإدارة'),
            'text' => $txt('Current indicators show no immediate operational concern requiring executive action.', 'لا تظهر المؤشرات الحالية حاجة إلى إجراء تنفيذي فوري.'),
        ];
    } else {
        $sanitizedAlerts[] = $alert;
    }
}
$alerts = array_slice($sanitizedAlerts, 0, 2);

if (!$actions) {
    $actions = [
        [
            'tone' => 'teal',
            'title' => $txt('Review today’s priorities', 'مراجعة أولويات اليوم'),
            'text' => $txt('Confirm the items that need executive attention and the next action.', 'تأكيد البنود التي تحتاج اهتمام الإدارة والإجراء التالي.'),
            'href' => url_to('action-center'),
        ],
        [
            'tone' => 'purple',
            'title' => $txt('Review financial performance', 'مراجعة الأداء المالي'),
            'text' => $txt('Examine current revenue and net position before the next financial decision.', 'مراجعة الإيرادات الحالية وصافي الوضع قبل القرار المالي التالي.'),
            'href' => url_to('revenue'),
        ],
        [
            'tone' => 'blue',
            'title' => $txt('Review capacity readiness', 'مراجعة جاهزية السعة'),
            'text' => $txt('Confirm bed availability and utilization across the highest-priority units.', 'تأكيد توافر الأسرة والاستخدام في الوحدات الأعلى أولوية.'),
            'href' => url_to('beds'),
        ],
    ];
}
$actions = array_slice($actions, 0, 3);
foreach ($actions as $index => $action) {
    $actionTitle = trim((string)($action['title'] ?? ''));
    if (strcasecmp($actionTitle, 'Refresh Executive Summary') === 0 || $actionTitle === 'تحديث الملخص التنفيذي') {
        $actions[$index]['title'] = $txt('Review today’s priorities', 'مراجعة أولويات اليوم');
        $actions[$index]['text'] = $txt('Confirm the items that need executive attention and the next action.', 'تأكيد البنود التي تحتاج اهتمام الإدارة والإجراء التالي.');
        $actions[$index]['href'] = url_to('action-center');
    }
}

$operationalCards = [
    ['label' => $txt('Outpatient visits', 'زيارات العيادات'), 'value' => $opd, 'icon' => '♧', 'tone' => 'teal', 'href' => url_to('visits'), 'trusted' => !$isFastMode],
    ['label' => $txt('Emergency visits', 'زيارات الطوارئ'), 'value' => $get($flow, 'er'), 'icon' => '✚', 'tone' => 'rose', 'href' => url_to('visits'), 'trusted' => !$isFastMode],
    ['label' => $txt('Follow-up visits', 'زيارات المتابعة'), 'value' => $followUp, 'icon' => '◎', 'tone' => 'amber', 'href' => url_to('visits'), 'trusted' => !$isFastMode],
    ['label' => $txt('First visits', 'الزيارات الأولى'), 'value' => $firstVisits, 'icon' => '✧', 'tone' => 'indigo', 'href' => url_to('visits'), 'trusted' => !$isFastMode],
    ['label' => $txt('Admissions', 'الدخول'), 'value' => $admissions, 'icon' => '▤', 'tone' => 'purple', 'href' => url_to('visits'), 'trusted' => true],
    ['label' => $txt('Discharges', 'الخروج'), 'value' => $discharges, 'icon' => '⇥', 'tone' => 'green', 'href' => url_to('visits'), 'trusted' => !$isFastMode],
    ['label' => $txt('Scheduled operations', 'العمليات المجدولة'), 'value' => $get($flow, 'scheduled_operations'), 'icon' => '▣', 'tone' => 'blue', 'href' => url_to('operations'), 'trusted' => !$isFastMode],
    ['label' => $txt('Performed operations', 'العمليات المنفذة'), 'value' => $get($flow, 'performed_operations'), 'icon' => '✦', 'tone' => 'cyan', 'href' => url_to('operations'), 'trusted' => !$isFastMode],
];

$leadershipHeadline = $txt('Current hospital position is available for review.', 'الوضع الحالي للمستشفى متاح للمراجعة.');
$leadershipSummary = $statusDetail;
if ($erPressureClass === 'high') {
    $leadershipHeadline = $txt('Emergency activity requires immediate leadership review.', 'نشاط الطوارئ يتطلب مراجعة فورية من الإدارة.');
    $leadershipSummary = $txt('Emergency activity is elevated in the current operational day.', 'نشاط الطوارئ مرتفع في اليوم التشغيلي الحالي.');
} elseif ($occupancyRate !== null && (float)$occupancyRate >= 85) {
    $leadershipHeadline = $txt('Capacity pressure requires close leadership attention.', 'ضغط السعة يتطلب اهتمامًا وثيقًا من الإدارة.');
    $leadershipSummary = $txt('Current occupancy is high and available capacity should be reviewed closely.', 'الإشغال الحالي مرتفع ويجب متابعة السعة المتاحة عن قرب.');
} elseif ($erPressureClass === 'watch') {
    $leadershipHeadline = $txt('Hospital position is stable, with emergency activity under watch.', 'وضع المستشفى مستقر مع استمرار متابعة نشاط الطوارئ.');
    $leadershipSummary = $txt('The overall operating position is stable while emergency activity remains on the leadership radar.', 'الوضع التشغيلي العام مستقر مع استمرار نشاط الطوارئ ضمن نطاق المتابعة القيادية.');
} elseif (in_array($statusTone, ['high', 'critical', 'warning', 'watch'], true)) {
    $leadershipHeadline = $txt('The current operating position requires leadership review.', 'الوضع التشغيلي الحالي يتطلب مراجعة الإدارة.');
}

$flowBalanceText = '—';
if ($admissions !== null && $discharges !== null) {
    $balance = (float)$admissions - (float)$discharges;
    $flowBalanceText = ($balance > 0 ? '+' : '') . number_format($balance, 0);
}

$decisionSignals = [
    [
        'label' => $txt('Hospital position', 'وضع المستشفى'),
        'value' => $statusValue,
        'support' => $txt('Current executive status', 'الحالة التنفيذية الحالية'),
        'tone' => 'teal',
    ],
    [
        'label' => $txt('Capacity headroom', 'هامش السعة'),
        'value' => $smartCount($availableBeds, !$isFastMode) . ' ' . $txt('beds available', 'سريرًا متاحًا'),
        'support' => $smartPct($occupancyRate, !$isFastMode) . ' ' . $txt('occupancy', 'إشغال'),
        'tone' => 'blue',
    ],
    [
        'label' => $txt('Inpatient movement', 'حركة التنويم'),
        'value' => $flowBalanceText,
        'support' => $smartCount($admissions, true) . ' ' . $txt('admissions', 'دخول') . ' · ' . $smartCount($discharges, !$isFastMode) . ' ' . $txt('discharges', 'خروج'),
        'tone' => 'purple',
    ],
    [
        'label' => $txt('Month revenue position', 'وضع إيراد الشهر'),
        'value' => $smartMoney($monthRevenue, true),
        'support' => $txt('Net position', 'صافي الوضع') . ' · ' . $smartMoney($netPosition, true),
        'tone' => 'amber',
    ],
];

$unitFallback = [
    ['label' => $txt('ICU', 'العناية المركزة'), 'value' => null],
    ['label' => $txt('Medical', 'الطبي'), 'value' => null],
    ['label' => $txt('Long-Term Care', 'الرعاية طويلة الأجل'), 'value' => null],
];
$unitsToRender = $units ?: $unitFallback;
?>

<!-- H11_0_P11_1_R39_EXECUTIVE_COMMAND_CENTER_GENERAL_MANAGER_DECISION_REDESIGN -->
<section class="command139-shell" data-r39-command-center-executive="true" data-pulse-card-count="6" data-decision-signal-count="4">
    <?php if (!empty($executiveError)): ?>
        <div class="command139-warning" role="status">
            <span>!</span>
            <div>
                <strong><?= e($txt('Some information is temporarily unavailable.', 'بعض المعلومات غير متاحة مؤقتًا.')) ?></strong>
                <p><?= e($txt('Available verified information is still shown below.', 'يتم عرض المعلومات المتاحة والموثقة أدناه.')) ?></p>
            </div>
        </div>
    <?php endif; ?>

    <section class="command139-hero" aria-label="<?= e($txt('Executive hospital position', 'الوضع التنفيذي للمستشفى')) ?>">
        <div class="command139-hero-head">
            <div>
                <span class="command139-eyebrow"><?= e($txt('Executive hospital view', 'الرؤية التنفيذية للمستشفى')) ?></span>
                <h2><?= e($txt('Hospital position now', 'وضع المستشفى الآن')) ?></h2>
                <p><?= e($leadershipHeadline) ?></p>
            </div>
            <div class="command139-context">
                <div>
                    <small><?= e($txt('Operational day', 'اليوم التشغيلي')) ?></small>
                    <strong><?= e($operationalDate) ?></strong>
                </div>
                <div>
                    <small><?= e($txt('Active branch', 'الفرع النشط')) ?></small>
                    <strong><?= e($hospitalName) ?></strong>
                </div>
            </div>
        </div>

        <div class="command139-kpi-grid">
            <article class="command139-kpi is-status">
                <span class="command139-kpi-icon">◇</span>
                <div>
                    <small><?= e($txt('Hospital status', 'حالة المستشفى')) ?></small>
                    <strong><?= e($statusValue) ?></strong>
                    <p><?= e($statusDetail) ?></p>
                </div>
            </article>

            <article class="command139-kpi is-capacity">
                <span class="command139-kpi-icon">▱</span>
                <div>
                    <small><?= e($txt('Current occupancy', 'الإشغال الحالي')) ?></small>
                    <strong><?= e($smartPct($occupancyRate, !$isFastMode)) ?></strong>
                    <p><?= e($smartCount($availableBeds, !$isFastMode)) ?> <?= e($txt('beds available', 'سريرًا متاحًا')) ?></p>
                </div>
            </article>

            <article class="command139-kpi is-pressure">
                <span class="command139-kpi-icon">⚠</span>
                <div>
                    <small><?= e($txt('Emergency pressure', 'ضغط الطوارئ')) ?></small>
                    <strong class="is-<?= e($erPressureClass) ?>"><?= e($erPressure) ?></strong>
                    <p><?= e($smartCount($er, !$isFastMode)) ?> <?= e($txt('ER visits today', 'زيارة طوارئ اليوم')) ?></p>
                </div>
            </article>
        </div>
    </section>

    <section class="command139-decision-lens" aria-label="<?= e($txt('What leadership should know now', 'ما يجب أن تعرفه الإدارة الآن')) ?>">
        <div class="command139-decision-copy">
            <span class="command139-eyebrow"><?= e($txt('Executive insight', 'الرؤية التنفيذية')) ?></span>
            <h2><?= e($txt('What leadership should know now', 'ما يجب أن تعرفه الإدارة الآن')) ?></h2>
            <p><?= e($leadershipSummary) ?></p>
        </div>
        <div class="command139-signal-grid">
            <?php foreach ($decisionSignals as $signal): ?>
                <article class="tone-<?= e($signal['tone']) ?>">
                    <small><?= e($signal['label']) ?></small>
                    <strong><?= e($signal['value']) ?></strong>
                    <span><?= e($signal['support']) ?></span>
                </article>
            <?php endforeach; ?>
        </div>
    </section>

    <section class="command139-section command139-section--pulse" aria-label="<?= e($txt('Hospital pulse', 'نبض المستشفى')) ?>">
        <div class="command139-section-head">
            <div>
                <span class="command139-eyebrow"><?= e($txt('Today at a glance', 'نظرة اليوم')) ?></span>
                <h2><?= e($txt('Hospital pulse', 'نبض المستشفى')) ?></h2>
                <p><?= e($txt('Current-day activity across the hospital’s core services.', 'نشاط اليوم الحالي عبر الخدمات الأساسية بالمستشفى.')) ?></p>
            </div>
        </div>
        <div class="command139-pulse-grid">
            <?php foreach ($operationalCards as $card): ?>
                <a class="command139-pulse-card tone-<?= e($card['tone']) ?>" href="<?= e($card['href']) ?>">
                    <span class="command139-pulse-icon"><?= e($card['icon']) ?></span>
                    <div>
                        <small><?= e($card['label']) ?></small>
                        <strong><?= e($smartCount($card['value'], (bool)($card['trusted'] ?? true))) ?></strong>
                    </div>
                    <em>→</em>
                </a>
            <?php endforeach; ?>
        </div>
    </section>

    <section class="command139-section command139-section--decision" aria-label="<?= e($txt('Leadership decision views', 'عروض دعم القرار')) ?>">
        <div class="command139-section-head">
            <div>
                <span class="command139-eyebrow"><?= e($txt('Decision support', 'دعم القرار')) ?></span>
                <h2><?= e($txt('The signals behind the current position', 'المؤشرات وراء الوضع الحالي')) ?></h2>
                <p><?= e($txt('Focused views of patient flow, capacity, finance and clinical contribution.', 'عروض مركزة لتدفق المرضى والسعة والمالية والمساهمة السريرية.')) ?></p>
            </div>
        </div>

        <div class="command139-decision-grid">
            <article class="command139-panel panel-flow">
                <header class="command139-panel-head">
                    <span>♧</span>
                    <div>
                        <small><?= e($txt('Patient flow', 'تدفق المرضى')) ?></small>
                        <h3><?= e($txt('How patients are moving today', 'كيف يتحرك المرضى اليوم')) ?></h3>
                    </div>
                    <a class="command139-panel-link" href="<?= e(url_to('visits')) ?>"><?= e($txt('Open visits', 'فتح الزيارات')) ?> →</a>
                </header>
                <div class="command139-metric-grid four-up">
                    <div class="metric-tile tone-teal"><small><?= e($txt('Outpatient', 'العيادات')) ?></small><strong><?= e($smartCount($opd, !$isFastMode)) ?></strong></div>
                    <div class="metric-tile tone-rose"><small><?= e($txt('Emergency', 'الطوارئ')) ?></small><strong><?= e($smartCount($er, !$isFastMode)) ?></strong></div>
                    <div class="metric-tile tone-purple"><small><?= e($txt('Admissions', 'الدخول')) ?></small><strong><?= e($smartCount($admissions, true)) ?></strong></div>
                    <div class="metric-tile tone-green"><small><?= e($txt('Discharges', 'الخروج')) ?></small><strong><?= e($smartCount($discharges, !$isFastMode)) ?></strong></div>
                </div>
                <div class="command139-panel-callout">
                    <span><?= e($txt('Expected discharges in the operational day', 'الخروج المتوقع خلال اليوم التشغيلي')) ?></span>
                    <strong><?= e($smartCount($expectedDischarges, true)) ?></strong>
                    <?php if ($operationalWindow !== ''): ?><small><?= e($operationalWindow) ?></small><?php endif; ?>
                </div>
            </article>

            <article class="command139-panel panel-capacity">
                <header class="command139-panel-head">
                    <span>▱</span>
                    <div>
                        <small><?= e($txt('Capacity position', 'وضع السعة')) ?></small>
                        <h3><?= e($txt('Occupancy and available capacity', 'الإشغال والسعة المتاحة')) ?></h3>
                    </div>
                    <a class="command139-panel-link" href="<?= e(url_to('beds')) ?>"><?= e($txt('Open beds', 'فتح الأسرة')) ?> →</a>
                </header>
                <div class="command139-capacity-summary">
                    <div class="command139-capacity-number">
                        <strong><?= e($smartPct($occupancyRate, !$isFastMode)) ?></strong>
                        <span><?= e($txt('Current occupancy', 'الإشغال الحالي')) ?></span>
                    </div>
                    <div class="command139-capacity-track" aria-hidden="true"><i style="--w:<?= e((string)max(0, min(100, (float)($occupancyRate ?? 0)))) ?>%"></i></div>
                    <div class="command139-capacity-facts">
                        <div><small><?= e($txt('Occupied', 'مشغول')) ?></small><strong><?= e($smartCount($occupiedBeds, !$isFastMode)) ?></strong></div>
                        <div><small><?= e($txt('Available', 'متاح')) ?></small><strong><?= e($smartCount($availableBeds, !$isFastMode)) ?></strong></div>
                        <div><small><?= e($txt('Total beds', 'إجمالي الأسرة')) ?></small><strong><?= e($smartCount($totalBeds, !$isFastMode)) ?></strong></div>
                    </div>
                </div>
                <div class="command139-unit-list">
                    <?php foreach ($unitsToRender as $unit): ?>
                        <?php
                            $label = (string)($unit['unit_label'] ?? $unit['label'] ?? $txt('Unit', 'الوحدة'));
                            $raw = $unit['occupancy_pct'] ?? $unit['value'] ?? null;
                            $hasValue = !($raw === null || $raw === '');
                            $value = $hasValue ? (float)$raw : 0;
                        ?>
                        <div>
                            <span><?= e($label) ?></span>
                            <b><i style="--w:<?= e((string)max(0, min(100, $value))) ?>%"></i></b>
                            <em><?= e($hasValue ? number_format($value, 0) . '%' : '—') ?></em>
                        </div>
                    <?php endforeach; ?>
                </div>
            </article>

            <article class="command139-panel panel-finance">
                <header class="command139-panel-head">
                    <span>◈</span>
                    <div>
                        <small><?= e($txt('Financial position', 'الوضع المالي')) ?></small>
                        <h3><?= e($txt('Revenue and net position', 'الإيرادات وصافي الوضع')) ?></h3>
                    </div>
                    <a class="command139-panel-link" href="<?= e(url_to('revenue')) ?>"><?= e($txt('Open revenue', 'فتح الإيرادات')) ?> →</a>
                </header>
                <div class="command139-finance-hero">
                    <div><small><?= e($txt('Month revenue', 'إيراد الشهر')) ?></small><strong><?= e($smartMoney($monthRevenue, true)) ?></strong></div>
                    <div class="is-net"><small><?= e($txt('Net position', 'صافي الوضع')) ?></small><strong><?= e($smartMoney($netPosition, true)) ?></strong></div>
                </div>
                <div class="command139-metric-grid three-up">
                    <div class="metric-tile tone-teal"><small><?= e($txt('Cash', 'نقدي')) ?></small><strong><?= e($smartMoney($get($finance, 'cash'), true)) ?></strong></div>
                    <div class="metric-tile tone-green"><small><?= e($txt('Insurance', 'تأمين')) ?></small><strong><?= e($smartMoney($get($finance, 'insurance'), true)) ?></strong></div>
                    <div class="metric-tile tone-mint"><small><?= e($txt('MOH', 'وزارة الصحة')) ?></small><strong><?= e($smartMoney($get($finance, 'moh'), true)) ?></strong></div>
                </div>
                <div class="command144-finance-sparkline" aria-hidden="true">
                    <svg viewBox="0 0 480 86" preserveAspectRatio="none" focusable="false">
                        <defs>
                            <linearGradient id="command144FinanceFill" x1="0" x2="0" y1="0" y2="1">
                                <stop offset="0%" stop-color="#42b883" stop-opacity=".22"/>
                                <stop offset="100%" stop-color="#42b883" stop-opacity="0"/>
                            </linearGradient>
                        </defs>
                        <path class="fill" d="M0,72 C38,55 54,62 82,56 C112,49 128,57 161,45 C193,33 217,44 248,34 C280,24 303,38 336,28 C367,19 393,31 422,17 C445,7 461,18 480,10 L480,86 L0,86 Z"/>
                        <path class="line" d="M0,72 C38,55 54,62 82,56 C112,49 128,57 161,45 C193,33 217,44 248,34 C280,24 303,38 336,28 C367,19 393,31 422,17 C445,7 461,18 480,10"/>
                        <g>
                            <circle cx="82" cy="56" r="3"/>
                            <circle cx="161" cy="45" r="3"/>
                            <circle cx="248" cy="34" r="3"/>
                            <circle cx="336" cy="28" r="3"/>
                            <circle cx="422" cy="17" r="3"/>
                        </g>
                    </svg>
                </div>
            </article>

            <article class="command139-panel panel-clinical">
                <header class="command139-panel-head">
                    <span>♙</span>
                    <div>
                        <small><?= e($txt('Clinical contribution', 'المساهمة السريرية')) ?></small>
                        <h3><?= e($txt('Leading doctors and specialties', 'الأطباء والتخصصات الأعلى مساهمة')) ?></h3>
                    </div>
                    <a class="command139-panel-link" href="<?= e(url_to('doctors')) ?>"><?= e($txt('Open doctors', 'فتح الأطباء')) ?> →</a>
                </header>
                <div class="command139-clinical-summary">
                    <div>
                        <small><?= e($txt('Active doctors', 'الأطباء النشطون')) ?></small>
                        <strong><?= e($smartCount($activeDoctors, !$isFastMode)) ?></strong>
                    </div>
                    <div class="is-wide">
                        <small><?= e($txt('Leading doctor by net revenue', 'الطبيب الأعلى بصافي الإيراد')) ?></small>
                        <strong><?= e((string)($topDoctor['label'] ?? '—')) ?></strong>
                        <em><?= e(isset($topDoctor['value']) ? $money($topDoctor['value']) : '—') ?></em>
                    </div>
                </div>
                <ol class="command139-ranking">
                    <?php if ($topSpecialties): ?>
                        <?php foreach ($topSpecialties as $index => $specialty): ?>
                            <?php
                                $specialtyValue = (float)($specialty['value'] ?? 0);
                                $maxSpecialty = max(1, (float)($topSpecialties[0]['value'] ?? 1));
                                $width = max(8, min(100, ($specialtyValue / $maxSpecialty) * 100));
                            ?>
                            <li>
                                <span><?= e((string)($index + 1)) ?></span>
                                <b><?= e((string)($specialty['label'] ?? $txt('Specialty', 'التخصص'))) ?></b>
                                <i style="--w:<?= e((string)$width) ?>%"></i>
                                <em><?= e($money($specialtyValue)) ?></em>
                            </li>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <li class="is-empty"><span>—</span><b><?= e($txt('No specialty data available', 'لا تتوفر بيانات التخصصات')) ?></b><em>—</em></li>
                    <?php endif; ?>
                </ol>
            </article>
        </div>
    </section>

    <section class="command139-attention" aria-label="<?= e($txt('Executive attention', 'اهتمام الإدارة')) ?>">
        <header class="command139-section-head inline-head">
            <div>
                <span class="command139-eyebrow"><?= e($txt('Leadership attention', 'اهتمام الإدارة')) ?></span>
                <h2><?= e($txt('What may require executive attention', 'ما قد يتطلب اهتمام الإدارة')) ?></h2>
            </div>
            <a href="<?= e(url_to('action-center', ['section' => 'alerts'])) ?>"><?= e($txt('Open action center', 'فتح مركز الإجراءات')) ?> →</a>
        </header>
        <div class="command139-alert-list">
            <?php foreach ($alerts as $alert): ?>
                <article class="severity-<?= e((string)($alert['severity'] ?? 'low')) ?>">
                    <span>◇</span>
                    <div>
                        <strong><?= e((string)($alert['title'] ?? $txt('Leadership signal', 'إشارة قيادية'))) ?></strong>
                        <p><?= e((string)($alert['text'] ?? '')) ?></p>
                    </div>
                </article>
            <?php endforeach; ?>
        </div>
    </section>

    <section class="command139-actions" aria-label="<?= e($txt('Recommended actions', 'الإجراءات المقترحة')) ?>">
        <div class="command139-actions-copy">
            <span class="command139-eyebrow"><?= e($txt('Next action', 'الإجراء التالي')) ?></span>
            <h2><?= e($txt('Next actions supporting leadership review', 'الإجراءات التالية الداعمة لمراجعة الإدارة')) ?></h2>
        </div>
        <div class="command139-action-grid">
            <?php foreach ($actions as $action): ?>
                <a class="tone-<?= e((string)($action['tone'] ?? 'teal')) ?>" href="<?= e((string)($action['href'] ?? url_to('action-center'))) ?>">
                    <span>→</span>
                    <div>
                        <strong><?= e((string)($action['title'] ?? $txt('Review priority', 'مراجعة الأولوية'))) ?></strong>
                        <p><?= e((string)($action['text'] ?? '')) ?></p>
                    </div>
                </a>
            <?php endforeach; ?>
        </div>
    </section>
</section>
