@extends('admin.layouts.app')

@section('title', admin_trans('users'))
@section('page-title', admin_trans('users'))

@section('content')

<div class="space-y-6" x-data="usersPage()">

    <!-- Header: Search & Add Button -->
    <div class="card">
        <div class="flex flex-col lg:flex-row gap-4 items-start lg:items-center justify-between">
            
            <!-- Search -->
            <div class="flex-1 w-full max-w-lg">
                <form method="GET" action="{{ route('admin.users.index') }}">
                    @foreach(request()->except(['search', 'page']) as $key => $value)
                        @if(is_array($value))
                            @foreach($value as $v)
                                <input type="hidden" name="{{ $key }}[]" value="{{ $v }}">
                            @endforeach
                        @else
                            <input type="hidden" name="{{ $key }}" value="{{ $value }}">
                        @endif
                    @endforeach
                    
                    <x-search-input 
                        name="search" 
                        :value="request('search')" 
                        :placeholder="admin_trans('search_users')" 
                        class="w-full"
                    />
                </form>
            </div>

            <!-- Add Button -->
            <x-button variant="primary" icon="plus" @click="$dispatch('open-modal', 'create-user-modal')">
                {{ admin_trans('add_user') }}
            </x-button>
        </div>
    </div>

    <!-- Advanced Filters -->
    <div class="card">
        <div class="flex items-center justify-between mb-4">
            <h3 class="text-lg font-semibold text-primary">{{ admin_trans('filters') }}</h3>
            <button @click="filtersExpanded = !filtersExpanded" class="p-2 rounded-lg hover:bg-primary-light">
                <i data-lucide="filter" class="w-5 h-5 text-primary"></i>
            </button>
        </div>

        <div x-show="filtersExpanded" x-collapse class="space-y-4">
            <form method="GET" action="{{ route('admin.users.index') }}" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
                @if(request('search'))<input type="hidden" name="search" value="{{ request('search') }}">@endif

                <!-- Role Filter -->
                <div>
                    <label class="block text-sm font-medium text-tertiary mb-1">{{ admin_trans('role') }}</label>
                    <select name="role" class="input text-sm">
                        <option value="">{{ admin_trans('all_roles') }}</option>
                        <option value="admin" {{ request('role') === 'admin' ? 'selected' : '' }}>{{ admin_trans('admin') }}</option>
                        <option value="store_owner" {{ request('role') === 'store_owner' ? 'selected' : '' }}>{{ admin_trans('store_owner') }}</option>
                        <option value="user" {{ request('role') === 'user' ? 'selected' : '' }}>{{ admin_trans('user') }}</option>
                    </select>
                </div>

                <!-- Verified Filter -->
                <div>
                    <label class="block text-sm font-medium text-tertiary mb-1">{{ admin_trans('verification_status') }}</label>
                    <select name="verified" class="input text-sm">
                        <option value="">{{ admin_trans('all') }}</option>
                        <option value="1" {{ request('verified') === '1' ? 'selected' : '' }}>{{ admin_trans('verified') }}</option>
                        <option value="0" {{ request('verified') === '0' ? 'selected' : '' }}>{{ admin_trans('unverified') }}</option>
                    </select>
                </div>

                <!-- Guest Filter -->
                <div>
                    <label class="block text-sm font-medium text-tertiary mb-1">{{ admin_trans('user_type') }}</label>
                    <select name="guest" class="input text-sm">
                        <option value="">{{ admin_trans('all') }}</option>
                        <option value="0" {{ request('guest') === '0' ? 'selected' : '' }}>{{ admin_trans('registered') }}</option>
                        <option value="1" {{ request('guest') === '1' ? 'selected' : '' }}>{{ admin_trans('guest') }}</option>
                    </select>
                </div>

                <!-- Banned Filter -->
                <div>
                    <label class="block text-sm font-medium text-tertiary mb-1">{{ admin_trans('status') }}</label>
                    <select name="banned" class="input text-sm">
                        <option value="">{{ admin_trans('all') }}</option>
                        <option value="0" {{ request('banned') === '0' ? 'selected' : '' }}>{{ admin_trans('active') }}</option>
                        <option value="1" {{ request('banned') === '1' ? 'selected' : '' }}>{{ admin_trans('banned') }}</option>
                    </select>
                </div>

                <!-- Country Filter -->
                @if($countries->count() > 0)
                    <x-searchable-select
                        name="country_id"
                        :label="admin_trans('country')"
                        :placeholder="admin_trans('search_countries')"
                        :options="$countries->toArray()"
                        :selected="request('country_id')"
                        valueKey="id"
                        labelKey="name"
                        prefixKey="flag_emoji"
                    />
                @endif

                <!-- Language Filter -->
                @if($languages->count() > 0)
                    <x-searchable-select
                        name="language_id"
                        :label="admin_trans('language')"
                        :placeholder="admin_trans('search_languages')"
                        :options="$languages->toArray()"
                        :selected="request('language_id')"
                        valueKey="id"
                        labelKey="name"
                    />
                @endif

                <!-- Date Range Filters -->
                <div>
                    <label class="block text-sm font-medium text-tertiary mb-1">{{ admin_trans('registered_from') }}</label>
                    <input type="date" name="date_from" value="{{ request('date_from') }}" class="input text-sm">
                </div>

                <div>
                    <label class="block text-sm font-medium text-tertiary mb-1">{{ admin_trans('registered_to') }}</label>
                    <input type="date" name="date_to" value="{{ request('date_to') }}" class="input text-sm">
                </div>

                <!-- Sort Options -->
                <div>
                    <label class="block text-sm font-medium text-tertiary mb-1">{{ admin_trans('sort_by') }}</label>
                    <select name="sort" class="input text-sm">
                        <option value="created_at" {{ request('sort') === 'created_at' ? 'selected' : '' }}>{{ admin_trans('registration_date') }}</option>
                        <option value="name" {{ request('sort') === 'name' ? 'selected' : '' }}>{{ admin_trans('name') }}</option>
                        <option value="email" {{ request('sort') === 'email' ? 'selected' : '' }}>{{ admin_trans('email') }}</option>
                        <option value="updated_at" {{ request('sort') === 'updated_at' ? 'selected' : '' }}>{{ admin_trans('last_activity') }}</option>
                    </select>
                </div>

                <!-- Apply/Clear Buttons -->
                <div class="flex items-end gap-2">
                    <x-button type="submit" variant="primary" class="flex-1">
                        {{ admin_trans('apply_filters') }}
                    </x-button>
                </div>
            </form>

            <!-- Clear Filters -->
            @if(request()->hasAny(['search', 'role', 'verified', 'guest', 'banned', 'country_id', 'language_id', 'date_from', 'date_to', 'sort']))
                <div class="pt-3 border-t" style="border-color: var(--color-border);">
                    <x-button variant="outline" size="sm" icon="x-circle" href="{{ route('admin.users.index') }}">
                        {{ admin_trans('clear_all_filters') }}
                    </x-button>
                </div>
            @endif
        </div>
    </div>

    <!-- Bulk Actions -->
    <div x-show="selectedItems.length > 0" x-cloak>
        <x-alert variant="info">
            <div class="flex items-center justify-between w-full">
                <span x-text="`${selectedItems.length} {{ admin_trans('items_selected') }}`"></span>
                <div class="flex gap-2">
                    <x-button size="sm" variant="outline" @click="performBulkAction('verify')">{{ admin_trans('verify') }}</x-button>
                    <x-button size="sm" variant="outline" @click="performBulkAction('unverify')">{{ admin_trans('unverify') }}</x-button>
                    <x-button size="sm" variant="warning" @click="openBulkBanModal()">{{ admin_trans('ban') }}</x-button>
                    <x-button size="sm" variant="outline" @click="performBulkAction('unban')">{{ admin_trans('unban') }}</x-button>
                    <x-button size="sm" variant="danger" @click="performBulkAction('delete')">{{ admin_trans('delete') }}</x-button>
                    <x-button size="sm" variant="outline" @click="clearSelection()">{{ admin_trans('clear') }}</x-button>
                </div>
            </div>
        </x-alert>
    </div>

    <!-- Users Table -->
    <x-card>
        @if ($users->isEmpty())
            <x-empty-state icon="users" :title="admin_trans('no_users_yet')" :description="admin_trans('start_by_adding_first_user')">
                <x-button variant="primary" icon="plus" @click="$dispatch('open-modal', 'create-user-modal')">
                    {{ admin_trans('add_user') }}
                </x-button>
            </x-empty-state>
        @else
            <x-enhanced-table 
                :headers="[
                    'select' => ['text' => '', 'align' => 'center', 'width' => '50px'],
                    'user' => ['text' => admin_trans('user'), 'align' => 'center', 'width' => '250px'],
                    'contact' => ['text' => admin_trans('contact'), 'align' => 'center', 'width' => '200px'],
                    'role' => ['text' => admin_trans('role'), 'align' => 'center', 'width' => '100px'],
                    'location' => ['text' => admin_trans('location'), 'align' => 'center', 'width' => '150px'],
                    'verification' => ['text' => admin_trans('verification'), 'align' => 'center', 'width' => '120px'],
                    'status' => ['text' => admin_trans('status'), 'align' => 'center', 'width' => '100px'],
                    'registered' => ['text' => admin_trans('registered'), 'align' => 'center', 'width' => '120px'],
                    'actions' => ['text' => admin_trans('actions'), 'align' => 'center', 'width' => '120px']
                ]"
                :responsive="true"
                :striped="true"
            >
                @foreach ($users as $user)
                    <tr class="user-row hover:bg-primary-light transition-colors" data-id="{{ $user->id }}">

                        <!-- Select -->
                        <x-table-cell type="actions">
                            <input type="checkbox" value="{{ $user->id }}" 
                                @change="toggleItem({{ $user->id }})" 
                                :checked="selectedItems.includes({{ $user->id }})" 
                                class="checkbox">
                        </x-table-cell>

                        <!-- User -->
                        <x-table-cell type="text">
                            <div class="flex items-center gap-3">
                                <div class="w-10 h-10 rounded-xl flex items-center justify-center text-white font-bold gradient-primary text-sm">
                                    {{ substr($user->name, 0, 1) }}
                                </div>
                                <div>
                                    <div class="flex items-center gap-2">
                                        <span class="text-sm font-medium text-primary">{{ $user->name }}</span>
                                        @if($user->is_guest)
                                            <x-badge variant="secondary" class="text-xs">{{ admin_trans('guest') }}</x-badge>
                                        @endif
                                    </div>
                                    <div class="text-xs text-tertiary">ID: {{ $user->id }}</div>
                                </div>
                            </div>
                        </x-table-cell>

                        <!-- Contact -->
                        <x-table-cell type="text">
                            <div>
                                <div class="text-sm font-medium text-primary">{{ $user->email }}</div>
                                @if($user->phone)
                                    <div class="text-xs text-tertiary  gap-1">
                                        <i data-lucide="phone" class="w-3 h-3"></i>
                                        {{ $user->country_code }}{{ $user->phone }}
                                    </div>
                                @endif
                            </div>
                        </x-table-cell>

                        <!-- Role -->
                        <x-table-cell type="badge">
                            @php
                                $roleVariant = match($user->role) {
                                    'admin' => 'danger',
                                    'store_owner' => 'warning',
                                    'user' => 'info',
                                    default => 'secondary'
                                };
                            @endphp
                            <x-badge variant="{{ $roleVariant }}" class="text-xs">
                                {{ admin_trans($user->role) }}
                            </x-badge>
                        </x-table-cell>

                        <!-- Location -->
                        <x-table-cell type="text">
                            <div class="text-center">
                                @if($user->country)
                                    <div class="flex items-center justify-center gap-1 text-xs">
                                        <span class="text-tertiary">{{ $user->country->code }}</span>
                                    </div>
                                @endif
                                @if($user->language)
                                    <div class="text-xs text-tertiary mt-1">{{ $user->language->code }}</div>
                                @endif
                            </div>
                        </x-table-cell>

                        <!-- Verification -->
                        <x-table-cell type="text">
                            <div class="flex items-center justify-center gap-2">
                                <!-- Email Verification -->
                                <div class="flex items-center gap-1" title="{{ admin_trans('email_verification') }}">
                                    <i data-lucide="mail" class="w-3 h-3 {{ $user->is_verified ? 'text-green-500' : 'text-gray-400' }}"></i>
                                    @if($user->is_verified)
                                        <i data-lucide="check" class="w-3 h-3 text-green-500"></i>
                                    @else
                                        <i data-lucide="x" class="w-3 h-3 text-gray-400"></i>
                                    @endif
                                </div>

                                <!-- Phone Verification -->
                                @if($user->phone)
                                    <div class="flex items-center gap-1" title="{{ admin_trans('phone_verification') }}">
                                        <i data-lucide="smartphone" class="w-3 h-3 {{ $user->otp_verified_at ? 'text-green-500' : 'text-gray-400' }}"></i>
                                        @if($user->otp_verified_at)
                                            <i data-lucide="check" class="w-3 h-3 text-green-500"></i>
                                        @else
                                            <i data-lucide="x" class="w-3 h-3 text-gray-400"></i>
                                        @endif
                                    </div>
                                @endif
                            </div>
                        </x-table-cell>

                        <!-- Status -->
                        <x-table-cell type="badge">
                            @if($user->is_banned)
                                <x-badge variant="danger" class="text-xs">{{ admin_trans('banned') }}</x-badge>
                            @else
                                <x-badge variant="success" class="text-xs">{{ admin_trans('active') }}</x-badge>
                            @endif
                        </x-table-cell>

                        <!-- Registered -->
                        <x-table-cell type="text">
                            <div class="text-center">
                                <div class="text-xs text-tertiary">{{ $user->created_at->format('d/m/Y') }}</div>
                                <div class="text-xs text-tertiary">{{ $user->created_at->diffForHumans() }}</div>
                            </div>
                        </x-table-cell>

                        <!-- Actions -->
                        <x-table-cell type="actions">
                            <div class="flex items-center justify-center gap-2">
                                <button onclick="viewUser({{ $user->id }})" class="p-1.5 rounded-lg hover:bg-blue-50 text-blue-600" title="{{ admin_trans('view') }}">
                                    <i data-lucide="eye" class="w-4 h-4"></i>
                                </button>
                                <button onclick="editUser({{ $user->id }})" class="p-1.5 rounded-lg hover:bg-blue-50 text-blue-600" title="{{ admin_trans('edit') }}">
                                    <i data-lucide="edit-3" class="w-4 h-4"></i>
                                </button>
                                
                                @if($user->is_banned)
                                    <button onclick="unbanUser({{ $user->id }})" class="p-1.5 rounded-lg hover:bg-green-50 text-green-600" title="{{ admin_trans('unban') }}">
                                        <i data-lucide="unlock" class="w-4 h-4"></i>
                                    </button>
                                @else
                                    <button onclick="banUser({{ $user->id }})" class="p-1.5 rounded-lg hover:bg-yellow-50 text-yellow-600" title="{{ admin_trans('ban') }}">
                                        <i data-lucide="lock" class="w-4 h-4"></i>
                                    </button>
                                @endif

                                @if($user->id !== auth()->id())
                                    <button onclick="confirmDelete({{ $user->id }}, '{{ addslashes($user->name) }}')" class="p-1.5 rounded-lg hover:bg-red-50 text-red-600" title="{{ admin_trans('delete') }}">
                                        <i data-lucide="trash-2" class="w-4 h-4"></i>
                                    </button>
                                @endif
                            </div>
                        </x-table-cell>
                    </tr>
                @endforeach
            </x-enhanced-table>

            @if ($users->hasPages())
                <div class="mt-6">
                    <x-pagination :paginator="$users" />
                </div>
            @endif
        @endif
    </x-card>
