{{define "modal-partial"}}
<div id="modal-overlay" class="modal-overlay fixed inset-0 bg-black bg-opacity-50 hidden items-center justify-center z-50">
    <div class="modal-container bg-gray-800 rounded-lg shadow-2xl max-w-md w-full mx-4 transform transition-all">
        <div class="modal-header p-6 border-b border-gray-700">
            <div class="flex items-center justify-between">
                <h3 class="modal-title text-xl font-semibold text-white">{{.Title}}</h3>
                <button class="modal-close text-gray-400 hover:text-white transition" aria-label="Close modal">
                    <i class="bx bx-x text-2xl"></i>
                </button>
            </div>
        </div>

        <div class="modal-body p-6">
            <p class="modal-message text-gray-300">{{.Message}}</p>
        </div>

        <div class="modal-footer p-6 border-t border-gray-700 flex justify-end gap-3">
            <button class="modal-cancel-btn bg-gray-700 hover:bg-gray-600 text-white px-4 py-2 rounded transition">
                {{.CancelText}}
            </button>
            <button class="modal-confirm-btn {{if .Danger}}bg-red-600 hover:bg-red-700{{else}}bg-purple-600 hover:bg-purple-700{{end}} text-white px-4 py-2 rounded transition"
                    data-confirm-url="{{.ConfirmURL}}"
                    data-confirm-data="{{.ConfirmData}}">
                {{.ConfirmText}}
            </button>
        </div>
    </div>
</div>

<style>
.modal-overlay {
    backdrop-filter: blur(4px);
}

.modal-container {
    animation: modalSlideIn 0.3s ease-out;
}

@keyframes modalSlideIn {
    from {
        opacity: 0;
        transform: scale(0.95) translateY(-10px);
    }
    to {
        opacity: 1;
        transform: scale(1) translateY(0);
    }
}

.modal-container.modal-closing {
    animation: modalSlideOut 0.2s ease-in forwards;
}

@keyframes modalSlideOut {
    from {
        opacity: 1;
        transform: scale(1) translateY(0);
    }
    to {
        opacity: 0;
        transform: scale(0.95) translateY(-10px);
    }
}
</style>

<script>
// Modal state
const modalOverlay = document.getElementById('modal-overlay');
const modalContainer = modalOverlay.querySelector('.modal-container');
const modalCloseBtn = modalOverlay.querySelector('.modal-close');
const modalCancelBtn = modalOverlay.querySelector('.modal-cancel-btn');
const modalConfirmBtn = modalOverlay.querySelector('.modal-confirm-btn');

let pendingAction = null;

// Show modal function
function showModal(modalData) {
    document.querySelector('.modal-title').textContent = modalData.title;
    document.querySelector('.modal-message').textContent = modalData.message;
    document.querySelector('.modal-cancel-btn').textContent = modalData.cancel_text;
    document.querySelector('.modal-confirm-btn').textContent = modalData.confirm_text;
    document.querySelector('.modal-confirm-btn').dataset.confirmUrl = modalData.confirm_url;
    document.querySelector('.modal-confirm-btn').dataset.confirmData = modalData.confirm_data || '';

    if (modalData.danger) {
        document.querySelector('.modal-confirm-btn').classList.remove('bg-purple-600', 'hover:bg-purple-700');
        document.querySelector('.modal-confirm-btn').classList.add('bg-red-600', 'hover:bg-red-700');
    } else {
        document.querySelector('.modal-confirm-btn').classList.remove('bg-red-600', 'hover:bg-red-700');
        document.querySelector('.modal-confirm-btn').classList.add('bg-purple-600', 'hover:bg-purple-700');
    }

    modalOverlay.classList.remove('hidden');
    modalOverlay.classList.add('flex');
    modalContainer.classList.remove('modal-closing');
}

// Hide modal function
function hideModal() {
    modalContainer.classList.add('modal-closing');
    setTimeout(() => {
        modalOverlay.classList.add('hidden');
        modalOverlay.classList.remove('flex');
        pendingAction = null;
    }, 200);
}

// Event listeners
modalCloseBtn.addEventListener('click', hideModal);
modalCancelBtn.addEventListener('click', hideModal);

modalOverlay.addEventListener('click', (e) => {
    if (e.target === modalOverlay) {
        hideModal();
    }
});

document.addEventListener('keydown', (e) => {
    if (e.key === 'Escape' && !modalOverlay.classList.contains('hidden')) {
        hideModal();
    }
});

modalConfirmBtn.addEventListener('click', async () => {
    const confirmUrl = modalConfirmBtn.dataset.confirmUrl;
    const confirmData = modalConfirmBtn.dataset.confirmData;

    if (!confirmUrl) {
        console.error('Missing confirm URL');
        hideModal();
        return;
    }

    try {
        const options = {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            }
        };

        if (confirmData) {
            options.body = confirmData;
        }

        const response = await fetch(confirmUrl, options);

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        // Refresh the page on success
        if (response.ok) {
            setTimeout(() => {
                window.location.reload();
            }, 500);
        }
    } catch (error) {
        console.error('Error executing modal action:', error);
        alert('Error executing action: ' + error.message);
    } finally {
        hideModal();
    }
});

// Handle data-modal attribute clicks
document.addEventListener('click', async (e) => {
    const button = e.target.closest('[data-modal]');
    if (!button) return;

    e.preventDefault();

    const modalType = button.dataset.modal;
    const modalParams = new URLSearchParams(button.dataset.modalParams || '');

    try {
        const response = await fetch(`/api/modal?type=${modalType}&${modalParams}`);

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        const modalData = await response.json();
        showModal(modalData);
    } catch (error) {
        console.error('Error loading modal:', error);
        // Fallback to browser confirm if modal fails to load
        if (button.hasAttribute('hx-confirm')) {
            const confirmMsg = button.getAttribute('hx-confirm');
            if (confirm(confirmMsg)) {
                // Trigger the HTMX request
                htmx.trigger(button, 'click');
            }
        }
    }
});

// Store original htmx-confirm and use it as fallback
document.querySelectorAll('[hx-confirm]').forEach(button => {
    const confirmMsg = button.getAttribute('hx-confirm');
    button.dataset.modalFallback = confirmMsg;
});
</script>
{{end}}
