<div class="card shadow-sm" x-data="{
    show: @entangle('showOffcanvas'),
    instance: null,
    init() {
        this.instance = new bootstrap.Offcanvas($refs.canvas);
        $watch('show', value => {
            if (value) {
                this.instance.show();
            } else {
                this.instance.hide();
            }
        });
        $refs.canvas.addEventListener('hidden.bs.offcanvas', () => {
            this.show = false;
        });
    }
}">
    <div class="card-body">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h4 class="fw-bold m-0">Institutions</h4>
            @can('claims.institutions.create')
                <button class="btn btn-primary btn-sm" wire:click="openOffcanvas">
                    <i class="mdi mdi-plus"></i>
                </button>
            @endcan
        </div>

        @if($institutions->isEmpty())
            <div class="text-center p-5 text-muted">
                <i class="mdi mdi-bank-outline" style="font-size: 48px;"></i>
                <p class="mt-2 mb-0 fw-bold">No institutions linked.</p>
            </div>
        @else
            @foreach($institutions as $recordTypeName => $group)
                <p class="text-uppercase fw-bold text-muted small mb-2 mt-3">{{ $recordTypeName }}</p>
                <div class="list-group mb-2">
                    @foreach($group as $record)
                        <a href="{{ route('institutions.show', $record->institution) }}" class="list-group-item bg-light mb-1 rounded border-0 d-flex justify-content-between align-items-center">
                            <div class="flex-grow-1">
                                <p class="mb-0 fw-semibold">{{ $record->institution->display_name }}</p>
                                <div class="d-flex gap-2 align-items-center">
                                    @if($record->institution->dsarType)
                                        <small class="text-muted">{{ $record->institution->dsarType->display_name }}</small>
                                    @endif
                                    @if($record->dates)
                                        <small class="text-muted">
                                            @if($record->institution->dsarType) &middot; @endif
                                            {{ $record->dates }}
                                        </small>
                                    @endif
                                </div>
                            </div>
                            @can('claims.institutions.delete')
                                <div class="ms-3">
                                    <button
                                        class="btn btn-md"
                                        wire:click="detach({{ $record->id }})"
                                        wire:confirm="Remove this institution from the claim?"
                                    >
                                        <i class="mdi mdi-trash-can text-danger"></i>
                                    </button>
                                </div>
                            @endcan
                        </a>
                    @endforeach
                </div>
            @endforeach
        @endif
    </div>

    <!-- Offcanvas: Search & Link -->
    <div wire:ignore.self
         x-ref="canvas"
         class="offcanvas offcanvas-end"
         tabindex="-1"
         style="--bs-offcanvas-width: 500px;"
         id="institutionOffcanvas">
        <div class="offcanvas-header border-bottom">
            <h5 class="offcanvas-title fw-bold">
                @if($step === 'details')
                    <button class="btn btn-sm btn-light me-2" wire:click="backToSearch">
                        <i class="mdi mdi-arrow-left"></i>
                    </button>
                @endif
                Link Institution
            </h5>
            <button type="button" class="btn-close text-reset" data-bs-dismiss="offcanvas"></button>
        </div>

        <div class="offcanvas-body bg-light">

            @if($step === 'search')

                <div class="card border-0 shadow-sm mb-3">
                    <div class="card-body">
                        <label class="form-label small fw-bold text-uppercase text-muted">Search Institutions</label>
                        <div class="input-group">
                            <span class="input-group-text bg-white"><i class="mdi mdi-magnify"></i></span>
                            <input
                                type="text"
                                class="form-control"
                                wire:model.live.debounce.300ms="searchTerm"
                                placeholder="Type to search..."
                            >
                        </div>

                        @if(!empty($searchResults))
                            <div class="list-group mt-2" style="max-height: 250px; overflow-y: auto;">
                                @foreach($searchResults as $result)
                                    <button
                                        type="button"
                                        class="list-group-item list-group-item-action py-2 {{ $result['already_linked'] ? 'text-muted' : '' }}"
                                        wire:click="selectInstitution({{ $result['id'] }}, '{{ addslashes($result['display_name']) }}')"
                                    >
                                        <div class="d-flex justify-content-between align-items-center">
                                            <span>{{ $result['display_name'] }}</span>
                                            @if($result['already_linked'])
                                                <span class="badge bg-secondary">linked</span>
                                            @else
                                                <i class="mdi mdi-link-variant text-primary"></i>
                                            @endif
                                        </div>
                                    </button>
                                @endforeach
                            </div>
                        @elseif(strlen(trim($searchTerm)) >= 2 && empty($searchResults))
                            <div class="alert alert-warning mt-2 mb-0">No institutions found.</div>
                        @endif
                    </div>
                </div>

                <div class="card border-0 shadow-sm">
                    <div class="card-body">
                        <button class="btn btn-outline-secondary btn-sm w-100" wire:click="toggleCreateForm">
                            <i class="mdi mdi-plus me-1"></i>
                            {{ $showCreateForm ? 'Cancel' : 'Create New Institution' }}
                        </button>

                        @if($showCreateForm)
                            <div class="mt-3">
                                <label class="form-label small fw-bold text-uppercase text-muted">Institution Name</label>
                                <input
                                    type="text"
                                    class="form-control @error('newInstitutionName') is-invalid @enderror"
                                    wire:model="newInstitutionName"
                                    placeholder="Enter institution name..."
                                    autofocus
                                >
                                @error('newInstitutionName')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror

                                <label class="form-label small fw-bold text-uppercase text-muted mt-3">Record Type</label>
                                <select class="form-select" wire:model="recordTypeId">
                                    <option value="">— None —</option>
                                    @foreach($recordTypes as $type)
                                        <option value="{{ $type->id }}">{{ $type->display_name }}</option>
                                    @endforeach
                                </select>

                                <label class="form-label small fw-bold text-uppercase text-muted mt-3">Dates</label>
                                <input
                                    type="text"
                                    class="form-control"
                                    wire:model="dates"
                                    placeholder="e.g. 1998 - 2003"
                                >

                                <button class="btn btn-success btn-sm mt-3 w-100" wire:click="createAndAttach"
                                        wire:loading.attr="disabled" wire:target="createAndAttach">
                                    <span wire:loading wire:target="createAndAttach"
                                          class="spinner-border spinner-border-sm me-1" role="status"></span>
                                    Create & Link
                                </button>
                            </div>
                        @endif
                    </div>
                </div>

            @elseif($step === 'details')

                <div class="card border-0 shadow-sm">
                    <div class="card-body">
                        <p class="fw-semibold mb-3">
                            <i class="mdi mdi-bank-outline me-1 text-primary"></i>
                            {{ $selectedInstitutionName }}
                        </p>

                        <label class="form-label small fw-bold text-uppercase text-muted">Record Type</label>
                        <select class="form-select mb-3" wire:model="recordTypeId">
                            <option value="">— None —</option>
                            @foreach($recordTypes as $type)
                                <option value="{{ $type->id }}">{{ $type->display_name }}</option>
                            @endforeach
                        </select>

                        <label class="form-label small fw-bold text-uppercase text-muted">Dates</label>
                        <input
                            type="text"
                            class="form-control mb-4"
                            wire:model="dates"
                            placeholder="e.g. 1998 - 2003"
                        >

                        <button class="btn btn-primary w-100" wire:click="attach"
                                wire:loading.attr="disabled" wire:target="attach">
                            <span wire:loading wire:target="attach"
                                  class="spinner-border spinner-border-sm me-1" role="status"></span>
                            Link Institution
                        </button>
                    </div>
                </div>

            @endif

        </div>
    </div>
</div>