</div>

<!-- Create User Modal -->
<x-modal name="create-user-modal" maxWidth="2xl">
    <div class="p-6">
        <div class="flex items-center justify-between mb-6">
            <h3 class="text-xl font-bold text-primary">{{ admin_trans('add_user') }}</h3>
            <button @click="$dispatch('close-modal', 'create-user-modal')" class="p-2 rounded-lg hover:bg-primary-light">
                <i data-lucide="x" class="w-5 h-5 text-tertiary"></i>
            </button>
        </div>

        <form method="POST" action="{{ route('admin.users.store') }}" class="space-y-6">
            @csrf
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <x-input :label="admin_trans('name')" name="name" :required="true" />
                <x-input :label="admin_trans('email')" name="email" type="email" :required="true" />
            </div>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <!-- Hidden country_code field - will be auto-filled from selected country -->
                <input type="hidden" name="country_code" value="">

                <x-input :label="admin_trans('phone')" name="phone" placeholder="1234567890" :hint="admin_trans('country_code_auto_filled_from_country')" />

                <!-- Empty div for grid alignment -->
                <div></div>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <x-input :label="admin_trans('password')" name="password" type="password" :required="true" />
                <x-input :label="admin_trans('confirm_password')" name="password_confirmation" type="password" :required="true" />
            </div>

            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                <x-select :label="admin_trans('role')" name="role" :required="true">
                    <option value="">{{ admin_trans('select_role') }}</option>
                    <option value="admin">{{ admin_trans('admin') }}</option>
                    <option value="store_owner">{{ admin_trans('store_owner') }}</option>
                    <option value="user">{{ admin_trans('user') }}</option>
                </x-select>

                <x-searchable-select
                    name="country_id"
                    :label="admin_trans('country')"
                    :placeholder="admin_trans('search_countries')"
                    :options="$countries->toArray()"
                    valueKey="id"
                    labelKey="name"
                    prefixKey="flag_emoji"
                />

                <x-select :label="admin_trans('language')" name="language_id">
                    <option value="">{{ admin_trans('select_language') }}</option>
                    @foreach($languages as $language)
                        <option value="{{ $language->id }}">{{ $language->name }}</option>
                    @endforeach
                </x-select>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <x-toggle name="is_guest" :label="admin_trans('guest_user')" />
                <x-toggle name="email_verified" :label="admin_trans('email_verified')" />
            </div>

            <div class="flex gap-3 justify-end pt-4 border-t" style="border-color: var(--color-border);">
                <x-button variant="outline" type="button" @click="$dispatch('close-modal', 'create-user-modal')">{{ admin_trans('cancel') }}</x-button>
                <x-button variant="primary" type="submit" icon="check">{{ admin_trans('create') }}</x-button>
            </div>
        </form>
    </div>
