/**
 * Alpine Modal Component
 */
export function registerModal(Alpine) {
    Alpine.data('modal', (id) => ({
        id,
        open: false,

        init() {
            window._modalRegistry = window._modalRegistry || {};
            window._modalRegistry[this.id] = this;
        },

        show() { this.open = true; },
        hide() { this.open = false; },
        toggle() { this.open = !this.open; },
    }));

    window.modalOpen = function(id) {
        const r = window._modalRegistry || {};
        if (r[id]) r[id].show();
        else { const el = document.getElementById(id); if (el) el.style.display = 'flex'; }
    };

    window.modalClose = function(id) {
        const r = window._modalRegistry || {};
        if (r[id]) r[id].hide();
        else { const el = document.getElementById(id); if (el) el.style.display = 'none'; }
    };

    window.openModal = window.modalOpen;
    window.closeModal = window.modalClose;

    window.handleConfirmAction = async function(button) {
        const url = button.dataset.confirmUrl;
        const method = button.dataset.confirmMethod || 'POST';
        if (!url) return;
        button.disabled = true;
        const originalText = button.textContent;
        button.textContent = 'Đang xử lý...';
        try {
            const response = await fetch(url, {
                method,
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.content || '',
                    'Accept': 'application/json',
                    'Content-Type': 'application/json',
                },
            });
            const data = await response.json();
            if (response.ok) {
                showSuccess('Thành công', data.message || 'Thao tác đã được thực hiện');
                if (data.reload) window.location.reload();
            } else {
                showError('Lỗi', data.message || 'Có lỗi xảy ra');
            }
        } catch (error) {
            showError('Lỗi', 'Không thể kết nối đến server');
        } finally {
            button.disabled = false;
            button.textContent = originalText;
        }
    };
}
