export function initBilletDesigner() {
    const designer = document.getElementById('billet-designer')
    if (!designer) return

    const previewUrl = designer.dataset.previewUrl
    const saveUrl = designer.dataset.saveUrl
    if (!previewUrl) return

    const iframe = document.getElementById('billet-preview-frame')
    const reloadBtn = document.getElementById('billet-reload-preview')
    const saveBtn = document.getElementById('billet-save-design')
    if (!iframe) return

    const inputs = designer.querySelectorAll('input[name]')

    function buildPreviewUrl() {
        const params = new URLSearchParams()

        for (const input of inputs) {
            if (input.type === 'checkbox') {
                params.set(input.name, input.checked ? '1' : '0')
            } else {
                params.set(input.name, input.value)
            }
        }

        return previewUrl + '?' + params.toString()
    }

    function reloadPreview() {
        iframe.src = buildPreviewUrl()
    }

    function saveDesign() {
        if (!saveUrl) return

        const formData = new FormData()
        for (const input of inputs) {
            if (input.type === 'checkbox') {
                formData.set(input.name, input.checked ? '1' : '0')
            } else {
                formData.set(input.name, input.value)
            }
        }

        if (saveBtn) {
            saveBtn.disabled = true
            saveBtn.textContent = 'Enregistrement...'
        }

        globalThis.fetch(saveUrl, {
            method: 'POST',
            body: formData,
        }).then(r => {
            if (!r.ok) throw new Error(r.status)
            if (saveBtn) {
                saveBtn.textContent = 'Enregistre !'
                setTimeout(() => { saveBtn.textContent = 'Enregistrer'; saveBtn.disabled = false }, 1500)
            }
        }).catch(() => {
            if (saveBtn) {
                saveBtn.textContent = 'Erreur — Reessayer'
                saveBtn.disabled = false
            }
        })
    }

    for (const input of inputs) {
        input.addEventListener('input', reloadPreview)
        input.addEventListener('change', reloadPreview)
    }

    if (reloadBtn) {
        reloadBtn.addEventListener('click', reloadPreview)
    }

    if (saveBtn) {
        saveBtn.addEventListener('click', saveDesign)
    }
}
