<?php
require_once dirname(__DIR__) . '/components/executive/components.php';

$hospitalName = $hospital['name'] ?? strtoupper($hospitalCode);
$moduleTitle = t($moduleConfig['title_key']);
$moduleHero = t($moduleConfig['hero_key']);
$moduleText = t($moduleConfig['text_key'], ['hospital' => $hospitalName]);
$moduleIcon = $moduleConfig['icon'];
$moduleTone = $moduleConfig['tone'];
$steps = [
    ['title' => t('operations.step_1_title'), 'text' => t('operations.step_1_text')],
    ['title' => t('operations.step_2_title'), 'text' => t('operations.step_2_text')],
    ['title' => t('operations.step_3_title'), 'text' => t('operations.step_3_text')],
];
$isVisits = $module === 'visits';
$isDoctors = $module === 'doctors';
$isBeds = $module === 'beds';
$isOperations = $module === 'operations';
$isLiveModule = $isVisits || $isDoctors || $isBeds || $isOperations;
?>

<?php if ($isVisits): ?>
    <!-- H11_P51_VISITS_SHARED_EXECUTIVE_UI_V2 -->
    <?php
        exec_ui_page_intro([
            'eyebrow' => t('visits.kicker_live'),
            'title' => $moduleTitle,
            'description' => $moduleText,
            'context_label' => t('layout.active_branch'),
            'context_value' => $hospitalName,
            'context_note' => t('visits.module_live_text'),
            'primary_label' => t('visits.open_live_data'),
            'primary_href' => '#visits-live-data',
            'secondary_label' => t('layout.change_hospital'),
            'status_label' => t('visits.data_verified_badge'),
        ]);
    ?>
<?php else: ?>
<section class="operations-hero executive-hero compact-hero tone-<?= e($moduleTone) ?>">
    <div class="hero-copy">
        <span class="overline light"><?= e($isVisits ? t('visits.kicker_live') : ($isDoctors ? t('doctors.kicker_live') : ($isBeds ? t('beds.kicker_live') : ($isOperations ? t('operations.kicker_live') : t('operations.kicker'))))) ?></span>
        <h2><span><?= e($moduleIcon) ?></span> <?= e($moduleHero) ?></h2>
        <p><?= e($moduleText) ?></p>
        <div class="hero-actions">
            <button type="button" class="btn subtle" data-branch-open><?= e(t('layout.change_hospital')) ?></button>
            <?php if ($isVisits): ?>
                <a class="btn primary" href="#visits-live-data"><?= e(t('visits.open_live_data')) ?></a>
            <?php elseif ($isDoctors): ?>
                <a class="btn primary" href="#doctors-live-data"><?= e(t('doctors.open_live_data')) ?></a>
            <?php elseif ($isBeds): ?>
                <a class="btn primary" href="#beds-live-data"><?= e(t('beds.open_live_data')) ?></a>
            <?php elseif ($isOperations): ?>
                <a class="btn primary" href="#operations-live-data"><?= e(t('operations.open_live_data')) ?></a>
            <?php else: ?>
                <a class="btn primary" href="<?= e(url_to('revenue')) ?>"><?= e(t('dashboard.open_revenue')) ?></a>
            <?php endif; ?>
        </div>
    </div>
    <div class="hero-command-card">
        <div class="command-topline"><span><?= e(t('layout.active_branch')) ?></span><i></i></div>
        <strong><?= e($hospitalName) ?></strong>
        <div class="operations-badge"><?= e($moduleIcon) ?></div>
        <h3><?= e($moduleTitle) ?></h3>
        <p><?= e($isVisits ? t('visits.module_live_text') : ($isDoctors ? t('doctors.module_live_text') : ($isBeds ? t('beds.module_live_text') : ($isOperations ? t('operations.module_live_text') : t('operations.module_ready_text'))))) ?></p>
    </div>
</section>
<?php endif; ?>

<?php if (!$isVisits): ?>
<section class="metric-grid four">
    <?php foreach ($stats as $stat): ?>
        <article class="metric-card tone-<?= e($stat['tone']) ?>">
            <div class="metric-orb"></div>
            <span><?= e($stat['label']) ?></span>
            <strong><?= e($stat['value']) ?></strong>
            <small><?= e($stat['hint']) ?></small>
        </article>
    <?php endforeach; ?>
</section>
<?php endif; ?>

