<x-filament-panels::page x-data="{
    startPolling: function() {
        setInterval(() => this.$wire.dispatch('pollResults'), 1000)
    }
}" x-init="startPolling()">
    {{ $this->form }}

    @if (false)
        <!-- Caso seja necessário exibir a tabela de resultados, altere a condição do "if" para verificar ($modalityId) -->
        <div class="flex flex-col mt-6 space-x-4">
            <!-- Div para a tabela de resultados com rolagem horizontal -->
            <div class="rounded-lg shadow p-4 overflow-auto">
                <h3 class="text-lg font-bold mb-4">Resultados</h3>
                <div class="overflow-x-auto w-full">
                    <table class="table-auto border-collapse border border-gray-200 min-w-[1200px]">
                        <thead>
                            <tr>
                                @if ($isTeams)
                                    <th class="border px-4 py-2">Grupo</th>
                                @endif
                                <th class="border px-4 py-2">Participante</th>
                                @foreach ($rounds as $round)
                                    <th class="border px-4 py-2">Volta {{ $round['number'] }}</th>
                                @endforeach
                                <th class="border px-4 py-2">Total de Acertos</th>
                                @if ($group === 'classification')
                                    <th class="border px-4 py-2">Força</th>
                                @endif
                            </tr>
                        </thead>
                        <tbody>
                            @php
                                $totalParticipants = 0;
                                $lastGroup = null;
                                $rowspanCount = 0;
                                $firstInGroup = true;
                            @endphp
                            @foreach ($tableData as $inscriptionKey => $inscription)
                                @foreach ($inscription as $key => $participant)
                                    @if ($participant['modality'])
                                        @php
                                            $totalParticipants++;
                                            // Se é um novo grupo ou o primeiro item
                                            if ($lastGroup !== $participant['inscription_group_name']) {
                                                // Conta quantos itens têm o mesmo grupo
                                                $rowspanCount = collect($tableData)
                                                    ->flatMap(fn($insc) => $insc)
                                                    ->filter(fn($p) => !empty($p['modality']))
                                                    ->filter(
                                                        fn($p) => $p['inscription_group_name'] ===
                                                            $participant['inscription_group_name'],
                                                    )
                                                    ->count();
                                                $lastGroup = $participant['inscription_group_name'];
                                                $firstInGroup = true;
                                            } else {
                                                $firstInGroup = false;
                                            }
                                        @endphp
                                        <tr>
                                            @if ($isTeams)
                                                @if ($firstInGroup)
                                                    <td class="border px-4 py-2" rowspan="{{ $rowspanCount }}">
                                                        {{ $participant['inscription_group_name'] }}
                                                    </td>
                                                @endif
                                            @endif
                                            <td class="border px-4 py-2">{{ $participant['name'] }}</td>
                                            @foreach ($rounds as $round)
                                                <td class="border px-4 py-2 text-center align-middle">
                                                    @if (isset($participant['rounds'][$round['number']]))
                                                        @if ($participant['rounds'][$round['number']] == 1)
                                                            <span style="color: #4caf50; display: inline-block;">
                                                                <svg xmlns="http://www.w3.org/2000/svg" fill="none"
                                                                    viewBox="0 0 24 24" stroke-width="4"
                                                                    stroke="currentColor" width="24" height="24"
                                                                    class="size-6">
                                                                    <path stroke-linecap="round" stroke-linejoin="round"
                                                                        d="m4.5 12.75 6 6 9-13.5" />
                                                                </svg>
                                                            </span>
                                                        @else
                                                            <span style="color: red; display: inline-block;">
                                                                <svg xmlns="http://www.w3.org/2000/svg" fill="none"
                                                                    viewBox="0 0 24 24" stroke-width="4"
                                                                    stroke="currentColor" width="24" height="24"
                                                                    lass="size-6">
                                                                    <path stroke-linecap="round" stroke-linejoin="round"
                                                                        d="M6 18 18 6M6 6l12 12" />
                                                                </svg>
                                                            </span>
                                                        @endif
                                                    @else
                                                        -
                                                    @endif
                                                </td>
                                            @endforeach
                                            <td class="border px-4 py-2 font-bold text-center">
                                                {{ $participant['total_hits'] }}</td>
                                            @if ($group === 'classification')
                                                <td class="border px-4 py-2 font-bold text-center">
                                                    {{ $participant['group'] }}</td>
                                            @endif
                                        </tr>
                                    @endif
                                @endforeach
                            @endforeach
                        </tbody>
                        <tfoot>
                            <tr>
                                <td class="border px-4 py-2 font-bold text-center"
                                    @if ($isTeams) colspan="2" @endif>Total (%)</td>
                                @foreach ($rounds as $round)
                                    @php
                                        $totalHits = 0;

                                        foreach ($tableData as $inscription) {
                                            foreach ($inscription as $key => $participant) {
                                                if (
                                                    !empty($participant['rounds']) &&
                                                    isset($participant['rounds'][$round['number']]) &&
                                                    $participant['rounds'][$round['number']] == 1
                                                ) {
                                                    $totalHits++;
                                                }
                                            }
                                        }

                                        $percentage =
                                            $totalParticipants > 0 ? ($totalHits / $totalParticipants) * 100 : 0;
                                    @endphp
                                    <td class="border px-4 py-2 font-semibold text-center"
                                        style="{{ $percentage >= 50 ? 'color: #4caf50;' : 'color: #f44336;' }}">
                                        {{ round($percentage) }}%
                                    </td>
                                @endforeach
                                <td class="border px-4 py-2" colspan="2"></td>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            </div>

            @if ($hasClassificationRounds && $group === 'classification')
                @php
                    $forces = [];
                    foreach ($tableData as $inscription) {
                        foreach ($inscription as $key => $participant) {
                            $forces[$participant['group'] ?? 'N/C'] = 0;
                        }
                    }

                    foreach ($forces as $forceKey => $value) {
                        $count = 0;
                        foreach ($tableData as $inscription) {
                            foreach ($inscription as $key => $participant) {
                                if ($participant['group'] == $forceKey) {
                                    $count++;
                                }
                            }
                        }
                        $forces[$forceKey] = $count;
                    }
                    ksort($forces);
                @endphp
                <div class="w-1/2 rounded-lg shadow p-4">
                    <h3 class="text-lg font-bold mb-4">Classificação</h3>
                    <table class="table-auto border-collapse border border-gray-200 w-full">
                        <thead>
                            <tr>
                                @foreach ($forces as $force => $quantity)
                                    @if ($force !== 'null')
                                        <th class="border px-4 py-2">Força {{ $force }}</th>
                                    @endif
                                @endforeach
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                @foreach ($forces as $force => $quantity)
                                    @if ($force !== 'null')
                                        <td class="border px-4 py-2 text-center">
                                            {{ $quantity }}
                                        </td>
                                    @endif
                                @endforeach
                            </tr>
                        </tbody>
                    </table>
                </div>
            @endif
        </div>
    @endif

    <x-filament::modal :width="'xl'" wire:model.live="showPendingRoundsModal" id="pending-rounds">
        <x-slot name="header">
            <h2 class="text-lg font-medium">Rounds Pendentes</h2>
        </x-slot>

        <div class="">
            @foreach ($pendingRounds as $index => $round)
                <div class="flex items-center justify-between border border-1 border-gray-210 dark:border-white/10 p-4">
                    <span>
                        {{ $round['participant_name'] }}
                        @if ($round['inscription_name'] ?? false)
                            <br>
                            <span class="text-gray-500">Grupo: {{ $round['inscription_name'] }}</span>
                        @endif
                    </span>
                    <span class="text-primary-400">Volta {{ $round['round_number'] }}</span>
                    {{ $this->getPendingRoundsForm($index, $round) }}
                </div>
            @endforeach
        </div>

        <x-slot name="footer">
            <x-filament::button wire:click="savePendingRounds">
                Salvar
            </x-filament::button>
        </x-slot>
    </x-filament::modal>

    <x-filament::modal :width="'md'" wire:model.live="showConfirmationModal" id="confirmation-modal">
        <x-slot name="header">
            <h2 class="text-lg font-medium">Confirmar Finalização</h2>
        </x-slot>

        <div class="p-4">
            <p>Deseja realmente finalizar todos os rounds pendentes?</p>
        </div>

        <x-slot name="footer">
            <div class="flex justify-end gap-3">
                <x-filament::button color="gray" wire:click="cancelFinalization">
                    Não
                </x-filament::button>
                <x-filament::button wire:click="finalizeRounds">
                    Sim
                </x-filament::button>
            </div>
        </x-slot>
    </x-filament::modal>

</x-filament-panels::page>
