@php
    $ultimoEstratto = $estratti->first();
    $storicoEstratti = $estratti->slice(1, 7);
@endphp

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

    @supports (height: 100dvh) {
        :root {
            --viewport-h: 100dvh;
        }
    }

    html, body {
        margin: 0;
        height: 100%;
        overflow: hidden;
        background: var(--tb-bg);
        color: var(--tb-text);
        font-family: "Public Sans", sans-serif;
    }

    .estratti-wrap {
        min-height: var(--viewport-h);
        display: flex;
        align-items: stretch;
        justify-content: stretch;
        padding: 0;
    }

    .estratti-card {
        width: 100%;
        height: var(--viewport-h);
        min-height: var(--viewport-h);
        background: var(--tb-card);
        border: 1px solid var(--tb-border);
        border-radius: 0;
        box-shadow: none;
        padding: 0.75rem 0.9rem max(0.75rem, env(safe-area-inset-bottom));
        display: grid;
        grid-template-rows: auto minmax(0, 1.25fr) auto minmax(0, 1fr) auto;
        gap: 0.45rem;
        overflow: hidden;
    }

    .estratti-title {
        margin: 0;
        font-size: clamp(1.1rem, 2.6vw, 1.6rem);
        font-weight: 700;
        color: #37475a;
        text-align: center;
    }

    .estratti-last {
        border: 1px solid var(--tb-border);
        border-radius: 0.85rem;
        background: #f8f9ff;
        padding: 0.65rem;
        text-align: center;
        display: flex;
        flex-direction: column;
        justify-content: center;
        min-height: 0;
    }

    .estratti-last-label {
        margin: 0;
        font-size: clamp(0.78rem, 1.9vw, 1rem);
        font-weight: 600;
        color: var(--tb-muted);
        text-transform: uppercase;
        letter-spacing: 0.04em;
    }

    .estratti-last-number {
        margin: 0.2rem 0 0;
        font-size: clamp(9.8rem, 34vw, 20rem);
        font-weight: 800;
        color: var(--tb-primary);
        line-height: 1;
    }

    .estratti-list {
        display: grid;
        grid-template-columns: repeat(4, minmax(0, 1fr));
        grid-template-rows: repeat(2, minmax(0, 1fr));
        justify-items: center;
        align-items: center;
        gap: 0.22rem;
        min-height: 0;
        overflow: hidden;
        padding-right: 0;
    }

    .estratti-recent-title {
        margin: 0 0 0.55rem;
        font-size: clamp(1.2rem, 3vw, 1.8rem);
        font-weight: 700;
        color: #6b7889;
        text-transform: uppercase;
        letter-spacing: 0.03em;
        justify-self: center;
    }

    .estratti-chip {
        background: var(--tb-success-soft);
        color: #4f8f2f;
        border: 1px solid rgba(113, 221, 55, 0.35);
        font-size: clamp(2.7rem, 7.4vw, 4.4rem);
        font-weight: 700;
        width: clamp(4rem, 13vw, 6rem);
        height: clamp(3.3rem, 9.2vh, 5rem);
        border-radius: 0.55rem;
        text-align: center;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .estratti-empty {
        font-size: 1rem;
        color: var(--tb-muted);
    }

    .estratti-footer {
        margin-top: 0;
        padding-top: 0.35rem;
        border-top: 1px dashed var(--tb-border);
        font-size: clamp(0.72rem, 1.6vw, 0.95rem);
        color: var(--tb-muted);
        display: flex;
        justify-content: space-between;
        gap: 0.55rem;
    }

    @media (max-width: 768px) {
        .estratti-wrap {
            padding: 0;
            align-items: stretch;
        }

        .estratti-card {
            width: 100%;
            height: var(--viewport-h);
            min-height: var(--viewport-h);
            border-radius: 0;
            border-left: 0;
            border-right: 0;
            box-shadow: none;
            padding: 0.5rem;
            grid-template-rows: auto minmax(0, 1.35fr) auto minmax(0, 1fr) auto;
            gap: 0.3rem;
        }

        .estratti-title {
            font-size: clamp(1.2rem, 5vw, 1.6rem);
            margin-bottom: 0.25rem;
        }

        .estratti-last {
            padding: 0.35rem;
            min-height: 0;
        }

        .estratti-last-label {
            font-size: clamp(0.9rem, 3vw, 1.1rem);
        }

        .estratti-last-number {
            font-size: clamp(11.8rem, 52vw, 20rem);
        }

        .estratti-recent-title {
            font-size: clamp(1.08rem, 4.3vw, 1.45rem);
            margin-bottom: 0.25rem;
        }

        .estratti-list {
            grid-template-columns: repeat(4, minmax(0, 1fr));
            grid-template-rows: repeat(2, minmax(0, 1fr));
            gap: 0.16rem;
            min-height: 0;
        }

        .estratti-chip {
            font-size: clamp(3.1rem, 9.2vw, 5rem);
            width: clamp(4.3rem, 22vw, 6.2rem);
            height: clamp(3.5rem, 9.8vh, 5.3rem);
        }

        .estratti-footer {
            margin-top: auto;
            font-size: clamp(0.72rem, 2.5vw, 0.95rem);
            flex-direction: column;
            gap: 0.1rem;
            padding-top: 0.2rem;
        }
    }

    @media (max-width: 430px) {
        .estratti-title {
            font-size: clamp(1.25rem, 6vw, 1.7rem);
        }

        .estratti-last-number {
            font-size: clamp(12.6rem, 56vw, 21rem);
        }

        .estratti-list {
            gap: 0.25rem;
        }

        .estratti-chip {
            font-size: clamp(3.25rem, 10vw, 5.3rem);
            width: clamp(4.4rem, 23vw, 6.3rem);
            height: clamp(3.55rem, 10.2vh, 5.5rem);
        }
    }
</style>

<div class="estratti-wrap">
    <div class="estratti-card">
        <h6 class="estratti-title">Numeri estratti</h6>

        <div class="estratti-last">
            <p class="estratti-last-label">Ultimo estratto</p>
            <p class="estratti-last-number" id="estratti-last-number">{{ $ultimoEstratto?->numero ?? '—' }}</p>
        </div>

        <p class="estratti-recent-title">Ultimi 7 numeri estratti</p>
        <div class="estratti-list" id="estratti-list">
            @foreach($storicoEstratti as $estratto)
                <span class="estratti-chip">{{ $estratto->numero }}</span>
            @endforeach
        </div>

        <p class="estratti-empty mb-0 mt-2 {{ $estratti->isEmpty() ? '' : 'd-none' }}" id="estratti-empty-state">Nessun numero estratto.</p>

        <div class="estratti-footer">
            <span>Totale: <strong id="estratti-count">{{ $estratti->count() }}</strong>/90</span>
            <span>
                Ultimo aggiornamento:
                <span id="estratti-updated-at">{{ $ultimoEstratto?->estratto_at ? $ultimoEstratto->estratto_at->format('d/m/Y H:i') : '-' }}</span>
            </span>
        </div>
    </div>
</div>

<script>
    (function () {
        const REFRESH_INTERVAL_MS = 5000;
        const url = window.location.href;
        const lastNumberNode = document.getElementById('estratti-last-number');
        const listNode = document.getElementById('estratti-list');
        const emptyStateNode = document.getElementById('estratti-empty-state');
        const countNode = document.getElementById('estratti-count');
        const updatedAtNode = document.getElementById('estratti-updated-at');

        if (!lastNumberNode || !listNode || !emptyStateNode || !countNode || !updatedAtNode) {
            return;
        }

        const toLabelDate = function (isoString) {
            if (!isoString) {
                return '-';
            }

            const date = new Date(isoString);
            if (Number.isNaN(date.getTime())) {
                return '-';
            }

            const pad = function (v) {
                return String(v).padStart(2, '0');
            };

            return pad(date.getDate()) + '/' + pad(date.getMonth() + 1) + '/' + date.getFullYear() + ' ' + pad(date.getHours()) + ':' + pad(date.getMinutes());
        };

        const renderPayload = function (payload) {
            if (!payload || payload.success !== true) {
                return;
            }

            const ultimo = payload.ultimo;
            const storico = Array.isArray(payload.storico) ? payload.storico : [];
            const count = Number.isFinite(Number(payload.count)) ? Number(payload.count) : 0;

            lastNumberNode.textContent = ultimo && Number.isFinite(Number(ultimo.numero))
                ? String(ultimo.numero)
                : '—';

            countNode.textContent = String(count);
            updatedAtNode.textContent = ultimo ? toLabelDate(ultimo.estratto_at) : '-';

            listNode.innerHTML = '';
            storico.forEach(function (item) {
                const chip = document.createElement('span');
                chip.className = 'estratti-chip';
                chip.textContent = String(item.numero);
                listNode.appendChild(chip);
            });

            if (count > 0) {
                emptyStateNode.classList.add('d-none');
            } else {
                emptyStateNode.classList.remove('d-none');
            }
        };

        const refreshData = async function () {
            if (document.visibilityState !== 'visible') {
                return;
            }

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

                if (!response.ok) {
                    return;
                }

                const payload = await response.json();
                renderPayload(payload);
            } catch (error) {
                // silent fail: next cycle will retry
            }
        };

        window.setInterval(function () {
            refreshData();
        }, REFRESH_INTERVAL_MS);
    })();
</script>