/**
 * Form Helper — AJAX form submission with validation display
 */
const FormHelper = {
    init() {
        document.addEventListener('submit', (e) => {
            const form = e.target;
            if (form.getAttribute('data-ajax') !== 'true') return;
            e.preventDefault();
            this.submit(form);
        });
    },

    submit(form) {
        this.clearErrors(form);
        const submitBtn = form.querySelector('[type="submit"]');
        const originalText = submitBtn ? submitBtn.innerHTML : '';

        if (submitBtn) {
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Processing...';
        }

        const formData = new FormData(form);
        const method = form.method.toUpperCase() || 'POST';
        const url = form.action;

        $.ajax({
            url: url,
            type: method,
            data: formData,
            processData: false,
            contentType: false,
            success: (response) => {
                if (response.success) {
                    this.showToast('success', response.message || 'Operation successful');
                    if (response.redirect) {
                        setTimeout(() => { window.location.href = response.redirect; }, 800);
                    }
                } else if (response.errors) {
                    this.showErrors(form, response.errors);
                } else {
                    this.showToast('error', response.message || 'Operation failed');
                }
            },
            error: (xhr) => {
                if (xhr.status === 422) {
                    const response = xhr.responseJSON;
                    if (response && response.errors) {
                        this.showErrors(form, response.errors);
                    }
                }
                // 401, 403, 500 handled by global handler
            },
            complete: () => {
                if (submitBtn) {
                    submitBtn.disabled = false;
                    submitBtn.innerHTML = originalText;
                }
            }
        });
    },

    clearErrors(form) {
        form.querySelectorAll('.is-invalid').forEach(el => el.classList.remove('is-invalid'));
        form.querySelectorAll('.invalid-feedback').forEach(el => el.textContent = '');
    },

    showErrors(form, errors) {
        for (const [field, messages] of Object.entries(errors)) {
            const input = form.querySelector(`[name="${field}"]`);
            const feedback = form.querySelector(`[data-field="${field}"]`) || (input ? input.parentElement.querySelector('.invalid-feedback') : null);

            if (input) {
                input.classList.add('is-invalid');
            }
            if (feedback) {
                feedback.textContent = Array.isArray(messages) ? messages[0] : messages;
                feedback.style.display = 'block';
            }
        }

        // Scroll to first error
        const firstError = form.querySelector('.is-invalid');
        if (firstError) {
            firstError.scrollIntoView({ behavior: 'smooth', block: 'center' });
            firstError.focus();
        }
    },

    showToast(type, message) {
        const Toast = Swal.mixin({
            toast: true,
            position: 'top-end',
            showConfirmButton: false,
            timer: 3000,
            timerProgressBar: true,
        });
        Toast.fire({
            icon: type,
            title: message
        });
    }
};

document.addEventListener('DOMContentLoaded', () => FormHelper.init());