<script>
    import { onMount, tick } from 'svelte'
    import './CookiePopUp.css'
    import Button from "../Button/Button.svelte"
    import Toggle from "../Toggle/Toggle.svelte"
    import { applyConsent, getStoredConsent, saveConsent } from "../../lib/cookieConsent"

    let isOpen = $state(false)
    let view = $state('main') // 'main' | 'prefs'
    let dialogEl = $state(null)

    let tecnici = $state(true)  // always enabled (required)
    let analitici = $state(false)
    let profilazione = $state(false)

    const applyAndSaveConsent = (consent) => {
        saveConsent(consent)
        applyConsent(consent)
    }

    const close = () => {
        isOpen = false
        view = 'main'
    }

    const acceptAll = () => {
        applyAndSaveConsent({
            value: 'accepted_all',
            preferences: { tecnici: true, analitici: true, profilazione: true }
        })
        close()
    }

    const rejectAll = () => {
        applyAndSaveConsent({
            value: 'rejected_all',
            preferences: { tecnici: true, analitici: false, profilazione: false }
        })
        close()
    }

    const openPrefs = () => {
        view = 'prefs'
        tick().then(() => {
            if (!dialogEl) return
            const first = dialogEl.querySelector('input, button, [href], select, textarea, [tabindex]:not([tabindex="-1"])')
            first?.focus?.()
        })
    }

    const savePrefs = () => {
        applyAndSaveConsent({
            value: 'custom',
            preferences: { tecnici, analitici, profilazione }
        })
        close()
    }

    const handleKeydown = (event) => {
        if (!isOpen) return
        if (event.key === 'Escape') {
            event.preventDefault()
            // Treat Escape as an explicit choice so the dialog doesn't reappear immediately.
            rejectAll()
        }
    }

    onMount(() => {
        const existing = getStoredConsent()

        if (existing?.preferences) {
            tecnici = true
            analitici = existing.preferences.analitici
            profilazione = existing.preferences.profilazione
        }

        isOpen = !existing

        if (isOpen) {
            tick().then(() => {
                if (!dialogEl) return
                const first = dialogEl.querySelector('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])')
                first?.focus?.()
            })
        }
    })
</script>

<svelte:window onkeydown={handleKeydown} />

{#if isOpen}
    <div class="cookie-backdrop" aria-hidden="true"></div>

    <div
        class="cookie-popup"
        role="dialog"
        aria-modal="true"
        aria-labelledby="cookie-dialog-title"
        bind:this={dialogEl}
    >
        <div class="cookie-popup-container">
            <div class="cookie-popup-content">
                <div class="cookie-popup-title">
                    <div class="cookie-icon" aria-hidden="true"></div>
                    <h2 id="cookie-dialog-title">Usiamo i cookie</h2>
                </div>

                {#if view === 'main'}
                    <p>Questo sito usa cookie per personalizzazione e analisi. Clicca "Accetta tutti" per continuare o gestisci le tue preferenze.</p>
                    <a href="/cookie-policy" class="cookie-link">Leggi la cookie policy ⇾</a>
                {:else}
                    <p>Questo sito usa cookie per personalizzazione e analisi. Clicca "Accetta tutti" per continuare o gestisci le tue preferenze.</p>
                    <div class="cookie-selector">
                        <p>Seleziona le categorie di cookie che desideri abilitare. </p>
                        <div class="cookie-toggle-container">
                            <label class="cookie-toggle-item">
                                <Toggle bind:checked={tecnici} label="Tecnici" disabled />
                            </label>
                            <label class="cookie-toggle-item">
                                <Toggle bind:checked={analitici} label="Analitici" />
                            </label>
                            <label class="cookie-toggle-item">
                                <Toggle bind:checked={profilazione} label="Profilazione" />
                            </label>
                        </div>
                    </div>
                    <a href="/cookie-policy" class="cookie-link">Leggi la cookie policy ⇾</a>

                {/if}
            </div>
        </div>

        <div class="cookie-popup-actions">
            {#if view === 'main'}
                <button type="button" class="cookie-link cookie-link-button" onclick={openPrefs}>
                    Personalizza
                </button>
                <div class="cookie-popup-buttons">
                    <Button text="Rifiuta" onclick={rejectAll} />
                    <Button text="Accetta tutti" onclick={acceptAll} />
                </div>
            {:else}
                <button type="button" class="cookie-link cookie-link-button" onclick={() => (view = 'main')}>
                    Indietro
                </button>
                <div class="cookie-popup-buttons">
                    <Button text="Rifiuta" onclick={rejectAll} />
                    <Button text="Salva preferenze" onclick={savePrefs} />
                </div>
            {/if}
        </div>
    </div>
{/if}