</x-modal>

<!-- Edit User Modal -->
<x-modal name="edit-user-modal" maxWidth="2xl">
    <div class="p-6" x-data="editUserModal()">
        <div class="flex items-center justify-between mb-6">
            <h3 class="text-xl font-bold text-primary">{{ admin_trans('edit_user') }}</h3>
            <button @click="$dispatch('close-modal', 'edit-user-modal')" class="p-2 rounded-lg hover:bg-primary-light">
                <i data-lucide="x" class="w-5 h-5 text-tertiary"></i>
            </button>
        </div>

        <div x-show="loading">
            <x-loading text="{{ admin_trans('loading') }}..." />
        </div>

        <div x-show="!loading && userData" x-cloak>
            <form :action="`/admin/users/${userData?.id}`" method="POST" class="space-y-6">
                @csrf @method('PUT')
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <x-input :label="admin_trans('name')" name="name" :required="true" x-bind:value="userData?.name" />
                    <x-input :label="admin_trans('email')" name="email" type="email" :required="true" x-bind:value="userData?.email" />
                </div>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <!-- Hidden country_code field - will be auto-filled from selected country -->
                    <input type="hidden" name="country_code" x-bind:value="userData?.country_code">

                    <x-input :label="admin_trans('phone')" name="phone" placeholder="1234567890" :hint="admin_trans('country_code_auto_filled_from_country')" x-bind:value="userData?.phone" />

                    <!-- Empty div for grid alignment -->
                    <div></div>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <x-input :label="admin_trans('new_password')" name="password" type="password" :hint="admin_trans('leave_empty_to_keep_current')" />
                    <x-input :label="admin_trans('confirm_password')" name="password_confirmation" type="password" />
                </div>

                <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <div>
                        <label class="block text-sm font-semibold mb-2 text-primary">{{ admin_trans('role') }} *</label>
                        <select name="role" required class="input" x-bind:value="userData?.role">
                            <option value="">{{ admin_trans('select_role') }}</option>
                            <option value="admin">{{ admin_trans('admin') }}</option>
                            <option value="store_owner">{{ admin_trans('store_owner') }}</option>
                            <option value="user">{{ admin_trans('user') }}</option>
                        </select>
                    </div>

                    <div x-data="editUserCountrySelect()">
                        <label class="block text-sm font-semibold mb-2 text-primary">{{ admin_trans('country') }}</label>

                        <!-- Hidden Input for Form -->
                        <input type="hidden" name="country_id" x-model="selectedCountry">

                        <!-- Custom Select Dropdown -->
                        <div class="relative">
                            <!-- Selected Display / Trigger -->
                            <button
                                type="button"
                                @click="open = !open"
                                @click.away="open = false"
                                class="input text-sm w-full flex items-center justify-between cursor-pointer"
                                style="padding-{{ is_rtl() ? 'left' : 'right' }}: 2.5rem;"
                            >
                                <span x-show="!selectedCountry" class="text-tertiary">{{ admin_trans('select_country') }}</span>
                                <span x-show="selectedCountry" class="flex items-center gap-2">
                                    <span x-text="getCountryPrefix()"></span>
                                    <span x-text="getCountryName()"></span>
                                </span>
                                <svg class="w-4 h-4 text-tertiary absolute {{ is_rtl() ? 'left-3' : 'right-3' }} top-1/2 -translate-y-1/2 transition-transform" :class="{ 'rotate-180': open }" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
                                </svg>
                            </button>

                            <!-- Dropdown Menu -->
                            <div
                                x-show="open"
                                x-transition:enter="transition ease-out duration-100"
                                x-transition:enter-start="opacity-0 scale-95"
                                x-transition:enter-end="opacity-100 scale-100"
                                x-transition:leave="transition ease-in duration-75"
                                x-transition:leave-start="opacity-100 scale-100"
                                x-transition:leave-end="opacity-0 scale-95"
                                class="absolute z-50 mt-2 w-full rounded-lg shadow-lg border overflow-hidden"
                                style="background: var(--color-bg-primary); border-color: var(--color-border); max-height: 300px;"
                                x-cloak
                            >
                                <!-- Search Input -->
                                <div class="p-2 border-b" style="border-color: var(--color-border);">
                                    <input
                                        type="text"
                                        x-model="search"
                                        class="input text-sm w-full"
                                        placeholder="{{ admin_trans('search_countries') }}"
                                        @click.stop
                                    >
                                </div>

                                <!-- Options List -->
                                <div class="overflow-y-auto" style="max-height: 250px;">
                                    <!-- Clear Option -->
                                    <div
                                        @click="selectCountry(null)"
                                        class="px-3 py-2 cursor-pointer transition-colors hover:bg-primary-light"
                                        :class="{ 'bg-primary-light font-medium': selectedCountry === null }"
                                    >
                                        <span class="text-sm text-tertiary">{{ admin_trans('select_country') }}</span>
                                    </div>

                                    <!-- Filtered Options -->
                                    <template x-for="country in filteredCountries()" :key="country.id">
                                        <div
                                            @click="selectCountry(country.id)"
                                            class="px-3 py-2 cursor-pointer transition-colors hover:bg-primary-light"
                                            :class="{ 'bg-primary-light font-medium': selectedCountry == country.id }"
                                        >
                                            <span class="text-sm text-primary flex items-center gap-2">
                                                <span x-text="country.flag_emoji"></span>
                                                <span x-text="country.name"></span>
                                            </span>
                                        </div>
                                    </template>

                                    <!-- No Results -->
                                    <div x-show="filteredCountries().length === 0" class="px-3 py-4 text-center">
                                        <span class="text-sm text-tertiary">{{ admin_trans('no_results_found') }}</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div>
                        <label class="block text-sm font-semibold mb-2 text-primary">{{ admin_trans('language') }}</label>
                        <select name="language_id" class="input" x-bind:value="userData?.language_id">
                            <option value="">{{ admin_trans('select_language') }}</option>
                            @foreach($languages as $language)
                                <option value="{{ $language->id }}">{{ $language->name }}</option>
                            @endforeach
                        </select>
                    </div>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <x-toggle name="is_guest" :label="admin_trans('guest_user')" x-bind:checked="userData?.is_guest" />
                    <x-toggle name="email_verified" :label="admin_trans('email_verified')" x-bind:checked="userData?.is_verified" />
                </div>

                <!-- User Info Display -->
                <div x-show="userData" class="p-4 rounded-xl border" style="border-color: var(--color-border);">
                    <div class="grid grid-cols-1 sm:grid-cols-3 gap-4 text-sm">
                        <div>
                            <span class="text-tertiary">{{ admin_trans('user_id') }}</span>
                            <p class="font-medium text-primary mt-1" x-text="userData?.id"></p>
                        </div>
                        <div>
                            <span class="text-tertiary">{{ admin_trans('registered') }}</span>
                            <p class="font-medium text-primary mt-1" x-text="formatDate(userData?.created_at)"></p>
                        </div>
                        <div>
                            <span class="text-tertiary">{{ admin_trans('last_update') }}</span>
                            <p class="font-medium text-primary mt-1" x-text="formatDate(userData?.updated_at)"></p>
                        </div>
                    </div>
                </div>

                <div class="flex gap-3 justify-end pt-4 border-t" style="border-color: var(--color-border);">
                    <x-button variant="outline" type="button" @click="$dispatch('close-modal', 'edit-user-modal')">{{ admin_trans('cancel') }}</x-button>
                    <x-button variant="primary" type="submit" icon="check">{{ admin_trans('update') }}</x-button>
                </div>
            </form>
        </div>
    </div>
