@extends('layouts.dashboard')

@section('title', 'Earn')

@push('css')
    <style>
        .earn-v2-intro { display:flex; align-items:flex-end; justify-content:space-between; gap:18px; margin-bottom:18px; }
        .earn-v2-intro h1 { margin:0; color:var(--user-text, #f7f8fc); font-size:clamp(1.7rem, 3vw, 2.35rem); font-weight:800; }
        .earn-v2-intro p { max-width:680px; margin:7px 0 0; color:var(--user-muted, #aab2c5); }
        .earn-v2-count { display:flex; min-width:150px; padding:12px 16px; align-items:center; gap:11px; color:var(--user-text, #f7f8fc); background:var(--user-surface, #11192a); border:1px solid var(--user-border, #263149); border-radius:8px; }
        .earn-v2-count svg { color:var(--user-cyan, #48bdf4); }
        .earn-v2-count strong, .earn-v2-count span { display:block; }
        .earn-v2-count span { color:var(--user-muted, #aab2c5); font-size:.74rem; }
        .user-portal-v2 .loot-earn-categories { display:grid; grid-template-columns:repeat(5, minmax(0, 1fr)); gap:9px; padding:0; margin-bottom:14px; background:transparent; border:0; }
        .user-portal-v2 .loot-earn-categories a { position:relative; min-height:62px; padding:10px 13px; justify-content:flex-start; color:var(--user-muted, #aab2c5); background:var(--user-surface, #11192a); border:1px solid var(--user-border, #263149); border-radius:8px; }
        .user-portal-v2 .loot-earn-categories a:hover { color:var(--user-text, #f7f8fc); border-color:rgba(72,189,244,.45); }
        .user-portal-v2 .loot-earn-categories a.active { color:var(--user-text, #f7f8fc); background:var(--user-surface-raised, #162034); border-color:rgba(72,189,244,.55); }
        .user-portal-v2 .loot-earn-categories a.active::after { content:""; position:absolute; right:12px; bottom:-1px; left:12px; height:3px; background:var(--user-cyan, #48bdf4); border-radius:3px 3px 0 0; }
        .user-portal-v2 .loot-earn-categories a svg { color:var(--user-cyan, #48bdf4); }
        .user-portal-v2 .loot-earn-categories a strong { margin-left:auto; color:var(--user-muted, #aab2c5); background:rgba(170,178,197,.09); }
        .user-portal-v2 .loot-offer-toolbar { padding:12px; background:#0d1425; border:1px solid var(--user-border, #263149); border-radius:8px; }
        .user-portal-v2 .loot-search-box, .user-portal-v2 .loot-filter-select { min-height:44px; background:var(--user-surface, #11192a); border-color:var(--user-border, #263149); border-radius:7px; }
        .user-portal-v2 .loot-search-box:focus-within, .user-portal-v2 .loot-filter-select:focus-within { border-color:var(--user-cyan, #48bdf4); box-shadow:0 0 0 3px rgba(72,189,244,.11); }
        .user-portal-v2 .loot-offer-grid { grid-template-columns:repeat(auto-fill, minmax(172px, 1fr)); gap:12px; }
        .user-portal-v2 .loot-direct-card { border-color:var(--user-border, #263149); background:var(--user-surface, #11192a); box-shadow:none; }
        .user-portal-v2 .loot-direct-card:hover { border-color:rgba(72,189,244,.55); transform:translateY(-2px); }
        @media (max-width:767px) {
            .earn-v2-intro { align-items:flex-start; flex-direction:column; }
            .earn-v2-count { width:100%; }
            .user-portal-v2 .loot-earn-categories { display:flex; overflow-x:auto; scroll-snap-type:x mandatory; }
            .user-portal-v2 .loot-earn-categories a { min-width:132px; scroll-snap-align:start; }
            .user-portal-v2 .loot-offer-toolbar { grid-template-columns:1fr 1fr; }
            .user-portal-v2 .loot-search-box { grid-column:1 / -1; }
            .user-portal-v2 .loot-search-submit { grid-column:1 / -1; min-height:44px; }
            .user-portal-v2 .loot-offer-grid { grid-template-columns:repeat(2, minmax(0, 1fr)); gap:9px; }
        }
        @media (max-width:390px) { .user-portal-v2 .loot-offer-grid { gap:7px; } }
    </style>
@endpush

@section('content')
    @php
        $categoryLinks = [
            'all' => ['label' => 'All', 'icon' => 'zap'],
            'games' => ['label' => 'Games', 'icon' => 'tag'],
            'other' => ['label' => 'Other', 'icon' => 'tag'],
            'surveys' => ['label' => 'Surveys', 'icon' => 'edit-3'],
            'partners' => ['label' => 'Partners', 'icon' => 'star'],
        ];
        $cleanQuery = array_filter([
            'q' => $filters['search'] ?? '',
            'provider' => $filters['provider'] ?? '',
            'device' => $filters['device'] ?? '',
            'sort' => $filters['sort'] ?? '',
        ], fn ($value) => $value !== '' && $value !== 'popular');
        $partnerReward = fn ($offerwall) => number_format((float) preg_replace('/[^0-9.]/', '', (string) $offerwall->rate) ?: 5);
        $hasSyncedOffers = ($categoryCounts['all'] ?? 0) > 0;
    @endphp

    <header class="earn-v2-intro">
        <div>
            <span class="user-home-eyebrow"><i data-feather="compass" aria-hidden="true"></i> Find your next reward</span>
            <h1>Tasks and offers</h1>
            <p>Explore tasks from connected providers, compare rewards, and filter for the device you are using now.</p>
        </div>
        <div class="earn-v2-count" aria-label="Available tasks">
            <i data-feather="layers" aria-hidden="true"></i>
            <span><strong>{{ number_format($categoryCounts['all'] ?? 0) }}</strong><span>available tasks</span></span>
        </div>
    </header>

    <div class="loot-earn-shell">
        <div class="loot-earn-categories" aria-label="Offer categories">
            @foreach($categoryLinks as $key => $item)
                <a class="{{ $selectedType === $key ? 'active' : '' }}" href="{{ route('user.earn', array_merge($cleanQuery, ['type' => $key])) }}" @if($selectedType === $key) aria-current="page" @endif>
                    <i data-feather="{{ $item['icon'] }}" aria-hidden="true"></i>
                    <span>{{ $item['label'] }}</span>
                    <strong>{{ $categoryCounts[$key] ?? 0 }}</strong>
                </a>
            @endforeach
        </div>

        <section class="user-page-card loot-earn-panel loot-offer-browser mb-2">
            <div class="loot-shelf-head">
                <h3 class="loot-section-title mb-0"><i data-feather="send" class="me-50"></i>Offers</h3>
                <span class="loot-muted">{{ number_format($offerGrid->count()) }} loaded · {{ number_format($offerTotal) }} total</span>
            </div>

            <form class="loot-offer-toolbar" method="GET" action="{{ route('user.earn') }}">
                <input type="hidden" name="type" value="{{ $selectedType }}">
                <label class="loot-search-box">
                    <span class="sr-only">Search tasks</span>
                    <input type="search" name="q" value="{{ $filters['search'] ?? '' }}" placeholder="Search for a task" aria-label="Search tasks">
                    <i data-feather="search" aria-hidden="true"></i>
                </label>

                <label class="loot-filter-select">
                    <span>Sort:</span>
                    <select name="sort" onchange="this.form.submit()" aria-label="Sort tasks">
                        <option value="popular" {{ ($filters['sort'] ?? 'popular') === 'popular' ? 'selected' : '' }}>Most Popular</option>
                        <option value="highest" {{ ($filters['sort'] ?? '') === 'highest' ? 'selected' : '' }}>Highest Reward</option>
                        <option value="lowest" {{ ($filters['sort'] ?? '') === 'lowest' ? 'selected' : '' }}>Lowest Reward</option>
                        <option value="newest" {{ ($filters['sort'] ?? '') === 'newest' ? 'selected' : '' }}>Newest</option>
                    </select>
                </label>

                <label class="loot-filter-select">
                    <select name="provider" onchange="this.form.submit()" aria-label="Filter by provider">
                        <option value="">All Providers</option>
                        @foreach($providerOptions as $providerName)
                            <option value="{{ $providerName }}" {{ ($filters['provider'] ?? '') === $providerName ? 'selected' : '' }}>{{ $providerName }}</option>
                        @endforeach
                    </select>
                </label>

                <label class="loot-filter-select">
                    <select name="device" onchange="this.form.submit()" aria-label="Filter by device">
                        <option value="">All Devices</option>
                        <option value="desktop" {{ ($filters['device'] ?? '') === 'desktop' ? 'selected' : '' }}>Desktop</option>
                        <option value="android" {{ ($filters['device'] ?? '') === 'android' ? 'selected' : '' }}>Android</option>
                        <option value="ios" {{ ($filters['device'] ?? '') === 'ios' ? 'selected' : '' }}>iOS</option>
                    </select>
                </label>

                <button class="btn btn-loot loot-search-submit" type="submit">Search</button>
            </form>

            @if($offerGrid->count())
                <div class="loot-offer-grid mt-2" aria-label="Filtered offers" id="offerGrid"
                     data-offers-url="{{ route('user.earn.offers', array_filter($filters)) }}"
                     data-next-page="2" data-has-more="{{ $hasMoreOffers ? '1' : '0' }}">
                    @foreach($offerGrid as $offer)
                        @include('user.partials.direct-offer-card', ['offer' => $offer, 'variant' => 'grid'])
                    @endforeach
                </div>
                <div id="offerGridSentinel" class="loot-offer-loadmore mt-2 text-center" @if(!$hasMoreOffers) style="display:none" @endif>
                    <span class="spinner-border spinner-border-sm"></span>
                    <span class="loot-muted ms-1">Loading more offers…</span>
                </div>
            @elseif(! $hasSyncedOffers)
                <div class="loot-provider-sync-empty">
                    <span class="loot-provider-sync-icon"><i data-feather="radio"></i></span>
                    <div>
                        <strong>Offer feeds are ready to sync</strong>
                        <p>Direct offers will appear here automatically after your active providers are connected with their official offer feed URLs. You can still open every active offerwall below.</p>
                    </div>
                    @if(auth()->user()?->is_admin)
                        <a href="{{ route('admin.provider-offers') }}" class="btn btn-loot">Sync offers</a>
                    @endif
                </div>
            @else
                <div class="loot-empty-state">
                    <i data-feather="search"></i>
                    <strong>No offers match these filters</strong>
                    <span>Try all providers, all devices, or a shorter search term.</span>
                </div>
            @endif
        </section>

        @if($topOffers->count())
            <section class="user-page-card loot-earn-panel mb-2">
                <div class="loot-shelf-head">
                    <h3 class="loot-section-title mb-0"><i data-feather="trending-up" class="me-50"></i>Hot Offers</h3>
                    <a href="{{ route('user.earn', array_merge($cleanQuery, ['type' => 'all', 'sort' => 'highest'])) }}" class="btn btn-sm btn-outline-light">View All</a>
                </div>
                <div class="loot-offer-shelf loot-direct-shelf" aria-label="Top offers">
                    @foreach($topOffers as $offer)
                        @include('user.partials.direct-offer-card', ['offer' => $offer, 'variant' => 'hot'])
                    @endforeach
                </div>
            </section>
        @endif

        @if($featuredOffers->count())
            <section class="user-page-card loot-earn-panel mb-2">
                <div class="loot-shelf-head">
                    <h3 class="loot-section-title mb-0"><i data-feather="send" class="me-50"></i>Featured Offers</h3>
                    <a href="{{ route('user.earn', array_merge($cleanQuery, ['type' => $selectedType])) }}" class="btn btn-sm btn-outline-light">Refresh</a>
                </div>
                <div class="loot-offer-shelf loot-direct-shelf" aria-label="Featured offers">
                    @foreach($featuredOffers as $offer)
                        @include('user.partials.direct-offer-card', ['offer' => $offer, 'variant' => 'featured'])
                    @endforeach
                </div>
            </section>
        @endif

        <section class="user-page-card loot-earn-panel mb-2">
            <div class="loot-shelf-head">
                <h3 class="loot-section-title mb-0"><i data-feather="star" class="me-50"></i>Offer Partners</h3>
                <a href="{{ route('user.earn', ['type' => 'partners']) }}" class="btn btn-sm btn-outline-light">View All</a>
            </div>
            <div class="loot-offer-shelf loot-partner-shelf" aria-label="Offer partners">
                @forelse($providers as $provider)
                    <button class="loot-partner-card" type="button" style="--offer-bg: {{ $provider->background_color ?? '#202637' }}"
                            data-bs-toggle="modal" data-bs-target="#offerwallModal"
                            data-open-url="{{ route('user.offerwalls.open', $provider) }}"
                            data-offer-name="{{ $provider->name }}"
                            onclick="openTrackedOfferwall(this)">
                        @if($provider->badge)
                            <span class="loot-wall-ribbon" style="--ribbon-color: {{ $provider->badge_color ?? '#86efac' }}">{{ $provider->badge }}</span>
                        @endif
                        <span class="loot-partner-media">
                            <img src="{{ Storage::url($provider->photo_path) }}" alt="{{ $provider->name }}">
                        </span>
                        <span class="loot-partner-name">{{ Str::limit($provider->name, 18) }}</span>
                        <span class="loot-rating">★★★★★</span>
                        <span class="loot-partner-badge">{{ $partnerReward($provider) }} coins</span>
                    </button>
                @empty
                    <p class="loot-muted mb-0">No offer partners are active.</p>
                @endforelse
            </div>
        </section>

        <section class="user-page-card loot-earn-panel">
            <div class="loot-shelf-head">
                <h3 class="loot-section-title mb-0"><i data-feather="edit" class="me-50"></i>Survey Partners</h3>
                <a href="{{ route('user.earn', ['type' => 'surveys']) }}" class="btn btn-sm btn-outline-light">View All</a>
            </div>
            <div class="loot-offer-shelf loot-partner-shelf" aria-label="Survey partners">
                @forelse($surveys as $provider)
                    <button class="loot-partner-card" type="button" style="--offer-bg: {{ $provider->background_color ?? '#202637' }}"
                            data-bs-toggle="modal" data-bs-target="#offerwallModal"
                            data-open-url="{{ route('user.offerwalls.open', $provider) }}"
                            data-offer-name="{{ $provider->name }}"
                            onclick="openTrackedOfferwall(this)">
                        @if($provider->badge)
                            <span class="loot-wall-ribbon" style="--ribbon-color: {{ $provider->badge_color ?? '#86efac' }}">{{ $provider->badge }}</span>
                        @endif
                        <span class="loot-partner-media">
                            <img src="{{ Storage::url($provider->photo_path) }}" alt="{{ $provider->name }}">
                        </span>
                        <span class="loot-partner-name">{{ Str::limit($provider->name, 18) }}</span>
                        <span class="loot-rating">★★★★★</span>
                        <span class="loot-partner-badge">Survey</span>
                    </button>
                @empty
                    <p class="loot-muted mb-0">No survey partners are active.</p>
                @endforelse
            </div>
        </section>
    </div>

    @include('user.partials.offerwall-modal')
@endsection

@push('scripts')
    <script>
        (function () {
            const refreshUrl = @json(route('user.earn.refresh'));
            const csrf = document.querySelector('meta[name="csrf-token"]')?.content;

            // A page reload asks the server to refresh only stale feeds. When
            // new provider data arrives, reload once to render the fresh cards.
            fetch(refreshUrl, {
                method: 'POST',
                headers: {
                    'Accept': 'application/json',
                    'X-Requested-With': 'XMLHttpRequest',
                    'X-CSRF-TOKEN': csrf || ''
                },
                cache: 'no-store'
            }).then((response) => response.ok ? response.json() : Promise.reject(response))
                .then((result) => {
                    if (result.changed) window.location.reload();
                })
                .catch(() => {
                    // Scheduled syncing remains the fallback when a provider is unavailable.
                });

            const grid = document.getElementById('offerGrid');
            const sentinel = document.getElementById('offerGridSentinel');
            if (!grid || !sentinel) return;

            let loading = false;

            function refreshIcons() {
                if (window.BasketLootIcons) window.BasketLootIcons.refresh();
                else if (window.feather) window.feather.replace();
            }

            function loadMore() {
                if (loading || grid.dataset.hasMore !== '1') return;
                loading = true;

                const page = grid.dataset.nextPage;
                const url = new URL(grid.dataset.offersUrl, window.location.origin);
                url.searchParams.set('page', page);

                fetch(url.toString(), { headers: { 'X-Requested-With': 'XMLHttpRequest' } })
                    .then((r) => r.ok ? r.json() : Promise.reject(r))
                    .then((data) => {
                        grid.insertAdjacentHTML('beforeend', data.html);
                        grid.dataset.nextPage = data.nextPage;
                        grid.dataset.hasMore = data.hasMore ? '1' : '0';
                        if (!data.hasMore) sentinel.style.display = 'none';
                        refreshIcons();
                        loading = false;
                    })
                    .catch(() => {
                        sentinel.style.display = 'none';
                        loading = false;
                    });
            }

            if ('IntersectionObserver' in window) {
                const observer = new IntersectionObserver(function (entries) {
                    entries.forEach(function (entry) { if (entry.isIntersecting) loadMore(); });
                }, { rootMargin: '400px' });
                observer.observe(sentinel);
            } else {
                // Fallback: click-to-load.
                sentinel.style.cursor = 'pointer';
                sentinel.addEventListener('click', loadMore);
            }
        })();
    </script>
@endpush
