<?php
/** @var array<string,mixed>|null $doctorData */
$isAr = current_lang() === 'ar';
$hospitalName = (string)($hospital['name'] ?? strtoupper((string)$hospitalCode));
$moneyMetrics = ['TOT_REV', 'NET_REV_AFTER_DRUG_MOH', 'MOH', 'DRUG_REV'];
$isMoneyMetric = in_array((string)$metric, $moneyMetrics, true);

$fmtCompact = static function ($value, string $format = 'count'): string {
    $value = (float)$value;
    $abs = abs($value);
    if ($format === 'money') {
        if ($abs >= 1000000000) {
            return number_format($value / 1000000000, 2) . 'B';
        }
        if ($abs >= 1000000) {
            return number_format($value / 1000000, 2) . 'M';
        }
        if ($abs >= 1000) {
            return number_format($value / 1000, 1) . 'K';
        }
        return number_format($value, 0);
    }
    if ($abs >= 1000000) {
        return number_format($value / 1000000, 2) . 'M';
    }
    if ($abs >= 1000) {
        return number_format($value / 1000, 1) . 'K';
    }
    return number_format($value, 0);
};

$fmtExact = static function ($value, bool $money = false): string {
    $text = number_format((float)$value, $money ? 2 : 0);
    return $money ? 'SAR ' . $text : $text;
};

$currentMetricLabel = t('doctors.metric_revenue');
if (is_array($doctorData)) {
    foreach (($doctorData['availableMetrics'] ?? []) as $metricRow) {
        if ((string)($metricRow['key'] ?? '') === (string)$metric) {
            $currentMetricLabel = t((string)($metricRow['label_key'] ?? 'doctors.metric_revenue'));
            break;
        }
    }
}

$topDoctor = is_array($doctorData) ? ($doctorData['topDoctor'] ?? null) : null;
$topSpecialty = is_array($doctorData) ? ($doctorData['topSpecialty'] ?? null) : null;
$movement = is_array($doctorData) ? ($doctorData['primaryMovement'] ?? null) : null;
$mixRows = is_array($doctorData) ? ($doctorData['mix'] ?? []) : [];
$specialtyFilter = is_array($doctorData['specialtyFilter'] ?? null)
    ? $doctorData['specialtyFilter']
    : [
        'available' => is_array($availableSpecialties ?? null) ? $availableSpecialties : [],
        'selected_ids' => is_array($selectedSpecialtyIds ?? null) ? $selectedSpecialtyIds : [],
        'selected_labels' => [],
        'active' => false,
    ];
$availableSpecialtyOptions = is_array($specialtyFilter['available'] ?? null)
    ? $specialtyFilter['available']
    : [];
$selectedSpecialtyIds = is_array($specialtyFilter['selected_ids'] ?? null)
    ? array_map('strval', $specialtyFilter['selected_ids'])
    : [];
$selectedSpecialtyLabels = is_array($specialtyFilter['selected_labels'] ?? null)
    ? $specialtyFilter['selected_labels']
    : [];
$specialtyFilterAvailable = (bool)($specialtyFilterAvailable ?? false);
$specialtyFilterWarning = (bool)($specialtyFilterWarning ?? false);
$specialtyScopeLabel = $selectedSpecialtyLabels === []
    ? ($isAr ? 'جميع التخصصات' : 'All Specialties')
    : (
        count($selectedSpecialtyLabels) === 1
            ? (string)$selectedSpecialtyLabels[0]
            : (
                $isAr
                    ? count($selectedSpecialtyLabels) . ' تخصصات محددة'
                    : count($selectedSpecialtyLabels) . ' specialties selected'
            )
    );
$comparisonContract = is_array($doctorData['comparisonContract'] ?? null)
    ? $doctorData['comparisonContract']
    : (is_array($comparisonContract ?? null) ? $comparisonContract : []);
$periodLabels = is_array($doctorData['periodLabels'] ?? null) ? $doctorData['periodLabels'] : [];
$currentPeriodLabel = (string)($periodLabels['current'] ?? $year);
$comparePeriodLabel = (string)($periodLabels['compare'] ?? $compareYear);
$isFairCurrentYearComparison = !empty($comparisonContract['fair_current_year_comparison']);
$mixMax = 0.0;
foreach ($mixRows as $mixRow) {
    $mixMax = max($mixMax, max(0.0, (float)($mixRow['value'] ?? 0)));
}
?>

