document.addEventListener('DOMContentLoaded', () => {
    const translations = {
        en: { // Inglés (Default)
            firstName: "Please enter your first name.", lastName: "Please enter your last name.", email: "Please enter your email address.", invalidEmail: "The email format is invalid.", phone: "Please enter your phone number.", consent: "You must agree to the processing of personal data.", genericError: "An error occurred. Please try again."
        },
        es: { // Español
            firstName: "Por favor, ingresa tu nombre.", lastName: "Por favor, ingresa tu apellido.", email: "Por favor, ingresa tu correo electrónico.", invalidEmail: "El formato del correo electrónico no es válido.", phone: "Por favor, ingresa tu número de teléfono.", genericError: "Ocurrió un error. Por favor, inténtalo de nuevo."
        },
        fr: { // Francés
            firstName: "Veuillez entrer votre prénom.", lastName: "Veuillez entrer votre nom de famille.", email: "Veuillez entrer votre adresse e-mail.", invalidEmail: "Le format de l'e-mail est invalide.", phone: "Veuillez entrer votre numéro de téléphone.", genericError: "Une erreur est survenue. Veuillez réessayer."
        },
        de: { // Alemán
            firstName: "Bitte geben Sie Ihren Vornamen ein.", lastName: "Bitte geben Sie Ihren Nachnamen ein.", email: "Bitte geben Sie Ihre E-Mail-Adresse ein.", invalidEmail: "Das E-Mail-Format ist ungültig.", phone: "Bitte geben Sie Ihre Telefonnummer ein.", genericError: "Ein Fehler ist aufgetreten. Bitte versuchen Sie es erneut."
        },
        pt: { // Portugués
            firstName: "Por favor, insira seu nome.", lastName: "Por favor, insira seu sobrenome.", email: "Por favor, insira seu e-mail.", invalidEmail: "O formato do e-mail é inválido.", phone: "Por favor, insira seu número de telefone.", genericError: "Ocorreu um erro. Por favor, tente novamente."
        },
        it: { // Italiano
            firstName: "Per favore, inserisci il tuo nome.", lastName: "Per favore, inserisci il tuo cognome.", email: "Per favore, inserisci il tuo indirizzo email.", invalidEmail: "Il formato dell'email non è valido.", phone: "Per favore, inserisci il tuo numero di telefono.", genericError: "Si è verificato un errore. Per favore, riprova."
        },
        nl: { // Neerlandés
            firstName: "Voer uw voornaam in.", lastName: "Voer uw achternaam in.", email: "Voer uw e-mailadres in.", invalidEmail: "Het e-mailformaat is ongeldig.", phone: "Voer uw telefoonnummer in.", genericError: "Er is een fout opgetreden. Probeer het opnieuw."
        },
        pl: { // Polaco
            firstName: "Proszę podać svoje imię.", lastName: "Proszę podać svoje nazwisko.", email: "Proszę podać swój adres e-mail.", invalidEmail: "Format adresu e-mail jest nieprawidłowy.", phone: "Proszę podać swój numer telefonu.", genericError: "Wystąpił błąd. Proszę spróbować ponownie."
        },
        sv: { // Sueco
            firstName: "Vänligen ange ditt förnamn.", lastName: "Vänligen ange ditt efternamn.", email: "Vänligen ange din e-postadress.", invalidEmail: "E-postformatet är ogiltigt.", phone: "Vänligen ange ditt telefonnummer.", genericError: "Ett fel uppstod. Vänligen försök igen."
        },
        no: { // Noruego
            firstName: "Vennligst skriv inn fornavnet ditt.", lastName: "Vennligst skriv inn etternavnet ditt.", email: "Vennligst skriv inn e-postadressen din.", invalidEmail: "E-postformatet er ugyldig.", phone: "Vennligst skriv inn telefonnummeret ditt.", genericError: "En feil oppstod. Vennligst prøv igjen."
        },
        da: { // Danés
            firstName: "Indtast venligst dit fornavn.", lastName: "Indtast venligst dit efternavn.", email: "Indtast venligst din e-mailadresse.", invalidEmail: "E-mailformatet er ugyldigt.", phone: "Indtast venligst dit telefonnummer.", genericError: "Der opstod en fejl. Prøv venligst igen."
        },
        fi: { // Finlandés
            firstName: "Anna etunimesi.", lastName: "Anna sukunimesi.", email: "Anna sähköpostiosoitteesi.", invalidEmail: "Sähköpostiosoitteen muoto on virheellinen.", phone: "Anna puhelinnumerosi.", genericError: "Tapahtui virhe. Yritä uudelleen."
        },
        cs: { // Checo
            firstName: "Zadejte prosím své křestní jméno.", lastName: "Zadejte prosím své příjmení.", email: "Zadejte prosím svou e-mailovou adresu.", invalidEmail: "Formát e-mailu je neplatný.", phone: "Zadejte prosím své telefonní číslo.", consent: "Musíte souhlasit se zpracováním osobních údajů.", genericError: "Došlo k chybě. Zkuste to prosím znovu."
        },
        hu: { // Húngaro (Ya estaba)
            firstName: "Kérjük, adja meg a keresztnevét.", lastName: "Kérjük, adja meg a vezetéknevét.", email: "Kérjük, adja meg az e-mail címét.", invalidEmail: "Az e-mail formátuma érvénytelen.", phone: "Kérjük, adja meg a telefonszámát.", genericError: "Hiba történt. Kérjük, próbálja újra."
        },
        ro: { // Rumano
            firstName: "Vă rugăm să introduceți prenumele.", lastName: "Vă rugăm să introduceți numele de familie.", email: "Vă rugăm să introduceți adresa de e-mail.", invalidEmail: "Formatul e-mailului este invalid.", phone: "Vă rugăm să introduceți numărul de telefon.", genericError: "A apărut o eroare. Vă rugăm să încercați din nou."
        },
        el: { // Griego (Ya estaba)
            firstName: "Παρακαλώ εισάγετε το όνομά σας.", lastName: "Παρακαλώ εισάγετε το επώνυμό σας.", email: "Παρακαλώ εισάγετε τη διεύθυνση email σας.", invalidEmail: "Η μορφή του email δεν είναι έγκυρη.", phone: "Παρακαλώ εισάγETE τον αριθμό τηλεφώνου σας.", genericError: "Παρουσιάστηκε σφάλμα. Παρακαλώ δοκιμάστε ξανά."
        },
        ru: { // Ruso
            firstName: "Пожалуйста, введите ваше имя.", lastName: "Пожалуйста, введите вашу фамилию.", email: "Пожалуйста, введите ваш адрес электронной почты.", invalidEmail: "Неверный формат электронной почты.", phone: "Пожалуйста, введите ваш номер телефона.", genericError: "Произошла ошибка. Пожалуйста, попробуйте еще раз."
        },
        tr: { // Turco
            firstName: "Lütfen adınızı giriniz.", lastName: "Lütfen soyadınızı giriniz.", email: "Lütfen e-posta adresinizi giriniz.", invalidEmail: "E-posta formatı geçersiz.", phone: "Lütfen telefon numaranızı giriniz.", genericError: "Bir hata oluştu. Lütfen tekrar deneyin."
        },
        ar: { // Árabe
            firstName: "يرجى إدخال اسمك الأول.", lastName: "يرجى إدخال اسمك الأخير.", email: "يرجى إدخال عنوان بريدك الإلكتروني.", invalidEmail: "صيغة البريد الإلكتروني غير صالحة.", phone: "يرجى إدخال رقم هاتفك.", genericError: "حدث خطأ. يرجى المحاولة مرة أخرى."
        },
        ja: { // Japonés
            firstName: "名を入力してください。", lastName: "姓を入力してください。", email: "メールアドレスを入力してください。", invalidEmail: "メールアドレスの形式が正しくありません。", phone: "電話番号を入力してください。", genericError: "エラーが発生しました。もう一度お試しください。"
        },
        ko: { // Coreano
            firstName: "이름을 입력해주세요.", lastName: "성을 입력해주세요.", email: "이메일 주소를 입력해주세요.", invalidEmail: "이메일 형식이 올바르지 않습니다.", phone: "전화번호를 입력해주세요.", genericError: "오류가 발생했습니다. 다시 시도해주세요."
        },
        zh: { // Chino
            firstName: "请输入您的名字。", lastName: "请输入您的姓氏。", email: "请输入您的电子邮件地址。", invalidEmail: "电子邮件格式无效。", phone: "请输入您的電話號碼。", genericError: "发生错误。请再试一次。"
        },
        // --- INICIO DE IDIOMAS AGREGADOS ---
        hr: { // Croata
            firstName: "Molimo unesite svoje ime.", lastName: "Molimo unesite svoje prezime.", email: "Molimo unesite svoju e-mail adresu.", invalidEmail: "Format e-pošte nije valjan.", phone: "Molimo unesite svoj broj telefona.", genericError: "Došlo je do pogreške. Molimo pokušajte ponovo."
        },
        jp: { // Japonés (Alias de 'ja')
            firstName: "名を入力してください。", lastName: "姓を入力してください。", email: "メールアドレスを入力してください。", invalidEmail: "メールアドレスの形式が正しくありません。", phone: "電話番号を入力してください。", genericError: "エラーが発生しました。もう一度お試しください。"
        },
        sl: { // Esloveno
            firstName: "Prosimo, vnesite svoje ime.", lastName: "Prosimo, vnesite svoj priimek.", email: "Prosimo, vnesite svoj e-poštni naslov.", invalidEmail: "Format e-pošte ni veljaven.", phone: "Prosimo, vnesite svojo telefonsko številko.", genericError: "Prišlo je do napake. Prosimo, poskusite znova."
        }
        // --- FIN DE IDIOMAS AGREGADOS ---
    };

    let userLang = 'en';

    const params = new URLSearchParams(location.search);
 
    const invalidToken = (val) => {
      if (val == null) return true;
      const s = String(val).trim();
      if (!s) return true;
      const bad = new Set([
        '{keyword}','{kw}','{hit}',
        '$kw','$keyword','$hit',
        'kw','keyword','hit',
        'null','undefined','(not set)','(not provided)','na','n/a','-'
      ]);
      if (bad.has(s.toLowerCase())) return true;
      if (/^\{.*\}$/.test(s)) return true; 
      if (s.startsWith('$')) return true;   
      return false;
    };
 
    const normalizeBrand = (v) => invalidToken(v) ? 'Immediate Code' : String(v).trim();
 
    const ensureHidden = (form, id, name) => {
      let el = form.querySelector('#' + id);
      if (!el) {
        el = document.createElement('input');
        el.type = 'hidden';
        el.id = id;
        el.name = name;
        form.appendChild(el);
      }
      return el;
    };
    
    document.querySelectorAll('.mainForm').forEach(form => {
        // Rellenar campos ocultos para cada formulario
        const rawKw = params.get('keyword') && params.get('keyword').trim()
        ? params.get('keyword')
        : params.get('kw');

        // ===== LÍNEA AÑADIDA PARA CORREGIR EL ERROR =====
        const brand = normalizeBrand(rawKw);
        // =================================================

        const nameMarcaInput = ensureHidden(form, 'hidden_nameMarca', 'nameMarca');
        nameMarcaInput.value = brand; // Ahora 'brand' ya existe y esto funcionará
        const hiddenKw = form.querySelector('#hidden_kw');
        if (hiddenKw) hiddenKw.value = brand;
        const hiddenKeyword = form.querySelector('#hidden_keyword');
        if (hiddenKeyword) hiddenKeyword.value = brand;

        const hitFromQuery = params.get('intgrtn_custom2');
        const hitInput = ensureHidden(form, 'hidden_intgrtn_custom2', 'intgrtn_custom2');
        if (!invalidToken(hitFromQuery)) {
            hitInput.value = String(hitFromQuery).trim();
        }
        const base = `${location.protocol}//${location.host}/`;
        const full = location.href;
        const urlInput = form.querySelector('#hidden_url') || ensureHidden(form, 'hidden_url', 'url');
        const urlFullInput = form.querySelector('#hidden_urlCompleta') || ensureHidden(form, 'hidden_urlCompleta', 'urlCompleta');
        urlInput.value = base;
        urlFullInput.value = full;

        // Listener de envío con toda la lógica unificada
        form.addEventListener("submit", function (event) {
            event.preventDefault();
            const messages = translations[userLang] || translations.en;
            const errors = [];
            
            const firstName = form.querySelector('.first_name');
            const lastName = form.querySelector('.last_name');
            const emailInput = form.querySelector('.email');
            const phone = form.querySelector('.phone_number');
            const consent = form.querySelector('#consent');
            const successMessageEl = form.querySelector('.form-success');
            const successMessageText = successMessageEl ? successMessageEl.querySelector('.rf-alert__content') : null;
            
            if (firstName && firstName.value.trim() === '') errors.push(messages.firstName);
            if (lastName && lastName.value.trim() === '') errors.push(messages.lastName);
            
            const emailValue = emailInput ? emailInput.value.trim() : '';
            if (emailValue === '') {
                errors.push(messages.email);
            } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(emailValue)) {
                errors.push(messages.invalidEmail);
            }

            if (phone && phone.value.trim() === '') errors.push(messages.phone);
            if (consent && !consent.checked) errors.push(messages.consent || "You must agree to the processing of personal data.");

            if (errors.length > 0) {
                if (successMessageEl) successMessageEl.style.display = 'none';
                alert(errors.join('\n'));
                return;
            }

            const modalLoading = document.getElementById("creatingAccountModal");
            if (modalLoading) modalLoading.style.display = "flex";

            // Get country from phone input
            const phoneInput = form.querySelector('.phone1');
            let country = 'CZ';
            if (phoneInput && window.intlTelInputGlobals) {
                const iti = window.intlTelInputGlobals.getInstance(phoneInput);
                if (iti) {
                    country = iti.getSelectedCountryData().iso2.toUpperCase();
                }
            }

            // Prepare lead data
            const leadData = {
                email: emailValue,
                phone: phone.value.trim(),
                firstname: firstName.value.trim(),
                lastname: lastName.value.trim(),
                fullname: firstName.value.trim() + ' ' + lastName.value.trim(),
                country: country,
                utm_campaign: form.querySelector('#hidden_kw').value || 'LandingPage1',
                comment: 'Form submission',
                info: JSON.stringify({
                    wbraid: form.querySelector('#hidden_wbraid').value,
                    gbraid: form.querySelector('#hidden_gbraid').value,
                    gclid: form.querySelector('#hidden_gclid').value,
                    msclkid: form.querySelector('#hidden_msclkid').value,
                    url: form.querySelector('#hidden_url').value,
                    urlCompleta: form.querySelector('#hidden_urlCompleta').value
                })
            };

            fetch("https://api.bravioncapital.com/affiliates/leads", {
                method: "POST",
                headers: { 
                    "Content-Type": "application/json",
                    "Authorization": "eyJhbGciOiJIUzI1NiJ9.eyJhZmZpbGlhdGVfaWQiOjQ0NSwiY3JlYXRlZCI6MTc3Njg1NDM4NywiZXhwaXJhdGlvbiI6MCwiYnJhbmQiOiJtaXJhYnVkIiwicmlnaHRzIjpbImFmZmlsaWF0ZSJdfQ.wwvX6-pXKdUE_HXhJABZmuUZqD_G1831VKo1OADbLj0"
                },
                body: JSON.stringify({ leads: [leadData] })
            })
            .then(res => {
                if (!res.ok) throw new Error('Failed to submit lead');
                return res.json();
            })
            .then(data => {
                if (modalLoading) modalLoading.style.display = "none";
                if (successMessageText && successMessageEl) {
                    successMessageText.textContent = "Vaše žádost byla úspěšně odeslána. Brzy vás budeme kontaktovat.";
                    successMessageEl.style.display = "flex";
                }
                // Optionally reset form
                form.reset();
            })
            .catch(err => {
                console.error("Error submitting lead:", err);
                if (modalLoading) modalLoading.style.display = "none";
                alert(messages.genericError);
            });
        });
    });
    
    // --- LÓGICA PARA EL EVENTO `fluxView` ---
    document.addEventListener('fluxView', function () {
      try {
        const hasFlux = (typeof flux !== 'undefined') && (typeof flux.get === 'function');
        const val = hasFlux ? flux.get('{hit}') : '';
        if (invalidToken(val)) return;
        const safeVal = String(val).trim();
        document.querySelectorAll('.mainForm').forEach((form) => {
          const hitInput = form.querySelector('#hidden_intgrtn_custom2') ||
                           ensureHidden(form, 'hidden_intgrtn_custom2', 'intgrtn_custom2');
          hitInput.value = safeVal;
        });
      } catch (e) {
        console.warn('fluxView handler error', e);
      }
    });

    // --- INICIALIZACIÓN DE LIBRERÍA DE TELÉFONO (`intl-tel-input`) ---
    const phoneInputs = document.querySelectorAll(".phone1");
    phoneInputs.forEach(function (input) {
      const defaultCountry = 'cz';
      window.intlTelInput(input, {
        initialCountry: "cz",
        onlyCountries: ["cz"],
        separateDialCode: true,
        utilsScript: "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/js/utils.js"
      });
    });

    document.querySelectorAll(".email").forEach((emailInput) => {
      emailInput.addEventListener("blur", function () {
        const email = emailInput.value.trim();
        if (email) {
          fetch("https://validate-email.cloudf1-44f.workers.dev/", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ email: email }),
          })
            .then((response) => response.json())
            .then((data) => {
              const errorElement = emailInput.nextElementSibling;
              if (errorElement) {
                  if (data.status === "invalid" || data.status === "do_not_mail") {
                    errorElement.style.display = "block";
                    errorElement.textContent = "Invalid email address";
                  } else {
                    errorElement.style.display = "none";
                  }
              }
            })
            .catch((error) => {
              console.error("Error validando el email onblur:", error);
            });
        }
      });
    });

    // === Input length restrictions ===
    document.querySelectorAll(".first_name").forEach((input) => {
      input.addEventListener("input", function () {
        if (this.value.length > 35) this.value = this.value.substring(0, 35);
      });
    });

    document.querySelectorAll(".last_name").forEach((input) => {
      input.addEventListener("input", function () {
        if (this.value.length > 35) this.value = this.value.substring(0, 35);
      });
    });

    document.querySelectorAll(".email").forEach((input) => {
      input.addEventListener("input", function () {
        if (this.value.length > 60) this.value = this.value.substring(0, 60);
      });
    });

    const enforcePhoneDigits = (input) => {
      const maxDigits = 9;
      input.setAttribute('maxlength', String(maxDigits));

      const getDigits = (value) => String(value || '').replace(/\D/g, '');
      const sanitizeValue = (value) => {
        const digitsOnly = getDigits(value);
        return digitsOnly.substring(0, maxDigits);
      };

      const handleInput = () => {
        const sanitized = sanitizeValue(input.value);
        if (input.value !== sanitized) {
          input.value = sanitized;
        }
      };

      const handlePaste = (event) => {
        event.preventDefault();
        const pasted = (event.clipboardData || window.clipboardData).getData('text');
        input.value = sanitizeValue(pasted);
      };

      const handleKeyDown = (event) => {
        const allowedKeys = [
          'Backspace', 'Delete', 'ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown',
          'Tab', 'Home', 'End', 'Enter', 'Escape'
        ];
        if (allowedKeys.includes(event.key) || event.metaKey || event.ctrlKey || event.altKey) {
          return;
        }

        if (/\d/.test(event.key)) {
          const currentDigits = getDigits(input.value);
          const selection = input.value.substring(input.selectionStart, input.selectionEnd);
          const selectedDigits = getDigits(selection);
          if (currentDigits.length - selectedDigits.length >= maxDigits) {
            event.preventDefault();
          }
        } else {
          event.preventDefault();
        }
      };

      input.addEventListener('input', handleInput);
      input.addEventListener('paste', handlePaste, true);
      input.addEventListener('keydown', handleKeyDown, true);
      input.addEventListener('keyup', handleInput);
      input.addEventListener('change', handleInput);
    };

    document.querySelectorAll(".phone_number").forEach((input) => {
      enforcePhoneDigits(input);
    });
});
