@props([
    'id'      => 'form_id',
    'action'  => '',
    'method'  => 'POST',
    'lang'    => true,
    'buttons' => true,
])

@php
    $httpMethod = strtoupper($method);
    $spoof      = !in_array($httpMethod, ['GET','POST']);
@endphp

<form id="{{ $id }}"
      action="{{ $action }}"
      method="POST"
      enctype="multipart/form-data"
      autocomplete="off">

    @csrf
    @if($spoof)
        @method($httpMethod)
    @endif

    {{ $slot }}

    @if($buttons)
        <div class="row mt-3">
            <div class="col-12">
                <button type="submit" class="btn btn-primary">
                    <i class="ri-save-line me-1"></i> {{ __('dashboard.save') }}
                </button>
            </div>
        </div>
    @endif
</form>

@push('scripts')
<style>
    .error-highlight {
        box-shadow: 0 0 0 3px rgba(220, 53, 69, 0.3);
        border-color: #dc3545 !important;
        transition: all 0.3s ease;
    }
</style>

<script>
document.addEventListener("DOMContentLoaded", function () {
    const form = document.getElementById('{{ $id }}');
    const submitBtn = form.querySelector('[type="submit"]');
    const originalBtnContent = submitBtn ? submitBtn.innerHTML : '';

    form.addEventListener('submit', function (e) {
        e.preventDefault();

        // Clear previous errors
        form.querySelectorAll('.is-invalid').forEach(el => el.classList.remove('is-invalid', 'error-highlight'));
        form.querySelectorAll('.ajax-invalid-feedback').forEach(el => el.remove());

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

        $.ajax({
            url: form.getAttribute('action'),
            method: "POST",
            data: new FormData(form),
            processData: false,
            contentType: false,

            success: function (res) {
                if (res.redirect_url) {
                    sessionStorage.setItem('create_toast', JSON.stringify({
                        title: res.message,
                        icon: 'success',
                        type: true
                    }));
                    window.location.href = res.redirect_url;
                } else {
                    if (submitBtn) {
                        submitBtn.disabled = false;
                        submitBtn.innerHTML = originalBtnContent;
                    }
                    if (typeof toastr !== 'undefined') {
                        toastr.success(res.message || 'Success');
                    }
                }
            },

            error: function (xhr) {
                // Re-enable button
                if (submitBtn) {
                    submitBtn.disabled = false;
                    submitBtn.innerHTML = originalBtnContent;
                }

                if (xhr.status === 422) {
                    const errors = xhr.responseJSON.errors;
                    let firstErrorElement = null;
                    let firstLang = null;

                    Object.entries(errors).forEach(function ([field, messages]) {
                        // Special case: permissions
                        if (field === 'permissions') {
                            const permDiv = document.querySelector('.error-permissions');
                            if (permDiv) {
                                permDiv.innerHTML = '<span class="text-danger small">' + messages[0] + '</span>';
                                if (!firstErrorElement) firstErrorElement = permDiv;
                            }
                            return;
                        }

                        let input = form.querySelector('[name="' + field + '"]');

                        // Dot notation → bracket notation
                        // name.en → name[en]  |  dependents.0.name → dependents[0][name]
                        if (!input && field.includes('.')) {
                            const bracketName = field.replace(/\.(\w+)/g, '[$1]');
                            input = form.querySelector('[name="' + bracketName + '"]');
                        }

                        if (!input) return;

                        input.classList.add('is-invalid');

                        // Create error feedback div dynamically
                        const errorDiv = document.createElement('div');
                        errorDiv.className = 'invalid-feedback d-block ajax-invalid-feedback';
                        errorDiv.innerHTML = messages.join('<br>');

                        // Place after input (handle input-group / select2 wrappers)
                        if (input.parentElement && input.parentElement.classList.contains('input-group')) {
                            input.parentElement.after(errorDiv);
                        } else if (input.nextElementSibling && input.nextElementSibling.classList.contains('select2-container')) {
                            input.nextElementSibling.after(errorDiv);
                        } else {
                            input.after(errorDiv);
                        }

                        if (!firstErrorElement) firstErrorElement = input;

                        // Auto-switch translation tab
                        @if($lang)
                        if (field.includes('.') && !firstLang) {
                            firstLang = field.split('.')[1];
                            if (typeof switchToTab === 'function') switchToTab(firstLang);
                        }
                        @endif
                    });

                    // Scroll to first error with highlight
                    if (firstErrorElement) {
                        setTimeout(function () {
                            firstErrorElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
                            firstErrorElement.focus();
                            firstErrorElement.classList.add('error-highlight');
                            setTimeout(function () {
                                firstErrorElement.classList.remove('error-highlight');
                            }, 2000);
                        }, 100);
                    }

                    if (typeof toastr !== 'undefined') {
                        toastr.error('{{ __("dashboard.please_fix_errors") }}');
                    }
                } else {
                    if (typeof toastr !== 'undefined') {
                        toastr.error(xhr.responseJSON?.message || '{{ __("dashboard.unexpected_error") }}');
                    }
                }
            }
        });
    });
});
</script>
@endpush