</x-modal>

<!-- View User Modal -->
<x-modal name="view-user-modal" maxWidth="3xl">
    <div class="p-6" x-data="viewUserModal()">
        <div class="flex items-center justify-between mb-6">
            <h3 class="text-xl font-bold text-primary">{{ admin_trans('user_details') }}</h3>
            <button @click="$dispatch('close-modal', 'view-user-modal')" class="p-2 rounded-lg hover:bg-primary-light">
                <i data-lucide="x" class="w-5 h-5 text-tertiary"></i>
            </button>
        </div>

        <div x-show="loading">
            <x-loading text="{{ admin_trans('loading') }}..." />
        </div>

        <div x-show="!loading && userData" x-cloak class="space-y-6">
            <!-- User Header -->
            <div class="flex items-center gap-4 p-4 rounded-xl" style="background: var(--color-bg-secondary);">
                <div class="w-16 h-16 rounded-xl flex items-center justify-center text-white font-bold gradient-primary text-xl">
                    <span x-text="userData?.name?.charAt(0)"></span>
                </div>
                <div>
                    <h2 class="text-xl font-bold text-primary" x-text="userData?.name"></h2>
                    <p class="text-sm text-secondary" x-text="userData?.email"></p>
                    <div class="flex items-center gap-2 mt-1">
                        <x-badge x-bind:variant="getRoleVariant(userData?.role)" class="text-xs" x-text="userData?.role"></x-badge>
                        <span x-show="userData?.is_guest" class="text-xs text-tertiary">• {{ admin_trans('guest') }}</span>
                        <span x-show="userData?.is_banned" class="text-xs text-red-600">• {{ admin_trans('banned') }}</span>
                    </div>
                </div>
            </div>

            <!-- Quick Actions -->
            <div class="flex gap-2">
                <x-button size="sm" variant="outline" x-show="!userData?.is_verified" @click="verifyUser(userData?.id)">
                    <i data-lucide="mail-check" class="w-4 h-4"></i>
                    {{ admin_trans('verify_email') }}
                </x-button>
                <x-button size="sm" variant="outline" x-show="userData?.is_verified" @click="unverifyUser(userData?.id)">
                    <i data-lucide="mail-x" class="w-4 h-4"></i>
                    {{ admin_trans('unverify_email') }}
                </x-button>
                <x-button size="sm" variant="warning" x-show="!userData?.is_banned" @click="banUser(userData?.id)">
                    <i data-lucide="lock" class="w-4 h-4"></i>
                    {{ admin_trans('ban_user') }}
                </x-button>
                <x-button size="sm" variant="success" x-show="userData?.is_banned" @click="unbanUser(userData?.id)">
                    <i data-lucide="unlock" class="w-4 h-4"></i>
                    {{ admin_trans('unban_user') }}
                </x-button>
            </div>

            <!-- User Details Grid -->
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <!-- Contact Information -->
                <div class="p-4 rounded-xl border" style="border-color: var(--color-border);">
                    <h4 class="font-semibold text-primary mb-3">{{ admin_trans('contact_information') }}</h4>
                    <div class="space-y-2 text-sm">
                        <div class="flex justify-between">
                            <span class="text-tertiary">{{ admin_trans('email') }}:</span>
                            <span class="text-primary" x-text="userData?.email"></span>
                        </div>
                        <div class="flex justify-between" x-show="userData?.phone">
                            <span class="text-tertiary">{{ admin_trans('phone') }}:</span>
                            <span class="text-primary" x-text="`${userData?.country_code || ''}${userData?.phone || ''}`"></span>
                        </div>
                        <div class="flex justify-between" x-show="userData?.e164_number">
                            <span class="text-tertiary">{{ admin_trans('e164_format') }}:</span>
                            <span class="text-primary" x-text="userData?.e164_number"></span>
                        </div>
                    </div>
                </div>

                <!-- Account Status -->
                <div class="p-4 rounded-xl border" style="border-color: var(--color-border);">
                    <h4 class="font-semibold text-primary mb-3">{{ admin_trans('account_status') }}</h4>
                    <div class="space-y-2 text-sm">
                        <div class="flex justify-between">
                            <span class="text-tertiary">{{ admin_trans('email_verified') }}:</span>
                            <span x-text="userData?.is_verified ? '{{ admin_trans('yes') }}' : '{{ admin_trans('no') }}'" 
                                  :class="userData?.is_verified ? 'text-green-600' : 'text-red-600'"></span>
                        </div>
                        <div class="flex justify-between">
                            <span class="text-tertiary">{{ admin_trans('account_type') }}:</span>
                            <span class="text-primary" x-text="userData?.is_guest ? '{{ admin_trans('guest') }}' : '{{ admin_trans('registered') }}'"></span>
                        </div>
                        <div class="flex justify-between">
                            <span class="text-tertiary">{{ admin_trans('status') }}:</span>
                            <span x-text="userData?.is_banned ? '{{ admin_trans('banned') }}' : '{{ admin_trans('active') }}'" 
                                  :class="userData?.is_banned ? 'text-red-600' : 'text-green-600'"></span>
                        </div>
                    </div>
                </div>

                <!-- Location & Preferences -->
                <div class="p-4 rounded-xl border" style="border-color: var(--color-border);">
                    <h4 class="font-semibold text-primary mb-3">{{ admin_trans('location_preferences') }}</h4>
                    <div class="space-y-2 text-sm">
                        <div class="flex justify-between" x-show="userData?.country">
                            <span class="text-tertiary">{{ admin_trans('country') }}:</span>
                            <span class="text-primary" x-text="userData?.country?.name"></span>
                        </div>
                        <div class="flex justify-between" x-show="userData?.language">
                            <span class="text-tertiary">{{ admin_trans('language') }}:</span>
                            <span class="text-primary" x-text="userData?.language?.name"></span>
                        </div>
                    </div>
                </div>

                <!-- Activity Summary -->
                <div class="p-4 rounded-xl border" style="border-color: var(--color-border);">
                    <h4 class="font-semibold text-primary mb-3">{{ admin_trans('activity_summary') }}</h4>
                    <div class="space-y-2 text-sm">
                        <div class="flex justify-between">
                            <span class="text-tertiary">{{ admin_trans('devices_count') }}:</span>
                            <span class="text-primary" x-text="userData?.devices_count || 0"></span>
                        </div>
                        <div class="flex justify-between" x-show="userData?.providers?.length">
                            <span class="text-tertiary">{{ admin_trans('oauth_providers') }}:</span>
                            <span class="text-primary" x-text="userData?.providers?.join(', ')"></span>
                        </div>
                        <div class="flex justify-between">
                            <span class="text-tertiary">{{ admin_trans('registered') }}:</span>
                            <span class="text-primary" x-text="formatDate(userData?.created_at)"></span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Ban Information (if banned) -->
            <div x-show="userData?.is_banned && userData?.ban_info" class="p-4 rounded-xl border border-red-200 bg-red-50">
                <h4 class="font-semibold text-red-600 mb-3">{{ admin_trans('ban_information') }}</h4>
                <div class="space-y-2 text-sm">
                    <div class="flex justify-between" x-show="userData?.ban_info?.comment">
                        <span class="text-red-500">{{ admin_trans('reason') }}:</span>
                        <span class="text-red-700" x-text="userData?.ban_info?.comment"></span>
                    </div>
                    <div class="flex justify-between">
                        <span class="text-red-500">{{ admin_trans('banned_at') }}:</span>
                        <span class="text-red-700" x-text="formatDate(userData?.banned_at)"></span>
                    </div>
                    <div class="flex justify-between" x-show="userData?.ban_info?.expired_at">
                        <span class="text-red-500">{{ admin_trans('expires_at') }}:</span>
                        <span class="text-red-700" x-text="formatDate(userData?.ban_info?.expired_at)"></span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</x-modal>

