@php
    $addresses = collect($addresses ?? []);
    $preselectedAddressId = old($name);

    if ($preselectedAddressId === null && is_string($name) && str_contains($name, '[')) {
        $dotName = preg_replace('/\[(.*?)\]/', '.$1', $name);
        $dotName = trim($dotName, '.');
        $preselectedAddressId = $dotName ? old($dotName) : null;
    }

    if (($preselectedAddressId === null || $preselectedAddressId === '') && $addresses->isNotEmpty()) {
        $defaultAddress = $addresses->firstWhere('priority', 1);

        if (! $defaultAddress) {
            $defaultAddress = $addresses
                ->filter(function ($address) {
                    return (int) ($address['priority'] ?? 0) > 0;
                })
                ->sortByDesc(function ($address) {
                    return (int) ($address['priority'] ?? 0);
                })
                ->first();
        }

        if (! $defaultAddress) {
            $defaultAddress = $addresses->firstWhere('is_default', true)
                ?? $addresses->firstWhere('default', true);
        }

        if (! $defaultAddress) {
            $defaultAddress = $addresses->first();
        }

        $preselectedAddressId = $defaultAddress['id'] ?? null;
    }

    $addresses = $addresses->all();
@endphp

@if ($addresses)
    @foreach ($addresses as $address)
        <div class="row mb-3">
            <div class="col-1">
                @include('components.form.radios.icheck', [
                    'name' => $name,
                    'val' => $address['id'],
                    'id' => $prefix . '_address_' . $address['id'],
                    'value' => $preselectedAddressId,
                ])
            </div>
            <div class="col-11">
                {{ $address['name'] }}<br />
                {{ $address['address'] }}<br />
                @if ($address['address2'])
                    {{ $address['address2'] }}<br />
                @endif
                {{ $address['zipcode'] }} {{ $address['city'] }}<br />
            </div>
        </div>
    @endforeach
@endif
