@push('styles')
    <style>
        .sale-channel-wrapper {
            border: none;
            background-color: transparent;
        }

        .sale-channel-wrapper:not(.blocked) .card-body {
            border: 1px solid #e5e7eb;
            border-radius: .75rem;
            background-color: #ffffff;
            transition: border-color 0.2s ease, box-shadow 0.2s ease;
        }

        .sale-channel-wrapper:not(.blocked) .card-body:hover {
            border-color: #3b82f6;
            box-shadow: 0 0.35rem 0.8rem rgba(37, 99, 235, 0.12);
        }

        .sale-channel-wrapper.blocked .card-body {
            border: 1px solid #d1d5db;
            border-radius: .75rem;
            background-color: #f3f4f6;
        }

        .sale-channel-wrapper .card-body {
            padding: 1.25rem;
        }

        .sale-channel-toggle {
            display: flex;
            align-items: flex-start;
            justify-content: center;
            padding-top: 0.25rem;
        }

        .sale-channel-content strong {
            font-size: 1.05rem;
        }

        .sale-channel-warning {
            font-size: 0.85rem;
        }

        .sale-channel-wrapper .icheck-success > input:first-child + label::before,
        .sale-channel-wrapper .icheck-primary > input:first-child + label::before,
        .sale-channel-wrapper .icheck-danger > input:first-child + label::before {
            opacity: 1;
            border-width: 2px;
            border-color: #9ca3af;
        }

        .sale-channel-wrapper.blocked .icheck-success > input:first-child + label::before,
        .sale-channel-wrapper.blocked .icheck-primary > input:first-child + label::before,
        .sale-channel-wrapper.blocked .icheck-danger > input:first-child + label::before {
            border-color: #cbd5f5;
            background-color: #f8fafc;
        }

        .sale-channel-wrapper .icheck-success > input:first-child + label,
        .sale-channel-wrapper .icheck-primary > input:first-child + label,
        .sale-channel-wrapper .icheck-danger > input:first-child + label {
            opacity: 1;
        }

        .sale-channel-wrapper [class*="icheck-"] > input:first-child:disabled + label {
            opacity: 1;
        }
    </style>
@endpush

@php
    $saleChannelsCollection = collect($sale_channels);
    $firstSaleChannel = $saleChannelsCollection->first();
    $selectedSaleChannelId = $customer['default_sale_channel_id'] ?? ($firstSaleChannel['id'] ?? null);
    $cartCount = app('App\\Repositories\\Core\\User\\ShopCart')::count();
@endphp

@if ($cartCount > 0)
    <div class="alert alert-warning">
        <strong>Note :</strong> en changeant votre mode d'achat, les articles de votre panier seront transférés sur la liste de prix correspondant au nouveau canal de vente sélectionné.
    </div>
@endif

@foreach ($saleChannelsCollection as $saleChannel)
    @php
        $check = $sale_channel_checks[$saleChannel['id']] ?? null;
        $isBlocked = $check && $saleChannel['id'] !== $selectedSaleChannelId;
    @endphp
    <div class="card sale-channel-wrapper mb-3 @if($isBlocked) blocked @endif">
        <div class="card-body py-3">
            <div class="row align-items-start">
                <div class="col-1 sale-channel-toggle">

            @include('components.form.radios.icheck', [
                'name' => 'sale_channel_id',
                'id_name' => 'sale_channel_id_' . $saleChannel['id'],
                'val' => $saleChannel['id'],
                'value' => $selectedSaleChannelId,
                'class' => 'sale-channel',
                'disabled' => $isBlocked,
            ])
                </div>
                <div class="col-11 sale-channel-content @if($isBlocked) text-muted @endif">
                    <strong>{{ $saleChannel['name'] }}</strong><br />
                    <p class="mb-2">{!! $saleChannel['description'] ?? '' !!}</p>
                    @if ($check)
                        <div class="text-danger small mb-0 sale-channel-warning">
                            @php $missingCount = $check['full_count'] ?? count($check['names']); @endphp
                            @if ($cartCount > 0 && $missingCount >= $cartCount)
                                {{ __('shop.sale_channels.missing_offers_all') }}
                            @else
                                {{ trans_choice('shop.sale_channels.missing_offers', $missingCount, ['count' => $missingCount]) }}
                                <br>
                                @if ($missingCount > 3)
                                    <span class="d-block">{{ implode(', ', array_slice($check['names'], 0, 3)) }}, …</span>
                                @else
                                    <span class="d-block">{{ implode(', ', $check['names']) }}</span>
                                @endif
                            @endif
                            <div class="d-flex align-items-start mt-1">
                                <span class="mr-1">⚠️</span>
                                <span>{{ __('shop.sale_channels.cannot_select_with_cart') }}</span>
                            </div>
                        </div>
                    @endif
                </div>
            </div>
        </div>
    </div>
@endforeach

@push('js')
    <script>
        const $saleChannels = $('.sale-channel');
        const updateUrl = '{{ route('Shop.Customers.storeProfileAjax') }}';
        const token = '{{ csrf_token() }}';
        const customerId = {{ $customer['id'] ?? 'null' }};
        let currentSaleChannelId = '{{ $selectedSaleChannelId }}';

        $saleChannels.off().change(function() {
            if (!customerId) {
                return;
            }

            const selectedSaleChannel = $(this).val();

            $.post(updateUrl, {
                _token: token,
                id: customerId,
                default_sale_channel_id: selectedSaleChannel,
            }).done(function() {
                currentSaleChannelId = selectedSaleChannel;
                window.location.reload();
            }).fail(function(xhr) {
                const message = xhr.responseJSON && xhr.responseJSON.message
                    ? xhr.responseJSON.message
                    : "{{ __('Une erreur est survenue lors de l\'enregistrement du canal de vente préféré.') }}";

                console.error('Sale channel update failed', {
                    status: xhr.status,
                    response: xhr.responseJSON || xhr.responseText,
                    selectedSaleChannel
                });

                alert(message);

                if (currentSaleChannelId) {
                    $saleChannels.filter('[value="' + currentSaleChannelId + '"]').prop('checked', true);
                }
            });
        });
    </script>
@endpush
