<?php
$isAr = current_lang() === 'ar';
$tr = static function (string $en, string $ar) use ($isAr): string {
    return $isAr ? $ar : $en;
};

$hospitalName = (string)($hospital['name'] ?? strtoupper((string)$hospitalCode));
$data = is_array($bedsData ?? null) ? $bedsData : null;
$snapshot = is_array($data['snapshot'] ?? null) ? $data['snapshot'] : [];
$units = is_array($data['units'] ?? null) ? $data['units'] : [];
$compareUnits = is_array($data['compare_units'] ?? null) ? $data['compare_units'] : [];
$unitOptions = is_array($data['unit_options'] ?? null) ? $data['unit_options'] : [];
$unitComparison = is_array($data['unit_comparison'] ?? null) ? $data['unit_comparison'] : [];
$scopeUnitComparison = is_array($data['scope_unit_comparison'] ?? null) ? $data['scope_unit_comparison'] : $unitComparison;
$scopeCurrentUnits = is_array($data['scope_current_units'] ?? null) ? $data['scope_current_units'] : $units;
$scopeCompareUnits = is_array($data['scope_compare_units'] ?? null) ? $data['scope_compare_units'] : $compareUnits;
$isAllUnits = !empty($data['is_all_units']);
$beds = is_array($data['beds'] ?? null) ? $data['beds'] : [];
$compareBeds = is_array($data['compare_beds'] ?? null) ? $data['compare_beds'] : [];
$bedComparison = is_array($data['bed_comparison'] ?? null) ? $data['bed_comparison'] : [];
$selectedUnit = is_array($data['selected_unit'] ?? null) ? $data['selected_unit'] : null;
$selectedCompareUnit = is_array($data['selected_compare_unit'] ?? null) ? $data['selected_compare_unit'] : null;
$periodSummary = is_array($data['period_summary'] ?? null) ? $data['period_summary'] : [];
$comparisonContract = is_array($data['comparison_contract'] ?? null)
    ? $data['comparison_contract']
    : (is_array($comparisonContract ?? null) ? $comparisonContract : []);
$periodLabels = is_array($data['period_labels'] ?? null)
    ? $data['period_labels']
    : (is_array($periodLabels ?? null) ? $periodLabels : []);

$currentPeriodLabel = (string)($periodLabels['current'] ?? $year);
$comparePeriodLabel = (string)($periodLabels['compare'] ?? $compareYear);
$comparisonReady = !empty($data['comparison_ready']);
$isFairCurrentYearComparison = !empty($comparisonContract['fair_current_year_comparison']);
$isMatchedCustomPeriod = !empty($comparisonContract['matched_custom_period']);

$occupancyRate = (float)($snapshot['occupancy_rate'] ?? 0);
$busyBeds = (float)($snapshot['busy'] ?? 0);
$availableBeds = (float)($snapshot['empty'] ?? 0);
$totalBeds = max(0.0, $busyBeds + $availableBeds);

$selectedUnitName = $isAllUnits
    ? $tr('All units', 'كل الوحدات')
    : (string)(
        $selectedUnit['bed_floor']
        ?? $selectedCompareUnit['bed_floor']
        ?? $tr('Selected unit', 'الوحدة المختارة')
    );
$scopeLabel = $isAllUnits
    ? $tr('All units', 'كل الوحدات')
    : $selectedUnitName;
$selectedUnitUtilization = is_array($selectedUnit)
    ? (float)($selectedUnit['bed_efficiency_percentage'] ?? 0)
    : null;
$selectedCompareUtilization = is_array($selectedCompareUnit)
    ? (float)($selectedCompareUnit['bed_efficiency_percentage'] ?? 0)
    : null;
$selectedUnitMovement = ($selectedUnitUtilization !== null && $selectedCompareUtilization !== null)
    ? $selectedUnitUtilization - $selectedCompareUtilization
    : null;
$scopeMovement = $isAllUnits ? null : $selectedUnitMovement;

$currentPeriodUtilization = isset($periodSummary['current_utilization'])
    && $periodSummary['current_utilization'] !== null
    ? (float)$periodSummary['current_utilization']
    : null;
$comparePeriodUtilization = isset($periodSummary['compare_utilization'])
    && $periodSummary['compare_utilization'] !== null
    ? (float)$periodSummary['compare_utilization']
    : null;
$periodMovement = isset($periodSummary['movement_pp'])
    && $periodSummary['movement_pp'] !== null
    ? (float)$periodSummary['movement_pp']
    : null;

