{{--
    SIFA P3-T8 — shared patient medical-alert banner.

    A compact, self-contained banner rendering the active medical-safety alerts
    for a patient. Designed to be reusable across ANY clinical screen (patient
    show, appointment/encounter, prescription…). Wave B will @include it into the
    appointment screen — DO NOT duplicate this markup elsewhere.

    Usage (the ONLY supported include shape):

        @include('clinicCore::partials.patient_alert_banner', [
            'patientId'    => $patient->id,          // required
            'activeAlerts' => $activeAlerts ?? null,  // optional: pre-fetched collection
        ])

    If $activeAlerts is not passed, the partial resolves them itself via
    MedicalAlertService (so screens that haven't wired the controller still work).
    Acknowledge/resolve actions are permission-gated and post to the P3 routes.
--}}
@php
    $clcBannerPatientId = $patientId ?? (isset($patient) ? $patient->id : null);
    $clcAlerts = $activeAlerts
        ?? ($clcBannerPatientId
            ? app(\Modules\ClinicCore\Entities\Services\MedicalAlertService::class)
                ->activeFor((int) $clcBannerPatientId, (int) session('user.business_id'))
            : collect());
@endphp

@if($clcBannerPatientId && $clcAlerts && count($clcAlerts))
<div class="clc-alert-banner" id="clc-alert-banner-{{ $clcBannerPatientId }}" style="margin-bottom:14px;">
    @foreach($clcAlerts as $clcAlert)
    <div class="alert alert-{{ $clcAlert->bannerClass() }} clc-alert-row"
         data-alert-id="{{ $clcAlert->id }}"
         style="border-radius:8px;border-left:5px solid;padding:9px 14px;display:flex;align-items:center;gap:10px;margin-bottom:8px;">
        <i class="fas {{ $clcAlert->icon() }}" style="font-size:17px;"></i>
        <div style="flex:1;min-width:0;">
            <strong style="text-transform:uppercase;font-size:11px;letter-spacing:.4px;">
                {{ __('clinicCore::lang.alert_type_' . $clcAlert->alert_type) }}
                @if($clcAlert->severity === 'critical')
                    <span class="label label-danger" style="font-size:9px;">{{ strtoupper(__('clinicCore::lang.critical')) }}</span>
                @endif
            </strong>
            <div style="font-size:13px;">{{ $clcAlert->title }}</div>
            @if($clcAlert->details)
                <div style="font-size:11px;opacity:.85;">{{ $clcAlert->details }}</div>
            @endif
            @if($clcAlert->acknowledged_at)
                <div style="font-size:10px;opacity:.7;font-style:italic;">
                    <i class="fa fa-check"></i> {{ __('clinicCore::lang.acknowledged') }}
                    {{ \Carbon\Carbon::parse($clcAlert->acknowledged_at)->diffForHumans() }}
                </div>
            @endif
        </div>
        <div style="display:flex;gap:6px;flex-shrink:0;">
            @can('clinic.alert.acknowledge')
            @if(!$clcAlert->acknowledged_at)
            <button type="button" class="btn btn-xs btn-default clc-alert-ack"
                    data-id="{{ $clcAlert->id }}" title="@lang('clinicCore::lang.acknowledge')">
                <i class="fa fa-check"></i>
            </button>
            @endif
            @endcan
            @can('clinic.alert.manage')
            <button type="button" class="btn btn-xs btn-default clc-alert-resolve"
                    data-id="{{ $clcAlert->id }}" title="@lang('clinicCore::lang.resolve')">
                <i class="fa fa-times"></i>
            </button>
            @endcan
        </div>
    </div>
    @endforeach
</div>

{{-- Inline (not @push): the ERP layout yields 'javascript' but exposes no
     @stack, and this partial can be included mid-content on any screen. @once
     guarantees the handler is bound a single time even with multiple banners. --}}
@once
<script>
(function initClcAlertBanner(){
    if (typeof window.jQuery === 'undefined') { return setTimeout(initClcAlertBanner, 50); }
    jQuery(function ($) {
        var token = $('meta[name="csrf-token"]').attr('content') || '{{ csrf_token() }}';

        function post(url, $row, doneMsg) {
            $.ajax({ url: url, method: 'POST', data: { _token: token } })
              .done(function (res) {
                  if (res && res.success) {
                      if (window.toastr) toastr.success(res.msg || doneMsg);
                      // Resolve removes the row; acknowledge just refreshes it.
                      $row.fadeOut(150, function () { $(this).remove(); });
                  }
              })
              .fail(function () { if (window.toastr) toastr.error('Action failed.'); });
        }

        $(document).on('click', '.clc-alert-resolve', function () {
            var id = $(this).data('id');
            post('{{ url('clinic/patients/alerts') }}/' + id + '/resolve',
                 $(this).closest('.clc-alert-row'), 'Alert resolved.');
        });
        $(document).on('click', '.clc-alert-ack', function () {
            var id = $(this).data('id');
            post('{{ url('clinic/patients/alerts') }}/' + id + '/acknowledge',
                 $(this).closest('.clc-alert-row'), 'Alert acknowledged.');
        });
    });
})();
</script>
@endonce
@endif
