@if ($patientHeader)
    @include('care.partials.patient-header', [
        'patient' => $patientHeader['patient'],
        'visit' => $patientHeader['visit'] ?? null,
        'appointment' => $patientHeader['appointment'] ?? null,
        'outstandingMinor' => $patientHeader['outstanding_minor'] ?? 0,
        'allergies' => $patientHeader['allergies'] ?? [],
        'insuranceSummary' => $patientHeader['insurance_summary'] ?? null,
        'emergency' => $patientHeader['emergency'] ?? false,
        'clinicalAlerts' => $patientHeader['clinical_alerts'] ?? ($clinicalAlerts ?? []),
        'currency' => $currency ?? 'GHS',
    ])
@endif

@if (! $workspaceVisit)
    <section class="rounded-2xl border border-dashed border-slate-200 bg-white px-4 py-12 text-center">
        <h2 class="text-sm font-semibold text-slate-900">No open visit selected</h2>
        <p class="mt-1 text-sm text-slate-500">
            @if (! empty($canAccessPatientQueue))
                Open a visit from the specialty list or GP queue, or call next from the waiting list.
            @else
                Open a patient from the specialty list to enter their workspace.
            @endif
        </p>
        @if (! empty($canAccessPatientQueue))
            <a href="{{ route('care.queue.index') }}" class="mt-4 inline-flex text-sm font-medium text-indigo-600">Back to queue</a>
        @else
            <a href="{{ route('care.specialty.show', $moduleKey) }}" class="mt-4 inline-flex text-sm font-medium text-indigo-600">Specialty home</a>
        @endif
    </section>