<!-- Ban User Modal -->
<x-modal name="ban-user-modal" maxWidth="md">
    <div class="p-6" x-data="banUserModal()">
        <div class="flex items-center justify-between mb-6">
            <h3 class="text-xl font-bold text-primary">{{ admin_trans('ban_user') }}</h3>
            <button @click="$dispatch('close-modal', 'ban-user-modal')" class="p-2 rounded-lg hover:bg-primary-light">
                <i data-lucide="x" class="w-5 h-5 text-tertiary"></i>
            </button>
        </div>

        <form @submit.prevent="submitBan()" class="space-y-4">
            <x-textarea :label="admin_trans('ban_reason')" name="comment" rows="3" x-model="banData.comment" :placeholder="admin_trans('optional_ban_reason')" />
            
            <x-input :label="admin_trans('ban_expires_at')" name="expired_at" type="datetime-local" x-model="banData.expired_at" :hint="admin_trans('leave_empty_for_permanent_ban')" />

            <div class="flex gap-3 justify-end pt-4 border-t" style="border-color: var(--color-border);">
                <x-button variant="outline" type="button" @click="$dispatch('close-modal', 'ban-user-modal')">{{ admin_trans('cancel') }}</x-button>
                <x-button variant="danger" type="submit" icon="lock" x-bind:disabled="loading">{{ admin_trans('ban_user') }}</x-button>
            </div>
        </form>
    </div>
