<div class="card shadow-sm mb-4 position-relative">
    <div class="card-body">

        <h4 class="fw-bold mb-3 d-flex justify-content-between align-items-center">
            Care Settings
            @can('claims.edit')
                <button class="btn btn-primary btn-sm" wire:click="addSetting">
                    <i class="mdi mdi-plus"></i>
                </button>
            @endcan
        </h4>

        @if(count($settings))
            <div class="accordion" id="careSettingsAccordion">
                @foreach($settings as $index => $set)
                    <div class="accordion-item mb-4" wire:key="setting-{{ $set['_ui_key'] }}">
                        <h2 class="accordion-header bg-light" id="heading-{{ $set['_ui_key'] }}">
                            <button
                                    class="accordion-button {{ $loop->last ? '' : 'collapsed' }}"
                                    type="button"
                                    data-bs-toggle="collapse"
                                    data-bs-target="#collapse-{{ $set['_ui_key'] }}"
                                    aria-expanded="{{ $loop->last ? 'true' : 'false' }}"
                                    aria-controls="collapse-{{ $set['_ui_key'] }}"
                            >
                                <div class="d-flex justify-content-between w-100 me-3 align-items-center">
                                    <span class="fw-bold">
                                        {{ $set['institution_name'] ?: 'New Care Setting' }}
                                    </span>
                                    <span class="text-muted small">
                                        {{ $set['date_text'] }}
                                    </span>
                                </div>
                            </button>
                        </h2>

                        <div
                                id="collapse-{{ $set['_ui_key'] }}"
                                class="accordion-collapse collapse {{ $loop->last ? 'show' : '' }}"
                                aria-labelledby="heading-{{ $set['_ui_key'] }}"
                                data-bs-parent="#careSettingsAccordion"
                                wire:ignore.self
                        >
                            <div class="accordion-body p-0">
                                <div class="row g-0">
                                    {{-- Metadata --}}
                                    <div class="col-12 bg-light">
                                        <div class="p-3">
                                            {{-- Institution Search --}}
                                            <div class="mb-3">
                                                <label class="form-label fw-bold small text-uppercase text-muted">Institution</label>

                                                <div class="input-group mb-1">
                                                    <input
                                                            type="text"
                                                            class="form-control @if($set['institution_id']) border-success @endif @error('settings.' . $index . '.institution_id') is-invalid @enderror"
                                                            wire:model="settings.{{ $index }}.institution_name"
                                                            wire:keydown.enter="search({{ $index }})"
                                                            placeholder="Type name and press Enter..."
                                                            @if($set['institution_id']) readonly @endif
                                                    >
                                                    @if($set['institution_id'])
                                                        <button class="btn btn-outline-danger" type="button"
                                                                wire:click="clearItem({{ $index }})">
                                                            <i class="mdi mdi-close"></i>
                                                        </button>
                                                    @else
                                                        <button class="btn btn-primary" type="button"
                                                                wire:click="search({{ $index }})">
                                                            <i class="mdi mdi-magnify"></i>
                                                        </button>
                                                        <button class="btn btn-outline-secondary" type="button"
                                                                wire:click="openModal({{ $index }})"
                                                                title="Add New Institution">
                                                            <i class="mdi mdi-plus"></i>
                                                        </button>
                                                    @endif
                                                </div>

                                                @error('settings.' . $index . '.institution_id')
                                                <div class="text-danger small mt-1 mb-2"
                                                     style="font-size: 0.75rem;">{{ $message }}</div>
                                                @enderror

                                                {{-- Inline Search Results --}}
                                                @if(!empty($set['search_results']) && count($set['search_results']) > 0 && empty($set['institution_id']))
                                                    <div class="list-group shadow-sm mb-3"
                                                         style="max-height: 200px; overflow-y: auto;">
                                                        @foreach($set['search_results'] as $result)
                                                            <button
                                                                    type="button"
                                                                    class="list-group-item list-group-item-action py-2"
                                                                    wire:click="setItem({{ $index }}, {{ $result['id'] }})"
                                                            >
                                                                <div class="d-flex justify-content-between align-items-center">
                                                                    <span>{{ $result['display_name'] }}</span>
                                                                    <i class="mdi mdi-chevron-right text-muted"></i>
                                                                </div>
                                                            </button>
                                                        @endforeach
                                                    </div>
                                                @elseif($set['institution_name'] && count($set['search_results']) == 0 && empty($set['institution_id']))
                                                    <div class="alert alert-border alert-warning">No care settings found with that name.</div>
                                                @endif
                                            </div>

                                            {{-- Area (searchable) — selecting an area fixes the Local Authority --}}
                                            <div class="mb-3">
                                                <label class="form-label fw-bold small text-uppercase text-muted">Area</label>
                                                <div class="input-group mb-1">
                                                    <input
                                                            type="text"
                                                            class="form-control @if($set['area_id']) border-success @endif"
                                                            wire:model="settings.{{ $index }}.area_name"
                                                            wire:keydown.enter.prevent="searchArea({{ $index }})"
                                                            placeholder="Type area/suburb and press Enter..."
                                                            @if($set['area_id']) readonly @endif
                                                    >
                                                    @if($set['area_id'])
                                                        <button class="btn btn-outline-danger" type="button"
                                                                wire:click="clearArea({{ $index }})">
                                                            <i class="mdi mdi-close"></i>
                                                        </button>
                                                    @else
                                                        <button class="btn btn-primary" type="button"
                                                                wire:click="searchArea({{ $index }})">
                                                            <i class="mdi mdi-magnify"></i>
                                                        </button>
                                                    @endif
                                                </div>

                                                @if(!empty($set['area_search_results']) && empty($set['area_id']))
                                                    <div class="list-group shadow-sm mb-2"
                                                         style="max-height: 200px; overflow-y: auto;">
                                                        @foreach($set['area_search_results'] as $result)
                                                            <button
                                                                    type="button"
                                                                    class="list-group-item list-group-item-action py-2"
                                                                    wire:click="setArea({{ $index }}, {{ $result['id'] }})"
                                                            >
                                                                <div class="d-flex justify-content-between align-items-center">
                                                                    <span>{{ $result['name'] }}</span>
                                                                    <small class="text-muted">{{ $result['council'] }}</small>
                                                                </div>
                                                            </button>
                                                        @endforeach
                                                    </div>
                                                @elseif($set['area_name'] && empty($set['area_search_results']) && empty($set['area_id']))
                                                    <div class="alert alert-border alert-warning py-2 small mb-2">No area found with that name.</div>
                                                @endif
                                            </div>

                                            {{-- Local Authority — auto-set from the area; a filter for the area search when none is chosen --}}
                                            <div class="mb-3">
                                                <label class="form-label fw-bold small text-uppercase text-muted">Local Authority</label>
                                                <select
                                                        class="form-select @if($set['area_id']) border-success @endif"
                                                        wire:model="settings.{{ $index }}.council_id"
                                                        @if($set['area_id']) disabled @endif
                                                >
                                                    <option value="">Any (pick to narrow the area search)</option>
                                                    @foreach($councils as $council)
                                                        <option value="{{ $council['id'] }}">{{ $council['name'] }}</option>
                                                    @endforeach
                                                </select>
                                                @if($set['area_id'])
                                                    <div class="form-text">Set automatically from the selected area.</div>
                                                @endif
                                            </div>

                                            {{-- Dates --}}
                                            <div class="mb-3">
                                                <label class="form-label fw-bold small text-uppercase text-muted">Date
                                                    Range</label>
                                                <input
                                                        type="text"
                                                        class="form-control @error('settings.' . $index . '.date_text') is-invalid @enderror"
                                                        wire:model="settings.{{ $index }}.date_text"
                                                        placeholder="e.g. 2020 - 2022"
                                                >
                                                @error('settings.' . $index . '.date_text')
                                                <div class="invalid-feedback">{{ $message }}</div>
                                                @enderror
                                            </div>

                                            {{-- People Involved --}}
                                            <div class="mb-3">
                                                <label class="form-label fw-bold small text-uppercase text-muted">People
                                                    Involved</label>
                                                <input
                                                        type="text"
                                                        class="form-control @error('settings.' . $index . '.people_involved') is-invalid @enderror"
                                                        wire:model="settings.{{ $index }}.people_involved"
                                                        placeholder="Names of the people involved"
                                                >
                                                @error('settings.' . $index . '.people_involved')
                                                <div class="invalid-feedback">{{ $message }}</div>
                                                @enderror
                                            </div>

                                            @can('claims.edit')
                                            <span
                                                    class="btn btn-md"
                                                    wire:confirm="Are you sure you want to delete this care setting?"
                                                    wire:click.stop="removeSetting({{ $index }})"
                                            >
                                                <i class="mdi mdi-delete text-danger"></i> Delete
                                            </span>
                                            @endcan
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                @endforeach
            </div>
        @else
            <div class="text-center p-5 text-muted">
                <i class="mdi mdi-hospital-building" style="font-size: 48px;"></i>
                <p class="mt-3 fw-bold">No care settings added.</p>
            </div>
        @endif
    </div>
    @can('claims.edit')
    @if(count($settings))
        <div class="card-footer">
            <div class="d-flex justify-content-start">
                <button
                        class="btn btn-success px-4"
                        wire:click="save"
                        wire:loading.attr="disabled"
                >
                    <span wire:loading.remove wire:target="save">
                        <i class="mdi mdi-content-save"></i> Save Changes
                    </span>
                    <span wire:loading wire:target="save">
                        <span class="spinner-border spinner-border-sm me-1" role="status" aria-hidden="true"></span>
                        Saving...
                    </span>
                </button>
            </div>
        </div>
    @endif
    @endcan

    <!-- Add New Institution Modal -->
    @if($isModalOpen)
        <div class="modal fade show d-block" tabindex="-1" style="background-color: rgba(0, 0, 0, 0.5);">
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title fw-bold">Add New Institution</h5>
                        <button type="button" class="btn-close" wire:click="closeModal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <div class="mb-3">
                            <label for="newInstName" class="form-label">Institution Name</label>
                            <input type="text"
                                   class="form-control @error('newInstitutionName') is-invalid @enderror"
                                   id="newInstName"
                                   wire:model="newInstitutionName"
                                   wire:keydown.enter="saveNewInstitution"
                                   autofocus>
                            @error('newInstitutionName')
                            <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>
                    <div class="modal-footer bg-light">
                        <button type="button" class="btn btn-secondary" wire:click="closeModal">Cancel</button>
                        <button type="button" class="btn btn-primary" wire:click="saveNewInstitution"
                                wire:loading.attr="disabled" wire:target="saveNewInstitution">
                            <span wire:loading wire:target="saveNewInstitution"
                                  class="spinner-border spinner-border-sm me-1" role="status" aria-hidden="true"></span>
                            Save & Select
                        </button>
                    </div>
                </div>
            </div>
        </div>
    @endif
</div>