{{-- resources/views/admin/stores/index.blade.php - Ø§Ù„Ù†Ø³Ø®Ø© Ø§Ù„Ù…Ø­Ø³Ù†Ø© Ø¨Ø¯ÙˆÙ† ØªØ¶Ø§Ø±Ø¨ --}}

@extends('admin.layouts.app')

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

@section('content')

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

    <!-- Header: Search & Add Button -->
    <div class="card">
        <div class="flex flex-col sm:flex-row gap-4 items-start sm:items-center justify-between">
            
            <!-- Search -->
            <div class="flex-1 w-full max-w-lg">
                <form method="GET" action="{{ route('admin.stores.index') }}">
                    @if(request('locale_id'))<input type="hidden" name="locale_id" value="{{ request('locale_id') }}">@endif
                    @if(request('status'))<input type="hidden" name="status" value="{{ request('status') }}">@endif
                    @if(request('featured'))<input type="hidden" name="featured" value="{{ request('featured') }}">@endif
                    
                    <x-search-input 
                        name="search" 
                        :value="request('search')" 
                        :placeholder="admin_trans('search_stores')" 
                        class="w-full"
                    />
                </form>
            </div>

             <!-- Filters Row -->
            <div class="flex flex-wrap items-center gap-4">
                
                <!-- Language Filter -->
                @if($currentCountry && $availableLocales->count() > 1)
                    <form method="GET" action="{{ route('admin.stores.index') }}" class="flex items-center gap-2">
                        @if(request('search'))<input type="hidden" name="search" value="{{ request('search') }}">@endif
                        @if(request('status'))<input type="hidden" name="status" value="{{ request('status') }}">@endif
                        @if(request('featured'))<input type="hidden" name="featured" value="{{ request('featured') }}">@endif
                        
                        <label class="text-sm font-medium text-tertiary">{{ admin_trans('language') }}:</label>
                        <select name="locale_id" onchange="this.form.submit()" class="input text-sm py-2 px-3">
                            <option value="">{{ admin_trans('all_languages') }}</option>
                            @foreach($availableLocales as $locale)
                                <option value="{{ $locale->id }}" {{ request('locale_id') == $locale->id ? 'selected' : '' }}>
                                    {{ $locale->language->name ?? $locale->name }}
                                </option>
                            @endforeach
                        </select>
                    </form>
                @endif

                <!-- Status Filter -->
                <form method="GET" action="{{ route('admin.stores.index') }}" class="flex items-center gap-2">
                    @if(request('search'))<input type="hidden" name="search" value="{{ request('search') }}">@endif
                    @if(request('locale_id'))<input type="hidden" name="locale_id" value="{{ request('locale_id') }}">@endif
                    @if(request('featured'))<input type="hidden" name="featured" value="{{ request('featured') }}">@endif
                    
                    <label class="text-sm font-medium text-tertiary">{{ admin_trans('status') }}:</label>
                    <select name="status" onchange="this.form.submit()" class="input text-sm py-2 px-3">
                        <option value="">{{ admin_trans('all_statuses') }}</option>
                        <option value="active" {{ request('status') === 'active' ? 'selected' : '' }}>{{ admin_trans('active') }}</option>
                        <option value="draft" {{ request('status') === 'draft' ? 'selected' : '' }}>{{ admin_trans('draft') }}</option>
                    </select>
                </form>

                <!-- Featured Filter -->
                <form method="GET" action="{{ route('admin.stores.index') }}" class="flex items-center gap-2">
                    @if(request('search'))<input type="hidden" name="search" value="{{ request('search') }}">@endif
                    @if(request('locale_id'))<input type="hidden" name="locale_id" value="{{ request('locale_id') }}">@endif
                    @if(request('status'))<input type="hidden" name="status" value="{{ request('status') }}">@endif
                    
                    <label class="text-sm font-medium text-tertiary">{{ admin_trans('featured') }}:</label>
                    <select name="featured" onchange="this.form.submit()" class="input text-sm py-2 px-3">
                        <option value="">{{ admin_trans('all') }}</option>
                        <option value="1" {{ request('featured') === '1' ? 'selected' : '' }}>{{ admin_trans('featured') }}</option>
                        <option value="0" {{ request('featured') === '0' ? 'selected' : '' }}>{{ admin_trans('not_featured') }}</option>
                    </select>
                </form>

                <!-- Clear Filters -->
                @if(request()->hasAny(['search', 'locale_id', 'status', 'featured']))
                    <x-button variant="outline" size="sm" icon="x-circle" href="{{ route('admin.stores.index') }}">
                        {{ admin_trans('clear_filters') }}
                    </x-button>
                @endif
            </div>

            <!-- Add Button -->
            <x-button variant="primary" icon="plus" @click="$dispatch('open-modal', 'create-store-modal')">
                {{ admin_trans('add_store') }}
            </x-button>
        </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('activate')">{{ admin_trans('activate') }}</x-button>
                    <x-button size="sm" variant="outline" @click="performBulkAction('deactivate')">{{ admin_trans('deactivate') }}</x-button>
                    <x-button size="sm" variant="outline" @click="performBulkAction('feature')">{{ admin_trans('feature') }}</x-button>
                    <x-button size="sm" variant="outline" @click="performBulkAction('unfeature')">{{ admin_trans('unfeature') }}</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>

    <!-- Stores Table -->
    <x-card>
        @if ($stores->isEmpty())
            @if($currentCountry)
                <x-empty-state icon="store" :title="admin_trans('no_stores_yet')" :description="admin_trans('start_by_adding_first_store')">
                    <x-button variant="primary" icon="plus" @click="$dispatch('open-modal', 'create-store-modal')">
                        {{ admin_trans('add_store') }}
                    </x-button>
                </x-empty-state>
            @else
                <x-empty-state icon="globe" :title="admin_trans('select_country_first')" :description="admin_trans('select_country_to_manage_stores')">
                    <p class="text-sm text-tertiary mt-2">{{ admin_trans('use_country_filter_navbar') }}</p>
                </x-empty-state>
            @endif
        @else
            <x-enhanced-table 
                :headers="[
                    'select' => ['text' => '', 'align' => 'center', 'width' => '50px'],
                    'order' => ['text' => admin_trans('order'), 'align' => 'center', 'width' => '80px'],
                    'logo' => ['text' => admin_trans('logo'), 'align' => 'center', 'width' => '60px'],
                    'name' => ['text' => admin_trans('name'), 'align' => 'left', 'width' => '200px'],
                    'owner' => ['text' => admin_trans('owner'), 'align' => 'left', 'width' => '150px'],
                    'languages' => ['text' => admin_trans('languages'), 'align' => 'center', 'width' => '120px'],
                    'stats' => ['text' => admin_trans('stats'), 'align' => 'center', 'width' => '150px'],
                    'featured' => ['text' => admin_trans('featured'), 'align' => 'center', 'width' => '80px'],
                    'status' => ['text' => admin_trans('status'), 'align' => 'center', 'width' => '80px'],
                    'actions' => ['text' => admin_trans('actions'), 'align' => 'center', 'width' => '100px']
                ]"
                :responsive="true"
                :striped="true"
            >
                @foreach ($stores as $store)
                    @php
                        $countryStore = $currentCountry 
                            ? $store->countryStores->where('country_id', $currentCountry->id)->first() 
                            : $store->countryStores->first();
                        
                        $translation = $store->translations->first();
                    @endphp
                    <tr class="store-row hover:bg-primary-light transition-colors" data-id="{{ $countryStore->id ?? $store->id }}">

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

                        <!-- Order -->
                        <x-table-cell type="number">
                            <div class="flex items-center justify-center gap-2">
                                <button class="drag-handle cursor-move p-1 rounded hover:bg-primary-light">
                                    <i data-lucide="grip-vertical" class="w-3 h-3 text-tertiary"></i>
                                </button>
                                <span class="text-sm font-medium text-tertiary">{{ $countryStore->order ?? 0 }}</span>
                            </div>
                        </x-table-cell>

                        <!-- Logo -->
                        <x-table-cell type="actions">
                            @if ($store->getFirstMediaUrl('logo'))
                                <img src="{{ $store->getFirstMediaUrl('logo') }}" alt="Logo" class="w-8 h-8 object-cover rounded-lg border mx-auto">
                            @else
                                <div class="w-8 h-8 bg-gray-200 rounded-lg border flex items-center justify-center mx-auto">
                                    <i data-lucide="store" class="w-4 h-4 text-gray-400"></i>
                                </div>
                            @endif
                        </x-table-cell>

                        <!-- Name -->
                        <x-table-cell type="text">
                            <div>
                                <span class="text-sm font-medium text-primary">
                                    {{ $translation->name ?? 'Store #' . $store->id }}
                                </span>
                                @if ($translation && $translation->description)
                                    <div class="text-xs text-tertiary mt-1">
                                        {{ Str::limit(strip_tags($translation->description), 50) }}
                                    </div>
                                @endif
                            </div>
                        </x-table-cell>

                        <!-- Owner -->
                        <x-table-cell type="text">
                                <div>
                                    <div class="text-sm font-medium text-primary">{{ $store->user->name ?? 'N/A' }}</div>
                                    <div class="text-xs text-tertiary">{{ $store->user->email ?? '' }}</div>
                                </div>
                        </x-table-cell>

                        <!-- Languages -->
                        <x-table-cell type="badge">
                            <div class="flex items-center justify-center gap-1 flex-wrap">
                                @foreach($store->translations->take(3) as $trans)
                                    <x-badge variant="info" class="text-xs">
                                        {{ $trans->locale->code ?? 'N/A' }}
                                    </x-badge>
                                @endforeach
                                @if($store->translations->count() > 3)
                                    <x-badge variant="secondary" class="text-xs">
                                        +{{ $store->translations->count() - 3 }}
                                    </x-badge>
                                @endif
                            </div>
                        </x-table-cell>

                        <!-- Stats -->
                        <x-table-cell type="text">
                            @if($countryStore && $countryStore->stats)
                                <div class="flex items-center justify-center gap-3 text-xs">
                                    <div class="flex items-center gap-1" title="{{ admin_trans('followers') }}">
                                        <i data-lucide="users" class="w-3 h-3 text-primary"></i>
                                        <span class="text-tertiary">{{ $countryStore->stats->followers_count ?? 0 }}</span>
                                    </div>
                                    <div class="flex items-center gap-1" title="{{ admin_trans('views') }}">
                                        <i data-lucide="eye" class="w-3 h-3 text-secondary"></i>
                                        <span class="text-tertiary">{{ $countryStore->stats->views_count ?? 0 }}</span>
                                    </div>
                                    <div class="flex items-center gap-1" title="{{ admin_trans('uses') }}">
                                        <i data-lucide="shopping-cart" class="w-3 h-3 text-success"></i>
                                        <span class="text-tertiary">{{ $countryStore->stats->uses_count ?? 0 }}</span>
                                    </div>
                                </div>
                            @else
                                <span class="text-xs text-tertiary">-</span>
                            @endif
                        </x-table-cell>

                        <!-- Featured -->
                        <x-table-cell type="actions">
                            @if($countryStore)
                                <form method="POST" action="{{ route('admin.stores.toggle-featured', $store) }}">
                                    @csrf @method('PATCH')
                                    <button type="submit" class="p-1 rounded-lg transition-colors {{ $countryStore->is_featured ? 'text-yellow-500 hover:bg-yellow-50' : 'text-gray-400 hover:bg-gray-50' }}">
                                        <i data-lucide="star" class="w-4 h-4 {{ $countryStore->is_featured ? 'fill-current' : '' }}"></i>
                                    </button>
                                </form>
                            @endif
                        </x-table-cell>

                        <!-- Status -->
                        <x-table-cell type="actions">
                            @if($countryStore)
                                <form method="POST" action="{{ route('admin.stores.toggle-status', $store) }}">
                                    @csrf @method('PATCH')
                                    <x-toggle name="status_toggle_{{ $store->id }}" :checked="$countryStore->status === 'active'" size="sm" variant="success" onchange="this.form.submit()" />
                                </form>
                            @endif
                        </x-table-cell>

                        <!-- Actions -->
                        <x-table-cell type="actions">
                            <div class="flex items-center justify-center gap-3">
                                <button onclick="editStore({{ $store->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>
                                <button onclick="viewStats({{ $store->id }})" class="p-1.5 rounded-lg hover:bg-purple-50 text-purple-600" title="{{ admin_trans('view_stats') }}">
                                    <i data-lucide="bar-chart-3" class="w-4 h-4"></i>
                                </button>
                                <button onclick="confirmDelete({{ $store->id }}, '{{ addslashes($translation->name ?? 'Store #' . $store->id) }}')" 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>
                            </div>
                        </x-table-cell>
                    </tr>
                @endforeach
            </x-enhanced-table>

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

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