<div class="doctors133-shell" data-r33-doctors-executive="true">
    <section class="doctors133-controls doctors711-controls-card doctors712-controls-card" aria-labelledby="doctors133-controls-title">
        <div class="doctors133-controls-context doctors711-controls-context doctors712-controls-context">
            <span class="doctors133-kicker"><?= e(t('doctors.r33_comparison_kicker')) ?></span>
            <strong id="doctors133-controls-title"><?= e($currentPeriodLabel) ?> · <?= e($hospitalName) ?></strong>
            <small><?= e(t('doctors.r33_comparison_hint')) ?></small>
            <span class="doctors130-scope" data-doctors-filter-scope><?= e($specialtyScopeLabel) ?></span>
        </div>
        <form method="get" action="index.php" class="doctors133-filter doctors711-filter doctors712-filter">
            <input type="hidden" name="page" value="doctors">
            <input type="hidden" name="lang" value="<?= e(current_lang()) ?>">
            <?php $years = is_array($doctorData) ? ($doctorData['availableYears'] ?? []) : []; ?>
            <label>
                <span><?= e(t('doctors.current_year')) ?></span>
                <?php if (!empty($years)): ?>
                    <select name="year">
                        <?php foreach ($years as $availableYear): ?>
                            <option value="<?= e((string)$availableYear) ?>" <?= (int)$availableYear === (int)$year ? 'selected' : '' ?>><?= e((string)$availableYear) ?></option>
                        <?php endforeach; ?>
                    </select>
                <?php else: ?>
                    <input type="number" name="year" min="2014" max="2100" value="<?= e((string)$year) ?>">
                <?php endif; ?>
            </label>
            <label>
                <span><?= e(t('doctors.compare_year')) ?></span>
                <?php if (!empty($years)): ?>
                    <select name="compare_year">
                        <?php foreach ($years as $availableYear): ?>
                            <option value="<?= e((string)$availableYear) ?>" <?= (int)$availableYear === (int)$compareYear ? 'selected' : '' ?>><?= e((string)$availableYear) ?></option>
                        <?php endforeach; ?>
                    </select>
                <?php else: ?>
                    <input type="number" name="compare_year" min="2014" max="2100" value="<?= e((string)$compareYear) ?>">
                <?php endif; ?>
            </label>
            <label>
                <span><?= e(t('doctors.metric')) ?></span>
                <select name="metric">
                    <?php foreach ((is_array($doctorData) ? ($doctorData['availableMetrics'] ?? []) : []) as $m): ?>
                        <option value="<?= e((string)$m['key']) ?>" <?= (string)$m['key'] === (string)$metric ? 'selected' : '' ?>><?= e(t((string)$m['label_key'])) ?></option>
                    <?php endforeach; ?>
                    <?php if (!is_array($doctorData) || empty($doctorData['availableMetrics'])): ?>
                        <option value="TOT_REV"><?= e(t('doctors.metric_revenue')) ?></option>
                    <?php endif; ?>
                </select>
            </label>
            <button class="doctors133-primary" type="submit"><?= e(t('doctors.update_report')) ?></button>

            <div
                class="doctors130-specialty-filter"
                data-doctors-specialty-filter
                data-all-label="<?= e($isAr ? 'جميع التخصصات' : 'All Specialties') ?>"
                data-count-label="<?= e($isAr ? 'تخصصات محددة' : 'specialties selected') ?>"
                data-no-results-label="<?= e($isAr ? 'لا توجد تخصصات مطابقة للبحث.' : 'No specialties match the search.') ?>"
            >
                <span class="doctors130-specialty-label"><?= e($isAr ? 'تخصصات الأطباء' : 'Doctor Specialties') ?></span>
                <?php if ($specialtyFilterAvailable): ?>
                    <details>
                        <summary>
                            <span data-doctors-specialty-summary><?= e($specialtyScopeLabel) ?></span>
                            <b aria-hidden="true">⌄</b>
                        </summary>
                        <div class="doctors130-specialty-panel">
                            <div class="doctors130-specialty-tools">
                                <input
                                    type="search"
                                    data-doctors-specialty-search
                                    placeholder="<?= e($isAr ? 'البحث في التخصصات' : 'Search specialties') ?>"
                                    autocomplete="off"
                                >
                                <button type="button" data-doctors-specialty-clear>
                                    <?= e($isAr ? 'مسح الاختيارات' : 'Clear selection') ?>
                                </button>
                            </div>
                            <div class="doctors130-specialty-options" data-doctors-specialty-options>
                                <?php foreach ($availableSpecialtyOptions as $specialtyOption): ?>
                                    <?php
                                    $specialtyId = (string)($specialtyOption['id'] ?? '');
                                    $specialtyLabel = (string)($specialtyOption['label'] ?? '');
                                    $isSelected = in_array($specialtyId, $selectedSpecialtyIds, true);
                                    ?>
                                    <label
                                        data-doctors-specialty-option
                                        data-search-value="<?= e($specialtyLabel) ?>"
                                    >
                                        <input
                                            type="checkbox"
                                            name="specialty_ids[]"
                                            value="<?= e($specialtyId) ?>"
                                            <?= $isSelected ? 'checked' : '' ?>
                                        >
                                        <span><?= e($specialtyLabel) ?></span>
                                        <small>
                                            <?= e(number_format((int)($specialtyOption['doctor_count'] ?? 0))) ?>
                                            <?= e($isAr ? 'طبيب' : 'doctors') ?>
                                        </small>
                                    </label>
                                <?php endforeach; ?>
                            </div>
                            <p class="doctors130-specialty-no-results" data-doctors-specialty-no-results hidden></p>
                        </div>
                    </details>
                <?php else: ?>
                    <div class="doctors130-specialty-unavailable" role="status">
                        <strong><?= e($isAr ? 'جميع التخصصات' : 'All Specialties') ?></strong>
                        <span>
                            <?= e($isAr
                                ? 'تعذر تحميل فلتر التخصصات الآن، ويعرض التقرير جميع التخصصات.'
                                : 'The specialty filter could not be loaded. The report shows all specialties.'
                            ) ?>
                        </span>
                    </div>
                <?php endif; ?>
                <small>
                    <?= e($isAr
                        ? 'يطبق الاختيار على المؤشرات والبطاقات والترتيب والجداول والرسوم.'
                        : 'The selection applies to indicators, rankings, tables and charts.'
                    ) ?>
                </small>
                <div class="doctors130-selected-chips" data-doctors-specialty-chips></div>
            </div>
        </form>
        <?php if ($isFairCurrentYearComparison): ?>
            <div class="doctors71-fair-comparison doctors711-fair-comparison doctors712-fair-comparison" role="note">
                <span class="doctors71-fair-comparison__icon" aria-hidden="true">✓</span>
                <div>
                    <strong><?= e($isAr ? 'مقارنة عادلة للسنة الحالية' : 'Fair current-year comparison') ?></strong>
                    <p><?= e($isAr
                        ? 'تتم مقارنة ' . $currentPeriodLabel . ' مع ' . $comparePeriodLabel . '، مع استبعاد الشهر الحالي غير المكتمل.'
                        : $currentPeriodLabel . ' is compared with ' . $comparePeriodLabel . '. The incomplete current month is excluded.'
                    ) ?></p>
                </div>
            </div>
        <?php endif; ?>
    </section>

    <?php if ($dataError || !is_array($doctorData)): ?>
        <section class="doctors133-state doctors133-state-error">
            <strong><?= e(t('doctors.friendly_error_title')) ?></strong>
            <p><?= e(t('doctors.friendly_error_text')) ?></p>
        </section>
    <?php else: ?>
        <section class="doctors133-kpi-grid" aria-label="<?= e(t('doctors.r33_primary_indicators')) ?>">
            <?php
            $kpiIcons = [
                'revenue' => 'SR',
                'opd' => '◎',
                'inpatient' => '◇',
                'active' => '●',
            ];
            ?>
            <?php foreach (($doctorData['cards'] ?? []) as $key => $card): ?>
                <?php $pct = $card['percent'] ?? null; $isMoneyCard = (string)($card['format'] ?? 'count') === 'money'; ?>
                <article class="doctors133-kpi doctors133-kpi-<?= e((string)$key) ?>">
                    <div class="doctors133-kpi-icon" aria-hidden="true"><?= e((string)($kpiIcons[$key] ?? '•')) ?></div>
                    <div class="doctors133-kpi-copy">
                        <div class="doctors133-kpi-top">
                            <span><?= e((string)$card['title']) ?></span>
                            <?php if ($pct !== null): ?>
                                <em class="<?= (float)$pct >= 0 ? 'up' : 'down' ?>"><?= e(((float)$pct >= 0 ? '↑ ' : '↓ ') . number_format(abs((float)$pct), 1) . '%') ?></em>
                            <?php endif; ?>
                        </div>
                        <strong title="<?= e($fmtExact((float)$card['current_total'], $isMoneyCard)) ?>"><?= $isMoneyCard ? '<small>SAR</small> ' : '' ?><?= e($fmtCompact((float)$card['current_total'], (string)($card['format'] ?? 'count'))) ?></strong>
                        <?php if ($card['compare_total'] !== null): ?>
                            <small><?= e(t('doctors.compare_value')) ?>: <?= e($fmtCompact((float)$card['compare_total'], (string)($card['format'] ?? 'count'))) ?></small>
                        <?php else: ?>
                            <small><?= e(t('doctors.active_hint')) ?></small>
                        <?php endif; ?>
                    </div>
                </article>
            <?php endforeach; ?>
        </section>

        <section class="doctors133-leadership-grid">
            <article class="doctors133-surface doctors133-decision-card">
                <div class="doctors133-section-head compact">
                    <span><?= e(t('doctors.r33_leadership_kicker')) ?></span>
                    <h2><?= e(t('doctors.r33_leadership_title')) ?></h2>
                    <p><?= e(t('doctors.r33_leadership_text')) ?></p>
                </div>
                <div class="doctors133-signal-grid">
                    <div class="doctors133-signal">
                        <small><?= e(t('doctors.r33_leading_doctor')) ?></small>
                        <strong><?= e((string)($topDoctor['label'] ?? t('common.not_available'))) ?></strong>
                        <?php if (is_array($topDoctor)): ?><b title="<?= e($fmtExact((float)$topDoctor['value'], $isMoneyMetric)) ?>"><?= e(($isMoneyMetric ? 'SAR ' : '') . $fmtCompact((float)$topDoctor['value'], $isMoneyMetric ? 'money' : 'count')) ?></b><?php endif; ?>
                    </div>
                    <div class="doctors133-signal">
                        <small><?= e(t('doctors.r33_leading_specialty')) ?></small>
                        <strong><?= e((string)($topSpecialty['label'] ?? t('common.not_available'))) ?></strong>
                        <?php if (is_array($topSpecialty)): ?><b title="<?= e($fmtExact((float)$topSpecialty['value'], $isMoneyMetric)) ?>"><?= e(($isMoneyMetric ? 'SAR ' : '') . $fmtCompact((float)$topSpecialty['value'], $isMoneyMetric ? 'money' : 'count')) ?></b><?php endif; ?>
                    </div>
                    <div class="doctors133-signal">
                        <small><?= e(t('doctors.r33_largest_movement')) ?></small>
                        <strong><?= e((string)($movement['title'] ?? t('common.not_available'))) ?></strong>
                        <?php if (is_array($movement)): ?><b class="<?= (float)$movement['percent'] >= 0 ? 'positive' : 'negative' ?>"><?= e(((float)$movement['percent'] >= 0 ? '↑ ' : '↓ ') . number_format(abs((float)$movement['percent']), 1) . '%') ?></b><?php endif; ?>
                    </div>
                    <div class="doctors133-signal">
                        <small><?= e(t('doctors.r33_ranking_metric')) ?></small>
                        <strong><?= e($currentMetricLabel) ?></strong>
                        <b><?= e($currentPeriodLabel) ?> · <?= e($comparePeriodLabel) ?></b>
                        <small><?= e($specialtyScopeLabel) ?></small>
                    </div>
                </div>
            </article>

            <article class="doctors133-surface doctors133-profile-card">
                <div class="doctors133-section-head compact">
                    <span><?= e(t('doctors.revenue_mix_kicker')) ?></span>
                    <h2><?= e(t('doctors.r33_revenue_profile_title')) ?></h2>
                    <p><?= e(t('doctors.r33_revenue_profile_text')) ?></p>
                </div>
                <div class="doctors133-profile-list">
                    <?php foreach ($mixRows as $row): ?>
                        <?php $width = $mixMax > 0 ? max(2.0, ((float)$row['value'] / $mixMax) * 100.0) : 0.0; ?>
                        <div class="doctors133-profile-row" title="<?= e($fmtExact((float)$row['value'], true)) ?>">
                            <div><span><?= e((string)$row['label']) ?></span><strong><?= e('SAR ' . $fmtCompact((float)$row['value'], 'money')) ?></strong></div>
                            <i><b style="width:<?= e(number_format($width, 2, '.', '')) ?>%"></b></i>
                        </div>
                    <?php endforeach; ?>
                    <?php if (empty($mixRows)): ?><p class="doctors133-empty-copy"><?= e(t('doctors.no_mix')) ?></p><?php endif; ?>
                </div>
            </article>
        </section>

        <section class="doctors133-chart-grid">
            <?php
            $chartDefinitions = [
                'doctors' => [
                    'kicker' => t('doctors.top_doctors_kicker'),
                    'title' => t('doctors.r33_top_doctors_title'),
                    'text' => t('doctors.r33_top5_text', ['metric' => $currentMetricLabel]),
                    'rows' => $doctorData['topDoctors'] ?? [],
                    'color' => 0,
                ],
                'specialties' => [
                    'kicker' => t('doctors.specialty_kicker'),
                    'title' => t('doctors.r33_specialty_title'),
                    'text' => t('doctors.r33_top5_text', ['metric' => $currentMetricLabel]),
                    'rows' => $doctorData['specialties'] ?? [],
                    'color' => 5,
                ],
            ];
            ?>
            <?php foreach ($chartDefinitions as $chartKey => $chart): ?>
                <article class="doctors133-surface doctors133-chart-card" data-doctors133-chart-shell="<?= e($chartKey) ?>" data-chart-state="pending">
                    <div class="doctors133-section-head compact">
                        <span><?= e((string)$chart['kicker']) ?></span>
                        <h2><?= e((string)$chart['title']) ?></h2>
                        <p><?= e((string)$chart['text']) ?></p>
                    </div>
                    <div class="doctors133-chart-stage">
                        <div id="doctors133_chart_<?= e($chartKey) ?>" class="doctors133-chart-target" aria-label="<?= e((string)$chart['title']) ?>"></div>
                        <div class="doctors133-chart-state doctors133-chart-empty">
                            <strong><?= e(t('doctors.no_chart_data_title')) ?></strong>
                            <p><?= e(t('doctors.no_chart_data_text')) ?></p>
                        </div>
                        <div class="doctors133-chart-state doctors133-chart-error">
                            <strong><?= e(t('doctors.chart_unavailable_title')) ?></strong>
                            <p><?= e(t('doctors.chart_unavailable_text')) ?></p>
                        </div>
                    </div>
                    <script type="application/json" id="doctors133_data_<?= e($chartKey) ?>"><?= json_encode(array_map(static function (array $row): array {
                        return ['label' => (string)($row['label'] ?? ''), 'value' => (float)($row['value'] ?? 0)];
                    }, (array)$chart['rows']), JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?></script>
                </article>
            <?php endforeach; ?>
        </section>

        <section class="doctors133-surface doctors133-table-card" id="doctors133-performance-overview">
            <div class="doctors133-table-heading">
                <div class="doctors133-section-head compact">
                    <span><?= e(t('doctors.r33_table_kicker')) ?></span>
                    <h2><?= e(t('doctors.r33_table_title')) ?></h2>
                    <p><?= e(t('doctors.r33_table_text')) ?></p>
                </div>
                <?php if (count($doctorData['topDoctors'] ?? []) > 5): ?>
                    <button type="button" class="doctors133-table-toggle" data-doctors133-table-toggle aria-expanded="false"><?= e(t('doctors.r33_view_all_doctors')) ?></button>
                <?php endif; ?>
            </div>
            <div class="doctors133-table-wrap">
                <table>
                    <thead>
                        <tr>
                            <th>#</th>
                            <th><?= e(t('doctors.doctor')) ?></th>
                            <th><?= e(t('doctors.specialty')) ?></th>
                            <th><?= e($currentMetricLabel) ?></th>
                            <th><?= e(t('doctors.opd')) ?></th>
                            <th><?= e(t('doctors.inpatient')) ?></th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php foreach (($doctorData['topDoctors'] ?? []) as $idx => $row): ?>
                        <tr class="<?= $idx >= 5 ? 'doctors133-extra-row' : '' ?>" <?= $idx >= 5 ? 'hidden' : '' ?>>
                            <td><span class="doctors133-rank"><?= e((string)($idx + 1)) ?></span></td>
                            <td><strong><?= e((string)$row['label']) ?></strong></td>
                            <td><?= e((string)($row['secondary'] ?: t('common.not_available'))) ?></td>
                            <td title="<?= e($fmtExact((float)$row['value'], $isMoneyMetric)) ?>"><strong><?= e(($isMoneyMetric ? 'SAR ' : '') . $fmtCompact((float)$row['value'], $isMoneyMetric ? 'money' : 'count')) ?></strong></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="6"><?= e(t('doctors.no_doctors')) ?></td></tr><?php endif; ?>
                    </tbody>
                </table>
            </div>
        </section>

        <section class="doctors133-surface doctors133-actions">
            <div class="doctors133-actions-title">
                <span class="doctors133-kicker"><?= e(t('doctors.r33_actions_kicker')) ?></span>
                <h2><?= e(t('doctors.r33_actions_title')) ?></h2>
            </div>
            <div class="doctors133-action-grid">
                <a href="#doctors133-performance-overview">
                    <span>◎</span>
                    <div><strong><?= e(t('doctors.r33_action_doctors_title')) ?></strong><small><?= e(t('doctors.r33_action_doctors_text')) ?></small></div>
                    <b>→</b>
                </a>
                <a href="#doctors133_chart_specialties">
                    <span>◇</span>
                    <div><strong><?= e(t('doctors.r33_action_specialty_title')) ?></strong><small><?= e(t('doctors.r33_action_specialty_text')) ?></small></div>
                    <b>→</b>
                </a>
                <a href="#doctors133-controls-title">
                    <span>↗</span>
                    <div><strong><?= e(t('doctors.r33_action_movement_title')) ?></strong><small><?= e(t('doctors.r33_action_movement_text')) ?></small></div>
                    <b>→</b>
                </a>
            </div>
        </section>

        <script>
        window.addEventListener('DOMContentLoaded', function () {
            var isMoneyMetric = <?= $isMoneyMetric ? 'true' : 'false' ?>;
            var metricLabel = <?= json_encode($currentMetricLabel, JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?>;
            var chartGate = { expected: 2, rendered: 0, empty: 0, failed: 0, status: 'PENDING' };

            ['doctors', 'specialties'].forEach(function (key, index) {
                var shell = document.querySelector('[data-doctors133-chart-shell="' + key + '"]');
                var node = document.getElementById('doctors133_data_' + key);
                try {
                    var rows = JSON.parse(node ? (node.textContent || '[]') : '[]');
                    if (!rows.some(function (row) { return Number(row.value || 0) !== 0; })) {
                        if (shell) shell.setAttribute('data-chart-state', 'empty');
                        chartGate.empty += 1;
                        return;
                    }
                    if (!window.DDBECharts || typeof window.DDBECharts.renderHorizontalBar !== 'function') {
                        throw new Error('Professional chart engine is unavailable.');
                    }
                    var result = window.DDBECharts.renderHorizontalBar('doctors133_chart_' + key, {
                        rows: rows,
                        limit: 5,
                        seriesLabel: metricLabel,
                        valuePrefix: isMoneyMetric ? 'SAR ' : '',
                        valueDecimals: isMoneyMetric ? 2 : 0,
                        preferredHeight: 330,
                        fitParent: true,
                        colorIndex: index === 0 ? 0 : 5
                    });
                    if (result && result.rendered) {
                        if (shell) shell.setAttribute('data-chart-state', 'rendered');
                        chartGate.rendered += 1;
                    } else if (result && result.empty) {
                        if (shell) shell.setAttribute('data-chart-state', 'empty');
                        chartGate.empty += 1;
                    } else {
                        if (shell) shell.setAttribute('data-chart-state', 'error');
                        chartGate.failed += 1;
                    }
                } catch (error) {
                    if (shell) shell.setAttribute('data-chart-state', 'error');
                    chartGate.failed += 1;
                }
            });

            chartGate.status = chartGate.failed === 0 && (chartGate.rendered + chartGate.empty) === chartGate.expected ? 'PASS' : 'FAIL';
            window.__DDB_DOCTORS_R33_CHART_GATE__ = chartGate;
            document.documentElement.setAttribute('data-doctors-r33-chart-gate', chartGate.status);

            var toggle = document.querySelector('[data-doctors133-table-toggle]');
            if (toggle) {
                toggle.addEventListener('click', function () {
                    var open = toggle.getAttribute('aria-expanded') === 'true';
                    document.querySelectorAll('.doctors133-extra-row').forEach(function (row) {
                        row.hidden = open;
                    });
                    toggle.setAttribute('aria-expanded', open ? 'false' : 'true');
                    toggle.textContent = open
                        ? <?= json_encode(t('doctors.r33_view_all_doctors'), JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?>
                        : <?= json_encode(t('doctors.r33_show_top5'), JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?>;
                });
            }
        });
        </script>
    <?php endif; ?>
</div>