$movementText = static function (?float $value) use ($tr): string {
    if ($value === null) {
        return '—';
    }
    if (abs($value) < 0.05) {
        return $tr('No material change', 'لا يوجد تغير جوهري');
    }
    return ($value > 0 ? '↑ +' : '↓ ') . number_format(abs($value), 1) . ' pp';
};
$movementClass = static function (?float $value): string {
    if ($value === null || abs($value) < 0.05) {
        return 'is-neutral';
    }
    return $value > 0 ? 'is-up' : 'is-down';
};
$percentValue = static function (?float $value): string {
    return $value === null ? '—' : number_format($value, 1) . '%';
};

$movementRows = array_values(array_filter($scopeUnitComparison, static function (array $row): bool {
    return array_key_exists('movement_pp', $row) && $row['movement_pp'] !== null;
}));
usort($movementRows, static function (array $a, array $b): int {
    return ((float)$b['movement_pp']) <=> ((float)$a['movement_pp']);
});

$improvedUnits = count(array_filter($movementRows, static function (array $row): bool {
    return (float)$row['movement_pp'] > 0.05;
}));
$declinedUnits = count(array_filter($movementRows, static function (array $row): bool {
    return (float)$row['movement_pp'] < -0.05;
}));
$stableUnits = max(0, count($movementRows) - $improvedUnits - $declinedUnits);

$largestIncrease = null;
foreach ($movementRows as $row) {
    if ((float)$row['movement_pp'] > 0.05) {
        $largestIncrease = $row;
        break;
    }
}
$largestDecline = null;
for ($i = count($movementRows) - 1; $i >= 0; $i--) {
    if ((float)$movementRows[$i]['movement_pp'] < -0.05) {
        $largestDecline = $movementRows[$i];
        break;
    }
}

$currentRanked = $unitComparison;
usort($currentRanked, static function (array $a, array $b): int {
    $av = $a['current_value'] === null ? -INF : (float)$a['current_value'];
    $bv = $b['current_value'] === null ? -INF : (float)$b['current_value'];
    return $bv <=> $av;
});
$compareRanked = $unitComparison;
usort($compareRanked, static function (array $a, array $b): int {
    $av = $a['compare_value'] === null ? -INF : (float)$a['compare_value'];
    $bv = $b['compare_value'] === null ? -INF : (float)$b['compare_value'];
    return $bv <=> $av;
});
$highestCurrentUnit = $currentRanked[0] ?? null;
$highestCompareUnit = $compareRanked[0] ?? null;

$unitChartRows = $isAllUnits ? $unitComparison : $scopeUnitComparison;
usort($unitChartRows, static function (array $a, array $b): int {
    $aMax = max(
        $a['current_value'] === null ? 0 : (float)$a['current_value'],
        $a['compare_value'] === null ? 0 : (float)$a['compare_value']
    );
    $bMax = max(
        $b['current_value'] === null ? 0 : (float)$b['current_value'],
        $b['compare_value'] === null ? 0 : (float)$b['compare_value']
    );
    return $bMax <=> $aMax;
});
$unitChartRows = array_slice($unitChartRows, 0, 5);

$bedChartRows = $bedComparison;
usort($bedChartRows, static function (array $a, array $b): int {
    $aMax = max(
        $a['current_value'] === null ? 0 : (float)$a['current_value'],
        $a['compare_value'] === null ? 0 : (float)$a['compare_value']
    );
    $bMax = max(
        $b['current_value'] === null ? 0 : (float)$b['current_value'],
        $b['compare_value'] === null ? 0 : (float)$b['compare_value']
    );
    return $bMax <=> $aMax;
});
$bedChartRows = array_slice($bedChartRows, 0, 5);

$chartRows = static function (array $rows): array {
    return array_map(static function (array $row): array {
        return [
            'label' => (string)($row['label'] ?? ''),
            'current' => $row['current_value'] === null ? null : (float)$row['current_value'],
            'compare' => $row['compare_value'] === null ? null : (float)$row['compare_value'],
            'movement' => $row['movement_pp'] === null ? null : (float)$row['movement_pp'],
        ];
    }, $rows);
};

$comparisonChartConfig = [
    'currentLabel' => $currentPeriodLabel,
    'compareLabel' => $comparePeriodLabel,
    'valueSuffix' => '%',
    'unit' => [
        'rows' => $chartRows($unitChartRows),
        'targetId' => 'beds82_units_chart',
        'shellKey' => 'units',
    ],
    'bed' => [
        'rows' => $chartRows($bedChartRows),
        'targetId' => 'beds82_beds_chart',
        'shellKey' => 'beds',
    ],
];