@if($currentCountry && $availableLocales->count() > 0)
    <form method="POST" action="{{ route('admin.stores.store') }}" enctype="multipart/form-data" class="space-y-6">
        @csrf
        <input type="hidden" name="countries[]" value="{{ $currentCountry->id }}">

        <x-alert variant="info" icon="info">
            <div class="flex items-center gap-3">
                <span class="text-2xl mb-2">{{ $currentCountry->flag_emoji }}</span>
                <div>
                    <h4 class="font-semibold">{{ admin_trans('creating_store_for') }}</h4>
                    <p class="text-sm opacity-75">{{ $currentCountry->getName() }}</p>
                </div>
            </div>
        </x-alert>

        @php
            $usersArray = $users->map(function($user) {
                return [
                    'id' => $user->id,
                    'name' => $user->name . ' (' . $user->email . ')'
                ];
            })->toArray();
        @endphp
        <x-searchable-select
            name="user_id"
            :label="admin_trans('store_owner')"
            :placeholder="admin_trans('search_users')"
            :options="$usersArray"
            :selected="old('user_id')"
            :required="true"
            valueKey="id"
            labelKey="name"
        />

        {{-- Multi-language Content Tabs --}}
        <x-tabs defaultTab="{{ $availableLocales->first()->id }}">
            <div class="flex flex-wrap gap-2 border-b mb-6" style="border-color: var(--color-border);">
                @foreach($availableLocales as $locale)
                    <button type="button" 
                        @click="activeTab = '{{ $locale->id }}'; $event.preventDefault();" 
                        :class="activeTab === '{{ $locale->id }}' ? 'text-primary bg-primary-light' : 'text-tertiary hover:text-primary'"
                        class="flex items-center gap-2 px-4 py-2 border-b transition-colors font-medium">
                        <i data-lucide="globe" class="w-4 h-4"></i>
                        {{ $locale->language->name ?? $locale->name }}
                        @if($locale->direction === 'rtl')
                            <span class="text-xs">(Ø¹)</span>
                        @endif
                    </button>
                @endforeach
            </div>

            @foreach($availableLocales as $locale)
                <x-tab-content :tab="$locale->id">
                    <div class="space-y-6" @if($locale->direction === 'rtl') dir="rtl" @endif>
                        <x-input
                            :label="admin_trans('store_name')"
                            name="translations[{{ $locale->id }}][name]"
                            placeholder="{{ admin_trans('enter_store_name') }}"
                            :required="$loop->first"
                            value="{{ old('translations.' . $locale->id . '.name') }}"
                        />

                        <x-tinymce
                            name="translations[{{ $locale->id }}][description]"
                            :height="200"
                            placeholder="{{ admin_trans('enter_description') }}"
                            :value="old('translations.' . $locale->id . '.description')"
                            :required="false"
                            :locale="$locale->code"
                            :direction="$locale->direction"
                            :language="$locale->direction === 'rtl' ? 'ar' : 'en'"
                        >
                       <span style="color: var(--color-text-primary) ; " class="text-sm"> {{ admin_trans('description') }} </span>
                        </x-tinymce>

                        <x-input
                            :label="admin_trans('home_url')"
                            name="translations[{{ $locale->id }}][home_url]"
                            type="url"
                            placeholder="https://example.com"
                            value="{{ old('translations.' . $locale->id . '.home_url') }}"
                        />

                        <x-input
                            :label="admin_trans('final_url')"
                            name="translations[{{ $locale->id }}][final_url]"
                            type="url"
                            placeholder="https://example.com/tracking"
                            value="{{ old('translations.' . $locale->id . '.final_url') }}"
                        />
                    </div>
                </x-tab-content>
            @endforeach
        </x-tabs>
         <!-- Categories Selection -->
                <div x-data="{ categorySearch: '' }">
                    <label class="block text-sm font-semibold mb-2 text-primary">{{ admin_trans('categories') }}</label>

                    <!-- Search Input -->
                    <input
                        type="text"
                        x-model="categorySearch"
                        placeholder="{{ admin_trans('search_categories') }}"
                        class="input text-sm w-full mb-3"
                        style="padding-{{ is_rtl() ? 'right' : 'left' }}: 2.5rem;"
                    >
                    <div class="relative mb-3">
                        <svg class="w-4 h-4 text-tertiary absolute {{ is_rtl() ? 'right-3' : 'left-3' }} top-1/2 transform -translate-y-1/2 pointer-events-none"
                            style="top: -2.25rem;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/>
                        </svg>
                    </div>

                    <div class="grid grid-cols-2 sm:grid-cols-3 gap-3 p-4 rounded-xl border max-h-64 overflow-y-auto" style="background: var(--color-bg-secondary); border-color: var(--color-border);">
                        @foreach($categories as $category)
                            @php
                                $categoryTranslation = $category->translations->first();
                                $categoryName = $categoryTranslation->name ?? 'Category #' . $category->id;
                            @endphp
                            <label
                                class="flex items-center gap-2 p-2 rounded-lg hover:bg-primary-light cursor-pointer"
                                x-show="categorySearch === '' || '{{ strtolower($categoryName) }}'.includes(categorySearch.toLowerCase())"
                            >
                                <input type="checkbox" name="categories[]" value="{{ $category->id }}" class="checkbox">
                                <span class="text-sm text-primary">{{ $categoryName }}</span>
                            </label>
                        @endforeach
                    </div>
                </div>
        <x-file-upload :label="admin_trans('store_logo')" name="logo" accept="image/*" maxSize="2MB" />

        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <x-input :label="admin_trans('order')" name="order" type="number" value="{{ old('order', 0) }}" />
            <x-select :label="admin_trans('status')" name="status" :required="true">
                <option value="draft" {{ old('status') === 'draft' ? 'selected' : '' }}>{{ admin_trans('draft') }}</option>
                <option value="active" {{ old('status', 'active') === 'active' ? 'selected' : '' }}>{{ admin_trans('active') }}</option>
            </x-select>
        </div>

        <x-toggle name="is_featured" :label="admin_trans('featured_store')" value="1" :checked="old('is_featured')" />

        <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-store-modal')">{{ admin_trans('cancel') }}</x-button>
            <x-button variant="primary" type="submit" icon="check">{{ admin_trans('create') }}</x-button>
        </div>
    </form>
