@extends('layouts/guest')
@php
    use App\Models\Tombola;
    $tutti = Tombola::where('attivita_id', $attivita->id)->orderBy('numero')->get();
    $estratti = Tombola::where('attivita_id', $attivita->id)->where('estratto', true)
        ->orderByDesc('estratto_at')
        ->pluck('numero')
        ->toArray();
    $ultimoEstratto = $estratti[0] ?? null;
    $storicoEstratti = array_slice($estratti, 1, 30);
    $estrattiPublicUrl = route('cliente.tombola.estratti', ['attivita_id' => $attivita->id]);
    $qrCodeUrl = 'https://api.qrserver.com/v1/create-qr-code/?size=240x240&data=' . rawurlencode($estrattiPublicUrl);
@endphp

<style>
    :root {
        --tb-bg: #f5f7fb;
        --tb-card: #ffffff;
        --tb-border: #e9edf4;
        --tb-muted: #8592a3;
        --tb-text: #566a7f;
        --tb-primary: #696cff;
        --tb-primary-soft: #eef0ff;
        --tb-success: #71dd37;
        --tb-success-soft: #f2fce8;
    }

    html, body {
        height: 100%;
        margin: 0;
        overflow: hidden;
    }

    body {
        background: var(--tb-bg);
        color: var(--tb-text);
    }

    .tabellone-root-outer {
        height: 100vh;
        padding: 1rem;
        display: flex;
        align-items: stretch;
        justify-content: center;
        overflow: hidden;
    }

    .tabellone-container {
        width: min(1500px, 100%);
        height: calc(100vh - 2rem);
        display: grid;
        grid-template-columns: minmax(0, 1fr) 320px;
        gap: 1rem;
    }

    .tabellone-main,
    .tabellone-sidebar {
        background: var(--tb-card);
        border: 1px solid var(--tb-border);
        border-radius: 1rem;
        box-shadow: 0 0.25rem 0.875rem rgba(161, 172, 184, 0.18);
    }

    .tabellone-main {
        min-width: 0;
        display: flex;
        flex-direction: column;
        overflow: hidden;
        position: relative;
    }

    .tabellone-header {
        padding: 1rem 1.25rem;
        border-bottom: 1px solid var(--tb-border);
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 0.75rem;
        background: linear-gradient(180deg, #fff 0%, #fcfcff 100%);
    }

    .tabellone-title-wrap {
        display: flex;
        align-items: center;
        gap: 0.75rem;
    }

    .tabellone-title-badge {
        width: 2.2rem;
        height: 2.2rem;
        border-radius: 0.65rem;
        background: var(--tb-primary-soft);
        color: var(--tb-primary);
        display: inline-flex;
        align-items: center;
        justify-content: center;
        font-weight: 700;
    }

    .tabellone-title {
        margin: 0;
        font-size: 1.1rem;
        font-weight: 700;
        color: #37475a;
        line-height: 1.2;
    }

    .tabellone-subtitle {
        margin: 0.1rem 0 0;
        font-size: 0.82rem;
        color: var(--tb-muted);
    }

    .tabellone-grid-outer {
        flex: 1 1 auto;
        padding: 1rem;
        min-height: 0;
        overflow: hidden;
    }

    .tabellone-grid {
        height: 100%;
        display: grid;
        grid-template-columns: repeat(3, minmax(0, 1fr));
        grid-template-rows: repeat(2, minmax(0, 1fr));
        gap: clamp(0.6rem, 1vw, 1rem);
        min-height: 0;
    }

    .tabellone-subgrid {
        border: 1px solid var(--tb-border);
        border-radius: 0.85rem;
        background: #fbfcff;
        padding: clamp(0.35rem, 0.65vw, 0.6rem);
        display: grid;
        grid-template-columns: repeat(5, minmax(0, 1fr));
        grid-template-rows: repeat(3, minmax(0, 1fr));
        gap: clamp(0.3rem, 0.5vw, 0.5rem);
        min-height: 0;
    }

    .tabellone-numero {
        border-radius: 999px;
        border: 1px solid #dfe5ef;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: 700;
        user-select: none;
        font-size: clamp(0.8rem, 1.25vw, 1.25rem);
        line-height: 1;
        background: #f7f9fc;
        color: #a1acb8;
        transition: all 0.2s ease;
        box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.5);
    }

    .tabellone-numero.estratto {
        background: linear-gradient(145deg, var(--tb-primary) 0%, #5f62e8 100%);
        color: #fff;
        border-color: #5f62e8;
        box-shadow: 0 0.3rem 0.8rem rgba(105, 108, 255, 0.35);
    }

    .tabellone-numero.is-newly-extracted {
        animation: scale-up 1s ease-out;
    }

    @keyframes scale-up {
        0% {
            transform: scale(1);
        }
        40% {
            transform: scale(1.14);
        }
        100% {
            transform: scale(1);
        }
    }

    .tabellone-sidebar {
        padding: 1rem;
        display: flex;
        min-height: 0;
    }

    .tabellone-sidebar-content {
        width: 100%;
        min-height: 0;
        display: flex;
        flex-direction: column;
    }

    .tabellone-sidebar-title {
        margin: 0 0 0.8rem;
        font-size: 0.95rem;
        font-weight: 700;
        color: #37475a;
    }

    .tabellone-last-wrap {
        border: 1px solid var(--tb-border);
        border-radius: 0.85rem;
        background: #f8f9ff;
        padding: 0.8rem;
        margin-bottom: 0.85rem;
        text-align: center;
        min-height: 12.5rem;
        display: flex;
        flex-direction: column;
        justify-content: center;
    }

    .tabellone-last-label {
        margin: 0;
        font-size: 0.76rem;
        font-weight: 600;
        color: var(--tb-muted);
        text-transform: uppercase;
        letter-spacing: 0.04em;
    }

    .tabellone-last-number {
        margin: 0.2rem 0 0;
        font-size: clamp(4.8rem, 14vw, 8.8rem);
        font-weight: 800;
        color: var(--tb-primary);
        line-height: 1;
    }

    .tabellone-extract-modal {
        position: absolute;
        inset: 0;
        z-index: 20;
        display: flex;
        align-items: center;
        justify-content: center;
        background: rgba(32, 41, 54, 0.5);
        opacity: 0;
        visibility: hidden;
        pointer-events: none;
        transition: opacity 0.2s ease, visibility 0.2s ease;
        backdrop-filter: blur(2px);
    }

    .tabellone-extract-modal.is-visible {
        opacity: 1;
        visibility: visible;
    }

    .tabellone-extract-modal-card {
        background: #fff;
        border: 1px solid var(--tb-border);
        border-radius: 1.2rem;
        box-shadow: 0 0.7rem 1.9rem rgba(30, 43, 60, 0.25);
        padding: 1rem 1.8rem 1.35rem;
        text-align: center;
        min-width: min(84vw, 460px);
        transform: scale(0.9);
        transition: transform 0.24s ease;
    }

    .tabellone-extract-modal.is-visible .tabellone-extract-modal-card {
        transform: scale(1);
    }

    .tabellone-extract-modal-label {
        margin: 0;
        font-size: clamp(0.95rem, 1.4vw, 1.25rem);
        color: var(--tb-muted);
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.08em;
    }

    .tabellone-extract-modal-number {
        margin: 0.35rem 0 0;
        font-size: clamp(18rem, 60vw, 36rem);
        line-height: 0.92;
        font-weight: 800;
        color: var(--tb-primary);
        text-shadow: 0 0.45rem 1.15rem rgba(105, 108, 255, 0.35);
    }

    @media (max-width: 576px) {
        .tabellone-extract-modal-card {
            padding: 0.8rem 1rem 1rem;
            min-width: min(90vw, 360px);
        }
    }

    .tabellone-sidebar-list {
        display: flex;
        flex-wrap: wrap;
        gap: 0.45rem;
        align-content: flex-start;
        min-height: 0;
        overflow: auto;
        padding-right: 0.2rem;
        height: 12rem;
        max-height: 12rem;
        position: relative;
    }

    .tabellone-sidebar-num {
        background: var(--tb-success-soft);
        color: #4f8f2f;
        border: 1px solid rgba(113, 221, 55, 0.35);
        font-size: 0.95rem;
        font-weight: 700;
        padding: 0.35rem 0.6rem;
        border-radius: 0.55rem;
        width: 2.5em;
    }

    .tabellone-sidebar-footer {
        margin-top: 0.9rem;
        padding-top: 0.75rem;
        border-top: 1px dashed var(--tb-border);
        font-size: 0.85rem;
        color: var(--tb-muted);
    }

    .tabellone-sidebar-actions {
        margin-top: auto;
        padding-top: 0.9rem;
        margin-bottom: 0;
        border-top: 1px solid var(--tb-border);
        display: flex;
        flex-direction: column;
        gap: 0.65rem;
    }

    .tabellone-qr-wrap {
        text-align: center;
    }

    .tabellone-qr-img {
        width: min(180px, 100%);
        aspect-ratio: 1 / 1;
        object-fit: contain;
        border-radius: 0.75rem;
        border: 1px solid var(--tb-border);
        background: #fff;
        padding: 0.35rem;
    }

    .tabellone-qr-caption {
        margin: 0.4rem 0 0;
        font-size: 0.75rem;
        color: var(--tb-muted);
    }

    @media (max-width: 1200px) {
        .tabellone-container {
            grid-template-columns: minmax(0, 1fr) 280px;
        }

        .tabellone-grid {
            grid-template-columns: repeat(2, minmax(0, 1fr));
            grid-template-rows: repeat(3, minmax(0, 1fr));
        }
    }

    @media (max-width: 992px) {
        .tabellone-root-outer {
            padding: 0.75rem;
        }

        .tabellone-container {
            height: calc(100vh - 1.5rem);
            min-height: 0;
            grid-template-columns: 1fr;
            grid-template-rows: auto auto;
        }

        .tabellone-sidebar {
            min-height: 520px;
            max-height: none;
        }
    }

    @media (max-width: 576px) {
        .tabellone-header {
            flex-direction: column;
            align-items: flex-start;
        }

        .tabellone-grid-outer {
            padding: 0.65rem;
        }

        .tabellone-grid {
            grid-template-columns: 1fr;
            grid-template-rows: repeat(6, minmax(0, 1fr));
        }
    }
</style>

<div class="tabellone-root-outer">
    <div class="tabellone-container w-100">
        <div class="tabellone-main">
            <div class="tabellone-extract-modal" id="tombola-extract-modal">
                <div class="tabellone-extract-modal-card">
                    <p class="tabellone-extract-modal-label">Numero estratto</p>
                    <p class="tabellone-extract-modal-number" id="tombola-extract-modal-number">-</p>
                </div>
            </div>
            <div class="tabellone-header" style="display: none;">
                <div class="tabellone-title-wrap">
                    <span class="tabellone-title-badge">90</span>
                    <div>
                        <h1 class="tabellone-title">Tabellone Tombola</h1>
                        <p class="tabellone-subtitle">Vista live numeri estratti</p>
                    </div>
                </div>
            </div>
            <div class="d-flex flex-column" style="flex: 1 1 0; min-height: 0;">
                <!-- <div id="tombola-alerts">
                    @if (session('success'))
                        <div class="alert alert-success m-3 mb-0">{{ session('success') }}</div>
                    @endif
                    @if (session('error'))
                        <div class="alert alert-danger m-3 mb-0">{{ session('error') }}</div>
                    @endif
                </div> -->
                <div class="tabellone-grid-outer" >
                    <div class="tabellone-grid">
                        @for ($blocco = 0; $blocco < 6; $blocco++)
                            <div class="tabellone-subgrid">
                                @for ($offset = 1; $offset <= 15; $offset++)
                                    @php
                                        $numero = ($blocco * 15) + $offset;
                                    @endphp
                                    <div class="rounded-4 fs-1 tabellone-numero {{ in_array($numero, $estratti) ? 'estratto' : 'non-estratto' }}" id="tombola-numero-{{ $numero }}">
                                        {{ $numero }}
                                    </div>
                                @endfor
                            </div>
                        @endfor
                    </div>
                </div>
            </div>
        </div>
        <div class="tabellone-sidebar">
            <div class="tabellone-sidebar-content">
                <h6 class="tabellone-sidebar-title">Numeri estratti</h6>
                <div class="tabellone-last-wrap" id="tombola-last-wrap">
                    <p class="tabellone-last-label">Ultimo estratto</p>
                    <p class="tabellone-last-number" id="tombola-last-number">{{ $ultimoEstratto ?? '—' }}</p>
                </div>
                <div class="tabellone-sidebar-list" id="tombola-estratti-list">
                    @foreach($storicoEstratti as $num)
                        <span class="tabellone-sidebar-num" data-numero="{{ $num }}">{{ $num }}</span>
                    @endforeach
                </div>
                <div class="text-muted small {{ count($estratti) > 0 ? 'd-none' : '' }}" id="tombola-empty-state">Nessun numero estratto.</div>
                <div class="tabellone-sidebar-footer">
                    Totale: <span class="fw-semibold" id="tombola-estratti-count">{{ count($estratti) }}</span>/90
                </div>
                <div class="tabellone-sidebar-actions">
                    <div class="tabellone-qr-wrap">
                        <img src="{{ $qrCodeUrl }}" alt="QR code numeri estratti" class="tabellone-qr-img">
                        <p class="tabellone-qr-caption">Scansiona per vedere solo gli estratti</p>
                    </div>
                    <form action="{{ route('tombola.estrai', ['attivita_id' => $attivita->id]) }}" method="POST" id="tombola-estrazione-form">
                        @csrf
                        <button type="submit" class="btn btn-primary w-100" id="tombola-estrazione-btn">Estrai Numero</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    (function () {
        const form = document.getElementById('tombola-estrazione-form');
        if (!form) {
            return;
        }

        const button = document.getElementById('tombola-estrazione-btn');
        const alerts = document.getElementById('tombola-alerts');
        const list = document.getElementById('tombola-estratti-list');
        const emptyState = document.getElementById('tombola-empty-state');
        const countNode = document.getElementById('tombola-estratti-count');
        const lastWrap = document.getElementById('tombola-last-wrap');
        const lastNumberNode = document.getElementById('tombola-last-number');
        const extractModal = document.getElementById('tombola-extract-modal');
        const extractModalNumber = document.getElementById('tombola-extract-modal-number');
        const csrfToken = form.querySelector('input[name="_token"]')?.value || '';
        let extractModalTimeout = null;

        const renderAlert = (message, type) => {
            if (!alerts) {
                return;
            }

            alerts.innerHTML = '<div class="alert alert-' + type + ' m-3 mb-0">' + message + '</div>';
        };

        const showExtractModal = (numero) => {
            if (!extractModal || !extractModalNumber || !Number.isFinite(numero)) {
                return;
            }

            extractModalNumber.textContent = String(numero);
            extractModal.classList.add('is-visible');

            if (extractModalTimeout) {
                window.clearTimeout(extractModalTimeout);
            }

            extractModalTimeout = window.setTimeout(function () {
                extractModal.classList.remove('is-visible');
            }, 3000);
        };

        form.addEventListener('submit', async function (event) {
            event.preventDefault();

            if (!button || button.disabled) {
                return;
            }

            button.disabled = true;
            const originalLabel = button.textContent;
            button.textContent = 'Estrazione...';

            try {
                const response = await fetch(form.action, {
                    method: 'POST',
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest',
                        'X-CSRF-TOKEN': csrfToken,
                        'Accept': 'application/json'
                    },
                    body: new FormData(form)
                });

                const payload = await response.json();

                if (!response.ok || !payload.success) {
                    renderAlert(payload.message || 'Errore durante l\'estrazione.', 'danger');
                    return;
                }

                const numero = Number(payload.numero);
                const cell = document.getElementById('tombola-numero-' + numero);

                if (cell) {
                    cell.classList.remove('non-estratto');
                    cell.classList.add('estratto', 'is-newly-extracted');
                    window.setTimeout(function () {
                        cell.classList.remove('is-newly-extracted');
                    }, 800);
                }

                showExtractModal(numero);

                const previousLast = lastNumberNode ? Number(lastNumberNode.textContent) : NaN;

                if (lastNumberNode && Number.isFinite(numero)) {
                    lastNumberNode.textContent = String(numero);
                }

                if (
                    list &&
                    Number.isFinite(previousLast) &&
                    previousLast > 0 &&
                    previousLast !== numero &&
                    !list.querySelector('[data-numero="' + previousLast + '"]')
                ) {
                    const previousChip = document.createElement('span');
                    previousChip.className = 'tabellone-sidebar-num';
                    previousChip.dataset.numero = String(previousLast);
                    previousChip.textContent = String(previousLast);
                    list.prepend(previousChip);

                    while (list.children.length > 30) {
                        list.removeChild(list.lastElementChild);
                    }
                }

                if (countNode && typeof payload.estratti_count !== 'undefined') {
                    countNode.textContent = String(payload.estratti_count);
                }

                if (emptyState) {
                    emptyState.classList.add('d-none');
                }

                renderAlert(payload.message || ('Estratto il numero ' + numero + '.'), 'success');

                if (payload.remaining === 0) {
                    button.disabled = true;
                    button.textContent = 'Completata';
                    renderAlert('Estrazione completata: tutti i numeri sono stati estratti.', 'success');
                    return;
                }
            } catch (error) {
                renderAlert('Errore di rete durante l\'estrazione.', 'danger');
            } finally {
                if (button && !button.disabled) {
                    button.textContent = originalLabel;
                }
                if (button && button.textContent === 'Estrazione...') {
                    button.textContent = originalLabel;
                }
                if (button && button.textContent !== 'Completata') {
                    button.disabled = false;
                }
            }
        });
    })();
</script>