{{-- Specialty action buttons (desktop sticky + mobile sheet). --}}
@php
    $btn = 'flex w-full items-center justify-center rounded-xl px-3 py-2.5 text-sm font-semibold transition';
    $btnPrimary = $btn.' bg-indigo-600 text-white hover:bg-indigo-700';
    $btnSecondary = $btn.' border border-slate-200 bg-white text-slate-800 hover:bg-slate-50';
    $btnAccent = $btn.' border border-indigo-200 bg-indigo-50 text-indigo-900 hover:bg-indigo-100';
    $onWorkspace = ($section ?? '') === 'workspace';
    $appointment = $workspaceVisit?->appointment;
    $openConsultation = $appointment?->consultation
        ?? $workspaceVisit?->consultations?->firstWhere('status', '!=', \App\Models\Consultation::STATUS_COMPLETED);
    $ticketCalled = $appointment && $appointment->queue_ticket_status === 'called';
    $canCallNext = $canCallNext ?? ($canManageSpecialty ?? false);
    $canConsult = $canConsult ?? false;
    $canAdvanceStage = $canAdvanceStage ?? $canConsult;
    $canStartConsultationFlag = $canStartConsultation ?? $canConsult;
    $canPrescribe = $canPrescribe ?? false;
    $canBookAppointments = $canBookAppointments ?? false;
    $canViewPatients = $canViewPatients ?? true;
    $canViewAppointments = $canViewAppointments ?? true;
    $appointmentReadyToStart = $appointment && in_array($appointment->status, [
        \App\Models\Appointment::STATUS_WAITING,
        \App\Models\Appointment::STATUS_CHECKED_IN,
    ], true);
    $consultationInProgress = $appointment
        && (
            $appointment->status === \App\Models\Appointment::STATUS_IN_CONSULTATION
            || ($openConsultation && $openConsultation->status !== \App\Models\Consultation::STATUS_COMPLETED)
        );
    $canCompleteConsultation = $canConsult
        && $consultationInProgress
        && $openConsultation
        && $openConsultation->status !== \App\Models\Consultation::STATUS_COMPLETED;
        $chartTab = collect($workspaceTabs ?? [])
            ->keys()
            ->first(fn ($key) => ! in_array($key, ['overview', 'timeline', 'plan', 'treat', 'notes', 'imaging', 'orders', 'billing', 'documents', 'perio', 'lab', 'recalls', 'vitals', 'disposition', 'observation', 'issue', 'transfusion', 'inventory'], true))
            ?: match ($moduleKey) {
                'emergency' => 'triage',
                'blood_bank' => 'requests',
                default => 'odontogram',
            };
    $stageRoute = $specialtyStageRoute ?? null;
    $stageFlow = $specialtyStageFlow ?? [];
    $defaultStartStage = match ($moduleKey) {
        'emergency' => 'arrival',
        'blood_bank' => 'request',
        'dentistry' => 'chair',
        'ophthalmology' => 'check_in',
        'physiotherapy' => 'check_in',
        'womens_health' => 'check_in',
        'radiology' => 'check_in',
        'cardiology' => 'check_in',
        'psychiatry' => 'check_in',
        'pediatrics' => 'check_in',
        'orthopedics' => 'check_in',
        'ent' => 'check_in',
        'dermatology' => 'check_in',
        'podiatry' => 'check_in',
        'fertility' => 'check_in',
        'child_welfare' => 'check_in',
        'ambulance' => 'check_in',
        default => collect($stages ?? [])->pluck('code')->first(),
    };
    $defaultStartLabel = match ($moduleKey) {
        'emergency' => 'Start triage',
        'blood_bank' => 'Start request',
        'dentistry' => 'Seat at chair',
        'ophthalmology' => 'Start check-in',
        'physiotherapy' => 'Start check-in',
        'womens_health' => 'Start check-in',
        'radiology' => 'Start check-in',
        'cardiology' => 'Start check-in',
        'psychiatry' => 'Start check-in',
        'pediatrics' => 'Start check-in',
        'orthopedics' => 'Start check-in',
        'ent' => 'Start check-in',
        'dermatology' => 'Start check-in',
        'podiatry' => 'Start check-in',
        'fertility' => 'Start check-in',
        'child_welfare' => 'Start check-in',
        'ambulance' => 'Start check-in',
        default => 'Start',
    };
    $currentStage = $workspaceVisit?->specialty_stage;
@endphp

@if ($onWorkspace && $canCallNext && ($moduleKey ?? '') !== 'ambulance')
    @include('care.partials.queue-ops', [
        'queueIntegration' => $queueIntegration ?? null,
        'queueCallNextRoute' => 'care.specialty.call-next',
        'queueCallNextParams' => ['module' => $moduleKey],
        'branchId' => $branchId ?? null,
        'currentAppointmentId' => $appointment?->id,
        'variant' => 'button',
    ])