@else
    <x-empty-state icon="globe" :title="admin_trans('select_country_first')" :description="admin_trans('use_country_filter_navbar')">
        <x-button variant="outline" @click="$dispatch('close-modal', 'create-store-modal')">{{ admin_trans('close') }}</x-button>
    </x-empty-state>
@endif

    </div>
</x-modal>

<!-- Edit Modal -->
<x-modal name="edit-store-modal" maxWidth="3xl">
    <div class="p-6" x-data="editStoreModal()">
        <div class="flex items-center justify-between mb-6">
            <h3 class="text-xl font-bold text-primary">{{ admin_trans('edit_store') }}</h3>
            <button @click="$dispatch('close-modal', 'edit-store-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 && storeData" x-cloak>
            <form :action="`/admin/stores/${storeData?.id}`" method="POST" enctype="multipart/form-data" class="space-y-6">
                @csrf @method('PUT')
                
                <input type="hidden" name="countries[]" value="{{ $currentCountry->id ?? '' }}">
                
                <!-- Owner Selection -->
                <div
                    x-data="editStoreUserSelect()"
                >
                    <label class="block text-sm font-semibold mb-2 text-primary">{{ admin_trans('store_owner') }} *</label>

                    <!-- Hidden Input for Form -->
                    <input type="hidden" name="user_id" x-model="selectedUser" required>

                    <!-- 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="!selectedUser" class="text-tertiary">{{ admin_trans('select_owner') }}</span>
                            <span x-show="selectedUser" class="flex items-center gap-2">
                                <span x-text="getUserName()"></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_users') }}"
                                    @click.stop
                                >
                            </div>

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

                                <!-- Filtered Options -->
                                <template x-for="user in filteredUsers()" :key="user.id">
                                    <div
                                        @click="selectUser(user.id)"
                                        class="px-3 py-2 cursor-pointer transition-colors hover:bg-primary-light"
                                        :class="{ 'bg-primary-light font-medium': selectedUser == user.id }"
                                    >
                                        <span class="text-sm text-primary" x-text="user.name + ' (' + user.email + ')'"></span>
                                    </div>
                                </template>

                                <!-- No Results -->
                                <div x-show="filteredUsers().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>
                
             @if($availableLocales->count() > 0)
    <x-tabs defaultTab="{{ $availableLocales->first()->id }}">
        <div class="flex flex-wrap gap-2 border-b mb-4" style="border-color: var(--color-border);">
            @foreach($availableLocales as $locale)
                <button type="button" 
                    @click="activeTab = '{{ $locale->id }}'; $event.preventDefault();" 
                    :class="activeTab === '{{ $locale->id }}' ? 'text-primary bg-primary-light' : 'text-tertiary hover:text-primary'" 
                    class="flex items-center gap-2 px-4 py-2 border-b transition-colors font-medium">
                    <i data-lucide="globe" class="w-4 h-4"></i>
                    {{ $locale->language->name ?? $locale->name }}
                    @if($locale->direction === 'rtl')
                        <span class="text-xs">(Ø¹)</span>
                    @endif
                </button>
            @endforeach
        </div>

        @foreach($availableLocales as $locale)
            @php
                $translation = isset($store) ? $store->translations->where('locale_id', $locale->id)->first() : null;
                $isRTL = $locale->direction === 'rtl';
            @endphp
            <x-tab-content :tab="$locale->id">
                <div class="space-y-4" @if($isRTL) dir="rtl" @endif>
                    <x-input
                        :label="admin_trans('store_name')"
                        :name="'translations[' . $locale->id . '][name]'"
                        placeholder="{{ admin_trans('enter_store_name') }}"
                        :required="$loop->first"
                        value="{{ old('translations.' . $locale->id . '.name', $translation ? $translation->name : '') }}"
                    />

                    <x-tinymce
                        name="translations[{{ $locale->id }}][description]"
                        :height="200"
                        placeholder="{{ admin_trans('enter_description') }}"
                        :value="old('translations.' . $locale->id . '.description', $translation ? $translation->description : '')"
                        :required="false"
                        :locale="$locale->code"
                        :direction="$locale->direction"
                        :language="$locale->direction === 'rtl' ? 'ar' : 'en'"
                    >
                       <span style="color: var(--color-text-primary) ; " class="text-sm"> {{ admin_trans('description') }} </span>
                    </x-tinymce>

                    <x-input
                        :label="admin_trans('home_url')"
                        :name="'translations[' . $locale->id . '][home_url]'"
                        type="url"
                        placeholder="https://example.com"
                        value="{{ old('translations.' . $locale->id . '.home_url', $translation ? $translation->home_url : '') }}"
                    />

                    <x-input
                        :label="admin_trans('final_url')"
                        :name="'translations[' . $locale->id . '][final_url]'"
                        type="url"
                        placeholder="https://example.com/tracking"
                        value="{{ old('translations.' . $locale->id . '.final_url', $translation ? $translation->final_url : '') }}"
                    />
                </div>
            </x-tab-content>
        @endforeach
    </x-tabs>
