<?php
$hospitalName = (string)($hospital['name'] ?? strtoupper((string)$hospitalCode));
$activeMode = $reportMode ?? 'year';
$periodCurrent = is_array($diagnosticsData) ? (string)($diagnosticsData['current_period_label'] ?? $year) : ($activeMode === 'range' ? ($fromDate . ' - ' . $toDate) : (string)$year);
$periodCompare = is_array($diagnosticsData) ? (string)($diagnosticsData['compare_period_label'] ?? $compareYear) : (string)$compareYear;
$availableYears = is_array($diagnosticsData) ? ($diagnosticsData['availableYears'] ?? []) : [];
?>

<section class="diagnostics1012-hero">
    <div>
        <span class="overline light"><?= e(t('diagnostics.kicker')) ?></span>
        <h1><?= e(t('diagnostics.hero_title')) ?></h1>
        <p><?= e(t('diagnostics.hero_text', ['hospital' => $hospitalName])) ?></p>
    </div>
    <div class="diagnostics1012-hero-summary" aria-label="<?= e(t('diagnostics.period_summary')) ?>">
        <article><span><?= e(t('diagnostics.stat_current_period')) ?></span><strong><?= e($periodCurrent) ?></strong></article>
        <article><span><?= e(t('diagnostics.stat_compare_period')) ?></span><strong><?= e($periodCompare) ?></strong></article>
        <article><span><?= e(t('diagnostics.stat_branch')) ?></span><strong><?= e($hospitalName) ?></strong></article>
    </div>
</section>

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

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

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

        <label data-year-field>
            <span><?= e(t('diagnostics.year')) ?></span>
            <?php if (!empty($availableYears)): ?>
                <select name="year">
                    <?php foreach ($availableYears 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('diagnostics.from_date')) ?></span>
            <input type="date" name="from_date" value="<?= e($fromDate ?? '') ?>">
        </label>

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

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

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

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

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

<?php if ($dataError): ?>
    <section class="surface-card diagnostics1012-state diagnostics1012-state-error">
        <span class="overline"><?= e(t('diagnostics.data_error_label')) ?></span>
        <h2><?= e(t('diagnostics.data_error_title')) ?></h2>
        <p><?= e(t('diagnostics.data_error_text')) ?></p>
    </section>