$bedMovementRows = array_values(array_filter($bedComparison, static function (array $row): bool {
    return array_key_exists('movement_pp', $row) && $row['movement_pp'] !== null;
}));
usort($bedMovementRows, static function (array $a, array $b): int {
    return ((float)$b['movement_pp']) <=> ((float)$a['movement_pp']);
});
$largestBedIncrease = null;
foreach ($bedMovementRows as $row) {
    if ((float)$row['movement_pp'] > 0.05) {
        $largestBedIncrease = $row;
        break;
    }
}
$largestBedDecline = null;
for ($i = count($bedMovementRows) - 1; $i >= 0; $i--) {
    if ((float)$bedMovementRows[$i]['movement_pp'] < -0.05) {
        $largestBedDecline = $bedMovementRows[$i];
        break;
    }
}

$totalComparedUnits = count($movementRows);
$movementAbsolute = $periodMovement === null ? null : abs($periodMovement);
$movementHeadline = $periodMovement === null
    ? $tr('Comparison unavailable', 'المقارنة غير متاحة')
    : ($periodMovement > 0.05
        ? $tr('Utilization increased', 'ارتفع الاستخدام')
        : ($periodMovement < -0.05
            ? $tr('Utilization decreased', 'انخفض الاستخدام')
            : $tr('Utilization remained stable', 'ظل الاستخدام مستقرًا')));

if ($periodMovement === null) {
    $executiveNarrative = $tr(
        'One of the selected periods does not have enough coverage for ' . $scopeLabel . '.',
        'إحدى الفترتين المحددتين لا تحتوي على تغطية كافية لنطاق ' . $scopeLabel . '.'
    );
} elseif ($periodMovement < -0.05) {
    $executiveNarrative = $tr(
        $isAllUnits
            ? 'Matched-period utilization is ' . number_format(abs($periodMovement), 1) . ' percentage points lower across all units. '
                . $declinedUnits . ' of ' . $totalComparedUnits . ' units declined. '
                . (isset($largestDecline['label']) ? (string)$largestDecline['label'] . ' requires the closest review.' : '')
            : $selectedUnitName . ' utilization is ' . number_format(abs($periodMovement), 1) . ' percentage points lower than the matched comparison period.',
        $isAllUnits
            ? 'استخدام الفترة المتطابقة أقل بمقدار ' . number_format(abs($periodMovement), 1) . ' نقطة مئوية عبر كل الوحدات. '
                . 'انخفضت ' . $declinedUnits . ' وحدات من أصل ' . $totalComparedUnits . '. '
                . (isset($largestDecline['label']) ? 'تحتاج وحدة ' . (string)$largestDecline['label'] . ' إلى المراجعة الأقرب.' : '')
            : 'استخدام وحدة ' . $selectedUnitName . ' أقل بمقدار ' . number_format(abs($periodMovement), 1) . ' نقطة مئوية عن فترة المقارنة المتطابقة.'
    );
} elseif ($periodMovement > 0.05) {
    $executiveNarrative = $tr(
        $isAllUnits
            ? 'Matched-period utilization is ' . number_format($periodMovement, 1) . ' percentage points higher across all units. '
                . $improvedUnits . ' of ' . $totalComparedUnits . ' units improved. '
                . (isset($largestIncrease['label']) ? (string)$largestIncrease['label'] . ' recorded the strongest movement.' : '')
            : $selectedUnitName . ' utilization is ' . number_format($periodMovement, 1) . ' percentage points higher than the matched comparison period.',
        $isAllUnits
            ? 'استخدام الفترة المتطابقة أعلى بمقدار ' . number_format($periodMovement, 1) . ' نقطة مئوية عبر كل الوحدات. '
                . 'تحسنت ' . $improvedUnits . ' وحدات من أصل ' . $totalComparedUnits . '. '
                . (isset($largestIncrease['label']) ? 'سجلت وحدة ' . (string)$largestIncrease['label'] . ' أقوى تغير.' : '')
            : 'استخدام وحدة ' . $selectedUnitName . ' أعلى بمقدار ' . number_format($periodMovement, 1) . ' نقطة مئوية عن فترة المقارنة المتطابقة.'
    );
} else {
    $executiveNarrative = $tr(
        $isAllUnits
            ? 'Overall utilization is stable across the matched periods. Review unit-level movements before changing capacity plans.'
            : $selectedUnitName . ' utilization is stable across the matched periods.',
        $isAllUnits
            ? 'الاستخدام الإجمالي مستقر بين الفترتين المتطابقتين. يجب مراجعة تغيرات الوحدات قبل تعديل خطط السعة.'
            : 'استخدام وحدة ' . $selectedUnitName . ' مستقر بين الفترتين المتطابقتين.'
    );
}