@endif
   <!-- Categories Selection -->
                <div x-data="{ categorySearch: '' }">
                    <label class="block text-sm font-semibold mb-2 text-primary">{{ admin_trans('categories') }}</label>

                    <!-- Search Input -->
                    <input
                        type="text"
                        x-model="categorySearch"
                        placeholder="{{ admin_trans('search_categories') }}"
                        class="input text-sm w-full mb-3"
                        style="padding-{{ is_rtl() ? 'right' : 'left' }}: 2.5rem;"
                    >
                    <div class="relative mb-3">
                        <svg class="w-4 h-4 text-tertiary absolute {{ is_rtl() ? 'right-3' : 'left-3' }} top-1/2 transform -translate-y-1/2 pointer-events-none"
                            style="top: -2.25rem;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/>
                        </svg>
                    </div>

                    <div class="grid grid-cols-2 sm:grid-cols-3 gap-3 p-4 rounded-xl border max-h-64 overflow-y-auto" style="background: var(--color-bg-secondary); border-color: var(--color-border);">
                        @foreach($categories as $category)
                            @php
                                $categoryTranslation = $category->translations->first();
                                $categoryName = $categoryTranslation->name ?? 'Category #' . $category->id;
                            @endphp
                            <label
                                class="flex items-center gap-2 p-2 rounded-lg hover:bg-primary-light cursor-pointer"
                                x-show="categorySearch === '' || '{{ strtolower($categoryName) }}'.includes(categorySearch.toLowerCase())"
                            >
                                <input type="checkbox" name="categories[]" value="{{ $category->id }}" class="checkbox"
                                    x-bind:checked="storeData?.categories?.includes({{ $category->id }})"
                                    @change="toggleCategory({{ $category->id }}, $event.target.checked)">
                                <span class="text-sm text-primary">{{ $categoryName }}</span>
                            </label>
                        @endforeach
                    </div>
                </div>        <!-- Logo Upload -->
                <div>
                    <x-file-upload :label="admin_trans('store_logo')" name="logo" accept="image/*" maxSize="2MB" />
                    <div x-show="storeData?.logo_url" class="mt-2">
                        <img :src="storeData?.logo_url" alt="Logo" class="w-16 h-16 object-cover rounded-lg border">
                    </div>
                </div>

                <!-- Settings -->
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <label class="block text-sm font-semibold mb-2 text-primary">{{ admin_trans('order') }}</label>
                        <input 
                            type="number" 
                            name="order" 
                            class="input"
                            x-bind:value="storeData?.order || 0"
                            @input="storeData.order = $event.target.value"
                        />
                    </div>
                    <div>
                        <label class="block text-sm font-semibold mb-2 text-primary">{{ admin_trans('status') }} *</label>
                        <select 
                            name="status" 
                            required 
                            class="input"
                            x-bind:value="storeData?.status"
                            @change="storeData.status = $event.target.value"
                        >
                            <option value="">{{ admin_trans('select_status') }}</option>
                            <option value="draft">{{ admin_trans('draft') }}</option>
                            <option value="active">{{ admin_trans('active') }}</option>
                        </select>
                    </div>
                </div>

                <div class="flex items-center gap-3">
                    <input 
                        type="checkbox" 
                        name="is_featured" 
                        value="1"
                        class="checkbox"
                        x-bind:checked="storeData?.is_featured"
                        @change="storeData.is_featured = $event.target.checked"
                    >
                    <label class="text-sm font-medium text-primary">
                        {{ admin_trans('featured_store') }}
                    </label>
                </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-store-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>

