document.addEventListener('DOMContentLoaded', () => {

    // =====================================================
    // ELEMENTOS BASE
    // =====================================================
    const customerList = document.getElementById('customer-list')
    const paginationControls = document.getElementById('pagination-controls')

    if (!customerList || !paginationControls || !window.customerListConfig) {
        return
    }

    const { apiUrl, csrfToken } = window.customerListConfig
    const toast = document.getElementById('toast')

    // =====================================================
    // DIALOG GLOBAL
    // =====================================================
    const dialogEl = document.getElementById('appDialog')

    if (!dialogEl || typeof dialogEl.dialog !== 'function') {
        console.error('Dialog não inicializado')
        return
    }

    // =====================================================
    // TOAST
    // =====================================================
    function showToast(message, isError = false) {
        if (!toast) return

        toast.textContent = message
        toast.style.backgroundColor = isError ? '#ef4444' : '#22c55e'
        toast.style.display = 'block'
        toast.style.opacity = 1

        setTimeout(() => {
            toast.style.opacity = 0
            setTimeout(() => toast.style.display = 'none', 400)
        }, 4000)
    }

    // =====================================================
    // FETCH CLIENTES
    // =====================================================
    async function fetchCustomers(page = 1) {
        try {
            const response = await fetch(`${apiUrl}/list?page=${page}`)
            const result = await response.json()

            if (result.success && result.pagination) {
                renderCustomers(result.pagination.data)
                renderPagination(result.pagination)
            } else {
                showToast(result.message || 'Erro ao carregar clientes.', true)
            }
        } catch {
            showToast('Erro de conexão.', true)
        }
    }

    // =====================================================
    // RENDER LISTAGEM
    // =====================================================
    function renderCustomers(customers) {
        customerList.innerHTML = ''

        if (!customers || customers.length === 0) {
            customerList.innerHTML = `
                <tr>
                    <td colspan="5" class="text-center py-4">
                        Nenhum cliente cadastrado.
                    </td>
                </tr>
            `
            return
        }

        customers.forEach(customer => {
            const tr = document.createElement('tr')
            tr.dataset.id = customer.id

            tr.innerHTML = `
                <td class="px-6 py-4 text-sm font-medium">${customer.id}</td>
                <td class="px-6 py-4 text-sm">${escapeHtml(customer.name)}</td>
                <td class="px-6 py-4 text-sm">${escapeHtml(customer.cpf)}</td>
                <td class="px-6 py-4 text-sm">${escapeHtml(customer.phone || '')}</td>
                <td class="px-6 py-4 text-right text-sm">
                    <a href="${apiUrl}/form/${customer.id}"
                       class="text-indigo-600 hover:text-indigo-900">
                        Editar
                    </a>
                    <button type="button"
                        class="ml-4 text-red-600 hover:text-red-900 delete-btn">
                        Excluir
                    </button>
                </td>
            `
            customerList.appendChild(tr)
        })
    }

    // =====================================================
    // PAGINAÇÃO
    // =====================================================
    function createPageButton(page, current) {
        const btn = document.createElement('button')
        btn.textContent = page
        btn.dataset.page = page
        btn.className = page === current
            ? 'px-4 py-2 bg-blue-600 text-white rounded-md'
            : 'px-4 py-2 bg-gray-200 rounded-md hover:bg-gray-300'
        btn.disabled = page === current
        return btn
    }

    function createEllipsis(totalPages) {
        const btn = document.createElement('button')
        btn.textContent = '...'
        btn.dataset.totalPages = totalPages
        btn.className = 'px-4 py-2 bg-gray-200 rounded-md hover:bg-gray-300 ellipsis-btn'
        return btn
    }

    function renderPagination(pagination) {
        paginationControls.innerHTML = ''
        if (!pagination || pagination.total_pages <= 1) return

        const { current_page, total_pages } = pagination

        const prev = document.createElement('button')
        prev.innerHTML = '&laquo; Anterior'
        prev.dataset.page = current_page - 1
        prev.disabled = current_page <= 1
        prev.className = 'px-4 py-2 bg-gray-200 rounded-md disabled:opacity-50'
        paginationControls.appendChild(prev)

        let start = Math.max(1, current_page - 2)
        let end = Math.min(total_pages, current_page + 2)

        if (start > 1) {
            paginationControls.appendChild(createPageButton(1, current_page))
            if (start > 2) paginationControls.appendChild(createEllipsis(total_pages))
        }

        for (let i = start; i <= end; i++) {
            paginationControls.appendChild(createPageButton(i, current_page))
        }

        if (end < total_pages) {
            if (end < total_pages - 1) {
                paginationControls.appendChild(createEllipsis(total_pages))
            }
            paginationControls.appendChild(createPageButton(total_pages, current_page))
        }

        const next = document.createElement('button')
        next.innerHTML = 'Próximo &raquo;'
        next.dataset.page = current_page + 1
        next.disabled = current_page >= total_pages
        next.className = 'px-4 py-2 bg-gray-200 rounded-md disabled:opacity-50'
        paginationControls.appendChild(next)
    }

    paginationControls.addEventListener('click', e => {
        if (e.target.dataset.page) {
            fetchCustomers(parseInt(e.target.dataset.page, 10))
        }

        if (e.target.classList.contains('ellipsis-btn')) {
            const total = parseInt(e.target.dataset.totalPages, 10)

            dialogEl.dialog({
                title: 'Ir para página',
                message: `Digite um número entre 1 e ${total}`,
                input: {
                    show: true,
                    type: 'number',
                    min: 1,
                    max: total
                },
                onApprove: value => {
                    const page = parseInt(value, 10)
                    if (page >= 1 && page <= total) {
                        fetchCustomers(page)
                    }
                }
            })
        }
    })

    // =====================================================
    // EXCLUSÃO (DIALOG)
    // =====================================================
    customerList.addEventListener('click', e => {
        const btn = e.target.closest('.delete-btn')
        if (!btn) return

        const row = btn.closest('tr')
        const id = row?.dataset.id
        if (!id) return

        dialogEl.dialog({
            title: 'Excluir cliente?',
            message: 'Esta ação não pode ser desfeita.',
            type: 'danger',
            onApprove: async () => {
                try {
                    const response = await fetch(`${apiUrl}/delete/${id}`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': csrfToken
                        }
                    })

                    const result = await response.json()

                    if (response.ok && result.success) {
                        showToast(result.message)
                        fetchCustomers()
                    } else {
                        showToast(result.message || 'Erro ao excluir.', true)
                    }
                } catch {
                    showToast('Erro de conexão.', true)
                }
            }
        })
    })

    // =====================================================
    // ESCAPE HTML (XSS SAFE)
    // =====================================================
    function escapeHtml(str) {
        if (str == null) return ''
        const p = document.createElement('p')
        p.textContent = str
        return p.innerHTML
    }

    // =====================================================
    // INIT
    // =====================================================
    fetchCustomers(1)

})
