@php
    $statusBadgeStyles = [
        'open' => 'bg-emerald-100 text-emerald-700',
        'pending' => 'bg-amber-100 text-amber-700',
        'closed' => 'bg-slate-100 text-slate-700',
    ];

    $messageBadgeStyles = [
        'new' => 'bg-slate-100 text-slate-700',
        'sent' => 'bg-sky-100 text-sky-700',
        'delivered' => 'bg-emerald-100 text-emerald-700',
        'read' => 'bg-indigo-100 text-indigo-700',
        'failed' => 'bg-rose-100 text-rose-700',
    ];

    $providerDictionary = is_array($providerDictionary ?? null) ? $providerDictionary : [];
    $selectedOperators = collect(old('allowed_operator_ids', $allowedOperatorIds ?? []))
        ->map(fn ($id) => (int) $id)
        ->filter(fn ($id) => $id > 0)
        ->values()
        ->all();
    $resolveProviderLabel = static function (?string $providerCode) use ($providerDictionary): string {
        $providerCode = (string) $providerCode;
        if ($providerCode !== '' && array_key_exists($providerCode, $providerDictionary)) {
            return __($providerDictionary[$providerCode]);
        }

        return $providerCode === '' ? '—' : ucfirst(str_replace('_', ' ', $providerCode));
    };
@endphp