<!-- Stats Modal -->
<x-modal name="stats-modal" maxWidth="2xl">
    <div class="p-6" x-data="statsModal()">
        <div class="flex items-center justify-between mb-6">
            <h3 class="text-xl font-bold text-primary">{{ admin_trans('store_statistics') }}</h3>
            <button @click="$dispatch('close-modal', 'stats-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_stats') }}..." />
        </div>

        <div x-show="!loading && stats" x-cloak class="space-y-4">
            <div class="grid grid-cols-2 sm:grid-cols-4 gap-4">
                <div class="p-4 rounded-xl" style="background: var(--color-primary-light);">
                    <div class="flex items-center gap-2 mb-2">
                        <i data-lucide="users" class="w-5 h-5 text-primary"></i>
                        <span class="text-sm font-medium text-primary">{{ admin_trans('followers') }}</span>
                    </div>
                    <p class="text-2xl font-bold text-primary" x-text="stats?.followers_count || 0"></p>
                </div>

                <div class="p-4 rounded-xl" style="background: var(--color-secondary-light);">
                    <div class="flex items-center gap-2 mb-2">
                        <i data-lucide="eye" class="w-5 h-5 text-secondary"></i>
                        <span class="text-sm font-medium text-secondary">{{ admin_trans('views') }}</span>
                    </div>
                    <p class="text-2xl font-bold text-secondary" x-text="stats?.views_count || 0"></p>
                </div>

                <div class="p-4 rounded-xl" style="background: var(--color-success-50);">
                    <div class="flex items-center gap-2 mb-2">
                        <i data-lucide="shopping-cart" class="w-5 h-5" style="color: var(--color-success-500);"></i>
                        <span class="text-sm font-medium" style="color: var(--color-success-500);">{{ admin_trans('uses') }}</span>
                    </div>
                    <p class="text-2xl font-bold" style="color: var(--color-success-500);" x-text="stats?.uses_count || 0"></p>
                </div>

                <div class="p-4 rounded-xl" style="background: var(--color-info-50);">
                    <div class="flex items-center gap-2 mb-2">
                        <i data-lucide="zap" class="w-5 h-5" style="color: var(--color-info-500);"></i>
                        <span class="text-sm font-medium" style="color: var(--color-info-500);">{{ admin_trans('impressions') }}</span>
                    </div>
                    <p class="text-2xl font-bold" style="color: var(--color-info-500);" x-text="stats?.impressions_count || 0"></p>
                </div>
            </div>

            <div class="grid grid-cols-1 sm:grid-cols-3 gap-4">
                <div class="p-4 rounded-xl border" style="border-color: var(--color-border);">
                    <span class="text-sm text-tertiary">{{ admin_trans('popularity_score') }}</span>
                    <p class="text-xl font-bold text-primary mt-1" x-text="stats?.popularity || 0"></p>
                </div>

                <div class="p-4 rounded-xl border" style="border-color: var(--color-border);">
                    <span class="text-sm text-tertiary">{{ admin_trans('max_discount') }}</span>
                    <p class="text-xl font-bold text-primary mt-1"><span x-text="stats?.max_discount || 0"></span>%</p>
                </div>

                <div class="p-4 rounded-xl border" style="border-color: var(--color-border);">
                    <span class="text-sm text-tertiary">{{ admin_trans('avg_discount') }}</span>
                    <p class="text-xl font-bold text-primary mt-1"><span x-text="stats?.avg_discount || 0"></span>%</p>
                </div>
            </div>

            <div class="p-4 rounded-xl border" style="border-color: var(--color-border);">
                <div class="flex items-center justify-between">
                    <div>
                        <span class="text-sm text-tertiary">{{ admin_trans('last_offer_added') }}</span>
                        <p class="text-sm font-medium text-primary mt-1" x-text="stats?.last_offer_added_at ? formatDate(stats.last_offer_added_at) : '{{ admin_trans('never') }}'"></p>
                    </div>
                    <div>
                        <span class="text-sm text-tertiary">{{ admin_trans('last_usage') }}</span>
                        <p class="text-sm font-medium text-primary mt-1" x-text="stats?.last_usage ? formatDate(stats.last_usage) : '{{ admin_trans('never') }}'"></p>
                    </div>
                </div>
            </div>
        </div>

        <div x-show="!loading && !stats" x-cloak>
            <x-empty-state icon="bar-chart-3" :title="admin_trans('no_stats_available')" :description="admin_trans('stats_will_appear_here')" />
        </div>
    </div>
