@extends('layouts.app')

@section('title', 'Thanks đã nhận')

@section('content')
<div class="max-w-[1280px] mx-auto w-full pb-10 px-2 lg:px-8">

    <x-hero-banner>
        <h2 class="text-[32px] md:text-[42px] font-extrabold text-[#1a2b49] mb-3">💜 Thanks đã nhận</h2>
        <p class="text-[16px] text-gray-600 mb-6">Các lời cảm ơn mà đồng nghiệp đã gửi đến bạn.</p>
    </x-hero-banner>

    <!-- Month Filter & Actions -->
    <div class="flex flex-col md:flex-row md:items-center justify-between gap-6 mb-8 mt-6">
        <form id="filterForm" class="flex items-center gap-4 bg-white p-3 md:p-4 pr-6 rounded-[24px] shadow-[0_4px_12px_rgba(0,0,0,0.03)] border border-gray-100 transition-all hover:shadow-md">
            <div class="w-12 h-12 rounded-full bg-purple-50 flex items-center justify-center text-[#8b5cf6]">
                <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"></path>
                </svg>
            </div>
            <div>
                <label for="month" class="block text-xs font-extrabold text-gray-400 uppercase tracking-wider mb-1">Lọc theo tháng</label>
                <input type="month" id="month" name="month" class="block w-full border-0 bg-transparent p-0 text-lg font-bold text-[#1a2b49] focus:ring-0 cursor-pointer" value="{{ $selectedMonth }}" />
            </div>
        </form>
    </div>

    <!-- Statistics Section -->
    <div class="grid grid-cols-1 md:grid-cols-2 gap-5 mb-8">
        <div class="bg-white rounded-[24px] border border-gray-100/80 p-5 shadow-sm flex items-center gap-4 hover:shadow-md transition-all duration-300">
            <div class="w-12 h-12 rounded-full bg-purple-50 text-[#8b5cf6] flex items-center justify-center shrink-0">
                <svg class="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"/>
                </svg>
            </div>
            <div>
                <p class="text-xs font-bold text-gray-400 uppercase tracking-wider">Tổng số thanks nhận trong <span id="statMonth">tháng {{ \Carbon\Carbon::parse($selectedMonth)->format('n/Y') }}</span></p>
                <h3 class="text-2xl font-extrabold text-[#1a2b49] mt-0.5" id="totalCardsVal">{{ $totalCards }}</h3>
            </div>
        </div>

        <div class="bg-white rounded-[24px] border border-gray-100/80 p-5 shadow-sm flex items-center gap-4 hover:shadow-md transition-all duration-300">
            <div class="w-12 h-12 rounded-full bg-blue-50 text-[#3462f7] flex items-center justify-center shrink-0">
                <svg class="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z" />
                </svg>
            </div>
            <div>
                <p class="text-xs font-bold text-gray-400 uppercase tracking-wider">Số người đã gửi tới</p>
                <h3 class="text-2xl font-extrabold text-[#1a2b49] mt-0.5" id="totalSendersVal">{{ $totalSenders }}</h3>
            </div>
        </div>
    </div>

    <!-- Empty State -->
    <div id="emptyState" class="bg-white rounded-[24px] border border-dashed border-gray-200 p-12 text-center shadow-sm {{ count($cards) === 0 ? '' : 'hidden' }}">
        <div class="w-16 h-16 rounded-full bg-purple-50 text-purple-500 flex items-center justify-center text-3xl mx-auto mb-4 animate-bounce">
            ❤️
        </div>
        <h3 class="text-lg font-extrabold text-[#1a2b49] mb-2">Chưa nhận được Thank Card nào</h3>
        <p class="text-sm text-gray-500 max-w-sm mx-auto font-medium">Bạn chưa nhận được Thank Card nào trong tháng này.</p>
    </div>

    <!-- Activity Feed Grid -->
    <div id="cardsGrid" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 {{ count($cards) === 0 ? 'hidden' : '' }}">
        @include('user.partials.received_cards_feed', ['cards' => $cards])
    </div>

    <!-- Load More Container -->
    <div id="loadMoreContainer" class="flex justify-center {{ $hasMore ? '' : 'hidden' }}" style="margin-top: 64px; margin-bottom: 32px;">
        <button id="loadMoreBtn" class="px-8 py-3 bg-[#3462f7] hover:bg-[#254edb] text-white font-bold rounded-2xl shadow-lg hover:shadow-xl transition-all duration-300 flex items-center gap-2 cursor-pointer">
            <span id="btnText">Xem thêm</span>
            <span id="btnSpinner" class="hidden animate-spin rounded-full h-4 w-4 border-2 border-white border-t-transparent"></span>
        </button>
    </div>

</div>
@endsection

@push('scripts')
<script>
    document.addEventListener('DOMContentLoaded', function() {
        const monthInput = document.getElementById('month');
        const cardsGrid = document.getElementById('cardsGrid');
        const emptyState = document.getElementById('emptyState');
        const loadMoreContainer = document.getElementById('loadMoreContainer');
        const loadMoreBtn = document.getElementById('loadMoreBtn');
        const btnText = document.getElementById('btnText');
        const btnSpinner = document.getElementById('btnSpinner');
        const totalCardsVal = document.getElementById('totalCardsVal');
        const totalSendersVal = document.getElementById('totalSendersVal');

        let offset = 12;

        async function fetchFeed(reset = false) {
            const month = monthInput.value;
            const currentOffset = reset ? 0 : offset;
            const url = `{{ route('user.received') }}?month=${month}&offset=${currentOffset}`;

            if (reset) {
                cardsGrid.style.opacity = '0.5';
            } else {
                loadMoreBtn.disabled = true;
                btnText.textContent = 'Đang tải...';
                btnSpinner.classList.remove('hidden');
            }

            try {
                const response = await fetch(url, {
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest'
                    }
                });
                const data = await response.json();

                if (data.success) {
                    if (reset) {
                        cardsGrid.innerHTML = data.html;
                        offset = 12;
                        cardsGrid.style.opacity = '1';
                    } else {
                        cardsGrid.insertAdjacentHTML('beforeend', data.html);
                        offset += 12;
                        loadMoreBtn.disabled = false;
                        btnText.textContent = 'Xem thêm';
                        btnSpinner.classList.add('hidden');
                    }

                    // Update statistics
                    totalCardsVal.textContent = data.totalCards;
                    totalSendersVal.textContent = data.totalSenders;
                    
                    const [year, month] = monthInput.value.split('-');
                    document.getElementById('statMonth').textContent = `tháng ${parseInt(month, 10)}/${year}`;

                    // Update Visibility
                    const cardCount = cardsGrid.children.length;
                    if (cardCount === 0) {
                        cardsGrid.classList.add('hidden');
                        emptyState.classList.remove('hidden');
                        loadMoreContainer.classList.add('hidden');
                    } else {
                        cardsGrid.classList.remove('hidden');
                        emptyState.classList.add('hidden');
                        if (data.hasMore) {
                            loadMoreContainer.classList.remove('hidden');
                        } else {
                            loadMoreContainer.classList.add('hidden');
                        }
                    }
                }
            } catch (error) {
                console.error('Error fetching received cards feed:', error);
                if (reset) {
                    cardsGrid.style.opacity = '1';
                } else {
                    loadMoreBtn.disabled = false;
                    btnText.textContent = 'Xem thêm';
                    btnSpinner.classList.add('hidden');
                }
            }
        }

        monthInput.addEventListener('change', () => {
            fetchFeed(true);
        });

        loadMoreBtn.addEventListener('click', () => {
            fetchFeed(false);
        });
    });
</script>
@endpush
