@php
    $pageTitle = match ($section) {
        'workspace' => ($patientHeader['patient'] ?? null)?->fullName() ?: 'Workspace',
        'history' => 'Visit history',
        'billing' => 'Billing',
        'visits' => ($moduleKey ?? '') === 'ambulance' ? 'Dispatch board' : 'Patient queue',
        default => ($moduleKey ?? '') === 'ambulance' ? 'Dispatch board' : 'Patient queue',
    };
@endphp
<x-app-layout :title="$pageTitle">
    <div class="space-y-4">
        @if ($section === 'workspace')
            <div class="flex flex-wrap items-center justify-between gap-3">
                @if (! empty($canAccessPatientQueue))
                    <a href="{{ route('care.queue.index') }}" class="text-sm font-medium text-indigo-600 hover:text-indigo-800">← Back to queue</a>
                @else
                    <span></span>
                @endif
                <div class="flex flex-wrap gap-3 text-sm">
                    @if ($moduleKey === 'dentistry')
                        <a href="{{ route('care.specialty.dentistry.reports') }}" class="text-slate-600 hover:text-slate-900">Reports</a>
                    @endif
                    @if ($moduleKey === 'emergency')
                        <a href="{{ route('care.specialty.emergency.reports') }}" class="text-slate-600 hover:text-slate-900">Reports</a>
                    @endif
                    @if ($moduleKey === 'blood_bank')
                        <a href="{{ route('care.specialty.blood-bank.reports') }}" class="text-slate-600 hover:text-slate-900">Reports</a>
                        @php
                            $bbAdminMember = auth()->user()
                                ? app(\App\Services\Care\OrganizationResolver::class)->memberFor(auth()->user(), $organization)
                                : null;
                        @endphp
                        @if (app(\App\Services\Care\CarePermissions::class)->can($bbAdminMember, 'blood_bank.manage'))
                            <a href="{{ route('care.blood-bank.admin.index') }}" class="text-slate-600 hover:text-slate-900">Admin</a>
                        @endif
                    @endif
                    @if ($moduleKey === 'ophthalmology')
                        <a href="{{ route('care.specialty.ophthalmology.reports') }}" class="text-slate-600 hover:text-slate-900">Reports</a>
                    @endif
                    @if ($moduleKey === 'physiotherapy')
                        <a href="{{ route('care.specialty.physiotherapy.reports') }}" class="text-slate-600 hover:text-slate-900">Reports</a>
                    @endif
                    @if ($moduleKey === 'womens_health')
                        <a href="{{ route('care.specialty.womens_health.reports') }}" class="text-slate-600 hover:text-slate-900">Reports</a>
                    @endif
                    @if ($moduleKey === 'radiology')
                        <a href="{{ route('care.specialty.radiology.reports') }}" class="text-slate-600 hover:text-slate-900">Reports</a>
                    @endif
                    @if ($moduleKey === 'cardiology')
                        <a href="{{ route('care.specialty.cardiology.reports') }}" class="text-slate-600 hover:text-slate-900">Reports</a>
                    @endif
                    @if ($moduleKey === 'psychiatry')
                        <a href="{{ route('care.specialty.psychiatry.reports') }}" class="text-slate-600 hover:text-slate-900">Reports</a>
                    @endif
                    @if ($moduleKey === 'pediatrics')
                        <a href="{{ route('care.specialty.pediatrics.reports') }}" class="text-slate-600 hover:text-slate-900">Reports</a>
                    @endif
                    @if ($moduleKey === 'orthopedics')
                        <a href="{{ route('care.specialty.orthopedics.reports') }}" class="text-slate-600 hover:text-slate-900">Reports</a>
                    @endif
                    @if ($moduleKey === 'ent')
                        <a href="{{ route('care.specialty.ent.reports') }}" class="text-slate-600 hover:text-slate-900">Reports</a>
                    @endif
                    @if ($moduleKey === 'oncology')
                        <a href="{{ route('care.specialty.oncology.reports') }}" class="text-slate-600 hover:text-slate-900">Reports</a>
                    @endif
                    @if ($moduleKey === 'renal')
                        <a href="{{ route('care.specialty.renal.reports') }}" class="text-slate-600 hover:text-slate-900">Reports</a>
                    @endif
                    @if ($moduleKey === 'surgery')
                        <a href="{{ route('care.specialty.surgery.reports') }}" class="text-slate-600 hover:text-slate-900">Reports</a>
                    @endif
                    @if ($moduleKey === 'vaccination')
                        <a href="{{ route('care.specialty.vaccination.reports') }}" class="text-slate-600 hover:text-slate-900">Reports</a>
                    @endif
                    @if ($moduleKey === 'pathology')
                        <a href="{{ route('care.specialty.pathology.reports') }}" class="text-slate-600 hover:text-slate-900">Reports</a>
                    @endif
                    @if ($moduleKey === 'infusion')
                        <a href="{{ route('care.specialty.infusion.reports') }}" class="text-slate-600 hover:text-slate-900">Reports</a>
                    @endif
                    @if ($moduleKey === 'dermatology')
                        <a href="{{ route('care.specialty.dermatology.reports') }}" class="text-slate-600 hover:text-slate-900">Reports</a>
                    @endif
                    @if ($moduleKey === 'podiatry')
                        <a href="{{ route('care.specialty.podiatry.reports') }}" class="text-slate-600 hover:text-slate-900">Reports</a>
                    @endif
                    @if ($moduleKey === 'fertility')
                        <a href="{{ route('care.specialty.fertility.reports') }}" class="text-slate-600 hover:text-slate-900">Reports</a>
                    @endif
                    @if ($moduleKey === 'child_welfare')
                        <a href="{{ route('care.specialty.child-welfare.reports') }}" class="text-slate-600 hover:text-slate-900">Reports</a>
                    @endif
                    @if ($moduleKey === 'ambulance')
                        <a href="{{ route('care.specialty.ambulance.reports') }}" class="text-slate-600 hover:text-slate-900">Reports</a>
                    @endif
                    <a href="{{ route('care.specialty.history', $moduleKey) }}" class="text-slate-600 hover:text-slate-900">History</a>
                    @if ($canManageClinical ?? $canManageSpecialty ?? true)
                        <a href="{{ route('care.specialty.billing', $moduleKey) }}" class="text-slate-600 hover:text-slate-900">Billing</a>
                    @endif
                </div>
            </div>

            @if (($specialtyAccessLevel ?? 'manage') !== 'manage')
                <div class="rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-950">
                    @if (($specialtyAccessLevel ?? '') === 'refer')
                        You have <strong>view + refer</strong> access. You can review results and refer patients into this specialty queue; clinical editing is limited to specialists and supporting staff.
                    @else
                        You have <strong>view-only</strong> access. Results and history are available; clinical edits require specialty access.
                    @endif
                </div>
            @elseif (($canManageSpecialty ?? false) && ! ($canConsult ?? false))
                <div class="rounded-xl border border-sky-200 bg-sky-50 px-4 py-3 text-sm text-sky-950">
                    You can work this specialty floor (queue, vitals, billing support) but starting encounters and clinical chart edits require a clinician with consultation access.
                </div>
            @endif

            <div class="lg:grid lg:grid-cols-[minmax(0,1fr)_16rem] lg:items-start lg:gap-6">
                <div class="min-w-0 space-y-4">
                    @include('care.specialty.sections.workspace')
                </div>
                @include('care.partials.clinical-actions-panel', [
                    'actionsView' => 'care.specialty.partials.actions-menu',
                    'title' => 'Actions',
                ])
            </div>
            @include('care.partials.clinical-actions-mobile', [
                'actionsView' => 'care.specialty.partials.actions-menu',
                'title' => 'Actions',
            ])

            @php
                $completeConsultation = ($canConsult ?? false)
                    ? ($workspaceVisit?->appointment?->consultation
                        ?? $workspaceVisit?->consultations?->firstWhere('status', '!=', \App\Models\Consultation::STATUS_COMPLETED))
                    : null;
                $prescribeConsultation = ($canPrescribe ?? false)
                    ? ($workspaceVisit?->appointment?->consultation
                        ?? $workspaceVisit?->consultations?->firstWhere('status', '!=', \App\Models\Consultation::STATUS_COMPLETED))
                    : null;
            @endphp
            @if ($completeConsultation && $completeConsultation->status !== \App\Models\Consultation::STATUS_COMPLETED)
                <x-confirm-dialog
                    :name="'complete-consultation-'.$completeConsultation->id"
                    title="Complete this consultation?"
                    message="Mark the consultation as finished. You can still prescribe or generate a bill afterward."
                    :action="route('care.consultations.complete', $completeConsultation)"
                    confirm-label="Complete consultation"
                    variant="primary"
                />
            @endif
            @if ($prescribeConsultation && $prescribeConsultation->status !== \App\Models\Consultation::STATUS_COMPLETED)
                <x-modal :name="'prescribe-'.$prescribeConsultation->id" maxWidth="2xl">
                    <div class="px-5 pb-6 pt-2 sm:px-6 sm:pb-6 sm:pt-4">
                        <h2 class="pr-8 text-lg font-semibold text-slate-900">New prescription</h2>
                        <p class="mt-1 text-sm text-slate-500">
                            {{ ($workspaceVisit->patient ?? $prescribeConsultation->patient)?->fullName() }}
                            @if (($workspaceVisit->patient ?? $prescribeConsultation->patient)?->patient_number)
                                ({{ ($workspaceVisit->patient ?? $prescribeConsultation->patient)->patient_number }})
                            @endif
                        </p>
                        <div class="mt-4 max-h-[70vh] overflow-y-auto pr-1">
                            @include('care.prescriptions.partials.form', [
                                'consultation' => $prescribeConsultation,
                                'routes' => config('care.medication_routes'),
                                'compact' => true,
                                'returnTo' => 'specialty',
                                'specialtyModule' => $moduleKey,
                                'specialtyVisit' => $workspaceVisit,
                            ])
                        </div>
                    </div>
                </x-modal>
            @endif
        @elseif ($section === 'history')
            <div class="flex flex-wrap items-center justify-between gap-3">
                <div class="flex items-start gap-2.5">
                    <x-care.specialty-icon :module="$moduleKey" boxed />
                    <div>
                        <h1 class="text-xl font-semibold text-slate-900">{{ $definition['nav_label'] ?? $definition['label'] ?? ucfirst($moduleKey) }} · Visit history</h1>
                        <p class="mt-1 text-sm text-slate-500">Completed encounters for this service line.</p>
                    </div>
                </div>
                <a href="{{ route('care.specialty.show', $moduleKey) }}" class="text-sm font-medium text-indigo-600 hover:text-indigo-800">← Specialty home</a>
            </div>
            @include('care.specialty.sections.history')
        @elseif ($section === 'billing')
            <div class="flex flex-wrap items-center justify-between gap-3">
                <div class="flex items-start gap-2.5">
                    <x-care.specialty-icon :module="$moduleKey" boxed />
                    <div>
                        <h1 class="text-xl font-semibold text-slate-900">{{ $definition['nav_label'] ?? $definition['label'] ?? ucfirst($moduleKey) }} · Billing</h1>
                        <p class="mt-1 text-sm text-slate-500">Service catalog for this module.</p>
                    </div>
                </div>
                <a href="{{ route('care.specialty.show', $moduleKey) }}" class="text-sm font-medium text-indigo-600 hover:text-indigo-800">← Specialty home</a>
            </div>
            @include('care.specialty.sections.billing')
        @else
            {{-- Queue / dispatch home --}}
            <div class="lg:grid lg:grid-cols-[minmax(0,1fr)_16rem] lg:items-start lg:gap-6">
                <div class="min-w-0 space-y-6">
                    @php
                        $specialtyLabel = $definition['nav_label'] ?? $definition['label'] ?? ucfirst($moduleKey);
                        $isAmbulanceHome = $moduleKey === 'ambulance';
                    @endphp
                    <div class="mb-1 flex items-center gap-2.5">
                        <x-care.specialty-icon :module="$moduleKey" boxed />
                        <p class="text-sm font-semibold text-slate-700">{{ $specialtyLabel }}</p>
                    </div>
                    @if ($isAmbulanceHome)
                        <x-care.page-hero
                            badge="EMS · Dispatch"
                            :title="$specialtyLabel.' dispatch'"
                            description="Respond to call-ins — track New call through dispatch, scene, transport, and handover."
                            :stats="[
                                ['value' => number_format($ambulanceDispatchBoard['active_count'] ?? 0), 'label' => 'Active calls'],
                                ['value' => number_format($ambulanceDispatchBoard['completed_today'] ?? 0), 'label' => 'Completed today'],
                                ['value' => number_format($kpis['clinical_open'] ?? 0), 'label' => 'On scene open'],
                            ]">
                            @if ($canManageQueue ?? false)
                                <x-slot name="actions">
                                    <a href="{{ route('care.specialty.ambulance.new-call') }}" class="btn-primary">New call</a>
                                </x-slot>
                            @endif
                        </x-care.page-hero>
                    @else
                        <x-care.page-hero
                            badge="Patient flow · Call next"
                            :title="$specialtyLabel.' queue'"
                            description="Move patients from waiting through called, in care, and done."
                            :stats="[
                                ['value' => number_format($kpis['waiting'] ?? $queue->count()), 'label' => 'Waiting'],
                                ['value' => number_format($kpis['in_progress'] ?? $inConsultation->count()), 'label' => 'In care'],
                                ['value' => number_format($kpis['completed_today'] ?? 0), 'label' => 'Today'],
                            ]">
                            @if ($canManageQueue ?? false)
                                <x-slot name="actions">
                                    <a href="{{ route('care.appointments.walk-in.create') }}" class="btn-primary">Walk-in</a>
                                </x-slot>
                            @endif
                        </x-care.page-hero>
                    @endif

                    <div class="flex flex-wrap gap-3 text-sm">
                        <a href="{{ route('care.specialty.history', $moduleKey) }}" class="rounded-lg border border-slate-200 bg-white px-3 py-1.5 font-medium text-slate-700 hover:bg-slate-50">History</a>
                        @if ($canManageClinical ?? $canManageSpecialty ?? true)
                            <a href="{{ route('care.specialty.billing', $moduleKey) }}" class="rounded-lg border border-slate-200 bg-white px-3 py-1.5 font-medium text-slate-700 hover:bg-slate-50">Billing</a>
                        @endif
                        @if ($isAmbulanceHome)
                            <a href="{{ route('care.specialty.ambulance.reports') }}" class="rounded-lg border border-slate-200 bg-white px-3 py-1.5 font-medium text-slate-700 hover:bg-slate-50">Reports</a>
                        @endif
                    </div>

                    @if ($isAmbulanceHome)
                        @include('care.specialty.ambulance.dispatch-board', [
                            'ambulanceDispatchBoard' => $ambulanceDispatchBoard ?? ['columns' => [], 'active_count' => 0, 'completed_today' => 0],
                            'canAdvanceStage' => $canAdvanceStage ?? false,
                            'specialtyStageRoute' => $specialtyStageRoute ?? 'care.specialty.ambulance.stage',
                        ])
                    @else
                        @include('care.partials.queue-board', [
                            'queue' => $queue,
                            'inConsultation' => $inConsultation,
                            'done' => $done ?? collect(),
                            'queueIntegration' => $queueIntegration ?? null,
                            'branchId' => $branchId,
                            'branchLabel' => $branchLabel ?? null,
                            'canConsult' => $canConsult ?? false,
                            'lockToPractitioner' => $lockToPractitioner ?? false,
                            'showFilters' => true,
                            'queueCallNextRoute' => ($canCallNext ?? $canManageSpecialty ?? false) ? 'care.specialty.call-next' : null,
                            'queueCallNextParams' => ['module' => $moduleKey],
                            'startRouteName' => 'care.queue.start',
                            'inCareLabel' => 'In care',
                            'openInCareUrl' => function ($appointment) use ($moduleKey) {
                                if ($appointment->visit) {
                                    return route('care.specialty.workspace', [
                                        'module' => $moduleKey,
                                        'visit' => $appointment->visit,
                                    ]);
                                }

                                return $appointment->consultation
                                    ? route('care.consultations.show', $appointment->consultation)
                                    : null;
                            },
                        ])
                    @endif
                </div>

                @include('care.partials.clinical-actions-panel', [
                    'actionsView' => 'care.specialty.partials.actions-menu',
                    'title' => 'Actions',
                ])
            </div>
            @include('care.partials.clinical-actions-mobile', [
                'actionsView' => 'care.specialty.partials.actions-menu',
                'title' => 'Actions',
            ])
        @endif
    </div>
</x-app-layout>