</x-modal>

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

@endsection

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.min.js"></script>
<script>
function storesPage() {
    return {
        selectedItems: [],

        init() {
            try {
                this.listenToCountryFilter();
                this.$nextTick(() => {
                    this.initSortable();
                });
            } catch (error) {
                console.log('Init error (safely handled):', error);
                this.$nextTick(() => {
                    this.initSortable();
                });
            }
        },

        listenToCountryFilter() {
            window.addEventListener('country-filter-changed', () => {
                if (window.toast) {
                    toast.info('{{ admin_trans("refreshing_stores") }}...');
                }
                setTimeout(() => window.location.reload(), 500);
            });
        },

        initSortable() {
            const tableBody = document.querySelector('.store-row')?.parentElement;
            if (tableBody) {
                new Sortable(tableBody, {
                    handle: '.drag-handle',
                    animation: 150,
                    onEnd: async (evt) => {
                        const rows = Array.from(tableBody.children);
                        const orders = rows.map(row => parseInt(row.dataset.id));

                        rows.forEach((row, index) => {
                            const orderSpan = row.querySelector('.text-sm.font-medium.text-tertiary');
                            if (orderSpan) {
                                orderSpan.textContent = index;
                            }
                        });

                        try {
                            const response = await fetch('/admin/stores/update-order', {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/json',
                                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
                                },
                                body: JSON.stringify({ orders })
                            });

                            const result = await response.json();
                            
                            if (result.success) {
                                if (window.toast) {
                                    toast.success('{{ admin_trans("order_updated_successfully") }}');
                                }
                            } else {
                                console.error('Order update failed:', result);
                                if (window.toast) {
                                    toast.error('{{ admin_trans("error_updating_order") }}');
                                }
                                window.location.reload();
                            }
                        } catch (error) {
                            console.error('Order update error:', error);
                            if (window.toast) {
                                toast.error('{{ admin_trans("error_updating_order") }}');
                            }
                            window.location.reload();
                        }
                    }
                });
            }
        },

        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/stores/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") }}');
                }
            }
        }
    }
}