</x-modal>

<!-- Bulk Ban Modal -->
<x-modal name="bulk-ban-modal" maxWidth="md">
    <div class="p-6" x-data="bulkBanModal()">
        <div class="flex items-center justify-between mb-6">
            <h3 class="text-xl font-bold text-primary">{{ admin_trans('ban_selected_users') }}</h3>
            <button @click="$dispatch('close-modal', 'bulk-ban-modal')" class="p-2 rounded-lg hover:bg-primary-light">
                <i data-lucide="x" class="w-5 h-5 text-tertiary"></i>
            </button>
        </div>

        <form @submit.prevent="submitBulkBan()" class="space-y-4">
            <x-textarea :label="admin_trans('ban_reason')" name="ban_comment" rows="3" x-model="banData.comment" :placeholder="admin_trans('optional_ban_reason')" />
            
            <x-input :label="admin_trans('ban_expires_at')" name="ban_expires_at" type="datetime-local" x-model="banData.expired_at" :hint="admin_trans('leave_empty_for_permanent_ban')" />

            <div class="flex gap-3 justify-end pt-4 border-t" style="border-color: var(--color-border);">
                <x-button variant="outline" type="button" @click="$dispatch('close-modal', 'bulk-ban-modal')">{{ admin_trans('cancel') }}</x-button>
                <x-button variant="danger" type="submit" icon="lock" x-bind:disabled="loading">{{ admin_trans('ban_users') }}</x-button>
            </div>
        </form>
    </div>