$selectedUnitAction = $selectedUnitMovement === null
    ? $tr('Coverage is incomplete for the selected unit.', 'التغطية غير مكتملة للوحدة المختارة.')
    : ($selectedUnitMovement < -0.05
        ? $tr('Review the operational causes behind the lower utilization.', 'راجع الأسباب التشغيلية وراء انخفاض الاستخدام.')
        : ($selectedUnitMovement > 0.05
            ? $tr('Confirm whether the increase reflects demand pressure or improved use.', 'تحقق مما إذا كانت الزيادة تعكس ضغط طلب أو تحسنًا في الاستخدام.')
            : $tr('No material unit movement requires escalation.', 'لا يوجد تغير جوهري في الوحدة يتطلب التصعيد.')));

?>
<div class="beds83-page"
     data-r45-p8-3-executive-redesign="true"
     data-comparison-current="<?= e($currentPeriodLabel) ?>"
     data-comparison-compare="<?= e($comparePeriodLabel) ?>">

    <section class="beds83-controls" aria-labelledby="beds83-controls-title">
        <div class="beds83-controls-copy">
            <span><?= e($tr('CAPACITY COMPARISON', 'مقارنة السعة')) ?></span>
            <strong id="beds83-controls-title"><?= e($currentPeriodLabel) ?> <i>vs</i> <?= e($comparePeriodLabel) ?></strong>
            <p><?= e($tr(
                'Compare matched periods, then focus on the units requiring a leadership decision.',
                'قارن الفترات المتطابقة ثم ركز على الوحدات التي تتطلب قرارًا إداريًا.'
            )) ?></p>
        </div>

        <form method="get" action="index.php" class="beds83-filter <?= $mode === 'range' ? 'is-range' : 'is-year' ?>" data-beds134-filter>
            <input type="hidden" name="page" value="beds">
            <input type="hidden" name="lang" value="<?= e(current_lang()) ?>">

            <label>
                <span><?= e($tr('View', 'العرض')) ?></span>
                <select name="mode" data-beds134-mode>
                    <option value="year" <?= $mode === 'year' ? 'selected' : '' ?>><?= e($tr('Year comparison', 'مقارنة السنوات')) ?></option>
                    <option value="range" <?= $mode === 'range' ? 'selected' : '' ?>><?= e($tr('Custom period', 'فترة مخصصة')) ?></option>
                </select>
            </label>

            <label data-beds134-year-field>
                <span><?= e($tr('Primary year', 'السنة الأساسية')) ?></span>
                <select name="year">
                    <?php foreach (($data['years'] ?? [$year]) as $y): ?>
                        <option value="<?= e((string)$y) ?>" <?= (int)$y === (int)$year ? 'selected' : '' ?>><?= e((string)$y) ?></option>
                    <?php endforeach; ?>
                </select>
            </label>

            <label>
                <span><?= e($tr('Comparison year', 'سنة المقارنة')) ?></span>
                <select name="compare_year">
                    <?php foreach (($data['years'] ?? [$compareYear]) as $y): ?>
                        <option value="<?= e((string)$y) ?>" <?= (int)$y === (int)$compareYear ? 'selected' : '' ?>><?= e((string)$y) ?></option>
                    <?php endforeach; ?>
                </select>
            </label>

            <label data-beds134-range-field>
                <span><?= e($tr('From', 'من')) ?></span>
                <input type="date" name="from_date" value="<?= e($fromDate) ?>">
            </label>

            <label data-beds134-range-field>
                <span><?= e($tr('To', 'إلى')) ?></span>
                <input type="date" name="to_date" value="<?= e($toDate) ?>">
            </label>

            <label class="beds83-unit-field">
                <span><?= e($tr('Unit', 'الوحدة')) ?></span>
                <select name="unit_id">
                    <option value="0" <?= $isAllUnits ? 'selected' : '' ?>><?= e($tr('All units', 'كل الوحدات')) ?></option>
                    <?php foreach ($unitOptions as $row): ?>
                        <option value="<?= e((string)$row['unit_id']) ?>" <?= (int)$row['unit_id'] === (int)$unitId ? 'selected' : '' ?>>
                            <?= e((string)$row['bed_floor']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </label>

            <button type="submit"><?= e($tr('Update', 'تحديث')) ?></button>
        </form>

        <div class="beds83-contract-note <?= $isFairCurrentYearComparison ? 'is-fair' : '' ?>">
            <span aria-hidden="true"><?= $isFairCurrentYearComparison ? '✓' : '↔' ?></span>
            <p>
                <?php if ($isFairCurrentYearComparison): ?>
                    <strong><?= e($tr('Fair comparison:', 'مقارنة عادلة:')) ?></strong>
                    <?= e($tr(
                        'the incomplete current month is excluded from both periods.',
                        'تم استبعاد الشهر الحالي غير المكتمل من الفترتين.'
                    )) ?>
                <?php else: ?>
                    <strong><?= e($tr('Matched comparison:', 'مقارنة متطابقة:')) ?></strong>
                    <?= e($currentPeriodLabel . ' vs ' . $comparePeriodLabel) ?>
                <?php endif; ?>
            </p>
        </div>

        <?php if ($filterError): ?><p class="beds83-alert"><?= e($filterError) ?></p><?php endif; ?>
    </section>

    <?php if ($dataError || !$data): ?>
        <section class="beds83-state">
            <strong><?= e($tr('Capacity information is temporarily unavailable', 'معلومات السعة غير متاحة مؤقتًا')) ?></strong>
            <p><?= e($tr('Try another period or branch.', 'جرّب فترة أو فرعًا آخر.')) ?></p>
        </section>
    <?php else: ?>

        <?php
            $periodSemantic = $periodMovement === null || abs($periodMovement) < 0.05
                ? 'neutral'
                : ($periodMovement > 0 ? 'positive' : 'negative');
            $selectedSemantic = $selectedUnitMovement === null || abs($selectedUnitMovement) < 0.05
                ? 'neutral'
                : ($selectedUnitMovement > 0 ? 'positive' : 'negative');

            $bedsKpis = [
                [
                    'title' => $tr('Primary utilization', 'استخدام الفترة الأساسية'),
                    'value' => $currentPeriodUtilization,
                    'suffix' => '%',
                    'subtitle' => $currentPeriodLabel,
                    'delta' => $periodMovement,
                    'tone' => 'violet',
                    'semantic' => $periodSemantic,
                ],
                [
                    'title' => $tr('Comparison utilization', 'استخدام فترة المقارنة'),
                    'value' => $comparePeriodUtilization,
                    'suffix' => '%',
                    'subtitle' => $comparePeriodLabel,
                    'delta' => null,
                    'tone' => 'blue',
                    'semantic' => 'neutral',
                ],
                [
                    'title' => $tr('Live occupancy', 'الإشغال الحي'),
                    'value' => $occupancyRate,
                    'suffix' => '%',
                    'subtitle' => $tr('Live now — independent of selected years', 'الآن — مستقل عن السنوات المختارة'),
                    'delta' => null,
                    'tone' => 'teal',
                    'semantic' => 'neutral',
                ],
                [
                    'title' => $isAllUnits
                        ? $tr('Units requiring review', 'الوحدات التي تتطلب مراجعة')
                        : $tr('Selected unit movement', 'تغير الوحدة المختارة'),
                    'value' => $isAllUnits ? $declinedUnits : $selectedUnitMovement,
                    'suffix' => $isAllUnits ? '' : ' pp',
                    'subtitle' => $isAllUnits
                        ? $tr('of ', 'من ') . $totalComparedUnits
                        : $selectedUnitName,
                    'delta' => $isAllUnits ? null : $selectedUnitMovement,
                    'tone' => 'amber',
                    'semantic' => $isAllUnits
                        ? ($declinedUnits > 0 ? 'negative' : 'positive')
                        : $selectedSemantic,
                ],
            ];
        ?>

        <section class="beds84-kpi-grid" aria-label="<?= e($tr('Key capacity indicators', 'مؤشرات السعة الرئيسية')) ?>">
            <?php foreach ($bedsKpis as $kpi): ?>
                <article class="beds84-kpi tone-<?= e((string)$kpi['tone']) ?>">
                    <span class="beds84-kpi-label"><?= e((string)$kpi['title']) ?></span>
                    <strong>
                        <?php if ($kpi['value'] === null): ?>
                            —
                        <?php elseif ($kpi['suffix'] === '%'): ?>
                            <?= e(number_format((float)$kpi['value'], 1)) ?>%
                        <?php elseif ($kpi['suffix'] === ' pp'): ?>
                            <?= e(number_format(abs((float)$kpi['value']), 1)) ?> pp
                        <?php else: ?>
                            <?= e(number_format((float)$kpi['value'], 0)) ?>
                        <?php endif; ?>
                    </strong>
                    <small><?= e((string)$kpi['subtitle']) ?></small>

                    <?php if ($kpi['delta'] !== null): ?>
                        <em class="beds84-delta <?= e((string)$kpi['semantic']) ?>">
                            <?= e($movementText((float)$kpi['delta'])) ?>
                        </em>
                    <?php elseif ($isAllUnits && $kpi['tone'] === 'amber'): ?>
                        <em class="beds84-delta <?= e((string)$kpi['semantic']) ?>">
                            <?= e($declinedUnits > 0
                                ? $tr('Review required', 'تتطلب مراجعة')
                                : $tr('No declining units', 'لا توجد وحدات متراجعة')
                            ) ?>
                        </em>
                    <?php endif; ?>
                </article>
            <?php endforeach; ?>
        </section>

        <section class="beds83-card beds84-summary-card">
            <div class="beds84-summary-intro">
                <span><?= e($tr('EXECUTIVE INSIGHT', 'الرؤية التنفيذية')) ?> · <?= e($scopeLabel) ?></span>
                <h2><?= e($tr('What leadership should know now', 'ما الذي يجب أن تعرفه الإدارة الآن')) ?></h2>
                <strong class="<?= e('is-' . $periodSemantic) ?>"><?= e($movementHeadline) ?></strong>
                <p><?= e($executiveNarrative) ?></p>
                <div class="beds84-period-line">
                    <b><?= e($currentPeriodLabel) ?></b>
                    <i>vs</i>
                    <b><?= e($comparePeriodLabel) ?></b>
                </div>
            </div>

            <div class="beds84-summary-signals">
                <article>
                    <span><?= e($tr('Overall movement', 'الحركة الإجمالية')) ?></span>
                    <strong class="<?= e('is-' . $periodSemantic) ?>"><?= e($movementText($periodMovement)) ?></strong>
                    <small><?= e($scopeLabel) ?></small>
                </article>

                <article>
                    <span><?= e($tr('Units improved', 'الوحدات المتحسنة')) ?></span>
                    <strong class="is-positive"><?= e((string)$improvedUnits) ?></strong>
                    <small><?= e($tr('of ', 'من ') . $totalComparedUnits) ?></small>
                </article>

                <article>
                    <span><?= e($tr('Units declined', 'الوحدات المتراجعة')) ?></span>
                    <strong class="<?= e($declinedUnits > 0 ? 'is-negative' : 'is-positive') ?>"><?= e((string)$declinedUnits) ?></strong>
                    <small><?= e((string)$stableUnits) ?> <?= e($tr('stable', 'مستقرة')) ?></small>
                </article>

                <article>
                    <span><?= e($tr('Live capacity now', 'السعة الحية الآن')) ?></span>
                    <strong><?= e(number_format($busyBeds, 0)) ?> / <?= e(number_format($totalBeds, 0)) ?></strong>
                    <small>
                        <?= e(number_format($availableBeds, 0)) ?>
                        <?= e($tr('beds available', 'سريرًا متاحًا')) ?>
                    </small>
                </article>
            </div>
        </section>

        <section class="beds83-main-grid">
            <article class="beds83-card beds83-chart-card"
                     data-beds82-chart-shell="units"
                     data-chart-state="pending">
                <header class="beds83-card-head">
                    <div>
                        <span><?= e($tr('UNIT COMPARISON', 'مقارنة الوحدات')) ?></span>
                        <h2><?= e($isAllUnits
                            ? $tr('Where capacity pressure changed', 'أين تغير ضغط السعة')
                            : $tr('Selected unit comparison', 'مقارنة الوحدة المختارة')
                        ) ?></h2>
                        <p><?= e($isAllUnits
                            ? $tr('Top five units, using the same matched periods.', 'أعلى خمس وحدات باستخدام الفترتين المتطابقتين نفسيهما.')
                            : $selectedUnitName . ' · ' . $currentPeriodLabel . ' vs ' . $comparePeriodLabel
                        ) ?></p>
                    </div>
                    <div class="beds83-legend">
                        <i class="is-primary"></i><?= e($currentPeriodLabel) ?>
                        <i class="is-compare"></i><?= e($comparePeriodLabel) ?>
                    </div>
                </header>
                <div class="beds83-chart-stage">
                    <div id="beds82_units_chart" class="beds83-chart-target"></div>
                    <div class="beds134-chart-state beds134-chart-empty"><strong><?= e($tr('No unit comparison is available', 'لا توجد مقارنة وحدات متاحة')) ?></strong></div>
                    <div class="beds134-chart-state beds134-chart-error"><strong><?= e($tr('The comparison chart is temporarily unavailable', 'رسم المقارنة غير متاح مؤقتًا')) ?></strong></div>
                </div>
            </article>

            <aside class="beds83-card beds83-agenda">
                <header>
                    <span><?= e($tr('DECISION AGENDA', 'أجندة القرار')) ?></span>
                    <h2><?= e($tr('What needs attention', 'ما الذي يحتاج إلى انتباه')) ?></h2>
                </header>

                <article class="is-attention">
                    <div><span>1</span></div>
                    <section>
                        <small><?= e($isAllUnits ? $tr('Closest review', 'المراجعة الأقرب') : $tr('Selected unit movement', 'تغير الوحدة المختارة')) ?></small>
                        <strong><?= e($isAllUnits
                            ? (string)($largestDecline['label'] ?? $tr('No decline identified', 'لم يتم تحديد انخفاض'))
                            : $selectedUnitName
                        ) ?></strong>
                        <?php $closestReviewMovement = isset($largestDecline['movement_pp']) ? (float)$largestDecline['movement_pp'] : null; ?>
                        <b class="<?= e($movementClass($closestReviewMovement)) ?>"><?= e($movementText($closestReviewMovement)) ?></b>
                        <p><?= e($tr(
                            'Confirm operational, seasonal or capacity-availability causes.',
                            'تحقق من الأسباب التشغيلية أو الموسمية أو توافر السعة.'
                        )) ?></p>
                    </section>
                </article>

                <article class="is-positive">
                    <div><span>2</span></div>
                    <section>
                        <small><?= e($tr('Strongest movement', 'أقوى تغير')) ?></small>
                        <strong><?= e((string)($largestIncrease['label'] ?? $tr('No increase identified', 'لم يتم تحديد زيادة'))) ?></strong>
                        <?php $strongestMovementValue = isset($largestIncrease['movement_pp']) ? (float)$largestIncrease['movement_pp'] : null; ?>
                        <b class="<?= e($movementClass($strongestMovementValue)) ?>"><?= e($movementText($strongestMovementValue)) ?></b>
                        <p><?= e($tr(
                            'Validate whether the gain reflects demand or improved utilization.',
                            'تحقق مما إذا كان التحسن يعكس الطلب أو تحسن الاستخدام.'
                        )) ?></p>
                    </section>
                </article>

                <article class="is-selected">
                    <div><span>3</span></div>
                    <section>
                        <small><?= e($tr('Selected unit', 'الوحدة المختارة')) ?></small>
                        <strong><?= e($selectedUnitName) ?></strong>
                        <b><?= e($movementText($selectedUnitMovement)) ?></b>
                        <p><?= e($selectedUnitAction) ?></p>
                    </section>
                </article>
            </aside>
        </section>

        <?php if (!$isAllUnits): ?>
        <section class="beds83-card beds83-unit-review">
            <header class="beds83-unit-head">
                <div>
                    <span><?= e($tr('SELECTED UNIT REVIEW', 'مراجعة الوحدة المختارة')) ?></span>
                    <h2><?= e($selectedUnitName) ?></h2>
                    <p><?= e($tr(
                        'Bed-level movement is shown only to explain the selected unit result.',
                        'يظهر التغير على مستوى الأسرة فقط لتفسير نتيجة الوحدة المختارة.'
                    )) ?></p>
                </div>
                <div class="beds83-unit-kpis">
                    <span><small><?= e($currentPeriodLabel) ?></small><b><?= e($percentValue($selectedUnitUtilization)) ?></b></span>
                    <span><small><?= e($comparePeriodLabel) ?></small><b><?= e($percentValue($selectedCompareUtilization)) ?></b></span>
                    <span class="<?= e($movementClass($selectedUnitMovement)) ?>"><small><?= e($tr('Movement', 'التغير')) ?></small><b><?= e($movementText($selectedUnitMovement)) ?></b></span>
                </div>
            </header>

            <div class="beds83-unit-grid">
                <div class="beds83-unit-chart" data-beds82-chart-shell="beds" data-chart-state="pending">
                    <div id="beds82_beds_chart" class="beds83-chart-target"></div>
                    <div class="beds134-chart-state beds134-chart-empty"><strong><?= e($tr('No bed comparison is available for this unit', 'لا توجد مقارنة أسرة متاحة لهذه الوحدة')) ?></strong></div>
                    <div class="beds134-chart-state beds134-chart-error"><strong><?= e($tr('The bed comparison chart is temporarily unavailable', 'رسم مقارنة الأسرة غير متاح مؤقتًا')) ?></strong></div>
                </div>

                <aside class="beds83-bed-signals">
                    <article>
                        <small><?= e($tr('Largest bed increase', 'أكبر زيادة لسرير')) ?></small>
                        <strong><?= e((string)($largestBedIncrease['label'] ?? '—')) ?></strong>
                        <b><?= e($movementText(isset($largestBedIncrease['movement_pp']) ? (float)$largestBedIncrease['movement_pp'] : null)) ?></b>
                    </article>
                    <article>
                        <small><?= e($tr('Largest bed decline', 'أكبر انخفاض لسرير')) ?></small>
                        <strong><?= e((string)($largestBedDecline['label'] ?? '—')) ?></strong>
                        <b><?= e($movementText(isset($largestBedDecline['movement_pp']) ? (float)$largestBedDecline['movement_pp'] : null)) ?></b>
                    </article>
                    <p><?= e($tr(
                        'Use these signals to identify the beds driving the unit-level movement.',
                        'استخدم هذه مؤشرات المراجعة لتحديد الأسرة التي تقود تغير الوحدة.'
                    )) ?></p>
                </aside>
            </div>
        </section>
        <?php endif; ?>

<details class="beds83-details" id="beds83-details">
            <summary>
                <div>
                    <span><?= e($tr('SUPPORTING DETAIL', 'التفاصيل الداعمة')) ?></span>
                    <strong><?= e($tr('Open full unit and bed comparison', 'فتح مقارنة الوحدات والأسرة كاملة')) ?></strong>
                </div>
                <b><?= e($tr('Open details', 'فتح التفاصيل')) ?></b>
            </summary>

            <div class="beds83-detail-content">
                <section>
                    <header>
                        <h3><?= e($tr('Unit-by-unit comparison', 'مقارنة وحدة بوحدة')) ?></h3>
                        <p><?= e($currentPeriodLabel . ' vs ' . $comparePeriodLabel) ?></p>
                    </header>
                    <div class="beds83-table-wrap">
                        <table>
                            <thead><tr>
                                <th><?= e($tr('Unit', 'الوحدة')) ?></th>
                                <th><?= e($tr('Beds', 'الأسرة')) ?></th>
                                <th><?= e($currentPeriodLabel) ?></th>
                                <th><?= e($comparePeriodLabel) ?></th>
                                <th><?= e($tr('Movement', 'التغير')) ?></th>
                            </tr></thead>
                            <tbody>
                            <?php foreach ($unitComparison as $row): ?>
                                <tr>
                                    <td><strong><?= e((string)$row['label']) ?></strong></td>
                                    <td><?= e(number_format((float)$row['bed_count'], 0)) ?></td>
                                    <td><?= e($percentValue($row['current_value'])) ?></td>
                                    <td><?= e($percentValue($row['compare_value'])) ?></td>
                                    <td class="<?= e($movementClass($row['movement_pp'])) ?>"><?= e($movementText($row['movement_pp'])) ?></td>
                                </tr>
                            <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </section>

                <?php if (!$isAllUnits): ?>
                <section>
                    <header>
                        <h3><?= e($tr('Beds in the selected unit', 'أسرة الوحدة المختارة')) ?></h3>
                        <p><?= e($selectedUnitName) ?></p>
                    </header>
                    <div class="beds83-table-wrap">
                        <table>
                            <thead><tr>
                                <th><?= e($tr('Bed', 'السرير')) ?></th>
                                <th><?= e($currentPeriodLabel) ?></th>
                                <th><?= e($comparePeriodLabel) ?></th>
                                <th><?= e($tr('Movement', 'التغير')) ?></th>
                            </tr></thead>
                            <tbody>
                            <?php foreach ($bedComparison as $row): ?>
                                <tr>
                                    <td><strong><?= e((string)$row['label']) ?></strong></td>
                                    <td><?= e($percentValue($row['current_value'])) ?></td>
                                    <td><?= e($percentValue($row['compare_value'])) ?></td>
                                    <td class="<?= e($movementClass($row['movement_pp'])) ?>"><?= e($movementText($row['movement_pp'])) ?></td>
                                </tr>
                            <?php endforeach; ?>
                            <?php if (!$bedComparison): ?><tr><td colspan="4">—</td></tr><?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </section>
                <?php endif; ?>
            </div>
        </details>

        <script type="application/json" id="beds82_comparison_config"><?= json_encode(
            $comparisonChartConfig,
            JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP
        ) ?></script>

        <script>
        window.addEventListener('DOMContentLoaded', function () {
            var mode = document.querySelector('[data-beds134-mode]');
            var filterForm = document.querySelector('[data-beds134-filter]');
            var rangeFields = Array.prototype.slice.call(document.querySelectorAll('[data-beds134-range-field]'));
            var yearField = document.querySelector('[data-beds134-year-field]');

            function syncPeriodFields() {
                var isRange = mode && mode.value === 'range';
                rangeFields.forEach(function (field) {
                    field.hidden = !isRange;
                    Array.prototype.forEach.call(field.querySelectorAll('input,select'), function (input) {
                        input.disabled = !isRange;
                    });
                });
                if (yearField) {
                    yearField.hidden = isRange;
                    Array.prototype.forEach.call(yearField.querySelectorAll('input,select'), function (input) {
                        input.disabled = isRange;
                    });
                }
                if (filterForm) {
                    filterForm.classList.toggle('is-range', !!isRange);
                    filterForm.classList.toggle('is-year', !isRange);
                }
            }

            if (mode) mode.addEventListener('change', syncPeriodFields);
            syncPeriodFields();
        });
        </script>
    <?php endif; ?>
</div>
