@extends('admin.layouts.app')

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

@section('content')

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

    <!-- 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.offers.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_offers')" 
                        class="w-full"
                    />
                </form>
            </div>

            <!-- Add Button -->
            <x-button variant="primary" icon="plus" href="{{ route('admin.offers.create') }}">
                {{ admin_trans('add_offer') }}
            </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.offers.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

                <!-- Language Filter -->
                @if($currentCountry && $availableLocales->count() > 1)
                    <div>
                        <label class="block text-sm font-medium text-tertiary mb-1">{{ admin_trans('language') }}</label>
                        <select name="locale_id" class="input text-sm">
                            <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>
                    </div>
                @endif

                <!-- Status Filter -->
                <div>
                    <label class="block text-sm font-medium text-tertiary mb-1">{{ admin_trans('status') }}</label>
                    <select name="status" class="input text-sm">
                        <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>
                </div>

                <!-- Type Filter -->
                <div>
                    <label class="block text-sm font-medium text-tertiary mb-1">{{ admin_trans('type') }}</label>
                    <select name="type" class="input text-sm">
                        <option value="">{{ admin_trans('all_types') }}</option>
                        <option value="code" {{ request('type') === 'code' ? 'selected' : '' }}>{{ admin_trans('coupon_code') }}</option>
                        <option value="deal" {{ request('type') === 'deal' ? 'selected' : '' }}>{{ admin_trans('deal') }}</option>
                    </select>
                </div>

                <!-- Store Filter -->
                @if($availableStores->count() > 0)
                    @php
                        $storesArray = $availableStores->map(function($countryStore) {
                            $translation = $countryStore->store->translations->first();
                            return [
                                'id' => $countryStore->store_id,
                                'name' => $translation->name ?? 'Store #' . $countryStore->store_id
                            ];
                        })->toArray();
                    @endphp
                    <x-searchable-select
                        name="store_id"
                        :label="admin_trans('store')"
                        :placeholder="admin_trans('search_stores')"
                        :options="$storesArray"
                        :selected="request('store_id')"
                        valueKey="id"
                        labelKey="name"
                    />
                @endif

                <!-- Brand Filter -->
                @if($brands->count() > 0)
                    @php
                        $brandsArray = $brands->map(function($brand) {
                            $translation = $brand->translations->first();
                            return [
                                'id' => $brand->id,
                                'name' => $translation->name ?? 'Brand #' . $brand->id
                            ];
                        })->toArray();
                    @endphp
                    <x-searchable-select
                        name="brand_id"
                        :label="admin_trans('brand')"
                        :placeholder="admin_trans('search_brands')"
                        :options="$brandsArray"
                        :selected="request('brand_id')"
                        valueKey="id"
                        labelKey="name"
                    />
                @endif

                <!-- Category Filter -->
                @if($categories->count() > 0)
                    @php
                        $categoriesArray = $categories->map(function($category) {
                            $translation = $category->translations->first();
                            return [
                                'id' => $category->id,
                                'name' => $translation->name ?? 'Category #' . $category->id
                            ];
                        })->toArray();
                    @endphp
                    <x-searchable-select
                        name="category_id"
                        :label="admin_trans('category')"
                        :placeholder="admin_trans('search_categories')"
                        :options="$categoriesArray"
                        :selected="request('category_id')"
                        valueKey="id"
                        labelKey="name"
                    />
                @endif

                <!-- Featured Filter -->
                <div>
                    <label class="block text-sm font-medium text-tertiary mb-1">{{ admin_trans('featured') }}</label>
                    <select name="featured" class="input text-sm">
                        <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>
                </div>

                <!-- Expiry Status Filter -->
                <div>
                    <label class="block text-sm font-medium text-tertiary mb-1">{{ admin_trans('expiry_status') }}</label>
                    <select name="expiry" class="input text-sm">
                        <option value="">{{ admin_trans('all') }}</option>
                        <option value="active" {{ request('expiry') === 'active' ? 'selected' : '' }}>{{ admin_trans('not_expired') }}</option>
                        <option value="expired" {{ request('expiry') === 'expired' ? 'selected' : '' }}>{{ admin_trans('expired') }}</option>
                        <option value="expiring_soon" {{ request('expiry') === 'expiring_soon' ? 'selected' : '' }}>{{ admin_trans('expiring_soon') }}</option>
                    </select>
                </div>

                <!-- Date Range Filters -->
                <div>
                    <label class="block text-sm font-medium text-tertiary mb-1">{{ admin_trans('created_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('created_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('created_date') }}</option>
                        <option value="popularity" {{ request('sort') === 'popularity' ? 'selected' : '' }}>{{ admin_trans('popularity') }}</option>
                        <option value="uses_count" {{ request('sort') === 'uses_count' ? 'selected' : '' }}>{{ admin_trans('uses_count') }}</option>
                        <option value="expires_at" {{ request('sort') === 'expires_at' ? 'selected' : '' }}>{{ admin_trans('expiry_date') }}</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', 'locale_id', 'status', 'type', 'store_id', 'brand_id', 'category_id', 'featured', 'expiry', '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.offers.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('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="warning" @click="performBulkAction('expire')">{{ admin_trans('expire') }}</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>

    <!-- Offers Table -->
    <x-card>
        @if ($offers->isEmpty())
            @if($currentCountry)
                <x-empty-state icon="tag" :title="admin_trans('no_offers_yet')" :description="admin_trans('start_by_adding_first_offer')">
                    <x-button variant="primary" icon="plus" href="{{ route('admin.offers.create') }}">
                        {{ admin_trans('add_offer') }}
                    </x-button>
                </x-empty-state>
            @else
                <x-empty-state icon="globe" :title="admin_trans('select_country_first')" :description="admin_trans('select_country_to_manage_offers')">
                    <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'],
                    'image' => ['text' => admin_trans('image'), 'align' => 'center', 'width' => '60px'],
                    'title' => ['text' => admin_trans('title'), 'align' => 'left', 'width' => '250px'],
                    'store' => ['text' => admin_trans('store'), 'align' => 'left', 'width' => '150px'],
                    'type' => ['text' => admin_trans('type'), 'align' => 'center', 'width' => '80px'],
                    'discount' => ['text' => admin_trans('discount'), 'align' => 'center', 'width' => '100px'],
                    'stats' => ['text' => admin_trans('stats'), 'align' => 'center', 'width' => '150px'],
                    'expiry' => ['text' => admin_trans('expiry'), 'align' => 'center', 'width' => '120px'],
                    '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' => '120px']
                ]"
                :responsive="true"
                :striped="true"
            >
                @foreach ($offers as $offer)
                    @php
                        $translation = $offer->translations->first();
                        $storeTranslation = $offer->countryStore->store->translations->first();
                    @endphp
                    <tr class="offer-row hover:bg-primary-light transition-colors" data-id="{{ $offer->id }}">

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

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

                        <!-- Title -->
                        <x-table-cell type="text">
                            <div>
                                <div class="flex items-center gap-2">
                                    <span class="text-sm font-medium text-primary">
                                        {{ $translation->title ?? 'Offer #' . $offer->id }}
                                    </span>
                                    
                                    <!-- Offer Badges -->
                                    <div class="flex gap-1">
                                        @if($offer->is_exclusive)
                                            <x-badge variant="warning" class="text-xs">{{ admin_trans('exclusive') }}</x-badge>
                                        @endif
                                        @if($offer->is_free_shipping)
                                            <x-badge variant="success" class="text-xs">{{ admin_trans('free_shipping') }}</x-badge>
                                        @endif
                                        @if($offer->is_new_customer)
                                            <x-badge variant="info" class="text-xs">{{ admin_trans('new_customer') }}</x-badge>
                                        @endif
                                    </div>
                                </div>
                                
                                @if($offer->code)
                                    <div class="text-xs text-tertiary mt-1 font-mono">
                                        {{ admin_trans('code') }}: {{ $offer->code }}
                                    </div>
                                @endif
                                
                                @if ($translation && $translation->description)
                                    <div class="text-xs text-tertiary mt-1">
                                        {{ Str::limit(strip_tags($translation->description), 60) }}
                                    </div>
                                @endif
                            </div>
                        </x-table-cell>

                        <!-- Store -->
                        <x-table-cell type="text">
                            <div>
                                <div class="text-sm font-medium text-primary">
                                    {{ $storeTranslation->name ?? 'Store #' . $offer->countryStore->store_id }}
                                </div>
                                @if($offer->brand)
                                    @php
                                        $brandTranslation = $offer->brand->translations->first();
                                    @endphp
                                    <div class="text-xs text-tertiary">
                                        {{ $brandTranslation->name ?? 'Brand #' . $offer->brand_id }}
                                    </div>
                                @endif
                            </div>
                        </x-table-cell>

                        <!-- Type -->
                        <x-table-cell type="badge">
                            <x-badge variant="{{ $offer->type === 'code' ? 'secondary' : 'info' }}" class="text-xs">
                                {{ admin_trans($offer->type) }}
                            </x-badge>
                        </x-table-cell>

                        <!-- Discount -->
                        <x-table-cell type="text">
                            <div class="text-center">
                                @if($offer->discount_value)
                                    <div class="text-sm font-bold text-success">{{ $offer->discount_value }}%</div>
                                @endif
                                
                                @if($offer->promotion_value)
                                    <div class="text-xs text-tertiary">
                                        @if($offer->promotion_type === 'monetary')
                                            {{ $offer->promotion_value }} {{ $offer->currency }}
                                        @elseif($offer->promotion_type === 'percent')
                                            {{ $offer->promotion_value }}%
                                        @elseif(in_array($offer->promotion_type, ['upto_monetary', 'upto_percent']))
                                            {{ admin_trans('up_to') }} {{ $offer->promotion_value }}
                                        @endif
                                    </div>
                                @endif
                                
                                @if($offer->regular_price && $offer->sale_price)
                                    <div class="text-xs text-tertiary">
                                        <s>{{ $offer->regular_price }}</s> → {{ $offer->sale_price }}
                                    </div>
                                @endif
                            </div>
                        </x-table-cell>

                        <!-- Stats -->
                        <x-table-cell type="text">
                            <div class="flex items-center justify-center gap-3 text-xs">
                                <div class="flex items-center gap-1" title="{{ admin_trans('favorites') }}">
                                    <i data-lucide="heart" class="w-3 h-3 text-red-500"></i>
                                    <span class="text-tertiary">{{ $offer->favorites_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-blue-500"></i>
                                    <span class="text-tertiary">{{ $offer->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-green-500"></i>
                                    <span class="text-tertiary">{{ $offer->uses_count ?? 0 }}</span>
                                </div>
                            </div>
                        </x-table-cell>

                        <!-- Expiry -->
                        <x-table-cell type="text">
                            @if($offer->expires_at)
                                @php
                                    $expiryDate = \Carbon\Carbon::parse($offer->expires_at);
                                    $isExpired = $expiryDate->isPast();
                                    $isExpiringSoon = $expiryDate->diffInDays(now()) <= 7 && !$isExpired;
                                @endphp
                                <div class="text-center">
                                    <div class="text-xs {{ $isExpired ? 'text-red-600' : ($isExpiringSoon ? 'text-yellow-600' : 'text-tertiary') }}">
                                        {{ $expiryDate->format('d/m/Y') }}
                                    </div>
                                    <div class="text-xs {{ $isExpired ? 'text-red-600' : ($isExpiringSoon ? 'text-yellow-600' : 'text-tertiary') }}">
                                        @if($isExpired)
                                            {{ admin_trans('expired') }}
                                        @elseif($isExpiringSoon)
                                            {{ admin_trans('expires_soon') }}
                                        @else
                                            {{ $expiryDate->diffForHumans() }}
                                        @endif
                                    </div>
                                </div>
                            @else
                                <div class="text-center">
                                    <span class="text-xs text-tertiary">{{ admin_trans('no_expiry') }}</span>
                                </div>
                            @endif
                        </x-table-cell>

                        <!-- Featured -->
                        <x-table-cell type="actions">
                            <form method="POST" action="{{ route('admin.offers.toggle-featured', $offer) }}">
                                @csrf @method('PATCH')
                                <button type="submit" class="p-1 rounded-lg transition-colors {{ $offer->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 {{ $offer->is_featured ? 'fill-current' : '' }}"></i>
                                </button>
                            </form>
                        </x-table-cell>

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

                        <!-- Actions -->
                        <x-table-cell type="actions">
                            <div class="flex items-center justify-center gap-2">
                                <a href="{{ route('admin.offers.edit', $offer) }}" 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>
                                </a>
                                <button onclick="viewStats({{ $offer->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({{ $offer->id }}, '{{ addslashes($translation->title ?? 'Offer #' . $offer->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 ($offers->hasPages())
                <div class="mt-6">
                    <x-pagination :paginator="$offers" />
                </div>
            @endif
        @endif
    </x-card>
</div>

<!-- 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('offer_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-danger-50);">
                    <div class="flex items-center gap-2 mb-2">
                        <i data-lucide="heart" class="w-5 h-5 text-red-500"></i>
                        <span class="text-sm font-medium text-red-600">{{ admin_trans('favorites') }}</span>
                    </div>
                    <p class="text-2xl font-bold text-red-600" x-text="stats?.favorites_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="eye" class="w-5 h-5 text-blue-500"></i>
                        <span class="text-sm font-medium text-blue-600">{{ admin_trans('views') }}</span>
                    </div>
                    <p class="text-2xl font-bold text-blue-600" 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-warning-50);">
                    <div class="flex items-center gap-2 mb-2">
                        <i data-lucide="zap" class="w-5 h-5 text-yellow-500"></i>
                        <span class="text-sm font-medium text-yellow-600">{{ admin_trans('impressions') }}</span>
                    </div>
                    <p class="text-2xl font-bold text-yellow-600" x-text="stats?.impressions_count || 0"></p>
                </div>
            </div>

            <div class="grid grid-cols-1 sm:grid-cols-2 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('saving_percentage') }}</span>
                    <p class="text-xl font-bold text-primary mt-1"><span x-text="stats?.saving_percentage || 0"></span>%</p>
                </div>
            </div>

            <div 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('created_at') }}</span>
                        <p class="font-medium text-primary mt-1" x-text="stats?.created_at ? formatDate(stats.created_at) : '-'"></p>
                    </div>
                    <div>
                        <span class="text-tertiary">{{ admin_trans('expires_at') }}</span>
                        <p class="font-medium text-primary mt-1" x-text="stats?.expires_at ? formatDate(stats.expires_at) : '{{ admin_trans('no_expiry') }}'"></p>
                    </div>
                    <div>
                        <span class="text-tertiary">{{ admin_trans('last_usage') }}</span>
                        <p class="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-offer-modal" :title="admin_trans('confirm_delete')" :message="admin_trans('delete_offer_message')" :confirmText="admin_trans('yes_delete')" :cancelText="admin_trans('cancel')" confirmVariant="danger" icon="trash-2" iconColor="danger" />

@endsection

@push('scripts')
<script>
function offersPage() {
    return {
        selectedItems: [],
        filtersExpanded: {{ request()->hasAny(['locale_id', 'status', 'type', 'store_id', 'brand_id', 'category_id', 'featured', 'expiry', 'date_from', 'date_to', 'sort']) ? 'true' : 'false' }},

        init() {
            this.listenToCountryFilter();
        },

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

        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/offers/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 statsModal() {
    return {
        loading: false,
        stats: null,

        async loadStats(id) {
            this.loading = true;
            this.stats = null;
            try {
                const response = await fetch(`/admin/offers/${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 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 confirmDelete(id, name) {
    window.addEventListener('confirm-action', function handler(e) {
        if (e.detail === 'delete-offer-modal') {
            const form = document.createElement('form');
            form.method = 'POST';
            form.action = `/admin/offers/${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-offer-modal' }));
}

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