<?php if ($isVisits): ?>
    <?php
        $activeMode = $reportMode ?? 'year';
        $periodCurrent = is_array($visitData) ? (string)($visitData['current_period_label'] ?? $year) : ($activeMode === 'range' ? ($fromDate . ' - ' . $toDate) : (string)$year);
        $periodCompare = is_array($visitData) ? (string)($visitData['compare_period_label'] ?? $compareYear) : (string)$compareYear;
    ?>

    <section id="visits-live-data" class="surface-card patient1010-control exec-filter-panel" data-patient-activity-controls>
        <div class="patient1010-control-head">
            <div>
                <span class="overline"><?= e(t('visits.control_kicker')) ?></span>
                <h2><?= e(t('visits.control_title')) ?></h2>
                <p><?= e(t('visits.control_text')) ?></p>
            </div>
            <span class="patient1010-parity-badge"><?= e(t('visits.parity_badge')) ?></span>
        </div>

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

            <label class="patient1010-mode-field">
                <span><?= e(t('visits.report_mode')) ?></span>
                <select name="mode" data-patient-mode>
                    <option value="year" <?= $activeMode === 'year' ? 'selected' : '' ?>><?= e(t('visits.mode_year')) ?></option>
                    <option value="range" <?= $activeMode === 'range' ? 'selected' : '' ?>><?= e(t('visits.mode_range')) ?></option>
                </select>
            </label>

            <label data-year-field>
                <span><?= e(t('visits.year')) ?></span>
                <input type="number" min="2014" max="2100" name="year" value="<?= e($year) ?>">
            </label>

            <label data-range-field>
                <span><?= e(t('visits.from_date')) ?></span>
                <input type="date" name="from_date" value="<?= e($fromDate ?? '') ?>">
            </label>

            <label data-range-field>
                <span><?= e(t('visits.to_date')) ?></span>
                <input type="date" name="to_date" value="<?= e($toDate ?? '') ?>">
            </label>

            <label>
                <span><?= e(t('visits.compare_year')) ?></span>
                <input type="number" min="2014" max="2100" name="compare_year" value="<?= e($compareYear) ?>">
            </label>

            <button class="btn primary patient1010-apply" type="submit"><?= e(t('visits.apply_filter')) ?></button>
            <button class="btn ghost patient1010-branch" type="button" data-branch-open><?= e(t('layout.change_hospital')) ?></button>
        </form>

        <?php if (!empty($visitsFilterError)): ?>
            <div class="patient1010-filter-message" role="alert"><?= e($visitsFilterError) ?></div>
        <?php endif; ?>
    </section>

    <section class="patient1010-period-strip exec-summary-strip" aria-label="<?= e(t('visits.period_summary')) ?>">
        <article>
            <span><?= e(t('visits.stat_period_mode')) ?></span>
            <strong><?= e(t($activeMode === 'range' ? 'visits.mode_range' : 'visits.mode_year')) ?></strong>
        </article>
        <article>
            <span><?= e(t('visits.stat_current_period')) ?></span>
            <strong><?= e($periodCurrent) ?></strong>
        </article>
        <article>
            <span><?= e(t('visits.stat_compare_period')) ?></span>
            <strong><?= e($periodCompare) ?></strong>
        </article>
        <article>
            <span><?= e(t('visits.stat_branch')) ?></span>
            <strong><?= e($hospitalName) ?></strong>
        </article>
    </section>

    <?php if ($dataError): ?>
        <section class="surface-card patient1010-state patient1010-state-error">
            <span class="overline"><?= e(t('visits.data_error_label')) ?></span>
            <h2><?= e(t('visits.data_error_title')) ?></h2>
            <p><?= e(t('visits.data_error_text')) ?></p>
        </section>
    <?php elseif (is_array($visitData)): ?>
        <?php if (!empty($visitData['warnings'])): ?>
            <section class="surface-card patient1010-state patient1010-state-warning">
                <span class="overline"><?= e(t('visits.data_warning_label')) ?></span>
                <h2><?= e(t('visits.data_warning_title')) ?></h2>
                <p><?= e(t('visits.data_warning_text')) ?></p>
            </section>
        <?php endif; ?>

        <section class="metric-grid four visits-kpi-grid patient1010-kpis exec-kpi-zone">
            <?php foreach ($visitData['cards'] as $key => $card): ?>
                <article class="metric-card visits-kpi patient1010-kpi tone-<?= e($key === 'er' ? 'amber' : ($key === 'admissions' ? 'violet' : ($key === 'followup' ? 'green' : 'blue'))) ?>">
                    <div class="metric-orb"></div>
                    <span><?= e($card['title']) ?></span>
                    <strong><?= e(number_format((float)$card['current_total'], 0)) ?></strong>
                    <?php if (($card['mode'] ?? '') === 'ratio'): ?>
                        <small><?= e(t('visits.new_visits')) ?>: <?= e(number_format((float)$card['compare_total'], 0)) ?> · <?= e(t('visits.followup_ratio')) ?>: <?= $card['percent'] === null ? e(t('common.not_available')) : e(number_format((float)$card['percent'], 1) . '%') ?></small>
                    <?php else: ?>
                        <small><?= e(t('visits.compared_with')) ?> <?= e($periodCompare) ?> · <?= e(t('visits.previous')) ?>: <?= e(number_format((float)$card['compare_total'], 0)) ?></small>
                    <?php endif; ?>
                    <?php if (($card['mode'] ?? '') === 'compare'): ?>
                        <em class="delta <?= ($card['percent'] ?? 0) >= 0 ? 'up' : 'down' ?>">
                            <?= $card['percent'] === null ? e(t('common.not_available')) : e(number_format((float)$card['percent'], 1) . '%') ?>
                        </em>
                    <?php endif; ?>
                </article>
            <?php endforeach; ?>
        </section>

        <?php
            $changeItems = [];
            foreach (['opd', 'er', 'admissions'] as $metricKey) {
                $card = $visitData['cards'][$metricKey] ?? null;
                if (!is_array($card)) continue;
                $pct = $card['percent'];
                if ($pct === null) continue;
                $changeItems[] = ['key' => $metricKey, 'title' => $card['title'], 'percent' => (float)$pct];
            }
            usort($changeItems, static function (array $a, array $b): int { return abs($b['percent']) <=> abs($a['percent']); });
            $primaryChange = $changeItems[0] ?? null;
        ?>
        <section class="surface-card patient1010-insight exec-insight-band">
            <div>
                <span class="overline"><?= e(t('visits.executive_insight_kicker')) ?></span>
                <h2><?= e(t('visits.executive_insight_title')) ?></h2>
            </div>
            <p>
                <?php if (is_array($primaryChange)): ?>
                    <?= e(t('visits.executive_insight_change', [
                        'metric' => (string)$primaryChange['title'],
                        'direction' => $primaryChange['percent'] >= 0 ? t('visits.direction_up') : t('visits.direction_down'),
                        'percent' => number_format(abs((float)$primaryChange['percent']), 1),
                    ])) ?>
                <?php else: ?>
                    <?= e(t('visits.executive_insight_stable')) ?>
                <?php endif; ?>
            </p>
        </section>

        <section class="workspace-grid visits-insight-grid patient1010-primary-grid exec-analysis-layout">
            <article class="surface-card operations-card wide patient1010-monthly-card">
                <div class="section-head compact">
                    <span class="overline"><?= e(t('visits.monthly_kicker')) ?></span>
                    <h2><?= e(t('visits.monthly_title')) ?></h2>
                    <p><?= e(t('visits.monthly_text_period', ['current' => $periodCurrent, 'compare' => $periodCompare])) ?></p>
                </div>
                <div class="visits-tabs patient1010-charts exec-chart-collection" data-patient-chart-grid>
                    <?php foreach ($visitData['charts'] as $key => $chart): ?>
                        <article class="patient1010-chart-card exec-chart-card--compact" data-patient-chart-card="<?= e($key) ?>" data-chart-state="pending">
                            <div class="patient1010-chart-head">
                                <h3><?= e($chart['title']) ?></h3>
                                <span><?= e($periodCurrent) ?> · <?= e(t('visits.vs')) ?> · <?= e($periodCompare) ?></span>
                            </div>
                            <canvas id="visits_chart_<?= e($key) ?>" class="chart visits-chart" height="132" data-patient-activity-chart="<?= e($key) ?>" data-chart-rendered="false"></canvas>
                            <div class="patient1010-chart-state patient1010-chart-empty" hidden><?= e(t('visits.chart_empty')) ?></div>
                            <div class="patient1010-chart-state patient1010-chart-error" hidden><?= e(t('visits.chart_unavailable')) ?></div>
                            <script type="application/json" id="visits_chart_data_<?= e($key) ?>"><?= json_encode($chart['payload'], JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?></script>
                        </article>
                    <?php endforeach; ?>
                </div>
            </article>

            <article class="surface-card operations-card visits-mix-card patient1010-mix-card">
                <div class="section-head compact">
                    <span class="overline"><?= e(t('visits.followup_kicker')) ?></span>
                    <h2><?= e(t('visits.followup_title')) ?></h2>
                    <p><?= e(t('visits.followup_text')) ?></p>
                </div>
                <?php $mix = $visitData['followup']; ?>
                <?php $followupPct = (float)($mix['ratio'] ?? 0); $newPct = (float)($mix['new_ratio'] ?? 0); ?>
                <div class="mix-meter" aria-label="<?= e(t('visits.followup_title')) ?>">
                    <span style="width: <?= e(number_format($newPct, 2, '.', '')) ?>%"></span>
                    <b style="width: <?= e(number_format($followupPct, 2, '.', '')) ?>%"></b>
                </div>
                <div class="mix-legend">
                    <div><i class="new"></i><strong><?= e(number_format((float)$mix['new'], 0)) ?></strong><span><?= e(t('visits.new_visits')) ?></span></div>
                    <div><i class="follow"></i><strong><?= e(number_format((float)$mix['followup'], 0)) ?></strong><span><?= e(t('visits.followup_visits')) ?></span></div>
                </div>
            </article>
        </section>

        <section class="surface-card visits-table-card patient1010-table-card" data-legacy-function="gmov" data-multi-branch-outpatient-visits>
            <div class="section-head compact">
                <span class="overline"><?= e(t('visits.multi_branch_kicker')) ?></span>
                <h2><?= e(t('visits.multi_branch_title')) ?></h2>
                <p><?= e(t('visits.multi_branch_text')) ?></p>
                <p class="muted-line"><?= e(t('visits.multi_branch_readiness_note')) ?></p>
            </div>
            <?php $multiBranchRows = $visitData['multiBranchOutpatient'] ?? []; ?>
            <?php if (!empty($multiBranchRows)): ?>
                <div class="table-wrap visits-table-wrap">
                    <table>
                        <thead>
                            <tr>
                                <th><?= e(t('visits.month')) ?></th>
                                <th><?= e(t('visits.branch_new_jeddah')) ?></th>
                                <th><?= e(t('visits.branch_jeddah')) ?></th>
                                <th><?= e(t('visits.branch_madina')) ?></th>
                                <th><?= e(t('visits.branch_total')) ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($multiBranchRows as $row): ?>
                                <tr>
                                    <td><strong><?= e(trim((string)($row['month_name'] ?? ''))) ?></strong></td>
                                    <td><?= e(number_format((float)($row['njch'] ?? 0), 0)) ?></td>
                                    <td>
                                        <?php if (array_key_exists('jckh', $row) && $row['jckh'] !== null): ?>
                                            <?= e(number_format((float)$row['jckh'], 0)) ?>
                                        <?php else: ?>
                                            <span class="muted-line"><?= e(t('visits.branch_deferred_not_ready')) ?></span>
                                        <?php endif; ?>
                                    </td>
                                    <td><?= e(number_format((float)($row['mnh'] ?? 0), 0)) ?></td>
                                    <td><strong><?= e(number_format((float)($row['total'] ?? 0), 0)) ?></strong></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php else: ?>
                <div class="exec-data-table-empty">
                    <?php
                        exec_ui_empty_state([
                            'title' => t('visits.multi_branch_unavailable_title'),
                            'text' => t('visits.multi_branch_no_data'),
                            'tone' => 'info',
                        ]);
                    ?>
                </div>
            <?php endif; ?>
        </section>

        <section class="workspace-grid visits-detail-grid patient1010-secondary-grid">
            <article class="surface-card operations-card" data-legacy-function="acty" data-admission-category-mix>
                <div class="section-head compact">
                    <span class="overline"><?= e(t('visits.admission_category_kicker')) ?></span>
                    <h2><?= e(t('visits.admission_category_title')) ?></h2>
                    <p><?= e(t('visits.admission_category_text')) ?></p>
                </div>
                <?php $admissionCategories = $visitData['admissionCategories'] ?? []; ?>
                <div class="rank-list">
                    <?php foreach ($admissionCategories as $idx => $row): ?>
                        <?php
                            $categoryKey = (string)($row['category'] ?? 'other');
                            $categoryLabelKey = 'visits.admission_category_' . $categoryKey;
                            $percent = max(0.0, min(100.0, (float)($row['percent'] ?? 0)));
                        ?>
                        <div class="rank-row">
                            <em><?= e($idx + 1) ?></em>
                            <div>
                                <strong><?= e(t($categoryLabelKey)) ?></strong>
                                <span><i style="width: <?= e(number_format(max(5.0, $percent), 2, '.', '')) ?>%"></i></span>
                            </div>
                            <b><?= e(number_format((float)($row['value'] ?? 0), 0)) ?></b>
                        </div>
                    <?php endforeach; ?>
                    <?php if (empty($admissionCategories)): ?>
                        <p class="muted-line"><?= e(t('visits.admission_category_no_data')) ?></p>
                    <?php endif; ?>
                </div>
            </article>

            <article class="surface-card operations-card" data-legacy-function="out_cash_cr" data-outpatient-payer-mix>
                <div class="section-head compact">
                    <span class="overline"><?= e(t('visits.outpatient_payer_kicker')) ?></span>
                    <h2><?= e(t('visits.outpatient_payer_title')) ?></h2>
                    <p><?= e(t('visits.outpatient_payer_text')) ?></p>
                </div>
                <?php $outpatientPayerMix = $visitData['outpatientPayerMix'] ?? []; ?>
                <div class="rank-list">
                    <?php foreach ($outpatientPayerMix as $idx => $row): ?>
                        <?php
                            $categoryKey = (string)($row['category'] ?? 'credit');
                            $categoryLabelKey = 'visits.outpatient_payer_' . $categoryKey;
                            $percent = max(0.0, min(100.0, (float)($row['percent'] ?? 0)));
                        ?>
                        <div class="rank-row">
                            <em><?= e($idx + 1) ?></em>
                            <div>
                                <strong><?= e(t($categoryLabelKey)) ?></strong>
                                <span><i style="width: <?= e(number_format(max(5.0, $percent), 2, '.', '')) ?>%"></i></span>
                            </div>
                            <b><?= e(number_format((float)($row['value'] ?? 0), 0)) ?></b>
                        </div>
                    <?php endforeach; ?>
                    <?php if (empty($outpatientPayerMix)): ?>
                        <p class="muted-line"><?= e(t('visits.outpatient_payer_no_data')) ?></p>
                    <?php endif; ?>
                </div>
            </article>

            <article class="surface-card operations-card exec-compact-data-card">
                <div class="section-head compact">
                    <span class="overline"><?= e(t('visits.daily_kicker')) ?></span>
                    <h2><?= e(t('visits.daily_title')) ?></h2>
                    <p><?= e(t('visits.daily_text')) ?></p>
                </div>
                <?php $dailyMax = 1; foreach ($visitData['daily'] as $row) { $dailyMax = max($dailyMax, (float)$row['value']); } ?>
                <div class="daily-bars">
                    <?php foreach ($visitData['daily'] as $row): ?>
                        <?php $height = max(8, ((float)$row['value'] / $dailyMax) * 100); ?>
                        <div title="<?= e($row['label'] . ': ' . number_format((float)$row['value'], 0)) ?>">
                            <span style="height: <?= e(number_format($height, 2, '.', '')) ?>%"></span>
                            <b><?= e(number_format((float)$row['value'], 0)) ?></b>
                            <small><?= e($row['label']) ?></small>
                        </div>
                    <?php endforeach; ?>
                    <?php if (empty($visitData['daily'])): ?><p class="muted-line"><?= e(t('visits.no_daily')) ?></p><?php endif; ?>
                </div>
            </article>

            <article class="surface-card operations-card exec-compact-data-card">
                <div class="section-head compact">
                    <span class="overline"><?= e(t('visits.specialty_kicker')) ?></span>
                    <h2><?= e(t('visits.specialty_title')) ?></h2>
                    <p><?= e(t('visits.specialty_text_executive')) ?></p>
                </div>
                <?php $maxSpec = 1; foreach ($visitData['specialties'] as $row) { $maxSpec = max($maxSpec, (float)$row['value']); } ?>
                <div class="rank-list">
                    <?php foreach ($visitData['specialties'] as $idx => $row): ?>
                        <?php $width = max(5, ((float)$row['value'] / $maxSpec) * 100); ?>
                        <div class="rank-row">
                            <em><?= e($idx + 1) ?></em>
                            <div>
                                <strong><?= e($row['label']) ?></strong>
                                <span><i style="width: <?= e(number_format($width, 2, '.', '')) ?>%"></i></span>
                            </div>
                            <b><?= e(number_format((float)$row['value'], 0)) ?></b>
                        </div>
                    <?php endforeach; ?>
                    <?php if (empty($visitData['specialties'])): ?>
                        <?php
                            exec_ui_empty_state([
                                'title' => t('visits.no_specialties_title'),
                                'text' => t('visits.no_specialties'),
                                'tone' => 'neutral',
                            ]);
                        ?>
                    <?php endif; ?>
                </div>
            </article>
        </section>

        <section class="surface-card visits-table-card patient1010-table-card">
            <div class="section-head compact">
                <span class="overline"><?= e(t('visits.table_kicker')) ?></span>
                <h2><?= e(t('visits.table_title')) ?></h2>
                <p><?= e(t('visits.table_text_period', ['current' => $periodCurrent, 'compare' => $periodCompare])) ?></p>
            </div>
            <div class="table-wrap visits-table-wrap">
                <table>
                    <thead>
                        <tr>
                            <th><?= e(t('visits.month')) ?></th>
                            <th><?= e(t('visits.opd')) ?> · <?= e($periodCurrent) ?></th>
                            <th><?= e(t('visits.opd')) ?> · <?= e($periodCompare) ?></th>
                            <th><?= e(t('visits.er')) ?> · <?= e($periodCurrent) ?></th>
                            <th><?= e(t('visits.er')) ?> · <?= e($periodCompare) ?></th>
                            <th><?= e(t('visits.admissions')) ?> · <?= e($periodCurrent) ?></th>
                            <th><?= e(t('visits.admissions')) ?> · <?= e($periodCompare) ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php $opd = $visitData['charts']['opd']['rows']; $er = $visitData['charts']['er']['rows']; $adm = $visitData['charts']['admissions']['rows']; ?>
                        <?php foreach ($opd as $idx => $row): ?>
                            <tr>
                                <td><?= e($row['month_name']) ?></td>
                                <td><?= e(number_format((float)$row['current_value'], 0)) ?></td>
                                <td><?= e(number_format((float)$row['compare_value'], 0)) ?></td>
                                <td><?= e(number_format((float)($er[$idx]['current_value'] ?? 0), 0)) ?></td>
                                <td><?= e(number_format((float)($er[$idx]['compare_value'] ?? 0), 0)) ?></td>
                                <td><?= e(number_format((float)($adm[$idx]['current_value'] ?? 0), 0)) ?></td>
                                <td><?= e(number_format((float)($adm[$idx]['compare_value'] ?? 0), 0)) ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </section>

        <script>
        window.addEventListener('DOMContentLoaded', function () {
            var modeSelect = document.querySelector('[data-patient-mode]');
            var filter = document.querySelector('[data-patient-filter]');
            if (modeSelect && filter) {
                var refreshMode = function () {
                    filter.classList.toggle('is-range', modeSelect.value === 'range');
                    filter.classList.toggle('is-year', modeSelect.value !== 'range');
                };
                modeSelect.addEventListener('change', refreshMode);
                refreshMode();
            }

            var gate = { expected: 0, rendered: 0, empty: 0, failed: 0 };
            document.querySelectorAll('script[type="application/json"][id^="visits_chart_data_"]').forEach(function (node) {
                var key = node.id.replace('visits_chart_data_', '');
                var card = document.querySelector('[data-patient-chart-card="' + key + '"]');
                var canvas = document.getElementById('visits_chart_' + key);
                gate.expected += 1;
                try {
                    var payload = JSON.parse(node.textContent || '{}');
                    var values = [];
                    (payload.series || []).forEach(function (series) {
                        (series.values || []).forEach(function (value) { values.push(Number(value || 0)); });
                    });
                    var hasData = values.some(function (value) { return value !== 0; });
                    if (!hasData) {
                        if (card) {
                            card.setAttribute('data-chart-state', 'empty');
                            var emptyState = card.querySelector('.patient1010-chart-empty');
                            if (emptyState) emptyState.hidden = false;
                        }
                        if (canvas) canvas.hidden = true;
                        gate.empty += 1;
                        return;
                    }
                    var result = window.renderBarCompareChart('visits_chart_' + key, payload);
                    if (result && result.rendered) {
                        if (card) card.setAttribute('data-chart-state', 'rendered');
                        gate.rendered += 1;
                    } else {
                        throw new Error('Chart renderer did not confirm success.');
                    }
                } catch (error) {
                    if (card) {
                        card.setAttribute('data-chart-state', 'error');
                        var errorState = card.querySelector('.patient1010-chart-error');
                        if (errorState) errorState.hidden = false;
                    }
                    if (canvas) canvas.hidden = true;
                    gate.failed += 1;
                }
            });
            gate.status = gate.failed === 0 && gate.expected === 3 ? 'PASS' : 'FAIL';
            window.__DDB_PATIENT_ACTIVITY_CHART_GATE__ = gate;
            document.documentElement.setAttribute('data-patient-chart-expected', String(gate.expected));
            document.documentElement.setAttribute('data-patient-chart-rendered', String(gate.rendered));
            document.documentElement.setAttribute('data-patient-chart-empty', String(gate.empty));
            document.documentElement.setAttribute('data-patient-chart-failed', String(gate.failed));
            document.documentElement.setAttribute('data-patient-chart-gate', gate.status);
        });
        </script>
    <?php endif; ?>

<?php elseif ($isOperations): ?>
    <?php
        $activeMode = $reportMode ?? 'year';
        $periodCurrent = is_array($operationData) ? (string)($operationData['current_period_label'] ?? $year) : ($activeMode === 'range' ? ($fromDate . ' - ' . $toDate) : (string)$year);
        $periodCompare = is_array($operationData) ? (string)($operationData['compare_period_label'] ?? $compareYear) : (string)$compareYear;
    ?>

    <section id="operations-live-data" class="surface-card operations1011-control" data-operations-controls>
        <div class="operations1011-control-head">
            <div>
                <span class="overline"><?= e(t('operations.control_kicker')) ?></span>
                <h2><?= e(t('operations.control_title')) ?></h2>
                <p><?= e(t('operations.control_text')) ?></p>
            </div>
            <span class="operations1011-parity-badge"><?= e(t('operations.parity_badge')) ?></span>
        </div>

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

            <label>
                <span><?= e(t('operations.report_mode')) ?></span>
                <select name="mode" data-operations-mode>
                    <option value="year" <?= $activeMode === 'year' ? 'selected' : '' ?>><?= e(t('operations.mode_year')) ?></option>
                    <option value="range" <?= $activeMode === 'range' ? 'selected' : '' ?>><?= e(t('operations.mode_range')) ?></option>
                </select>
            </label>

            <label data-year-field>
                <span><?= e(t('operations.year')) ?></span>
                <?php $operationYears = is_array($operationData) ? ($operationData['availableYears'] ?? []) : []; ?>
                <?php if (!empty($operationYears)): ?>
                    <select name="year">
                        <?php foreach ($operationYears as $availableYear): ?>
                            <option value="<?= e($availableYear) ?>" <?= ((int)$availableYear === (int)$year) ? 'selected' : '' ?>><?= e($availableYear) ?></option>
                        <?php endforeach; ?>
                    </select>
                <?php else: ?>
                    <input type="number" min="2014" max="2100" name="year" value="<?= e($year) ?>">
                <?php endif; ?>
            </label>

            <label data-range-field>
                <span><?= e(t('operations.from_date')) ?></span>
                <input type="date" name="from_date" value="<?= e($fromDate ?? '') ?>">
            </label>

            <label data-range-field>
                <span><?= e(t('operations.to_date')) ?></span>
                <input type="date" name="to_date" value="<?= e($toDate ?? '') ?>">
            </label>

            <label>
                <span><?= e(t('operations.compare_year')) ?></span>
                <input type="number" min="2014" max="2100" name="compare_year" value="<?= e($compareYear) ?>">
            </label>

            <button class="btn primary operations1011-apply" type="submit"><?= e(t('operations.apply_filter')) ?></button>
            <button class="btn ghost operations1011-branch" type="button" data-branch-open><?= e(t('layout.change_hospital')) ?></button>
        </form>

        <?php if (!empty($operationsFilterError)): ?>
            <div class="operations1011-filter-message" role="alert"><?= e($operationsFilterError) ?></div>
        <?php endif; ?>
    </section>

    <section class="operations1011-period-strip" aria-label="<?= e(t('operations.period_summary')) ?>">
        <article><span><?= e(t('operations.stat_period_mode')) ?></span><strong><?= e(t($activeMode === 'range' ? 'operations.mode_range' : 'operations.mode_year')) ?></strong></article>
        <article><span><?= e(t('operations.stat_current_period')) ?></span><strong><?= e($periodCurrent) ?></strong></article>
        <article><span><?= e(t('operations.stat_compare_period')) ?></span><strong><?= e($periodCompare) ?></strong></article>
        <article><span><?= e(t('operations.stat_branch')) ?></span><strong><?= e($hospitalName) ?></strong></article>
    </section>

    <?php if ($dataError): ?>
        <section class="surface-card operations1011-state operations1011-state-error">
            <span class="overline"><?= e(t('operations.data_error_label')) ?></span>
            <h2><?= e(t('operations.data_error_title')) ?></h2>
            <p><?= e(t('operations.data_error_text')) ?></p>
        </section>
    <?php elseif (is_array($operationData)): ?>
        <?php if (!empty($operationData['warnings'])): ?>
            <section class="surface-card operations1011-state operations1011-state-warning">
                <span class="overline"><?= e(t('operations.data_warning_label')) ?></span>
                <h2><?= e(t('operations.data_warning_title')) ?></h2>
                <p><?= e(t('operations.data_warning_text')) ?></p>
            </section>
        <?php endif; ?>

        <section class="metric-grid four operations1011-kpis">
            <?php foreach ($operationData['cards'] as $key => $card): ?>
                <?php
                    $tone = $key === 'cancelled' ? 'amber' : ($key === 'completion' ? 'violet' : ($key === 'performed' ? 'green' : 'blue'));
                    $isPercent = ($card['mode'] ?? '') === 'percent';
                    $currentValue = $card['current_total'];
                    $compareValue = $card['compare_total'];
                ?>
                <article class="metric-card operations1011-kpi tone-<?= e($tone) ?>">
                    <div class="metric-orb"></div>
                    <span><?= e($card['title']) ?></span>
                    <strong><?= $currentValue === null ? e(t('common.not_available')) : e(number_format((float)$currentValue, $isPercent ? 1 : 0) . ($isPercent ? '%' : '')) ?></strong>
                    <small>
                        <?php if ($isPercent): ?>
                            <?= e(t('operations.compared_with')) ?> <?= e($periodCompare) ?> · <?= $compareValue === null ? e(t('common.not_available')) : e(number_format((float)$compareValue, 1) . '%') ?>
                        <?php else: ?>
                            <?= e(t('operations.compared_with')) ?> <?= e($periodCompare) ?> · <?= e(t('operations.previous')) ?>: <?= e(number_format((float)$compareValue, 0)) ?>
                        <?php endif; ?>
                    </small>
                    <?php if (($card['percent'] ?? null) !== null): ?>
                        <em class="delta <?= ((float)$card['percent']) >= 0 ? 'up' : 'down' ?>">
                            <?= e(number_format((float)$card['percent'], 1) . ($isPercent ? ' pp' : '%')) ?>
                        </em>
                    <?php endif; ?>
                </article>
            <?php endforeach; ?>
        </section>

        <?php
            $summary = $operationData['summary'] ?? [];
            $completionCurrent = $summary['completion_rate_current'] ?? null;
            $completionCompare = $summary['completion_rate_compare'] ?? null;
            $volumeChanges = [];
            foreach (['scheduled', 'performed', 'cancelled'] as $metricKey) {
                $card = $operationData['cards'][$metricKey] ?? null;
                if (!is_array($card) || ($card['percent'] ?? null) === null) continue;
                $volumeChanges[] = ['title' => $card['title'], 'percent' => (float)$card['percent']];
            }
            usort($volumeChanges, static function (array $a, array $b): int { return abs($b['percent']) <=> abs($a['percent']); });
            $primaryVolumeChange = $volumeChanges[0] ?? null;
        ?>

        <section class="surface-card operations1011-insight">
            <div class="operations1011-insight-icon">✦</div>
            <div>
                <span class="overline"><?= e(t('operations.executive_insight_kicker')) ?></span>
                <h2><?= e(t('operations.executive_insight_title')) ?></h2>
                <?php if ($completionCurrent !== null): ?>
                    <p><?= e(t('operations.executive_completion', ['rate' => number_format((float)$completionCurrent, 1)])) ?></p>
                    <?php if ($completionCompare !== null): ?>
                        <?php $pointChange = (float)$completionCurrent - (float)$completionCompare; ?>
                        <p><?= e(t('operations.executive_completion_compare', [
                            'direction' => t($pointChange >= 0 ? 'operations.direction_up' : 'operations.direction_down'),
                            'points' => number_format(abs($pointChange), 1),
                        ])) ?></p>
                    <?php endif; ?>
                <?php endif; ?>
                <?php if ($primaryVolumeChange): ?>
                    <p><?= e(t('operations.executive_volume', [
                        'metric' => $primaryVolumeChange['title'],
                        'percent' => number_format(abs((float)$primaryVolumeChange['percent']), 1),
                    ])) ?></p>
                <?php elseif ($completionCurrent === null): ?>
                    <p><?= e(t('operations.executive_stable')) ?></p>
                <?php endif; ?>
            </div>
        </section>

        <section class="section-head operations1011-section-head">
            <span class="overline"><?= e(t('operations.monthly_kicker')) ?></span>
            <h2><?= e(t('operations.monthly_title')) ?></h2>
            <p><?= e(t('operations.monthly_text_period', ['current' => $periodCurrent, 'compare' => $periodCompare])) ?></p>
        </section>

        <section class="operations1011-chart-grid" data-operations-chart-grid>
            <?php foreach ($operationData['charts'] as $chartKey => $chart): ?>
                <article class="surface-card operations1011-chart-card" data-operations-chart-card="<?= e($chartKey) ?>" data-chart-state="pending">
                    <div class="operations1011-chart-head">
                        <h3><?= e($chart['title']) ?></h3>
                        <span><?= e($periodCurrent) ?> · <?= e($periodCompare) ?></span>
                    </div>
                    <div class="operations1011-chart-stage">
                        <canvas id="operations_chart_<?= e($chartKey) ?>" height="300"></canvas>
                        <div class="operations1011-chart-state operations1011-chart-empty" hidden><?= e(t('operations.chart_empty')) ?></div>
                        <div class="operations1011-chart-state operations1011-chart-error" hidden><?= e(t('operations.chart_unavailable')) ?></div>
                    </div>
                    <script type="application/json" id="operations_chart_data_<?= e($chartKey) ?>"><?= json_encode($chart['payload'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?></script>
                </article>
            <?php endforeach; ?>
        </section>

        <section class="operations1011-breakdown-grid">
            <?php
                $breakdowns = [
                    ['title' => t('operations.specialties_title'), 'rows' => $operationData['topSpecialties'] ?? [], 'empty' => t('operations.no_specialties')],
                    ['title' => t('operations.doctors_title'), 'rows' => $operationData['topDoctors'] ?? [], 'empty' => t('operations.no_doctors')],
                    ['title' => t('operations.rooms_title'), 'rows' => $operationData['topRooms'] ?? [], 'empty' => t('operations.no_rooms')],
                ];
            ?>
            <?php foreach ($breakdowns as $breakdown): ?>
                <article class="surface-card operations1011-breakdown-card">
                    <span class="overline"><?= e(t('operations.breakdown_kicker')) ?></span>
                    <h3><?= e($breakdown['title']) ?></h3>
                    <?php $rankMax = 1.0; foreach ($breakdown['rows'] as $row) { $rankMax = max($rankMax, (float)($row['value'] ?? 0)); } ?>
                    <div class="operations1011-rank-list">
                        <?php foreach ($breakdown['rows'] as $idx => $row): ?>
                            <?php $width = max(5.0, ((float)($row['value'] ?? 0) / $rankMax) * 100); ?>
                            <div class="operations1011-rank-row">
                                <em><?= e($idx + 1) ?></em>
                                <div><strong><?= e($row['label'] ?? '') ?></strong><span><i style="width: <?= e(number_format($width, 2, '.', '')) ?>%"></i></span></div>
                                <b><?= e(number_format((float)($row['value'] ?? 0), 0)) ?></b>
                            </div>
                        <?php endforeach; ?>
                        <?php if (empty($breakdown['rows'])): ?><p class="muted-line"><?= e($breakdown['empty']) ?></p><?php endif; ?>
                    </div>
                </article>
            <?php endforeach; ?>
        </section>

        <section class="surface-card operations1011-table-card">
            <div class="section-head compact">
                <span class="overline"><?= e(t('operations.table_kicker')) ?></span>
                <h2><?= e(t('operations.table_title')) ?></h2>
                <p><?= e(t('operations.table_text_period', ['current' => $periodCurrent, 'compare' => $periodCompare])) ?></p>
            </div>
            <div class="table-wrap operations1011-table-wrap">
                <table>
                    <thead><tr>
                        <th><?= e(t('operations.month')) ?></th>
                        <th><?= e(t('operations.scheduled')) ?> · <?= e($periodCurrent) ?></th>
                        <th><?= e(t('operations.scheduled')) ?> · <?= e($periodCompare) ?></th>
                        <th><?= e(t('operations.performed')) ?> · <?= e($periodCurrent) ?></th>
                        <th><?= e(t('operations.performed')) ?> · <?= e($periodCompare) ?></th>
                        <th><?= e(t('operations.cancelled')) ?> · <?= e($periodCurrent) ?></th>
                        <th><?= e(t('operations.cancelled')) ?> · <?= e($periodCompare) ?></th>
                    </tr></thead>
                    <tbody>
                        <?php $scheduled = $operationData['charts']['scheduled']['rows']; $performed = $operationData['charts']['performed']['rows']; $cancelled = $operationData['charts']['cancelled']['rows']; ?>
                        <?php foreach ($scheduled as $idx => $row): ?>
                            <tr>
                                <td><?= e($row['month_name']) ?></td>
                                <td><?= e(number_format((float)$row['current_value'], 0)) ?></td>
                                <td><?= e(number_format((float)$row['compare_value'], 0)) ?></td>
                                <td><?= e(number_format((float)($performed[$idx]['current_value'] ?? 0), 0)) ?></td>
                                <td><?= e(number_format((float)($performed[$idx]['compare_value'] ?? 0), 0)) ?></td>
                                <td><?= e(number_format((float)($cancelled[$idx]['current_value'] ?? 0), 0)) ?></td>
                                <td><?= e(number_format((float)($cancelled[$idx]['compare_value'] ?? 0), 0)) ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </section>

        <script>
        window.addEventListener('DOMContentLoaded', function () {
            var modeSelect = document.querySelector('[data-operations-mode]');
            var filter = document.querySelector('[data-operations-filter]');
            if (modeSelect && filter) {
                var refreshMode = function () {
                    filter.classList.toggle('is-range', modeSelect.value === 'range');
                    filter.classList.toggle('is-year', modeSelect.value !== 'range');
                };
                modeSelect.addEventListener('change', refreshMode);
                refreshMode();
            }

            var gate = { expected: 0, rendered: 0, empty: 0, failed: 0 };
            document.querySelectorAll('script[type="application/json"][id^="operations_chart_data_"]').forEach(function (node) {
                var key = node.id.replace('operations_chart_data_', '');
                var card = document.querySelector('[data-operations-chart-card="' + key + '"]');
                var canvas = document.getElementById('operations_chart_' + key);
                gate.expected += 1;
                try {
                    var payload = JSON.parse(node.textContent || '{}');
                    var values = [];
                    (payload.series || []).forEach(function (series) {
                        (series.values || []).forEach(function (value) { values.push(Number(value || 0)); });
                    });
                    var hasData = values.some(function (value) { return value !== 0; });
                    if (!hasData) {
                        if (card) {
                            card.setAttribute('data-chart-state', 'empty');
                            var emptyState = card.querySelector('.operations1011-chart-empty');
                            if (emptyState) emptyState.hidden = false;
                        }
                        if (canvas) canvas.hidden = true;
                        gate.empty += 1;
                        return;
                    }
                    var result = window.renderBarCompareChart('operations_chart_' + key, payload);
                    if (result && result.rendered) {
                        if (card) card.setAttribute('data-chart-state', 'rendered');
                        gate.rendered += 1;
                    } else {
                        throw new Error('Chart renderer did not confirm success.');
                    }
                } catch (error) {
                    if (card) {
                        card.setAttribute('data-chart-state', 'error');
                        var errorState = card.querySelector('.operations1011-chart-error');
                        if (errorState) errorState.hidden = false;
                    }
                    if (canvas) canvas.hidden = true;
                    gate.failed += 1;
                }
            });
            gate.status = gate.failed === 0 && gate.expected === 3 ? 'PASS' : 'FAIL';
            window.__DDB_OPERATIONS_CHART_GATE__ = gate;
            document.documentElement.setAttribute('data-operations-chart-expected', String(gate.expected));
            document.documentElement.setAttribute('data-operations-chart-rendered', String(gate.rendered));
            document.documentElement.setAttribute('data-operations-chart-empty', String(gate.empty));
            document.documentElement.setAttribute('data-operations-chart-failed', String(gate.failed));
            document.documentElement.setAttribute('data-operations-chart-gate', gate.status);
        });
        </script>
    <?php endif; ?>

<?php elseif ($isDoctors): ?>
    <section id="doctors-live-data" class="surface-card visits-control-panel doctors-control-panel">
        <form method="get" action="index.php" class="visits-filter doctors-filter">
            <input type="hidden" name="page" value="doctors">
            <input type="hidden" name="lang" value="<?= e(current_lang()) ?>">
            <?php $doctorYears = $doctorData['availableYears'] ?? []; ?>
            <label>
                <span><?= e(t('visits.year')) ?></span>
                <?php if (!empty($doctorYears)): ?>
                    <select name="year">
                        <?php foreach ($doctorYears as $availableYear): ?>
                            <option value="<?= e($availableYear) ?>" <?= ((int)$availableYear === (int)$year) ? 'selected' : '' ?>><?= e($availableYear) ?></option>
                        <?php endforeach; ?>
                    </select>
                <?php else: ?>
                    <input type="number" min="2014" max="2100" name="year" value="<?= e($year) ?>">
                <?php endif; ?>
            </label>
            <label>
                <span><?= e(t('visits.compare_year')) ?></span>
                <?php if (!empty($doctorYears)): ?>
                    <select name="compare_year">
                        <?php foreach ($doctorYears as $availableYear): ?>
                            <option value="<?= e($availableYear) ?>" <?= ((int)$availableYear === (int)$compareYear) ? 'selected' : '' ?>><?= e($availableYear) ?></option>
                        <?php endforeach; ?>
                    </select>
                <?php else: ?>
                    <input type="number" min="2014" max="2100" name="compare_year" value="<?= e($compareYear) ?>">
                <?php endif; ?>
            </label>
            <label>
                <span><?= e(t('doctors.metric')) ?></span>
                <select name="metric">
                    <?php foreach (($doctorData['availableMetrics'] ?? []) as $m): ?>
                        <option value="<?= e($m['key']) ?>" <?= (($doctorData['metric'] ?? $metric) === $m['key']) ? 'selected' : '' ?>><?= e(t($m['label_key'])) ?></option>
                    <?php endforeach; ?>
                    <?php if (empty($doctorData['availableMetrics'])): ?>
                        <option value="TOT_REV"><?= e(t('doctors.metric_revenue')) ?></option>
                    <?php endif; ?>
                </select>
            </label>
            <button class="btn primary" type="submit"><?= e(t('visits.apply_filter')) ?></button>
            <button class="btn ghost" type="button" data-branch-open><?= e(t('layout.change_hospital')) ?></button>
        </form>
        <?php if (!empty($doctorYears)): ?>
            <p class="filter-hint"><?= e(t('doctors.available_years_hint', ['years' => implode(', ', $doctorYears)])) ?></p>
        <?php endif; ?>
    </section>

    <?php if ($dataError): ?>
        <section class="surface-card data-alert">
            <span class="overline"><?= e(t('doctors.data_error_label')) ?></span>
            <h2><?= e(t('doctors.data_error_title')) ?></h2>
            <p><?= e(t('doctors.data_error_text')) ?></p>
            <pre><?= e($dataError) ?></pre>
        </section>
    <?php elseif (is_array($doctorData)): ?>
        <?php if (!empty($doctorData['warnings'])): ?>
            <section class="surface-card data-alert soft-alert">
                <span class="overline"><?= e(t('visits.data_warning_label')) ?></span>
                <h2><?= e(t('doctors.data_warning_title')) ?></h2>
                <p><?= e(t('doctors.data_warning_text')) ?></p>
                <pre><?= e(implode("\n", $doctorData['warnings'])) ?></pre>
            </section>
        <?php endif; ?>

        <section class="metric-grid four visits-kpi-grid doctors-kpi-grid">
            <?php foreach ($doctorData['cards'] as $key => $card): ?>
                <article class="metric-card visits-kpi tone-<?= e($key === 'opd' ? 'blue' : ($key === 'inpatient' ? 'violet' : ($key === 'active' ? 'amber' : 'green'))) ?>">
                    <div class="metric-orb"></div>
                    <span><?= e($card['title']) ?></span>
                    <strong><?= e(number_format((float)$card['current_total'], 0)) ?></strong>
                    <small><?= e($card['hint']) ?><?php if (($card['mode'] ?? '') === 'compare'): ?> · <?= e(t('visits.previous')) ?>: <?= e(number_format((float)$card['compare_total'], 0)) ?><?php endif; ?></small>
                    <?php if (($card['mode'] ?? '') === 'compare'): ?>
                        <em class="delta <?= ($card['percent'] ?? 0) >= 0 ? 'up' : 'down' ?>">
                            <?= $card['percent'] === null ? e(t('common.not_available')) : e(number_format((float)$card['percent'], 1) . '%') ?>
                        </em>
                    <?php endif; ?>
                </article>
            <?php endforeach; ?>
        </section>

        <section class="workspace-grid visits-insight-grid doctors-insight-grid">
            <article class="surface-card operations-card wide">
                <div class="section-head compact">
                    <span class="overline"><?= e(t('doctors.top_doctors_kicker')) ?></span>
                    <h2><?= e(t('doctors.top_doctors_title')) ?></h2>
                    <p><?= e(t('doctors.top_doctors_text', ['year' => $year])) ?></p>
                </div>
                <canvas id="doctors_chart_top" class="chart visits-chart doctors-chart" height="145"></canvas>
                <script type="application/json" id="doctors_chart_data_top"><?= json_encode($doctorData['topDoctorsPayload'], JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?></script>
            </article>

            <article class="surface-card operations-card visits-mix-card doctors-mix-card">
                <div class="section-head compact">
                    <span class="overline"><?= e(t('doctors.revenue_mix_kicker')) ?></span>
                    <h2><?= e(t('doctors.revenue_mix_title')) ?></h2>
                    <p><?= e(t('doctors.revenue_mix_text')) ?></p>
                </div>
                <?php $mixTotal = 0.0; foreach (($doctorData['mix'] ?? []) as $row) { $mixTotal += max(0, (float)$row['value']); } ?>
                <div class="doctor-mix-stack">
                    <?php foreach (($doctorData['mix'] ?? []) as $row): ?>
                        <?php $pct = $mixTotal > 0 ? (((float)$row['value'] / $mixTotal) * 100) : 0; ?>
                        <div>
                            <span><?= e($row['label']) ?></span>
                            <strong><?= e(number_format((float)$row['value'], 0)) ?></strong>
                            <i><b style="width: <?= e(number_format(max(2, $pct), 2, '.', '')) ?>%"></b></i>
                        </div>
                    <?php endforeach; ?>
                    <?php if (empty($doctorData['mix'])): ?>
                        <p class="muted-line"><?= e(t('doctors.no_mix')) ?></p>
                    <?php endif; ?>
                </div>
            </article>
        </section>

        <section class="workspace-grid visits-detail-grid doctors-detail-grid">
            <article class="surface-card operations-card">
                <div class="section-head compact">
                    <span class="overline"><?= e(t('doctors.specialty_kicker')) ?></span>
                    <h2><?= e(t('doctors.specialty_title')) ?></h2>
                    <p><?= e(t('doctors.specialty_text')) ?></p>
                </div>
                <?php $maxSpec = 1; foreach (($doctorData['specialties'] ?? []) as $row) { $maxSpec = max($maxSpec, (float)$row['value']); } ?>
                <div class="rank-list">
                    <?php foreach (($doctorData['specialties'] ?? []) as $idx => $row): ?>
                        <?php $width = max(5, ((float)$row['value'] / $maxSpec) * 100); ?>
                        <div class="rank-row">
                            <em><?= e($idx + 1) ?></em>
                            <div>
                                <strong><?= e($row['label']) ?></strong>
                                <span><i style="width: <?= e(number_format($width, 2, '.', '')) ?>%"></i></span>
                            </div>
                            <b><?= e(number_format((float)$row['value'], 0)) ?></b>
                        </div>
                    <?php endforeach; ?>
                    <?php if (empty($doctorData['specialties'])): ?>
                        <p class="muted-line"><?= e(t('doctors.no_specialties')) ?></p>
                    <?php endif; ?>
                </div>
            </article>

            <article class="surface-card operations-card">
                <div class="section-head compact">
                    <span class="overline"><?= e(t('doctors.table_kicker')) ?></span>
                    <h2><?= e(t('doctors.table_title')) ?></h2>
                    <p><?= e(t('doctors.table_text')) ?></p>
                </div>
                <div class="table-wrap visits-table-wrap doctors-table-wrap">
                    <table>
                        <thead>
                            <tr>
                                <th><?= e(t('doctors.doctor')) ?></th>
                                <th><?= e(t('doctors.specialty')) ?></th>
                                <th><?= e(t('doctors.value')) ?></th>
                                <th><?= e(t('doctors.opd')) ?></th>
                                <th><?= e(t('doctors.inpatient')) ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach (($doctorData['topDoctors'] ?? []) as $row): ?>
                                <tr>
                                    <td><?= e($row['label']) ?></td>
                                    <td><?= e($row['secondary'] ?: t('common.not_available')) ?></td>
                                    <td><?= e(number_format((float)$row['value'], 0)) ?></td>
                                    <td><?= e(number_format((float)$row['op_visits'], 0)) ?></td>
                                    <td><?= e(number_format((float)$row['inpat_visits'], 0)) ?></td>
                                </tr>
                            <?php endforeach; ?>
                            <?php if (empty($doctorData['topDoctors'])): ?>
                                <tr><td colspan="5"><?= e(t('doctors.no_doctors')) ?></td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </article>
        </section>

        <script>
        window.addEventListener('DOMContentLoaded', function () {
            document.querySelectorAll('script[type="application/json"][id^="doctors_chart_data_"]').forEach(function (node) {
                var key = node.id.replace('doctors_chart_data_', '');
                var payload = JSON.parse(node.textContent || '{}');
                window.renderBarCompareChart('doctors_chart_' + key, payload);
            });
        });
        </script>
    <?php endif; ?>

<?php elseif ($isBeds): ?>
    <section id="beds-live-data" class="surface-card visits-control-panel beds-control-panel">
        <form method="get" action="index.php" class="visits-filter">
            <input type="hidden" name="page" value="beds">
            <input type="hidden" name="lang" value="<?= e(current_lang()) ?>">
            <?php $bedYears = $bedsData['availableYears'] ?? []; ?>
            <label>
                <span><?= e(t('visits.year')) ?></span>
                <?php if (!empty($bedYears)): ?>
                    <select name="year">
                        <?php foreach ($bedYears as $availableYear): ?>
                            <option value="<?= e($availableYear) ?>" <?= ((int)$availableYear === (int)$year) ? 'selected' : '' ?>><?= e($availableYear) ?></option>
                        <?php endforeach; ?>
                    </select>
                <?php else: ?>
                    <input type="number" min="2014" max="2100" name="year" value="<?= e($year) ?>">
                <?php endif; ?>
            </label>
            <label>
                <span><?= e(t('visits.compare_year')) ?></span>
                <?php if (!empty($bedYears)): ?>
                    <select name="compare_year">
                        <?php foreach ($bedYears as $availableYear): ?>
                            <option value="<?= e($availableYear) ?>" <?= ((int)$availableYear === (int)$compareYear) ? 'selected' : '' ?>><?= e($availableYear) ?></option>
                        <?php endforeach; ?>
                    </select>
                <?php else: ?>
                    <input type="number" min="2014" max="2100" name="compare_year" value="<?= e($compareYear) ?>">
                <?php endif; ?>
            </label>
            <button class="btn primary" type="submit"><?= e(t('visits.apply_filter')) ?></button>
            <button class="btn ghost" type="button" data-branch-open><?= e(t('layout.change_hospital')) ?></button>
        </form>
        <?php if (!empty($bedYears)): ?>
            <p class="filter-hint"><?= e(t('beds.available_years_hint', ['years' => implode(', ', $bedYears)])) ?></p>
        <?php endif; ?>
    </section>

    <?php if ($dataError): ?>
        <section class="surface-card data-alert">
            <span class="overline"><?= e(t('beds.data_error_label')) ?></span>
            <h2><?= e(t('beds.data_error_title')) ?></h2>
            <p><?= e(t('beds.data_error_text')) ?></p>
            <pre><?= e($dataError) ?></pre>
        </section>
    <?php elseif (is_array($bedsData)): ?>
        <?php if (!empty($bedsData['warnings'])): ?>
            <section class="surface-card data-alert soft-alert">
                <span class="overline"><?= e(t('visits.data_warning_label')) ?></span>
                <h2><?= e(t('beds.data_warning_title')) ?></h2>
                <p><?= e(t('beds.data_warning_text')) ?></p>
                <pre><?= e(implode("\n", $bedsData['warnings'])) ?></pre>
            </section>
        <?php endif; ?>

        <section class="metric-grid four visits-kpi-grid beds-kpi-grid">
            <?php foreach ($bedsData['cards'] as $key => $card): ?>
                <article class="metric-card visits-kpi tone-<?= e($key === 'available' ? 'green' : ($key === 'hours' ? 'violet' : ($key === 'occupied' ? 'amber' : 'blue'))) ?>">
                    <div class="metric-orb"></div>
                    <span><?= e($card['title']) ?></span>
                    <strong><?= e(($card['mode'] ?? '') === 'percent' ? number_format((float)$card['current_total'], 1) . '%' : number_format((float)$card['current_total'], 0)) ?></strong>
                    <small><?= e($card['hint']) ?><?php if (($card['mode'] ?? '') === 'compare'): ?> · <?= e(t('visits.previous')) ?>: <?= e(number_format((float)$card['compare_total'], 0)) ?><?php endif; ?></small>
                    <?php if (($card['mode'] ?? '') === 'compare'): ?>
                        <em class="delta <?= ($card['percent'] ?? 0) >= 0 ? 'up' : 'down' ?>">
                            <?= $card['percent'] === null ? e(t('common.not_available')) : e(number_format((float)$card['percent'], 1) . '%') ?>
                        </em>
                    <?php endif; ?>
                </article>
            <?php endforeach; ?>
        </section>

        <section class="workspace-grid visits-insight-grid beds-insight-grid">
            <article class="surface-card operations-card wide">
                <div class="section-head compact">
                    <span class="overline"><?= e(t('beds.unit_kicker')) ?></span>
                    <h2><?= e(t('beds.unit_chart_title')) ?></h2>
                    <p><?= e(t('beds.unit_chart_text', ['year' => $year])) ?></p>
                </div>
                <canvas id="beds_chart_units" class="chart visits-chart beds-chart" height="145"></canvas>
                <script type="application/json" id="beds_chart_data_units"><?= json_encode($bedsData['unitsPayload'], JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?></script>
            </article>

            <article class="surface-card operations-card visits-mix-card beds-mix-card">
                <div class="section-head compact">
                    <span class="overline"><?= e(t('beds.live_kicker')) ?></span>
                    <h2><?= e(t('beds.live_title')) ?></h2>
                    <p><?= e(t('beds.live_text')) ?></p>
                </div>
                <?php $current = $bedsData['current'] ?? []; $totalBeds = max(1, (float)($current['total_beds'] ?? 0)); $occPct = ((float)($current['occupied_beds'] ?? 0) / $totalBeds) * 100; $freePct = ((float)($current['available_beds'] ?? 0) / $totalBeds) * 100; ?>
                <div class="mix-meter beds-meter" aria-label="<?= e(t('beds.live_title')) ?>">
                    <span style="width: <?= e(number_format($occPct, 2, '.', '')) ?>%"></span>
                    <b style="width: <?= e(number_format($freePct, 2, '.', '')) ?>%"></b>
                </div>
                <div class="mix-legend">
                    <div><i class="new"></i><strong><?= e(number_format((float)($current['occupied_beds'] ?? 0), 0)) ?></strong><span><?= e(t('beds.occupied')) ?></span></div>
                    <div><i class="follow"></i><strong><?= e(number_format((float)($current['available_beds'] ?? 0), 0)) ?></strong><span><?= e(t('beds.available')) ?></span></div>
                </div>
                <p class="muted-line"><?= e(t('beds.total_beds_hint', ['total' => number_format((float)($current['total_beds'] ?? 0), 0)])) ?></p>
            </article>
        </section>

        <section class="workspace-grid visits-detail-grid beds-detail-grid">
            <article class="surface-card operations-card">
                <div class="section-head compact">
                    <span class="overline"><?= e(t('beds.top_beds_kicker')) ?></span>
                    <h2><?= e(t('beds.top_beds_title')) ?></h2>
                    <p><?= e(t('beds.top_beds_text', ['year' => $year])) ?></p>
                </div>
                <canvas id="beds_chart_top_beds" class="chart visits-chart beds-chart" height="132"></canvas>
                <script type="application/json" id="beds_chart_data_top_beds"><?= json_encode($bedsData['topBedsPayload'], JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?></script>
            </article>

            <article class="surface-card operations-card">
                <div class="section-head compact">
                    <span class="overline"><?= e(t('beds.table_kicker')) ?></span>
                    <h2><?= e(t('beds.table_title')) ?></h2>
                    <p><?= e(t('beds.table_text')) ?></p>
                </div>
                <div class="table-wrap visits-table-wrap beds-table-wrap">
                    <table>
                        <thead>
                            <tr>
                                <th><?= e(t('beds.unit')) ?></th>
                                <th><?= e(t('beds.beds_count')) ?></th>
                                <th><?= e(t('beds.occupied_hours')) ?></th>
                                <th><?= e(t('beds.occupancy_percent')) ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach (($bedsData['units'] ?? []) as $row): ?>
                                <tr>
                                    <td><?= e($row['label']) ?></td>
                                    <td><?= e(number_format((float)$row['bed_count'], 0)) ?></td>
                                    <td><?= e(number_format((float)$row['occupied_hours'], 0)) ?></td>
                                    <td><?= e(number_format((float)$row['value'], 1)) ?>%</td>
                                </tr>
                            <?php endforeach; ?>
                            <?php if (empty($bedsData['units'])): ?>
                                <tr><td colspan="4"><?= e(t('beds.no_units')) ?></td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </article>
        </section>

        <section class="surface-card operations-card beds-table-card">
            <div class="section-head compact">
                <span class="overline"><?= e(t('beds.bed_table_kicker')) ?></span>
                <h2><?= e(t('beds.bed_table_title')) ?></h2>
                <p><?= e(t('beds.bed_table_text')) ?></p>
            </div>
            <div class="table-wrap visits-table-wrap beds-table-wrap">
                <table>
                    <thead>
                        <tr>
                            <th><?= e(t('beds.bed')) ?></th>
                            <th><?= e(t('beds.unit')) ?></th>
                            <th><?= e(t('beds.occupied_hours')) ?></th>
                            <th><?= e(t('beds.occupancy_percent')) ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach (($bedsData['topBeds'] ?? []) as $row): ?>
                            <tr>
                                <td><?= e($row['label']) ?></td>
                                <td><?= e($row['secondary'] ?: t('common.not_available')) ?></td>
                                <td><?= e(number_format((float)$row['occupied_hours'], 0)) ?></td>
                                <td><?= e(number_format((float)$row['value'], 1)) ?>%</td>
                            </tr>
                        <?php endforeach; ?>
                        <?php if (empty($bedsData['topBeds'])): ?>
                            <tr><td colspan="4"><?= e(t('beds.no_beds')) ?></td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </section>

        <script>
        window.addEventListener('DOMContentLoaded', function () {
            document.querySelectorAll('script[type="application/json"][id^="beds_chart_data_"]').forEach(function (node) {
                var key = node.id.replace('beds_chart_data_', '');
                var payload = JSON.parse(node.textContent || '{}');
                window.renderBarCompareChart('beds_chart_' + key, payload);
            });
        });
        </script>
    <?php endif; ?>

<?php else: ?>
    <section class="workspace-grid operations-grid">
        <article class="surface-card operations-card wide">
            <div class="section-head">
                <span class="overline"><?= e(t('operations.blueprint')) ?></span>
                <h2><?= e(t('operations.blueprint_title')) ?></h2>
                <p><?= e(t('operations.blueprint_text')) ?></p>
            </div>
            <div class="operations-steps">
                <?php foreach ($steps as $index => $step): ?>
                    <div>
                        <b><?= e('0' . ($index + 1)) ?></b>
                        <strong><?= e($step['title']) ?></strong>
                        <span><?= e($step['text']) ?></span>
                    </div>
                <?php endforeach; ?>
            </div>
        </article>

        <article class="surface-card operations-card">
            <div class="section-head compact">
                <span class="overline"><?= e(t('operations.branch_scope')) ?></span>
                <h2><?= e($hospitalName) ?></h2>
                <p><?= e(t('operations.branch_scope_text')) ?></p>
            </div>
            <div class="branch-scope-actions">
                <button type="button" class="btn primary full" data-branch-open><?= e(t('layout.branch_matrix')) ?></button>
                <a class="btn ghost full" href="<?= e(url_to('dashboard')) ?>"><?= e(t('nav.home')) ?></a>
            </div>
        </article>
    </section>
<?php endif; ?>