</x-modal>

<!-- Delete Confirmation -->
<x-confirm-modal name="delete-user-modal" :title="admin_trans('confirm_delete')" :message="admin_trans('delete_user_message')" :confirmText="admin_trans('yes_delete')" :cancelText="admin_trans('cancel')" confirmVariant="danger" icon="trash-2" iconColor="danger" />

@endsection

@push('scripts')
<script>
function usersPage() {
    return {
        selectedItems: [],
        filtersExpanded: {{ request()->hasAny(['role', 'verified', 'guest', 'banned', 'country_id', 'language_id', 'date_from', 'date_to', 'sort']) ? 'true' : 'false' }},

        toggleItem(id) {
            const index = this.selectedItems.indexOf(id);
            if (index > -1) {
                this.selectedItems.splice(index, 1);
            } else {
                this.selectedItems.push(id);
            }
        },

        clearSelection() {
            this.selectedItems = [];
            document.querySelectorAll('input[type="checkbox"]').forEach(cb => cb.checked = false);
        },

        async performBulkAction(action) {
            if (this.selectedItems.length === 0) {
                if (window.toast) {
                    toast.warning('{{ admin_trans("please_select_items") }}');
                }
                return;
            }

            if (action === 'delete' && !confirm('{{ admin_trans("confirm_bulk_delete") }}')) return;

            try {
                const formData = new FormData();
                formData.append('_token', document.querySelector('meta[name="csrf-token"]').content);
                formData.append('action', action);
                this.selectedItems.forEach(id => formData.append('selected[]', id));

                const response = await fetch('/admin/users/bulk-action', {
                    method: 'POST',
                    body: formData
                });

                const result = await response.json();
                if (result.success) {
                    if (window.toast) {
                        toast.success(result.message);
                    }
                    setTimeout(() => window.location.reload(), 1000);
                } else {
                    if (window.toast) {
                        toast.error(result.message);
                    }
                }
            } catch (error) {
                console.error('Bulk action error:', error);
                if (window.toast) {
                    toast.error('{{ admin_trans("error_bulk_action") }}');
                }
            }
        },

        openBulkBanModal() {
            window.dispatchEvent(new CustomEvent('open-modal', { detail: 'bulk-ban-modal' }));
        }
    }
}

function editUserModal() {
    return {
        loading: false,
        userData: null,

        async loadUser(id) {
            this.loading = true;
            try {
                const response = await fetch(`/admin/users/${id}/edit`);
                const result = await response.json();
                if (result.success) {
                    this.userData = result.data;
                }
            } catch (error) {
                if (window.toast) {
                    toast.error('{{ admin_trans("error_loading_user") }}');
                }
            } finally {
                this.loading = false;
            }
        },

        formatDate(dateString) {
            if (!dateString) return '{{ admin_trans("never") }}';
            const date = new Date(dateString);
            return date.toLocaleDateString('{{ admin_locale() }}', {
                year: 'numeric',
                month: 'short',
                day: 'numeric',
                hour: '2-digit',
                minute: '2-digit'
            });
        }
    }
}

function viewUserModal() {
    return {
        loading: false,
        userData: null,

        async loadUser(id) {
            this.loading = true;
            try {
                const response = await fetch(`/admin/users/${id}/edit`);
                const result = await response.json();
                if (result.success) {
                    this.userData = result.data;
                }
            } catch (error) {
                if (window.toast) {
                    toast.error('{{ admin_trans("error_loading_user") }}');
                }
            } finally {
                this.loading = false;
            }
        },

        getRoleVariant(role) {
            const variants = {
                'admin': 'danger',
                'store_owner': 'warning',
                'shopper': 'info'
            };
            return variants[role] || 'secondary';
        },

        formatDate(dateString) {
            if (!dateString) return '{{ admin_trans("never") }}';
            const date = new Date(dateString);
            return date.toLocaleDateString('{{ admin_locale() }}', {
                year: 'numeric',
                month: 'short',
                day: 'numeric',
                hour: '2-digit',
                minute: '2-digit'
            });
        }
    }
}

function banUserModal() {
    return {
        loading: false,
        userId: null,
        banData: {
            comment: '',
            expired_at: ''
        },

        init(id) {
            this.userId = id;
        },

        async submitBan() {
            this.loading = true;
            try {
                const response = await fetch(`/admin/users/${this.userId}/ban`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
                    },
                    body: JSON.stringify(this.banData)
                });

                const result = await response.json();
                if (result.success) {
                    if (window.toast) {
                        toast.success(result.message);
                    }
                    this.$dispatch('close-modal', 'ban-user-modal');
                    setTimeout(() => window.location.reload(), 1000);
                } else {
                    if (window.toast) {
                        toast.error(result.message);
                    }
                }
            } catch (error) {
                if (window.toast) {
                    toast.error('{{ admin_trans("error_banning_user") }}');
                }
            } finally {
                this.loading = false;
            }
        }
    }
}

