<x-admin-app-layout>
    <div class="white-box">
        <x-admin::page-header title="{{ __('Add Hexling Game') }}" :buttons="$buttons" :isFilterable="false" />
        <div class="mt-4">
            <form action="{{ route('admin.games.hexling.store') }}" method="POST" class="form-submit-add"
                id="hexling-form">
                @csrf

                <div
                    class="grid border border-neutral-30 dark:border-neutral-500 rounded p-4 xl:p-6 grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">

                    <!-- Root Word -->
                    <div class="form-group">
                        <label for="root_word" class="block text-sm font-medium mb-2">{{ __('Root Word') }}</label>
                        <input type="text" name="root_word" id="root_word" class="w-full text-input"
                            value="{{ old('root_word') }}" placeholder="{{ __('Enter root word') }}" required
                            minlength="3" maxlength="20" />
                        @error('root_word')
                            <p class="text-red-500 text-xs mt-1">{{ $message }}</p>
                        @enderror
                    </div>

                    <!-- Center Letter -->
                    <div class="form-group">
                        <label for="center_letter"
                            class="block text-sm font-medium mb-2">{{ __('Center Letter') }}</label>
                        <input type="text" name="center_letter" id="center_letter"
                            class="w-full text-input text-center text-xl font-bold" value="{{ old('center_letter') }}"
                            placeholder="{{ __('A') }}" required maxlength="1" style="text-transform: uppercase;" />
                        @error('center_letter')
                            <p class="text-red-500 text-xs mt-1">{{ $message }}</p>
                        @enderror
                    </div>

                    <!-- Game Date -->
                    <div class="input-group">
                        <x-admin::label for="game_date">
                            {{ __('Game Date') }}
                        </x-admin::label>
                        <input type="text" class="date-picker text-input" name="game_date"
                            value="{{ old('game_date', now()->format('Y-m-d')) }}" />
                        <x-admin::input-error name="game_date" />
                    </div>

                    <!-- Secret Words -->
                    <div class="form-group md:col-span-2">
                        <label for="secret_words"
                            class="block text-sm font-medium mb-2">{{ __('Secret Words') }}</label>
                        <textarea name="secret_words" id="secret_words" class="w-full text-input" rows="3"
                            placeholder="{{ __('Enter secret words separated by commas') }}"
                            required>{{ old('secret_words') }}</textarea>
                        <small
                            class="text-gray-500">{{ __('Separate words with commas, e.g.: word1, word2, word3') }}</small>
                        @error('secret_words')
                            <p class="text-red-500 text-xs mt-1">{{ $message }}</p>
                        @enderror
                    </div>

                    <!-- Status -->
                    <div class="form-group">
                        <label for="status" class="block text-sm font-medium mb-2">{{ __('Status') }}</label>
                        <select name="status" id="status" class="w-full text-input" required>
                            @foreach (\App\Enums\GameEnum::cases() as $enum)
                                <option value="{{ $enum->value }}" {{ old('status', 'active') == $enum->value ? 'selected' : '' }}>
                                    {{ $enum->label() }}
                                </option>
                            @endforeach
                        </select>
                        @error('status')
                            <p class="text-red-500 text-xs mt-1">{{ $message }}</p>
                        @enderror
                    </div>

                    <!-- Stats Display -->
                    <div class="form-group md:col-span-2">
                        <div class="bg-gray-50 p-4 rounded-lg border">
                            <h4 class="text-sm font-medium mb-3">{{ __('Game Stats') }}</h4>
                            <div class="grid grid-cols-2 gap-4">
                                <div>
                                    <label class="text-xs text-gray-500">{{ __('Total Levels') }}</label>
                                    <div id="total-levels-display" class="text-lg font-bold text-blue-600">0</div>
                                </div>
                                <div>
                                    <label class="text-xs text-gray-500">{{ __('Total Points') }}</label>
                                    <div id="total-points-display" class="text-lg font-bold text-green-600">0</div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Replace the badges section with this: -->
                    <div class="form-group md:col-span-3">
                        <label class="block text-sm font-medium mb-2">{{ __('Available Badges') }} <span
                                class="text-red-500">*</span></label>

                        <!-- Hidden select for badges -->
                        <select name="badges[]" id="badges-select" multiple class="hidden">
                            @foreach($badges as $badge)
                                <option value="{{ $badge->id }}" {{ in_array($badge->id, old('badges', [])) ? 'selected' : '' }}>
                                    {{ $badge->badge_name }}
                                </option>
                            @endforeach
                        </select>

                        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3" id="badges-container">
                            @foreach($badges as $badge)
                                <label
                                    class="flex items-center space-x-3 p-3 border rounded-lg cursor-pointer hover:bg-gray-50 badge-checkbox">
                                    <input type="checkbox" value="{{ $badge->id }}"
                                        class="rounded border-gray-300 badge-selector" {{ in_array($badge->id, old('badges', [])) ? 'checked' : '' }}>
                                    <div class="flex-1">
                                        <div class="flex justify-between items-center">
                                            <span class="text-sm font-medium">{{ $badge->badge_name }}</span>
                                            <span
                                                class="text-xs bg-blue-100 text-blue-800 px-2 py-1 rounded">{{ $badge->badge_points }}
                                                pts</span>
                                        </div>
                                        <p class="text-xs text-gray-500 mt-1">{{ $badge->badge_description }}</p>
                                    </div>
                                </label>
                            @endforeach
                        </div>
                        @error('badges')
                            <p class="text-red-500 text-xs mt-1">{{ $message }}</p>
                        @enderror
                    </div>

                    <!-- Hidden field to store selected badges as JSON -->
                    <input type="hidden" name="selected_badges" id="selected-badges" value="">

                    <!-- Submit Button -->
                    <div class="md:col-span-3">
                        <div class="flex items-center justify-end mt-4">
                            <button type="submit" class="btn btn-primary" id="submit-btn">
                                {{ __('Save Hexling Game') }}
                            </button>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>

    @push('scripts')
        <script>
            // Auto-uppercase center letter input
            document.getElementById('center_letter').addEventListener('input', function (e) {
                this.value = this.value.toUpperCase();
            });

            // Store selected badges
            let selectedBadges = [];

            // Calculate total levels and points when badges are selected
            function calculateBadgeStats() {
                selectedBadges = Array.from(document.querySelectorAll('.badge-selector:checked'))
                    .map(checkbox => checkbox.value);

                // Update hidden field
                document.getElementById('selected-badges').value = JSON.stringify(selectedBadges);

                if (selectedBadges.length === 0) {
                    document.getElementById('total-levels-display').textContent = '0';
                    document.getElementById('total-points-display').textContent = '0';
                    return;
                }

                // Make AJAX request to calculate stats
                fetch('{{ route("admin.games.hexling.calculate-badge-stats") }}', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': '{{ csrf_token() }}'
                    },
                    body: JSON.stringify({ badges: selectedBadges })
                })
                    .then(response => {
                        if (!response.ok) {
                            throw new Error('Network response was not ok');
                        }
                        return response.json();
                    })
                    .then(data => {
                        document.getElementById('total-levels-display').textContent = data.total_levels;
                        document.getElementById('total-points-display').textContent = data.total_points;
                    })
                    .catch(error => {
                        console.error('Error calculating badge stats:', error);
                        // Fallback calculation
                        const totalLevels = selectedBadges.length;
                        document.getElementById('total-levels-display').textContent = totalLevels;
                        document.getElementById('total-points-display').textContent = '?';
                    });
            }

            // Add event listeners to all badge checkboxes
            document.querySelectorAll('.badge-selector').forEach(checkbox => {
                checkbox.addEventListener('change', calculateBadgeStats);
            });

            // Form submission handler
            document.getElementById('hexling-form').addEventListener('submit', function (e) {
                // Ensure badges are properly submitted
                if (selectedBadges.length === 0) {
                    e.preventDefault();
                    alert('Please select at least one badge');
                    return false;
                }

                // Uncheck all checkboxes and rely on the hidden field
                document.querySelectorAll('.badge-selector').forEach(checkbox => {
                    checkbox.checked = false;
                });

                // Re-check only the selected ones
                selectedBadges.forEach(badgeId => {
                    const checkbox = document.querySelector(`.badge-selector[value="${badgeId}"]`);
                    if (checkbox) {
                        checkbox.checked = true;
                    }
                });
            });

            // Update the badge selection handling
            function updateBadgesSelect() {
                const selectedBadges = Array.from(document.querySelectorAll('.badge-selector:checked'))
                    .map(checkbox => checkbox.value);

                // Clear and update the hidden select
                const badgesSelect = document.getElementById('badges-select');
                badgesSelect.innerHTML = '';

                selectedBadges.forEach(badgeId => {
                    const option = document.createElement('option');
                    option.value = badgeId;
                    option.selected = true;
                    badgesSelect.appendChild(option);
                });

                calculateBadgeStats();
            }

            // Add event listeners
            document.querySelectorAll('.badge-selector').forEach(checkbox => {
                checkbox.addEventListener('change', updateBadgesSelect);
            });

            // Initial update
            updateBadgesSelect();


            // Initial calculation
            calculateBadgeStats();
        </script>
    @endpush
</x-admin-app-layout>