@endif

@if ($canConsult && $ticketCalled && $appointment)
    <form method="POST" action="{{ route('care.queue.recall', $appointment) }}" class="w-full" @click.stop>
        @csrf
        <button type="submit" class="{{ $btnAccent }}">Call again</button>
    </form>
@endif

@if ($workspaceVisit)
    @if ($canAdvanceStage && $stageRoute && $currentStage && isset($stageFlow[$currentStage]) && ($stageFlow[$currentStage]['next'] ?? null) !== $currentStage)
        <form method="POST" action="{{ route($stageRoute, $workspaceVisit) }}" class="w-full" @click.stop>
            @csrf
            <input type="hidden" name="stage" value="{{ $stageFlow[$currentStage]['next'] }}">
            <button type="submit" class="{{ $btnAccent }}">{{ $stageFlow[$currentStage]['label'] }}</button>
        </form>
    @elseif ($canAdvanceStage && $stageRoute && ! $currentStage && $defaultStartStage)
        <form method="POST" action="{{ route($stageRoute, $workspaceVisit) }}" class="w-full" @click.stop>
            @csrf
            <input type="hidden" name="stage" value="{{ $defaultStartStage }}">
            <button type="submit" class="{{ $btnAccent }}">{{ $defaultStartLabel }}</button>
        </form>
    @endif

    @if ($canCompleteConsultation)
        <button
            type="button"
            class="{{ $btnPrimary }}"
            @click.stop="$dispatch('open-modal', {{ \Illuminate\Support\Js::from('complete-consultation-'.$openConsultation->id) }})"
        >
            Complete consultation
        </button>
    @endif

    @if ($canPrescribe && $openConsultation && $openConsultation->status !== \App\Models\Consultation::STATUS_COMPLETED)
        <button
            type="button"
            class="{{ $btnSecondary }}"
            @click.stop="$dispatch('open-modal', {{ \Illuminate\Support\Js::from('prescribe-'.$openConsultation->id) }})"
        >
            {{ $actions['prescribe'] ?? 'Prescribe' }}
        </button>
    @endif

    @if ($consultationInProgress)
        <a href="{{ route('care.specialty.workspace', ['module' => $moduleKey, 'visit' => $workspaceVisit, 'tab' => $chartTab]) }}"
           class="{{ $btnSecondary }}">
            Open chart
        </a>
    @elseif ($canStartConsultationFlag && $appointmentReadyToStart)
        <form method="POST" action="{{ route('care.specialty.consultation.start', ['module' => $moduleKey, 'visit' => $workspaceVisit]) }}" class="w-full" @click.stop>
            @csrf
            <button type="submit" class="{{ $btnPrimary }}">
                {{ $actions['start'] ?? 'Start' }}
            </button>
        </form>
    @endif
    @if (($canReferSpecialty ?? false) && ! ($canManageSpecialty ?? true) && $workspaceVisit->patient)
        <form method="POST" action="{{ route('care.specialty.refer', $moduleKey) }}" class="w-full space-y-2" @click.stop>
            @csrf
            <input type="hidden" name="patient_id" value="{{ $workspaceVisit->patient->id }}">
            <input type="hidden" name="branch_id" value="{{ $workspaceVisit->branch_id }}">
            <input type="text" name="reason" placeholder="Referral reason" class="w-full rounded-lg border border-slate-200 px-2 py-1.5 text-xs">
            <button type="submit" class="{{ $btnAccent }}">Refer to specialty queue</button>
        </form>
    @endif
    @if ($canViewPatients && $workspaceVisit->patient)
        <a href="{{ route('care.patients.show', $workspaceVisit->patient) }}" class="{{ $btnSecondary }}">
            Patient chart
        </a>
    @endif
    @if ($canViewAppointments && $workspaceVisit->appointment)
        <a href="{{ route('care.appointments.show', $workspaceVisit->appointment) }}" class="{{ $btnSecondary }}">
            Appointment
        </a>
    @endif
@endif

@if (! empty($canAccessPatientQueue))
<a href="{{ route('care.queue.index') }}" class="{{ $btnSecondary }}">
    Back to queue
</a>
@else
<a href="{{ route('care.specialty.show', $moduleKey) }}" class="{{ $btnSecondary }}">
    Specialty home
</a>
@endif

@if ($canBookAppointments)
    <a href="{{ route('care.appointments.create') }}" class="{{ $btnAccent }}">
        Register / book
    </a>
@endif