function editStoreModal() {
    return {
        loading: false,
        storeData: null,

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

        getTranslationValue(localeId, field) {
            const translation = this.storeData?.translations?.find(t => t.locale_id == localeId);
            return translation ? translation[field] || '' : '';
        },

        setTranslationValue(localeId, field, value) {
            if (!this.storeData || !this.storeData.translations) return;
            let translation = this.storeData.translations.find(t => t.locale_id == localeId);
            if (!translation) {
                translation = { locale_id: localeId };
                this.storeData.translations.push(translation);
            }
            translation[field] = value;
        },

        toggleCategory(categoryId, checked) {
            if (!this.storeData.categories) {
                this.storeData.categories = [];
            }
            if (checked) {
                if (!this.storeData.categories.includes(categoryId)) {
                    this.storeData.categories.push(categoryId);
                }
            } else {
                this.storeData.categories = this.storeData.categories.filter(id => id !== categoryId);
            }
        }
    }
}

function statsModal() {
    return {
        loading: false,
        stats: null,

        async loadStats(id) {
            this.loading = true;
            this.stats = null;
            try {
                const response = await fetch(`/admin/stores/${id}/stats`);
                const result = await response.json();
                if (result.success) {
                    this.stats = result.stats;
                }
            } catch (error) {
                if (window.toast) {
                    toast.error('{{ admin_trans("error_loading_stats") }}');
                }
            } 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 editStore(id) {
    window.dispatchEvent(new CustomEvent('open-modal', { detail: 'edit-store-modal' }));
    setTimeout(() => {
        const modal = document.querySelector('[x-data*="editStoreModal"]');
        if (modal && modal._x_dataStack) {
            modal._x_dataStack[0].loadStore(id);
        }
    }, 100);
}

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

function editStoreUserSelect() {
    const users = @json($users->toArray());

    return {
        open: false,
        search: '',
        selectedUser: null,
        users: users,

        init() {
            // Watch storeData and update selectedUser when it changes
            this.$watch('storeData', (newStoreData) => {
                if (newStoreData && newStoreData.user_id) {
                    this.selectedUser = newStoreData.user_id;
                }
            });
        },

        filteredUsers() {
            const searchLower = this.search.toLowerCase().trim();
            if (!searchLower) return this.users;
            return this.users.filter(user =>
                user.name.toLowerCase().includes(searchLower) ||
                user.email.toLowerCase().includes(searchLower)
            );
        },

        selectUser(userId) {
            this.selectedUser = userId;
            this.open = false;
            this.search = '';
        },

        getUserName() {
            if (!this.selectedUser) return '';
            const user = this.users.find(u => u.id == this.selectedUser);
            return user ? `${user.name} (${user.email})` : '';
        }
    };
}

function confirmDelete(id, name) {
    window.addEventListener('confirm-action', function handler(e) {
        if (e.detail === 'delete-store-modal') {
            const form = document.createElement('form');
            form.method = 'POST';
            form.action = `/admin/stores/${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-store-modal' }));
}

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