<?php elseif (is_array($diagnosticsData)): ?>
    <section class="metric-grid four diagnostics1012-kpis">
        <?php foreach ($diagnosticsData['cards'] as $key => $card): ?>
            <?php
                $tone = $key === 'lab' ? 'green' : ($key === 'radiology' ? 'blue' : ($key === 'combined' ? 'violet' : 'amber'));
                $isPercent = ($card['mode'] ?? '') === 'percent';
                $currentValue = $card['current_total'];
                $compareValue = $card['compare_total'];
            ?>
            <article class="metric-card diagnostics1012-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>
                    <?= e(t('diagnostics.compared_with')) ?> <?= e($periodCompare) ?> ·
                    <?= $compareValue === null ? e(t('common.not_available')) : e(number_format((float)$compareValue, $isPercent ? 1 : 0) . ($isPercent ? '%' : '')) ?>
                </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 = $diagnosticsData['summary'] ?? [];
        $primaryMovement = $summary['primary_movement'] ?? null;
        $combinedCurrent = (float)($summary['combined_current'] ?? 0);
        $radiologyShare = $summary['radiology_share_current'] ?? null;
    ?>
    <section class="surface-card diagnostics1012-insight">
        <div class="diagnostics1012-insight-icon">⌬</div>
        <div>
            <span class="overline"><?= e(t('diagnostics.executive_insight_kicker')) ?></span>
            <h2><?= e(t('diagnostics.executive_insight_title')) ?></h2>
            <p><?= e(t('diagnostics.executive_total', ['count' => number_format($combinedCurrent, 0)])) ?></p>
            <?php if (is_array($primaryMovement)): ?>
                <p><?= e(t('diagnostics.executive_movement', [
                    'metric' => (string)$primaryMovement['title'],
                    'direction' => t(((float)$primaryMovement['percent']) >= 0 ? 'diagnostics.direction_up' : 'diagnostics.direction_down'),
                    'percent' => number_format(abs((float)$primaryMovement['percent']), 1),
                ])) ?></p>
            <?php endif; ?>
            <?php if ($radiologyShare !== null): ?>
                <p><?= e(t('diagnostics.executive_mix', ['percent' => number_format((float)$radiologyShare, 1)])) ?></p>
            <?php endif; ?>
        </div>
    </section>

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

    <section class="diagnostics1012-chart-grid" data-diagnostics-chart-grid>
        <?php foreach ($diagnosticsData['charts'] as $chartKey => $chart): ?>
            <?php $payloadJson = json_encode($chart['payload'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP); ?>
            <article class="surface-card diagnostics1012-chart-card" data-diagnostics-chart-card="<?= e($chartKey) ?>" data-chart-state="pending">
                <div class="diagnostics1012-chart-head">
                    <h3><?= e($chart['title']) ?></h3>
                    <span><?= e($periodCurrent) ?> · <?= e($periodCompare) ?></span>
                </div>
                <div class="diagnostics1012-chart-stage">
                    <canvas id="diagnostics_chart_<?= e($chartKey) ?>" height="142" data-chart-rendered="false"></canvas>
                    <div class="diagnostics1012-chart-state diagnostics1012-chart-empty" hidden><?= e(t('diagnostics.chart_empty')) ?></div>
                    <div class="diagnostics1012-chart-state diagnostics1012-chart-error" hidden><?= e(t('diagnostics.chart_unavailable')) ?></div>
                </div>
                <script id="diagnostics_chart_data_<?= e($chartKey) ?>" type="application/json"><?= $payloadJson ?: '{}' ?></script>
            </article>
        <?php endforeach; ?>
    </section>

    <section class="surface-card diagnostics1012-table-card">
        <div class="section-head">
            <div>
                <span class="overline"><?= e(t('diagnostics.table_kicker')) ?></span>
                <h2><?= e(t('diagnostics.table_title')) ?></h2>
                <p><?= e(t('diagnostics.table_text_period', ['current' => $periodCurrent, 'compare' => $periodCompare])) ?></p>
            </div>
        </div>
        <div class="table-wrap diagnostics1012-table-wrap">
            <table>
                <thead>
                    <tr>
                        <th><?= e(t('diagnostics.month')) ?></th>
                        <th><?= e(t('diagnostics.lab')) ?> · <?= e($periodCurrent) ?></th>
                        <th><?= e(t('diagnostics.lab')) ?> · <?= e($periodCompare) ?></th>
                        <th><?= e(t('diagnostics.radiology')) ?> · <?= e($periodCurrent) ?></th>
                        <th><?= e(t('diagnostics.radiology')) ?> · <?= e($periodCompare) ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    $labRows = $diagnosticsData['charts']['lab']['rows'] ?? [];
                    $radRows = $diagnosticsData['charts']['radiology']['rows'] ?? [];
                    for ($i = 0; $i < 12; $i++):
                        $lab = $labRows[$i] ?? [];
                        $rad = $radRows[$i] ?? [];
                    ?>
                    <tr>
                        <td><?= e((string)($lab['month_name'] ?? $rad['month_name'] ?? '')) ?></td>
                        <td><?= e(number_format((float)($lab['current_value'] ?? 0), 0)) ?></td>
                        <td><?= e(number_format((float)($lab['compare_value'] ?? 0), 0)) ?></td>
                        <td><?= e(number_format((float)($rad['current_value'] ?? 0), 0)) ?></td>
                        <td><?= e(number_format((float)($rad['compare_value'] ?? 0), 0)) ?></td>
                    </tr>
                    <?php endfor; ?>
                </tbody>
            </table>
        </div>
    </section>

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

        var gate = { expected: 2, rendered: 0, empty: 0, failed: 0, status: 'PENDING' };
        ['lab', 'radiology'].forEach(function (key) {
            var card = document.querySelector('[data-diagnostics-chart-card="' + key + '"]');
            var payloadNode = document.getElementById('diagnostics_chart_data_' + key);
            var canvas = document.getElementById('diagnostics_chart_' + key);
            if (!card || !payloadNode || !canvas) {
                gate.failed += 1;
                return;
            }
            try {
                var payload = JSON.parse(payloadNode.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; });
                var emptyState = card.querySelector('.diagnostics1012-chart-empty');
                var errorState = card.querySelector('.diagnostics1012-chart-error');
                if (!hasData) {
                    canvas.hidden = true;
                    if (emptyState) emptyState.hidden = false;
                    if (errorState) errorState.hidden = true;
                    card.setAttribute('data-chart-state', 'empty');
                    gate.empty += 1;
                    return;
                }
                var result = window.renderBarCompareChart('diagnostics_chart_' + key, payload);
                if (result && result.rendered) {
                    canvas.hidden = false;
                    if (emptyState) emptyState.hidden = true;
                    if (errorState) errorState.hidden = true;
                    card.setAttribute('data-chart-state', 'rendered');
                    gate.rendered += 1;
                } else {
                    throw new Error('chart-not-rendered');
                }
            } catch (error) {
                canvas.hidden = true;
                var errorState = card.querySelector('.diagnostics1012-chart-error');
                if (errorState) errorState.hidden = false;
                card.setAttribute('data-chart-state', 'error');
                gate.failed += 1;
            }
        });
        gate.status = gate.expected === 2 && gate.failed === 0 && (gate.rendered + gate.empty) === 2 ? 'PASS' : 'FAIL';
        window.__DDB_DIAGNOSTICS_CHART_GATE__ = gate;
        document.documentElement.setAttribute('data-diagnostics-chart-expected', String(gate.expected));
        document.documentElement.setAttribute('data-diagnostics-chart-rendered', String(gate.rendered));
        document.documentElement.setAttribute('data-diagnostics-chart-empty', String(gate.empty));
        document.documentElement.setAttribute('data-diagnostics-chart-failed', String(gate.failed));
        document.documentElement.setAttribute('data-diagnostics-chart-gate', gate.status);
    });
    </script>
<?php endif; ?>