<x-app-layout>
    <x-slot name="header">
        <div class="flex flex-wrap items-center justify-between gap-3">
            <div>
                <h2 class="font-semibold text-xl text-gray-800 leading-tight">{{ __('Messengers') }}</h2>
                <p class="text-sm text-gray-500">{{ __('Connect messengers and keep external chats inside CRM.') }}</p>
            </div>
            <div class="flex items-center gap-2">
                @include('partials.section-access-controls', [
                    'sectionAccessEntity' => 'messengers',
                    'sectionAccessTitle' => __('Messengers'),
                    'canManageSectionAccess' => $canManageSectionAccess ?? false,
                    'sectionAccessUsers' => $sectionAccessUsers ?? collect(),
                ])
            </div>
        </div>
    </x-slot>

    <div class="pb-12" data-sidepanel-scope>
        <div class="w-full px-6 space-y-4">
            <section class="bg-white border border-gray-200 rounded-xl p-4 space-y-4">
                <div class="flex flex-wrap items-start justify-between gap-3">
                    <div>
                        <h3 class="text-lg font-semibold text-gray-900">{{ __('Messenger settings') }}</h3>
                        <p class="text-sm text-gray-500">{{ __('Store provider credentials and webhook for message imports.') }}</p>
                    </div>
                    <span class="inline-flex items-center rounded-full px-2.5 py-1 text-xs font-medium {{ ($settings->is_active ?? false) ? 'bg-emerald-100 text-emerald-700' : 'bg-slate-100 text-slate-600' }}">
                        {{ ($settings->is_active ?? false) ? __('Active') : __('Disabled') }}
                    </span>
                </div>

                <div class="rounded-lg border border-slate-200 bg-slate-50 p-3 text-xs text-slate-600">
                    <div class="flex flex-col gap-1">
                        <span class="font-semibold text-slate-700">{{ __('Webhook URL') }}</span>
                        <code class="rounded bg-white px-2 py-1 text-slate-800 break-all">{{ $webhookUrl }}</code>
                        <span>{{ __('Send header') }} <code class="rounded bg-white px-1 py-0.5">X-CRM-Webhook-Secret</code></span>
                    </div>
                </div>

                @if ($canManageSettings)
                    <form method="POST" action="{{ route('messengers.settings.update') }}" class="grid grid-cols-1 gap-4">
                        @csrf
                        @method('PATCH')

                        <div class="grid grid-cols-1 gap-4 md:grid-cols-2">
                            <div>
                                <label class="block text-sm font-medium text-gray-700">{{ __('Provider') }}</label>
                                <select name="provider" class="mt-1 w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                                    @foreach ($providerDictionary as $providerCode => $providerName)
                                        <option value="{{ $providerCode }}" @selected(old('provider', $settings->provider) === $providerCode)>{{ __($providerName) }}</option>
                                    @endforeach
                                </select>
                                <x-input-error class="mt-1" :messages="$errors->get('provider')" />
                            </div>

                            <div class="flex items-end">
                                <label class="inline-flex items-center gap-2 text-sm text-gray-700">
                                    <input type="checkbox" name="is_active" value="1" class="rounded border-gray-300 text-indigo-600 shadow-sm focus:ring-indigo-500" @checked(old('is_active', $settings->is_active))>
                                    {{ __('Active integration') }}
                                </label>
                                <x-input-error class="mt-1" :messages="$errors->get('is_active')" />
                            </div>
                        </div>

                        <div class="grid grid-cols-1 gap-4 md:grid-cols-2">
                            <div>
                                <label class="block text-sm font-medium text-gray-700">{{ __('API base URL') }}</label>
                                <input name="api_base_url" type="text" value="{{ old('api_base_url', $settings->api_base_url) }}" class="mt-1 w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500" placeholder="https://api.provider.com">
                                <x-input-error class="mt-1" :messages="$errors->get('api_base_url')" />
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700">{{ __('Account ID') }}</label>
                                <input name="account_id" type="text" value="{{ old('account_id', $settings->account_id) }}" class="mt-1 w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500" placeholder="account-123">
                                <x-input-error class="mt-1" :messages="$errors->get('account_id')" />
                            </div>
                        </div>

                        <div class="grid grid-cols-1 gap-4 md:grid-cols-2">
                            <div>
                                <label class="block text-sm font-medium text-gray-700">{{ __('API key') }}</label>
                                <input name="api_key" type="text" value="{{ old('api_key', $settings->api_key) }}" class="mt-1 w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                                <x-input-error class="mt-1" :messages="$errors->get('api_key')" />
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700">{{ __('API secret') }}</label>
                                <input name="api_secret" type="text" value="{{ old('api_secret', $settings->api_secret) }}" class="mt-1 w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                                <x-input-error class="mt-1" :messages="$errors->get('api_secret')" />
                            </div>
                        </div>

                        <div class="rounded-lg border border-gray-200 bg-gray-50 p-4 space-y-3">
                            <div class="flex items-center justify-between gap-3">
                                <p class="text-sm font-medium text-gray-900">{{ __('Incoming chats') }}</p>
                                <label class="inline-flex items-center gap-2 text-sm text-gray-700">
                                    <input type="hidden" name="auto_create_contact" value="0">
                                    <input type="checkbox" name="auto_create_contact" value="1" class="rounded border-gray-300 text-indigo-600 shadow-sm focus:ring-indigo-500" @checked(old('auto_create_contact', $settings->auto_create_contact ?? true))>
                                    {{ __('Auto-create contact for new messenger user') }}
                                </label>
                            </div>

                            <div>
                                <label class="block text-xs font-medium uppercase tracking-wide text-gray-500">{{ __('Who can accept chats') }}</label>
                                <div class="mt-2 grid grid-cols-1 gap-2 md:grid-cols-2 xl:grid-cols-3">
                                    @foreach ($userOptions as $operatorOption)
                                        <label class="inline-flex items-center gap-2 rounded-md border border-gray-200 bg-white px-2 py-1.5 text-sm text-gray-700">
                                            <input type="checkbox" name="allowed_operator_ids[]" value="{{ $operatorOption->id }}" class="rounded border-gray-300 text-indigo-600 shadow-sm focus:ring-indigo-500" @checked(in_array((int) $operatorOption->id, $selectedOperators, true))>
                                            <span>{{ $operatorOption->name }}</span>
                                        </label>
                                    @endforeach
                                </div>
                                <x-input-error class="mt-1" :messages="$errors->get('allowed_operator_ids')" />
                            </div>

                            <div class="grid grid-cols-1 gap-3 md:grid-cols-2">
                                <div>
                                    <label class="block text-xs font-medium uppercase tracking-wide text-gray-500">{{ __('Action for new contact') }}</label>
                                    <select name="new_contact_action" class="mt-1 w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                                        @foreach ($newContactActionOptions as $actionCode => $actionLabel)
                                            <option value="{{ $actionCode }}" @selected(old('new_contact_action', $settings->new_contact_action ?? 'none') === $actionCode)>{{ __($actionLabel) }}</option>
                                        @endforeach
                                    </select>
                                    <x-input-error class="mt-1" :messages="$errors->get('new_contact_action')" />
                                </div>
                                <div>
                                    <label class="block text-xs font-medium uppercase tracking-wide text-gray-500">{{ __('Responsible for auto action') }}</label>
                                    <x-user-search-select
                                        id="messengers-action-user"
                                        name="new_contact_action_user_id"
                                        :users="$userOptions"
                                        :selected="old('new_contact_action_user_id', $settings->new_contact_action_user_id)"
                                        :placeholder="__('Select user')"
                                        :empty-label="__('Not selected')"
                                    />
                                    <x-input-error class="mt-1" :messages="$errors->get('new_contact_action_user_id')" />
                                </div>
                            </div>
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700">{{ __('Webhook secret') }}</label>
                            <input name="webhook_secret" type="text" value="{{ old('webhook_secret', $settings->webhook_secret) }}" class="mt-1 w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                            <x-input-error class="mt-1" :messages="$errors->get('webhook_secret')" />
                        </div>

                        <div class="flex justify-end">
                            <button type="submit" class="inline-flex items-center rounded-md bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-500">
                                {{ __('Save settings') }}
                            </button>
                        </div>
                    </form>
                @else
                    <p class="text-sm text-gray-500">{{ __('You do not have rights to edit messenger settings.') }}</p>
                @endif
            </section>

            <section class="bg-white border border-gray-200 rounded-xl p-4 space-y-4">
                <div class="flex flex-wrap items-center justify-between gap-3">
                    <div>
                        <h3 class="text-lg font-semibold text-gray-900">{{ __('Channels') }}</h3>
                        <p class="text-sm text-gray-500">{{ __('Connected messenger accounts and inboxes.') }}</p>
                    </div>
                    <div class="text-xs text-gray-500">{{ __('Total:') }} {{ $channels->count() }}</div>
                </div>

                @if ($canCreateChannel)
                    <details class="rounded-lg border border-gray-200 bg-gray-50 p-3">
                        <summary class="cursor-pointer text-sm font-medium text-gray-700">{{ __('Add channel') }}</summary>
                        <form method="POST" action="{{ route('messengers.channels.store') }}" class="mt-3 grid grid-cols-1 gap-3 md:grid-cols-2 xl:grid-cols-6">
                            @csrf

                            <div>
                                <label class="block text-xs font-medium text-gray-500 uppercase">{{ __('Provider') }}</label>
                                <select name="provider" class="mt-1 w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                                    @foreach ($providerDictionary as $providerCode => $providerName)
                                        <option value="{{ $providerCode }}" @selected(old('provider', $settings->provider ?? 'telegram') === $providerCode)>{{ __($providerName) }}</option>
                                    @endforeach
                                </select>
                                <x-input-error class="mt-1" :messages="$errors->get('provider')" />
                            </div>

                            <div>
                                <label class="block text-xs font-medium text-gray-500 uppercase">{{ __('Channel name') }}</label>
                                <input name="name" type="text" value="{{ old('name') }}" class="mt-1 w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                                <x-input-error class="mt-1" :messages="$errors->get('name')" />
                            </div>

                            <div>
                                <label class="block text-xs font-medium text-gray-500 uppercase">{{ __('Handle') }}</label>
                                <input name="handle" type="text" value="{{ old('handle') }}" class="mt-1 w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500" placeholder="@crm">
                                <x-input-error class="mt-1" :messages="$errors->get('handle')" />
                            </div>

                            <div>
                                <label class="block text-xs font-medium text-gray-500 uppercase">{{ __('External ID') }}</label>
                                <input name="external_id" type="text" value="{{ old('external_id') }}" class="mt-1 w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                                <x-input-error class="mt-1" :messages="$errors->get('external_id')" />
                            </div>

                            <div>
                                <label class="block text-xs font-medium text-gray-500 uppercase">{{ __('Status') }}</label>
                                <select name="status" class="mt-1 w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                                    @foreach (['active' => __('Active'), 'disabled' => __('Disabled')] as $value => $label)
                                        <option value="{{ $value }}" @selected(old('status', 'active') === $value)>{{ $label }}</option>
                                    @endforeach
                                </select>
                                <x-input-error class="mt-1" :messages="$errors->get('status')" />
                            </div>

                            <div class="flex items-end">
                                <label class="inline-flex items-center gap-2 text-sm text-gray-700">
                                    <input type="checkbox" name="is_default" value="1" class="rounded border-gray-300 text-indigo-600 shadow-sm focus:ring-indigo-500" @checked(old('is_default'))>
                                    {{ __('Default channel') }}
                                </label>
                            </div>

                            <div class="md:col-span-2 xl:col-span-6 flex justify-end">
                                <button type="submit" class="inline-flex items-center rounded-md bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-500">
                                    {{ __('Create') }}
                                </button>
                            </div>
                        </form>
                    </details>
                @endif

                <div class="overflow-hidden rounded-lg border border-gray-200">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gray-50">
                            <tr>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">{{ __('Channel') }}</th>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">{{ __('Provider') }}</th>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">{{ __('Handle') }}</th>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">{{ __('Status') }}</th>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">{{ __('Default') }}</th>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">{{ __('External ID') }}</th>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">{{ __('Conversations') }}</th>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">{{ __('Actions') }}</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-100 bg-white">
                            @forelse ($channels as $channel)
                                <tr class="hover:bg-gray-50">
                                    <td class="px-4 py-3">
                                        <div class="font-medium text-gray-900">{{ $channel->name }}</div>
                                        <div class="text-xs text-gray-500">{{ $channel->handle ?: '—' }}</div>
                                    </td>
                                    <td class="px-4 py-3 text-sm text-gray-700">{{ $resolveProviderLabel($channel->provider) }}</td>
                                    <td class="px-4 py-3 text-sm text-gray-700">{{ $channel->handle ?: '—' }}</td>
                                    <td class="px-4 py-3 text-sm text-gray-700">{{ $channel->status }}</td>
                                    <td class="px-4 py-3 text-sm text-gray-700">{{ $channel->is_default ? __('Yes') : __('No') }}</td>
                                    <td class="px-4 py-3 text-sm text-gray-700">{{ $channel->external_id ?: '—' }}</td>
                                    <td class="px-4 py-3 text-sm text-gray-700">{{ $channel->conversations()->count() }}</td>
                                    <td class="px-4 py-3 text-sm text-gray-700">
                                        @if ($canCreateChannel)
                                            <details>
                                                <summary class="cursor-pointer text-sm text-indigo-600">{{ __('Edit') }}</summary>
                                                <form method="POST" action="{{ route('messengers.channels.update', $channel) }}" class="mt-2 space-y-2">
                                                    @csrf
                                                    @method('PATCH')
                                                    <div>
                                                        <label class="block text-xs font-medium text-gray-500 uppercase">{{ __('Channel name') }}</label>
                                                        <input name="name" type="text" value="{{ old('name', $channel->name) }}" class="mt-1 w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                                                    </div>
                                                    <div>
                                                        <label class="block text-xs font-medium text-gray-500 uppercase">{{ __('Handle') }}</label>
                                                        <input name="handle" type="text" value="{{ old('handle', $channel->handle) }}" class="mt-1 w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                                                    </div>
                                                    <div>
                                                        <label class="block text-xs font-medium text-gray-500 uppercase">{{ __('Provider') }}</label>
                                                        <select name="provider" class="mt-1 w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                                                            @foreach ($providerDictionary as $providerCode => $providerName)
                                                                <option value="{{ $providerCode }}" @selected(old('provider', $channel->provider) === $providerCode)>{{ __($providerName) }}</option>
                                                            @endforeach
                                                        </select>
                                                    </div>
                                                    <div>
                                                        <label class="block text-xs font-medium text-gray-500 uppercase">{{ __('External ID') }}</label>
                                                        <input name="external_id" type="text" value="{{ old('external_id', $channel->external_id) }}" class="mt-1 w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                                                    </div>
                                                    <div>
                                                        <label class="block text-xs font-medium text-gray-500 uppercase">{{ __('Status') }}</label>
                                                        <select name="status" class="mt-1 w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                                                            @foreach (['active' => __('Active'), 'disabled' => __('Disabled')] as $value => $label)
                                                                <option value="{{ $value }}" @selected(old('status', $channel->status) === $value)>{{ $label }}</option>
                                                            @endforeach
                                                        </select>
                                                    </div>
                                                    <label class="inline-flex items-center gap-2 text-sm text-gray-700">
                                                        <input type="checkbox" name="is_default" value="1" class="rounded border-gray-300 text-indigo-600 shadow-sm focus:ring-indigo-500" @checked(old('is_default', $channel->is_default))>
                                                        {{ __('Default channel') }}
                                                    </label>
                                                    <div class="flex justify-end">
                                                        <button type="submit" class="inline-flex items-center rounded-md bg-gray-800 px-3 py-1.5 text-xs font-medium text-white hover:bg-gray-700">
                                                            {{ __('Save') }}
                                                        </button>
                                                    </div>
                                                </form>
                                            </details>
                                        @else
                                            —
                                        @endif
                                    </td>
                                </tr>
                            @empty
                                <tr>
                                    <td colspan="8" class="px-4 py-8 text-center text-sm text-gray-500">{{ __('No channels found.') }}</td>
                                </tr>
                            @endforelse
                        </tbody>
                    </table>
                </div>
            </section>

            <section class="bg-white border border-gray-200 rounded-xl p-4 space-y-4">
                <div class="flex flex-wrap items-center justify-between gap-3">
                    <div>
                        <h3 class="text-lg font-semibold text-gray-900">{{ __('Conversations') }}</h3>
                        <p class="text-sm text-gray-500">{{ __('All messenger conversations with filters.') }}</p>
                    </div>
                    <div class="text-xs text-gray-500">{{ __('Total:') }} {{ $conversations->total() }}</div>
                </div>

                <form method="GET" action="{{ route('messengers.index') }}" class="grid grid-cols-1 gap-3 md:grid-cols-2 xl:grid-cols-6">
                    <div class="xl:col-span-2">
                        <label class="block text-xs font-medium text-gray-500 uppercase">{{ __('Search') }}</label>
                        <input type="text" name="q" value="{{ $search }}" placeholder="{{ __('Contact or conversation ID') }}" class="mt-1 w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                    </div>

                    <div>
                        <label class="block text-xs font-medium text-gray-500 uppercase">{{ __('Status') }}</label>
                        <select name="status" class="mt-1 w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                            <option value="">{{ __('All') }}</option>
                            @foreach ($conversationStatusOptions as $value => $label)
                                <option value="{{ $value }}" @selected($status === $value)>{{ $label }}</option>
                            @endforeach
                        </select>
                    </div>

                    <div>
                        <label class="block text-xs font-medium text-gray-500 uppercase">{{ __('Provider') }}</label>
                        <select name="provider" class="mt-1 w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                            <option value="">{{ __('All') }}</option>
                            @foreach ($providerOptions as $providerOption)
                                <option value="{{ $providerOption }}" @selected($provider === $providerOption)>{{ $resolveProviderLabel($providerOption) }}</option>
                            @endforeach
                        </select>
                    </div>

                    <div>
                        <label class="block text-xs font-medium text-gray-500 uppercase">{{ __('Channel') }}</label>
                        <select name="channel_id" class="mt-1 w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                            <option value="">{{ __('All') }}</option>
                            @foreach ($channels as $channel)
                                <option value="{{ $channel->id }}" @selected($channelId === $channel->id)>{{ $channel->name }}</option>
                            @endforeach
                        </select>
                    </div>

                    <div>
                        <label class="block text-xs font-medium text-gray-500 uppercase">{{ __('User') }}</label>
                        <x-user-search-select
                            id="messengers-user-filter"
                            name="user_id"
                            :users="$userOptions"
                            :selected="$selectedUserId"
                            placeholder="{{ __('All users') }}"
                            empty-label="{{ __('All') }}"
                        />
                    </div>

                    <div class="flex items-end gap-2">
                        <button type="submit" class="inline-flex items-center rounded-md bg-gray-800 px-4 py-2 text-sm font-medium text-white hover:bg-gray-700">
                            {{ __('Find') }}
                        </button>
                        <a href="{{ route('messengers.index') }}" class="inline-flex items-center rounded-md border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50">
                            {{ __('Reset') }}
                        </a>
                    </div>

                    <div>
                        <label class="block text-xs font-medium text-gray-500 uppercase">{{ __('From date') }}</label>
                        <input type="date" name="date_from" value="{{ $dateFrom }}" class="mt-1 w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                    </div>

                    <div>
                        <label class="block text-xs font-medium text-gray-500 uppercase">{{ __('To date') }}</label>
                        <input type="date" name="date_to" value="{{ $dateTo }}" class="mt-1 w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                    </div>
                </form>

                @if ($canCreateConversation)
                    <details class="rounded-lg border border-gray-200 bg-gray-50 p-3">
                        <summary class="cursor-pointer text-sm font-medium text-gray-700">{{ __('Add conversation') }}</summary>
                        <form method="POST" action="{{ route('messengers.conversations.store') }}" class="mt-3 grid grid-cols-1 gap-3 md:grid-cols-2 xl:grid-cols-6">
                            @csrf

                            <div class="xl:col-span-2">
                                <label class="block text-xs font-medium text-gray-500 uppercase">{{ __('Channel') }}</label>
                                <select name="channel_id" class="mt-1 w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                                    @foreach ($channels as $channel)
                                        <option value="{{ $channel->id }}" @selected((int) old('channel_id') === $channel->id)>{{ $channel->name }}</option>
                                    @endforeach
                                </select>
                                <x-input-error class="mt-1" :messages="$errors->get('channel_id')" />
                            </div>

                            <div>
                                <label class="block text-xs font-medium text-gray-500 uppercase">{{ __('Contact name') }}</label>
                                <input name="contact_name" type="text" value="{{ old('contact_name') }}" class="mt-1 w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                                <x-input-error class="mt-1" :messages="$errors->get('contact_name')" />
                            </div>

                            <div>
                                <label class="block text-xs font-medium text-gray-500 uppercase">{{ __('Contact handle') }}</label>
                                <input name="contact_handle" type="text" value="{{ old('contact_handle') }}" class="mt-1 w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500" placeholder="@client">
                                <x-input-error class="mt-1" :messages="$errors->get('contact_handle')" />
                            </div>

                            <div>
                                <label class="block text-xs font-medium text-gray-500 uppercase">{{ __('Status') }}</label>
                                <select name="status" class="mt-1 w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                                    @foreach ($conversationStatusOptions as $value => $label)
                                        <option value="{{ $value }}" @selected(old('status', 'open') === $value)>{{ $label }}</option>
                                    @endforeach
                                </select>
                                <x-input-error class="mt-1" :messages="$errors->get('status')" />
                            </div>

                            <div>
                                <label class="block text-xs font-medium text-gray-500 uppercase">{{ __('External ID') }}</label>
                                <input name="external_id" type="text" value="{{ old('external_id') }}" class="mt-1 w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                                <x-input-error class="mt-1" :messages="$errors->get('external_id')" />
                            </div>

                            <div class="xl:col-span-2">
                                <label class="block text-xs font-medium text-gray-500 uppercase">{{ __('User') }}</label>
                                <x-user-search-select
                                    id="messengers-user-create"
                                    name="user_id"
                                    :users="$userOptions"
                                    :selected="old('user_id')"
                                    placeholder="{{ __('Select user') }}"
                                    empty-label="{{ __('Not selected') }}"
                                />
                                <x-input-error class="mt-1" :messages="$errors->get('user_id')" />
                            </div>

                            <div class="md:col-span-2 xl:col-span-6 flex justify-end">
                                <button type="submit" class="inline-flex items-center rounded-md bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-500">
                                    {{ __('Create') }}
                                </button>
                            </div>
                        </form>
                    </details>
                @endif

                <div class="overflow-hidden rounded-lg border border-gray-200">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gray-50">
                            <tr>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">{{ __('Contact') }}</th>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">{{ __('Channel') }}</th>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">{{ __('Status') }}</th>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">{{ __('Last message') }}</th>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">{{ __('Messages') }}</th>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">{{ __('Responsible') }}</th>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">{{ __('Updated') }}</th>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">{{ __('Actions') }}</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-100 bg-white">
                            @forelse ($conversations as $conversation)
                                @php
                                    $badgeClass = $statusBadgeStyles[$conversation->status] ?? 'bg-slate-100 text-slate-700';
                                    $lastMessage = $conversation->lastMessage;
                                @endphp
                                <tr class="hover:bg-gray-50">
                                    <td class="px-4 py-3">
                                        <div class="font-medium text-gray-900">{{ $conversation->contact_name ?: __('Unknown contact') }}</div>
                                        <div class="text-xs text-gray-500">{{ $conversation->contact_handle ?: '—' }}</div>
                                    </td>
                                    <td class="px-4 py-3 text-sm text-gray-700">{{ $conversation->channel?->name ?: '—' }}</td>
                                    <td class="px-4 py-3 text-sm text-gray-700">
                                        <span class="inline-flex items-center rounded-full px-2.5 py-1 text-xs font-medium {{ $badgeClass }}">
                                            {{ $conversationStatusOptions[$conversation->status] ?? $conversation->status }}
                                        </span>
                                    </td>
                                    <td class="px-4 py-3 text-sm text-gray-700">
                                        @if ($lastMessage)
                                            <div class="text-gray-900">{{ \Illuminate\Support\Str::limit((string) $lastMessage->body, 80) }}</div>
                                            <div class="text-xs text-gray-500">{{ $lastMessage->sent_at?->format('d.m.Y H:i') ?? $lastMessage->created_at?->format('d.m.Y H:i') }}</div>
                                        @else
                                            —
                                        @endif
                                    </td>
                                    <td class="px-4 py-3 text-sm text-gray-700">{{ $conversation->messages_count ?? 0 }}</td>
                                    <td class="px-4 py-3 text-sm text-gray-700">{{ $conversation->user?->name ?: '—' }}</td>
                                    <td class="px-4 py-3 text-sm text-gray-700">{{ $conversation->last_message_at?->format('d.m.Y H:i') ?: $conversation->updated_at?->format('d.m.Y H:i') }}</td>
                                    <td class="px-4 py-3 text-sm text-gray-700">
                                        <div class="flex flex-wrap items-center gap-2">
                                            <a href="{{ route('messengers.index', ['conversation_id' => $conversation->id]) }}" class="text-indigo-600 hover:text-indigo-500">
                                                {{ __('Open') }}
                                            </a>
                                            @if ($canAssignConversation && ! $conversation->user_id)
                                                <form method="POST" action="{{ route('messengers.conversations.accept', $conversation) }}">
                                                    @csrf
                                                    @method('PATCH')
                                                    <button type="submit" class="inline-flex items-center rounded-md border border-indigo-200 bg-indigo-50 px-2 py-1 text-xs font-medium text-indigo-700 hover:bg-indigo-100">
                                                        {{ __('Accept chat') }}
                                                    </button>
                                                </form>
                                            @endif
                                        </div>
                                    </td>
                                </tr>
                            @empty
                                <tr>
                                    <td colspan="8" class="px-4 py-8 text-center text-sm text-gray-500">{{ __('No conversations found.') }}</td>
                                </tr>
                            @endforelse
                        </tbody>
                    </table>
                </div>

                <div>
                    {{ $conversations->links() }}
                </div>
            </section>

            @if ($activeConversation)
                @php
                    $activeContact = $activeConversation->contact;
                    $activeContactName = trim((string) ($activeContact?->full_name ?? ''));
                    if ($activeContactName === '') {
                        $activeContactName = $activeConversation->contact_name ?: __('Unknown contact');
                    }
                @endphp
                <section class="bg-white border border-gray-200 rounded-xl p-4 space-y-4">
                    <div class="grid grid-cols-1 gap-4 xl:grid-cols-[minmax(0,1fr)_22rem]">
                        <div class="space-y-4">
                            <div class="flex flex-wrap items-start justify-between gap-3">
                                <div>
                                    <h3 class="text-lg font-semibold text-gray-900">{{ __('Conversation') }}</h3>
                                    <p class="text-sm text-gray-500">
                                        {{ $activeContactName }}
                                        @if ($activeConversation->contact_handle)
                                            · {{ $activeConversation->contact_handle }}
                                        @endif
                                    </p>
                                    <div class="mt-1 text-xs text-gray-500">
                                        {{ __('Channel') }}: {{ $activeConversation->channel?->name ?: '—' }} ·
                                        {{ __('Provider') }}: {{ $resolveProviderLabel($activeConversation->provider) }}
                                    </div>
                                </div>
                                <div class="flex items-center gap-2">
                                    @if ($activeConversation->user)
                                        <span class="inline-flex items-center rounded-full bg-slate-100 px-2.5 py-1 text-xs font-medium text-slate-700">
                                            {{ __('Responsible') }}: {{ $activeConversation->user->name }}
                                        </span>
                                    @else
                                        <span class="inline-flex items-center rounded-full bg-amber-100 px-2.5 py-1 text-xs font-medium text-amber-700">
                                            {{ __('No responsible user') }}
                                        </span>
                                    @endif

                                    @if ($canAssignConversation && ! $activeConversation->user_id)
                                        <form method="POST" action="{{ route('messengers.conversations.accept', $activeConversation) }}">
                                            @csrf
                                            @method('PATCH')
                                            <button type="submit" class="inline-flex items-center rounded-md bg-indigo-600 px-3 py-1.5 text-xs font-medium text-white hover:bg-indigo-500">
                                                {{ __('Accept chat') }}
                                            </button>
                                        </form>
                                    @endif
                                </div>
                            </div>

                            <div class="max-h-[540px] space-y-3 overflow-y-auto rounded-lg border border-slate-200 bg-slate-50 p-4">
                                @forelse ($conversationMessages as $message)
                                    @php
                                        $isOutbound = $message->direction === 'outbound';
                                        $badgeClass = $messageBadgeStyles[$message->status] ?? 'bg-slate-100 text-slate-700';
                                    @endphp
                                    <div class="flex {{ $isOutbound ? 'justify-end' : 'justify-start' }}">
                                        <div class="max-w-[74%] rounded-xl border border-slate-200 bg-white px-4 py-2 shadow-sm">
                                            <div class="mb-1 flex items-center justify-between gap-2 text-xs text-slate-500">
                                                <span>{{ $isOutbound ? __('Outgoing') : __('Incoming') }}</span>
                                                <span class="inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-medium {{ $badgeClass }}">
                                                    {{ $messageStatusOptions[$message->status] ?? $message->status }}
                                                </span>
                                            </div>
                                            <div class="text-sm text-slate-800">{{ $message->body ?: '—' }}</div>
                                            <div class="mt-1 text-[10px] text-slate-400">
                                                {{ $message->sent_at?->format('d.m.Y H:i') ?? $message->created_at?->format('d.m.Y H:i') }}
                                            </div>
                                        </div>
                                    </div>
                                @empty
                                    <div class="text-sm text-slate-500">{{ __('No messages yet.') }}</div>
                                @endforelse
                            </div>

                            @if ($canCreateMessage)
                                <form method="POST" action="{{ route('messengers.messages.store', $activeConversation) }}" class="space-y-3">
                                    @csrf
                                    <div>
                                        <label class="block text-sm font-medium text-gray-700">{{ __('Message text') }}</label>
                                        <textarea name="body" rows="3" class="mt-1 w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">{{ old('body') }}</textarea>
                                        <x-input-error class="mt-1" :messages="$errors->get('body')" />
                                    </div>
                                    <div class="flex justify-end">
                                        <button type="submit" class="inline-flex items-center rounded-md bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-500">
                                            {{ __('Send message') }}
                                        </button>
                                    </div>
                                </form>
                            @endif
                        </div>

                        <aside class="h-fit space-y-4 rounded-lg border border-slate-200 bg-slate-50 p-4 xl:sticky xl:top-4">
                            <div class="flex items-center justify-between gap-2">
                                <h4 class="text-sm font-semibold text-slate-900">{{ __('Contact') }}</h4>
                                @if ($activeContact)
                                    <a href="{{ route('contacts.show', $activeContact) }}" class="text-xs text-indigo-600 hover:text-indigo-500">
                                        {{ __('Open contact') }}
                                    </a>
                                @endif
                            </div>

                            <div class="rounded-lg border border-slate-200 bg-white p-3 text-xs text-slate-600">
                                <div class="grid grid-cols-1 gap-2">
                                    <div>
                                        <span class="font-medium text-slate-700">{{ __('Name') }}:</span>
                                        <span>{{ $activeContactName }}</span>
                                    </div>
                                    <div>
                                        <span class="font-medium text-slate-700">{{ __('Handle') }}:</span>
                                        <span>{{ $activeConversation->contact_handle ?: '—' }}</span>
                                    </div>
                                    <div>
                                        <span class="font-medium text-slate-700">{{ __('Email') }}:</span>
                                        <span>{{ $activeContact?->email ?: '—' }}</span>
                                    </div>
                                    <div>
                                        <span class="font-medium text-slate-700">{{ __('Phone') }}:</span>
                                        <span>{{ $activeContact?->phone ?: '—' }}</span>
                                    </div>
                                </div>
                            </div>

                            @if ($canEditConversationContact)
                                <form method="POST" action="{{ route('messengers.conversations.contact.update', $activeConversation) }}" class="space-y-3 rounded-lg border border-slate-200 bg-white p-3">
                                    @csrf
                                    @method('PATCH')

                                    <div>
                                        <label class="block text-xs font-medium uppercase tracking-wide text-gray-500">{{ __('First name') }}</label>
                                        <input name="first_name" type="text" required value="{{ old('first_name', $activeContact?->first_name ?: $activeConversation->contact_name) }}" class="mt-1 w-full rounded-md border-gray-300 text-sm shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                                        <x-input-error class="mt-1" :messages="$errors->get('first_name')" />
                                    </div>

                                    <div>
                                        <label class="block text-xs font-medium uppercase tracking-wide text-gray-500">{{ __('Last name') }}</label>
                                        <input name="last_name" type="text" value="{{ old('last_name', $activeContact?->last_name) }}" class="mt-1 w-full rounded-md border-gray-300 text-sm shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                                        <x-input-error class="mt-1" :messages="$errors->get('last_name')" />
                                    </div>

                                    <div>
                                        <label class="block text-xs font-medium uppercase tracking-wide text-gray-500">{{ __('Job title') }}</label>
                                        <input name="title" type="text" value="{{ old('title', $activeContact?->title) }}" class="mt-1 w-full rounded-md border-gray-300 text-sm shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                                        <x-input-error class="mt-1" :messages="$errors->get('title')" />
                                    </div>

                                    <div>
                                        <label class="block text-xs font-medium uppercase tracking-wide text-gray-500">{{ __('Email') }}</label>
                                        <input name="email" type="email" value="{{ old('email', $activeContact?->email) }}" class="mt-1 w-full rounded-md border-gray-300 text-sm shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                                        <x-input-error class="mt-1" :messages="$errors->get('email')" />
                                    </div>

                                    <div>
                                        <label class="block text-xs font-medium uppercase tracking-wide text-gray-500">{{ __('Phone') }}</label>
                                        <input name="phone" type="text" value="{{ old('phone', $activeContact?->phone ?: $activeConversation->contact_handle) }}" class="mt-1 w-full rounded-md border-gray-300 text-sm shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                                        <x-input-error class="mt-1" :messages="$errors->get('phone')" />
                                    </div>

                                    <div>
                                        <label class="block text-xs font-medium uppercase tracking-wide text-gray-500">{{ __('Owner') }}</label>
                                        <x-user-search-select
                                            id="messengers-contact-owner-{{ $activeConversation->id }}"
                                            name="owner_id"
                                            :users="$userOptions"
                                            :selected="old('owner_id', $activeContact?->owner_id ?: $activeConversation->user_id)"
                                            :placeholder="__('Select user')"
                                            :empty-label="__('Not selected')"
                                        />
                                        <x-input-error class="mt-1" :messages="$errors->get('owner_id')" />
                                    </div>

                                    <div>
                                        <label class="block text-xs font-medium uppercase tracking-wide text-gray-500">{{ __('Source') }}</label>
                                        <input name="source" type="text" value="{{ old('source', $activeContact?->source ?: ('messenger:'.$activeConversation->provider)) }}" class="mt-1 w-full rounded-md border-gray-300 text-sm shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                                        <x-input-error class="mt-1" :messages="$errors->get('source')" />
                                    </div>

                                    <div>
                                        <label class="block text-xs font-medium uppercase tracking-wide text-gray-500">{{ __('Notes') }}</label>
                                        <textarea name="notes" rows="3" class="mt-1 w-full rounded-md border-gray-300 text-sm shadow-sm focus:border-indigo-500 focus:ring-indigo-500">{{ old('notes', $activeContact?->notes) }}</textarea>
                                        <x-input-error class="mt-1" :messages="$errors->get('notes')" />
                                    </div>

                                    <div class="flex justify-end">
                                        <button type="submit" class="inline-flex items-center rounded-md bg-indigo-600 px-3 py-2 text-xs font-medium text-white hover:bg-indigo-500">
                                            {{ __('Save contact') }}
                                        </button>
                                    </div>
                                </form>
                            @else
                                <p class="text-xs text-slate-500">
                                    {{ __('Only the responsible user or administrator can edit this contact from chat.') }}
                                </p>
                            @endif
                        </aside>
                    </div>
                </section>
            @endif
        </div>
    </div>
</x-app-layout>