@else
    <x-care.specialty-stage-bar
        :stages="$stages ?? []"
        :current-stage="$workspaceVisit->specialty_stage"
        :stage-flow="$specialtyStageFlow ?? []"
        :stage-route="$specialtyStageRoute ?? null"
        :visit="$workspaceVisit"
        :can-advance="$canAdvanceStage ?? false"
    />

    {{-- Module tabs --}}
    <div class="flex flex-wrap gap-1 border-b border-slate-200 pb-2">
        @foreach ($workspaceTabs as $tabKey => $tabLabel)
            <a href="{{ route('care.specialty.workspace', ['module' => $moduleKey, 'visit' => $workspaceVisit, 'tab' => $tabKey]) }}"
               @class([
                   'rounded-lg px-3 py-1.5 text-sm font-medium',
                   'bg-indigo-50 text-indigo-800' => $activeTab === $tabKey,
                   'text-slate-600 hover:bg-slate-50' => $activeTab !== $tabKey,
               ])>
                {{ $tabLabel }}
            </a>
        @endforeach
    </div>

    <div class="space-y-4">
        @if ($activeTab === 'timeline')
            @include('care.partials.patient-timeline', ['events' => $timeline ?? []])
        @elseif ($moduleKey === 'dentistry' && in_array($activeTab, ['odontogram', 'plan', 'treat', 'notes', 'imaging', 'overview', 'perio', 'lab', 'recalls'], true))
            @include('care.specialty.dentistry.workspace-'.$activeTab)
        @elseif ($moduleKey === 'emergency' && in_array($activeTab, ['overview', 'vitals', 'disposition'], true))
            @include('care.specialty.emergency.workspace-'.$activeTab)
        @elseif ($moduleKey === 'blood_bank' && in_array($activeTab, ['overview', 'issue', 'transfusion'], true))
            @include('care.specialty.blood-bank.workspace-'.$activeTab)
        @elseif ($moduleKey === 'ophthalmology' && in_array($activeTab, ['overview', 'treat'], true))
            @include('care.specialty.ophthalmology.workspace-'.$activeTab)
        @elseif ($moduleKey === 'physiotherapy' && in_array($activeTab, ['overview', 'session'], true))
            @include('care.specialty.physiotherapy.workspace-'.$activeTab)
        @elseif ($moduleKey === 'womens_health' && in_array($activeTab, ['overview', 'postnatal'], true))
            @include('care.specialty.womens_health.workspace-'.$activeTab)
        @elseif ($moduleKey === 'radiology' && in_array($activeTab, ['overview', 'verification'], true))
            @include('care.specialty.radiology.workspace-'.$activeTab)
        @elseif ($moduleKey === 'cardiology' && in_array($activeTab, ['overview', 'procedures'], true))
            @include('care.specialty.cardiology.workspace-'.$activeTab)
        @elseif ($moduleKey === 'psychiatry' && in_array($activeTab, ['overview', 'followup'], true))
            @include('care.specialty.psychiatry.workspace-'.$activeTab)
        @elseif ($moduleKey === 'pediatrics' && in_array($activeTab, ['overview', 'treatment'], true))
            @include('care.specialty.pediatrics.workspace-'.$activeTab)
        @elseif ($moduleKey === 'orthopedics' && in_array($activeTab, ['overview', 'procedure'], true))
            @include('care.specialty.orthopedics.workspace-'.$activeTab)
        @elseif ($moduleKey === 'ent' && in_array($activeTab, ['overview', 'procedure'], true))
            @include('care.specialty.ent.workspace-'.$activeTab)
        @elseif ($moduleKey === 'oncology' && in_array($activeTab, ['overview', 'treatment'], true))
            @include('care.specialty.oncology.workspace-'.$activeTab)
        @elseif ($moduleKey === 'renal' && in_array($activeTab, ['overview', 'plan'], true))
            @include('care.specialty.renal.workspace-'.$activeTab)
        @elseif ($moduleKey === 'surgery' && in_array($activeTab, ['overview', 'postop'], true))
            @include('care.specialty.surgery.workspace-'.$activeTab)
        @elseif ($moduleKey === 'vaccination' && in_array($activeTab, ['overview', 'observation'], true))
            @include('care.specialty.vaccination.workspace-'.$activeTab)
        @elseif ($moduleKey === 'pathology' && in_array($activeTab, ['overview', 'verification'], true))
            @include('care.specialty.pathology.workspace-'.$activeTab)
        @elseif ($moduleKey === 'infusion' && in_array($activeTab, ['overview', 'monitoring'], true))
            @include('care.specialty.infusion.workspace-'.$activeTab)
        @elseif ($moduleKey === 'dermatology' && in_array($activeTab, ['overview', 'procedure'], true))
            @include('care.specialty.dermatology.workspace-'.$activeTab)
        @elseif ($moduleKey === 'podiatry' && in_array($activeTab, ['overview', 'procedure'], true))
            @include('care.specialty.podiatry.workspace-'.$activeTab)
        @elseif ($moduleKey === 'fertility' && in_array($activeTab, ['overview', 'cycle'], true))
            @include('care.specialty.fertility.workspace-'.$activeTab)
        @elseif ($moduleKey === 'child_welfare' && in_array($activeTab, ['overview', 'followup'], true))
            @include('care.specialty.child-welfare.workspace-'.$activeTab)
        @elseif ($moduleKey === 'ambulance' && in_array($activeTab, ['overview', 'handover'], true))
            @include('care.specialty.ambulance.workspace-'.$activeTab)
        @elseif ($activeTab === 'billing')
            <section class="rounded-2xl border border-slate-200 bg-white p-5">
                <h3 class="text-sm font-semibold text-slate-900">
                    {{ ($canManageClinical ?? $canManageSpecialty ?? true) ? 'Add specialty service' : 'Visit billing' }}
                </h3>
                @if ($canManageClinical ?? $canManageSpecialty ?? true)
                    <form method="POST" action="{{ route('care.specialty.services.add', ['module' => $moduleKey, 'visit' => $workspaceVisit]) }}" class="mt-3 space-y-3">
                        @csrf
                        <select name="service_code" required class="w-full rounded-xl border border-slate-200 px-3 py-2 text-sm">
                            <option value="">Select service…</option>
                            @foreach ($services as $service)
                                <option value="{{ $service['code'] }}">
                                    {{ $service['label'] }} — {{ $currency ?? 'GHS' }} {{ number_format(((int) $service['amount_minor']) / 100, 2) }}
                                </option>
                            @endforeach
                        </select>
                        <button type="submit" class="btn-primary">{{ $actions['invoice'] ?? 'Add to invoice' }}</button>
                    </form>
                @endif

                @if ($workspaceVisit->bill)
                    <div @class(['mt-6 border-t border-slate-100 pt-4' => ($canManageClinical ?? $canManageSpecialty ?? true), 'mt-3' => ! ($canManageClinical ?? $canManageSpecialty ?? true)])>
                        <p class="text-xs font-semibold uppercase tracking-wide text-slate-500">Current invoice {{ $workspaceVisit->bill->invoice_number }}</p>
                        <ul class="mt-2 space-y-1 text-sm">
                            @forelse ($workspaceVisit->bill->lineItems as $line)
                                <li class="flex justify-between gap-3">
                                    <span>{{ $line->description }}</span>
                                    <span class="tabular-nums">{{ number_format($line->total_minor / 100, 2) }}</span>
                                </li>
                            @empty
                                <li class="text-slate-500">No line items yet.</li>
                            @endforelse
                        </ul>
                        <a href="{{ route('care.bills.show', $workspaceVisit->bill) }}" class="mt-3 inline-flex text-sm font-medium text-indigo-600">Open bill</a>
                    </div>
                @elseif (! ($canManageClinical ?? $canManageSpecialty ?? true))
                    <p class="mt-3 text-sm text-slate-500">No invoice on this visit yet.</p>
                @endif
            </section>
        @elseif (! empty($clinicalFields))
            @include('care.specialty.partials.clinical-form')
        @elseif ($activeTab === 'orders')
            @include('care.specialty.partials.orders')
        @elseif ($activeTab === 'documents')
            <section class="rounded-2xl border border-slate-200 bg-white p-5">
                <h3 class="text-sm font-semibold text-slate-900">Documents</h3>
                <p class="mt-1 text-xs text-slate-500">Specialty documents attach to the patient chart for this episode.</p>

                @if ($canManageClinical ?? $canManageSpecialty ?? false)
                    <form method="POST" action="{{ route('care.specialty.documents.upload', ['module' => $moduleKey, 'visit' => $workspaceVisit]) }}" enctype="multipart/form-data" class="mt-4 space-y-3">
                        @csrf
                        <input type="file" name="attachment" required accept=".pdf,.jpg,.jpeg,.png,.webp" class="block w-full text-sm">
                        <button type="submit" class="btn-primary">Upload document</button>
                    </form>
                @endif

                <ul class="mt-4 space-y-2 text-sm">
                    @forelse ($visitDocuments ?? [] as $doc)
                        <li class="flex items-center justify-between gap-3 rounded-xl border border-slate-100 bg-slate-50 px-3 py-2">
                            <div class="min-w-0">
                                <p class="truncate font-medium text-slate-800">{{ $doc->original_name }}</p>
                                <p class="text-xs text-slate-500">{{ $doc->document_type }} · {{ $doc->created_at?->format('d M Y H:i') }}</p>
                            </div>
                            @if ($doc->file_path)
                                <a href="{{ \Illuminate\Support\Facades\Storage::disk('public')->url($doc->file_path) }}" target="_blank" class="shrink-0 text-xs font-medium text-sky-600">Open</a>
                            @endif
                        </li>
                    @empty
                        <li class="text-slate-500">No documents yet.</li>
                    @endforelse
                </ul>

                @if ($workspaceVisit->patient)
                    <a href="{{ route('care.patients.show', $workspaceVisit->patient) }}" class="mt-3 inline-flex text-sm font-medium text-indigo-600">Patient chart</a>
                @endif
            </section>
        @else
            <section class="rounded-2xl border border-slate-200 bg-white p-5">
                <h3 class="text-sm font-semibold text-slate-900">Overview</h3>
                <dl class="mt-3 grid gap-3 text-sm sm:grid-cols-2">
                    <div>
                        <dt class="text-slate-500">Visit status</dt>
                        <dd class="font-medium text-slate-900">{{ ucfirst(str_replace('_', ' ', $workspaceVisit->status)) }}</dd>
                    </div>
                    <div>
                        <dt class="text-slate-500">Checked in</dt>
                        <dd class="font-medium text-slate-900">{{ $workspaceVisit->checked_in_at?->format('d M Y H:i') ?? '—' }}</dd>
                    </div>
                    <div>
                        <dt class="text-slate-500">Department</dt>
                        <dd class="font-medium text-slate-900">{{ $workspaceVisit->appointment?->department?->name ?? '—' }}</dd>
                    </div>
                    <div>
                        <dt class="text-slate-500">Queue</dt>
                        <dd class="font-medium text-slate-900">
                            {{ $workspaceVisit->appointment?->queue_ticket_number ?? '—' }}
                            @if ($workspaceVisit->appointment?->queue_ticket_status)
                                <span class="text-slate-500">({{ $workspaceVisit->appointment->queue_ticket_status }})</span>
                            @endif
                        </dd>
                    </div>
                </dl>

                @if (! empty($clinicalAlerts))
                    <div class="mt-4 space-y-1.5 border-t border-slate-100 pt-4">
                        <p class="text-xs font-semibold uppercase tracking-wide text-slate-500">Clinical alerts</p>
                        @foreach ($clinicalAlerts as $alert)
                            <p class="text-sm {{ ($alert['severity'] ?? '') === 'critical' ? 'text-rose-700' : 'text-amber-800' }}">
                                {{ $alert['message'] ?? '' }}
                            </p>
                        @endforeach
                    </div>
                @endif
            </section>
        @endif
    </div>
@endif
