(function () {
    'use strict';

    const modal = document.getElementById('deleteContractModal');
    if (!modal) {
        return;
    }

    const tokenInput = document.getElementById('deleteContractToken');
    const contractIdInput = document.getElementById('deleteContractId');
    const passwordInput = document.getElementById('deleteContractPassword');
    const submitBtn = document.getElementById('deleteContractSubmitBtn');
    const refLabel = document.getElementById('deleteContractRef');
    const requirePassword = modal.getAttribute('data-require-password') === '1';
    const backdrop = modal.querySelector('[data-modal-close]');
    const cancelButtons = modal.querySelectorAll('[data-modal-cancel]');

    function openModal(token, ref, contractId) {
        if (tokenInput) {
            tokenInput.value = token;
        }
        if (contractIdInput) {
            contractIdInput.value = contractId || '';
        }
        if (refLabel) {
            refLabel.textContent = ref;
        }
        if (passwordInput) {
            passwordInput.value = '';
        }
        modal.classList.remove('hidden');
        document.body.classList.add('admin-modal-open');
        if (requirePassword && passwordInput) {
            passwordInput.focus();
        } else if (submitBtn) {
            submitBtn.focus();
        }
    }

    function closeModal() {
        modal.classList.add('hidden');
        document.body.classList.remove('admin-modal-open');
    }

    document.querySelectorAll('[data-delete-contract]').forEach(function (button) {
        button.addEventListener('click', function () {
            openModal(
                button.getAttribute('data-token') || '',
                button.getAttribute('data-ref') || '',
                button.getAttribute('data-id') || ''
            );
        });
    });

    if (backdrop) {
        backdrop.addEventListener('click', closeModal);
    }

    cancelButtons.forEach(function (button) {
        button.addEventListener('click', closeModal);
    });

    document.addEventListener('keydown', function (event) {
        if (event.key === 'Escape' && !modal.classList.contains('hidden')) {
            closeModal();
        }
    });

    document.querySelectorAll('[data-duplicate-contract]').forEach(function (button) {
        button.addEventListener('click', function () {
            const message = button.getAttribute('data-confirm') || 'Create duplicate contract?';
            if (!window.confirm(message)) {
                return;
            }

            const form = button.closest('form');
            if (form) {
                form.submit();
            }
        });
    });
})();
