<?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';
$isLiveModule = $isVisits || $isDoctors || $isBeds;
?>

<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') : 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 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') : t('operations.module_ready_text')))) ?></p>
    </div>
</section>

<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 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" 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" 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">
            <?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">
            <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">
            <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" data-patient-chart-grid>
                    <?php foreach ($visitData['charts'] as $key => $chart): ?>
                        <article class="patient1010-chart-card" 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="workspace-grid visits-detail-grid patient1010-secondary-grid">
            <article class="surface-card operations-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">
                <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'])): ?>
                        <p class="muted-line"><?= e(t('visits.no_specialties')) ?></p>
                    <?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 ($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; ?>