function bulkBanModal() {
    return {
        loading: false,
        banData: {
            comment: '',
            expired_at: ''
        },

        async submitBulkBan() {
            this.loading = true;
            try {
                const formData = new FormData();
                formData.append('_token', document.querySelector('meta[name="csrf-token"]').content);
                formData.append('action', 'ban');
                formData.append('ban_comment', this.banData.comment);
                formData.append('ban_expires_at', this.banData.expired_at);
                
                // Get selected items from parent scope
                const selectedItems = this.$root.selectedItems || [];
                selectedItems.forEach(id => formData.append('selected[]', id));

                const response = await fetch('/admin/users/bulk-action', {
                    method: 'POST',
                    body: formData
                });

                const result = await response.json();
                if (result.success) {
                    if (window.toast) {
                        toast.success(result.message);
                    }
                    this.$dispatch('close-modal', 'bulk-ban-modal');
                    setTimeout(() => window.location.reload(), 1000);
                } else {
                    if (window.toast) {
                        toast.error(result.message);
                    }
                }
            } catch (error) {
                if (window.toast) {
                    toast.error('{{ admin_trans("error_bulk_action") }}');
                }
            } finally {
                this.loading = false;
            }
        }
    }
}

function editUser(id) {
    window.dispatchEvent(new CustomEvent('open-modal', { detail: 'edit-user-modal' }));
    setTimeout(() => {
        const modal = document.querySelector('[x-data*="editUserModal"]');
        if (modal && modal._x_dataStack) {
            modal._x_dataStack[0].loadUser(id);
        }
    }, 100);
}

function viewUser(id) {
    window.dispatchEvent(new CustomEvent('open-modal', { detail: 'view-user-modal' }));
    setTimeout(() => {
        const modal = document.querySelector('[x-data*="viewUserModal"]');
        if (modal && modal._x_dataStack) {
            modal._x_dataStack[0].loadUser(id);
        }
    }, 100);
}

function banUser(id) {
    window.dispatchEvent(new CustomEvent('open-modal', { detail: 'ban-user-modal' }));
    setTimeout(() => {
        const modal = document.querySelector('[x-data*="banUserModal"]');
        if (modal && modal._x_dataStack) {
            modal._x_dataStack[0].init(id);
        }
    }, 100);
}

async function unbanUser(id) {
    if (!confirm('{{ admin_trans("confirm_unban_user") }}')) return;

    try {
        const response = await fetch(`/admin/users/${id}/unban`, {
            method: 'POST',
            headers: {
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
            }
        });

        const result = await response.json();
        if (result.success) {
            if (window.toast) {
                toast.success(result.message);
            }
            setTimeout(() => window.location.reload(), 1000);
        } else {
            if (window.toast) {
                toast.error(result.message);
            }
        }
    } catch (error) {
        if (window.toast) {
            toast.error('{{ admin_trans("error_unbanning_user") }}');
        }
    }
}

async function verifyUser(id) {
    try {
        const response = await fetch(`/admin/users/${id}/verify-email`, {
            method: 'POST',
            headers: {
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
            }
        });

        const result = await response.json();
        if (result.success) {
            if (window.toast) {
                toast.success(result.message);
            }
            setTimeout(() => window.location.reload(), 1000);
        } else {
            if (window.toast) {
                toast.error(result.message);
            }
        }
    } catch (error) {
        if (window.toast) {
            toast.error('{{ admin_trans("error_verifying_user") }}');
        }
    }
}

async function unverifyUser(id) {
    try {
        const response = await fetch(`/admin/users/${id}/unverify-email`, {
            method: 'POST',
            headers: {
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
            }
        });

        const result = await response.json();
        if (result.success) {
            if (window.toast) {
                toast.success(result.message);
            }
            setTimeout(() => window.location.reload(), 1000);
        } else {
            if (window.toast) {
                toast.error(result.message);
            }
        }
    } catch (error) {
        if (window.toast) {
            toast.error('{{ admin_trans("error_unverifying_user") }}');
        }
    }
}

function editUserCountrySelect() {
    const countries = @json($countries->toArray());

    return {
        open: false,
        search: '',
        selectedCountry: null,
        countries: countries,

        init() {
            // Watch parent's userData and sync selectedCountry
            this.$watch('userData', (newUserData) => {
                if (newUserData && newUserData.country_id) {
                    this.selectedCountry = newUserData.country_id;
                }
            });
        },

        filteredCountries() {
            const searchLower = this.search.toLowerCase().trim();
            if (!searchLower) return this.countries;
            return this.countries.filter(country =>
                country.name.toLowerCase().includes(searchLower)
            );
        },

        selectCountry(countryId) {
            this.selectedCountry = countryId;
            this.open = false;
            this.search = '';
        },

        getCountryName() {
            if (!this.selectedCountry) return '';
            const country = this.countries.find(c => c.id == this.selectedCountry);
            return country ? country.name : '';
        },

        getCountryPrefix() {
            if (!this.selectedCountry) return '';
            const country = this.countries.find(c => c.id == this.selectedCountry);
            return country ? country.flag_emoji : '';
        }
    };
}

function confirmDelete(id, name) {
    window.addEventListener('confirm-action', function handler(e) {
        if (e.detail === 'delete-user-modal') {
            const form = document.createElement('form');
            form.method = 'POST';
            form.action = `/admin/users/${id}`;
            form.innerHTML = '@csrf @method("DELETE")';
            document.body.appendChild(form);
            form.submit();
            window.removeEventListener('confirm-action', handler);
        }
    });
    window.dispatchEvent(new CustomEvent('open-modal', { detail: 'delete-user-modal' }));
}

document.addEventListener('DOMContentLoaded', function() {
    if (typeof lucide !== 'undefined') {
        lucide.createIcons();
    }
});
</script>
@endpush