(function initFivaFormContent(global) {
  "use strict";

  if (global.location?.hostname !== "indianvisa-bangladesh.nic.in") return;
  const ENGINE_VERSION = "2026-05-14-strict-current-file";
  if (global.__FIVAFormEngineVersion === ENGINE_VERSION) return;
  global.__FIVAFormEngineVersion = ENGINE_VERSION;
  global.__FIVAFormEngineReady = true;

  const LOG = "[FIVA]";
  const FILLED_CLASS = "fiva-filled-field";
  const FIVA_SESSION_KEY = "fiva.autofillSession";
  const Validators = global.FIVA?.Validators || null;
  const RuntimeConfig = global.FIVA?.RuntimeConfig || null;
  const NormalizeOptionText = global.FIVA?.NormalizeOptionText || null;
  const StrictDobValidator = global.FIVA?.StrictDobValidator || null;
  const NormalizeParsedData = global.FIVA?.NormalizeParsedData || null;
  const ProfileNormalizer = global.FIVA?.ProfileNormalizer || null;
  const DetectFieldType = global.FIVA?.DetectFieldType || null;
  const SelectSmartOption = global.FIVA?.SelectSmartOption || null;
  const HumanDropdownSelect = global.FIVA?.HumanDropdownSelect || null;
  const HumanSelectOption = global.FIVA?.HumanSelectOption || null;
  const HardPaste = global.FIVA?.HardPaste || null;
  const HardPasteEngine = global.FIVA?.HardPasteEngine || null;
  const DropdownEngine = global.FIVA?.DropdownEngine || null;
  const FivaStateMachine = global.FIVA?.FivaStateMachine || null;
  const activeTimers = new Set();
  let fivaRunActive = false;
  let fivaRunning = false;
  let globalAbortController = null;

  function validatorsEngine() {
    return global.FIVA?.Validators || Validators;
  }

  function runtimeConfig() {
    return global.FIVA?.RuntimeConfig || RuntimeConfig || {};
  }

  function optionTextNormalizer() {
    return global.FIVA?.NormalizeOptionText || NormalizeOptionText;
  }

  function strictDobValidator() {
    return global.FIVA?.StrictDobValidator || StrictDobValidator;
  }

  function strictProfileNormalizer() {
    return global.FIVA?.NormalizeParsedData || NormalizeParsedData;
  }

  function profileNormalizer() {
    return global.FIVA?.ProfileNormalizer || ProfileNormalizer;
  }

  function fieldTypeDetector() {
    return global.FIVA?.DetectFieldType || DetectFieldType;
  }

  function selectSmartOption() {
    return global.FIVA?.SelectSmartOption || SelectSmartOption;
  }

  function humanDropdownSelect() {
    return global.FIVA?.HumanDropdownSelect || HumanDropdownSelect;
  }

  function humanSelectOption() {
    return global.FIVA?.HumanSelectOption || HumanSelectOption;
  }

  function hardPaste() {
    return global.FIVA?.HardPaste || HardPaste;
  }

  function hardPasteEngine() {
    return global.FIVA?.HardPasteEngine || HardPasteEngine;
  }

  function dropdownEngine() {
    return global.FIVA?.DropdownEngine || DropdownEngine;
  }

  function stateMachine() {
    return global.FIVA?.FivaStateMachine || FivaStateMachine;
  }

  function fivaCapabilities() {
    return {
      runtimeConfig: Boolean(runtimeConfig()?.globalAutofillTimeoutMs),
      stateMachine: Boolean(stateMachine()?.STATES),
      normalizeOptionText: Boolean(optionTextNormalizer()?.normalizeOptionText),
      strictDobValidator: Boolean(strictDobValidator()?.validateDob),
      normalizeParsedData: Boolean(strictProfileNormalizer()?.normalizeParsedData && strictProfileNormalizer()?.toQueueProfile),
      profileNormalizer: Boolean(profileNormalizer()?.normalizeProfile && profileNormalizer()?.toQueueProfile),
      detectFieldType: Boolean(fieldTypeDetector()?.detectFieldType),
      selectSmartOption: Boolean(selectSmartOption()?.choose && selectSmartOption()?.validOptions),
      humanDropdownSelect: Boolean(humanDropdownSelect()?.choose && humanDropdownSelect()?.waitForDropdownReady),
      humanSelectOption: Boolean(humanSelectOption()?.choose && humanSelectOption()?.waitForDropdownReady),
      validators: Boolean(validatorsEngine()?.validateField && validatorsEngine()?.sanitizeProfile),
      hardPaste: Boolean(hardPaste()?.fill || hardPasteEngine()?.fillText),
      dropdown: Boolean(dropdownEngine()?.choose)
    };
  }

  const FIELD_ALIASES = Object.freeze({
    fullName: ["full name", "fullname", "applicant name", "name of applicant", "name as in passport", "applicant_name", "name"],
    surname: ["surname", "last name", "family name", "family_name"],
    givenNames: ["given name", "given names", "givenname", "first name", "middle name"],
    passportNumber: ["passport no", "passport number", "passportnumber", "passport", "passport details", "pass no", "pass_no"],
    nationality: ["nationality", "present nationality", "current nationality"],
    country: ["country/region you are applying visa from", "applying visa from", "country", "country/region"],
    mission: ["mission", "indian mission", "indian mission office", "mission office", "ivac center", "application center", "visa application center"],
    dateOfBirth: ["date of birth", "dateofbirth", "dob", "birth date", "birth_date"],
    gender: ["sex", "gender"],
    email: ["email", "email address", "e-mail", "mail"],
    reEnterEmail: ["re-enter email", "re enter email", "confirm email", "email confirmation"],
    expectedArrivalDate: ["expected date of arrival", "date of arrival", "arrival date"],
    visaType: ["visa service", "visa type", "type of visa", "visa category"],
    purpose: ["purpose", "purpose of visit", "visit purpose", "visa purpose"],
    cityOfBirth: ["city of birth", "place of birth", "birth city", "birth place"],
    countryOfBirth: ["country of birth", "birth country"],
    religion: ["religion"],
    education: ["education", "educational qualification", "education qualification"],
    passportIssueDate: ["passport issue", "issue date", "date of issue", "passport issue date"],
    passportExpiryDate: ["passport expiry", "expiry date", "date of expiry", "passport expiry date"]
  });

  const PAGE_FIELD_GROUPS = Object.freeze({
    registration: ["country", "mission", "nationality", "dateOfBirth", "email", "reEnterEmail", "expectedArrivalDate", "visaType", "purpose"],
    basicDetails: ["surname", "givenNames", "fullName", "gender", "dateOfBirth", "cityOfBirth", "countryOfBirth", "nationality", "religion", "education", "passportNumber", "passportIssueDate", "passportExpiryDate", "email", "reEnterEmail"],
    passport: ["passportNumber", "passportIssueDate", "passportExpiryDate", "dateOfBirth", "fullName", "givenNames", "surname", "nationality"],
    address: ["country", "email"],
    family: ["fullName", "givenNames", "surname"],
    occupation: ["fullName"],
    reference: ["email"],
    finalReview: []
  });

  const REGISTRATION_REQUIRED_FIELDS = Object.freeze([
    "country",
    "mission",
    "nationality",
    "dateOfBirth",
    "email",
    "reEnterEmail",
    "expectedArrivalDate",
    "visaType",
    "purpose"
  ]);
  const REGISTRATION_QUEUE = Object.freeze([
    "country",
    "mission",
    "nationality",
    "dateOfBirth",
    "email",
    "reEnterEmail",
    "expectedArrivalDate",
    "visaType",
    "purpose"
  ]);

  const FIELD_SELECTORS = Object.freeze({
    fullName: [
      "input[name*='full' i]",
      "input[id*='full' i]",
      "input[name*='applicant' i]",
      "input[id*='applicant' i]",
      "input[name*='name' i]",
      "input[id*='name' i]"
    ],
    surname: ["input[name*='surname' i]", "input[id*='surname' i]", "input[name*='family' i]", "input[id*='family' i]", "input[name*='last' i]"],
    givenNames: ["input[name*='given' i]", "input[id*='given' i]", "input[name*='first' i]", "input[id*='first' i]"],
    passportNumber: [
      "input[name*='passport' i]",
      "input[id*='passport' i]",
      "input[name*='pp' i]",
      "input[id*='pp' i]"
    ],
    nationality: [
      "select[name*='nationality' i]",
      "select[id*='nationality' i]",
      "input[name*='nationality' i]",
      "input[id*='nationality' i]"
    ],
    country: [
      "select[name*='country' i]",
      "select[id*='country' i]",
      "input[name*='country' i]",
      "input[id*='country' i]"
    ],
    mission: [
      "select[name*='mission' i]",
      "select[id*='mission' i]",
      "select[name*='center' i]",
      "select[id*='center' i]",
      "input[name*='mission' i]",
      "input[id*='mission' i]"
    ],
    dateOfBirth: [
      "input[type='date'][name*='birth' i]",
      "input[type='date'][id*='birth' i]",
      "input[name*='dob' i]",
      "input[id*='dob' i]",
      "input[name*='birth' i]",
      "input[id*='birth' i]"
    ],
    gender: ["select[name*='gender' i]", "select[id*='gender' i]", "select[name*='sex' i]", "select[id*='sex' i]"],
    email: ["input[type='email']", "input[name*='email' i]", "input[id*='email' i]", "input[name*='mail' i]"],
    reEnterEmail: [
      "input[name*='re' i][name*='mail' i]",
      "input[id*='re' i][id*='mail' i]",
      "input[name*='confirm' i][name*='mail' i]",
      "input[id*='confirm' i][id*='mail' i]",
      "input[name*='email' i]",
      "input[id*='email' i]",
      "input[name*='mail' i]"
    ],
    expectedArrivalDate: [
      "input[type='date'][name*='arrival' i]",
      "input[type='date'][id*='arrival' i]",
      "input[name*='arrival' i]",
      "input[id*='arrival' i]"
    ],
    visaType: ["select[name*='visa' i]", "select[id*='visa' i]", "select[name*='service' i]", "select[id*='service' i]", "input[name*='visa' i]", "input[id*='visa' i]"],
    purpose: ["select[name*='purpose' i]", "select[id*='purpose' i]", "input[name*='purpose' i]", "input[id*='purpose' i]"],
    cityOfBirth: ["input[name*='birth' i][name*='city' i]", "input[id*='birth' i][id*='city' i]", "input[name*='place' i][name*='birth' i]", "input[id*='place' i][id*='birth' i]"],
    countryOfBirth: ["select[name*='birth' i][name*='country' i]", "select[id*='birth' i][id*='country' i]", "input[name*='birth' i][name*='country' i]", "input[id*='birth' i][id*='country' i]"],
    religion: ["select[name*='religion' i]", "select[id*='religion' i]", "input[name*='religion' i]", "input[id*='religion' i]"],
    education: ["select[name*='education' i]", "select[id*='education' i]", "select[name*='qualification' i]", "select[id*='qualification' i]", "input[name*='education' i]", "input[id*='education' i]"],
    passportIssueDate: [
      "input[type='date'][name*='issue' i]",
      "input[type='date'][id*='issue' i]",
      "input[name*='issue' i]",
      "input[id*='issue' i]"
    ],
    passportExpiryDate: [
      "input[type='date'][name*='expiry' i]",
      "input[type='date'][id*='expiry' i]",
      "input[name*='expiry' i]",
      "input[id*='expiry' i]"
    ]
  });

  const FIELD_ORDER = Object.freeze([
    "country",
    "mission",
    "nationality",
    "dateOfBirth",
    "email",
    "reEnterEmail",
    "expectedArrivalDate",
    "visaType",
    "purpose",
    "passportNumber",
    "fullName",
    "givenNames",
    "surname",
    "gender",
    "cityOfBirth",
    "countryOfBirth",
    "religion",
    "education",
    "passportIssueDate",
    "passportExpiryDate"
  ]);

  const DYNAMIC_FIELDS = new Set(["country", "nationality", "mission", "visaType", "purpose", "countryOfBirth", "religion", "education"]);
  const CRITICAL_DEPENDENCY_FIELDS = new Set(["country", "mission", "nationality"]);
  const NATIVE_SELECT_REQUIRED_FIELDS = new Set(["country", "mission", "nationality"]);
  const MAX_DROPDOWN_RETRIES = Number((RuntimeConfig || {}).dropdownRetryCount || 3);
  const MAX_WAIT_PER_FIELD = Number((RuntimeConfig || {}).fieldTimeoutMs || 8000);
  const GLOBAL_AUTOFILL_TIMEOUT = Number((RuntimeConfig || {}).globalAutofillTimeoutMs || 90000);
  const DEPENDENT_WAIT_TARGETS = Object.freeze({
    country: "mission",
    mission: "nationality",
    nationality: "dateOfBirth",
    visaType: "purpose",
    purpose: null
  });
  const FIELD_DEPENDENCY_REQUIREMENTS = Object.freeze({
    mission: "country",
    nationality: "mission",
    purpose: "visaType"
  });
  const RADIO_FIELDS = new Set(["gender", "visaType", "purpose"]);
  const UPPERCASE_FIELDS = new Set(["country", "nationality", "mission", "gender", "countryOfBirth", "religion", "education"]);

  function currentSignal() {
    return globalAbortController?.signal || null;
  }

  function isStopped() {
    return !fivaRunning || currentSignal()?.aborted === true;
  }

  function wait(ms = 80) {
    const signal = currentSignal();
    if (signal?.aborted) return Promise.resolve(false);
    return new Promise((resolve) => {
      const timer = setTimeout(() => {
        activeTimers.delete(timer);
        signal?.removeEventListener?.("abort", onAbort);
        resolve(true);
      }, ms);
      activeTimers.add(timer);
      function onAbort() {
        clearTimeout(timer);
        activeTimers.delete(timer);
        resolve(false);
      }
      signal?.addEventListener?.("abort", onAbort, { once: true });
    });
  }

  function randomDelay(min = 30, max = 80) {
    const duration = Math.floor(min + (Math.random() * (max - min)));
    return wait(duration);
  }

  function storageGet(keys) {
    return chrome.storage.local.get(keys);
  }

  function storageSet(value) {
    return chrome.storage.local.set(value);
  }

  function storageRemove(keys) {
    return chrome.storage.local.remove(keys);
  }

  function emitActivity(message, level = "info", patch = {}) {
    const text = compact(message);
    if (!text) return;
    console.log(LOG, text);
    chrome.runtime.sendMessage({ type: "FIVA_ACTIVITY", message: text, level, ...patch }).catch(() => {});
  }

  function emitState(state, status, level = "info") {
    emitActivity(status || state, level, { state, status });
  }

  function reasonLabel(reason = "") {
    return String(reason || "verification_failed").replace(/_/g, " ");
  }

  function normalize(value = "") {
    return String(value || "")
      .toLowerCase()
      .replace(/&/g, " and ")
      .replace(/[^a-z0-9]+/g, " ")
      .replace(/\s+/g, " ")
      .trim();
  }

  function tightNormalize(value = "") {
    return normalize(value).replace(/\s+/g, "");
  }

  function compact(value = "") {
    return String(value || "").replace(/\s+/g, " ").trim();
  }

  function hasProfileInputData(profile = {}) {
    return Object.entries(profile || {}).some(([key, value]) => (
      !String(key).startsWith("__") && Boolean(compact(value))
    ));
  }

  function splitFullName(value = "") {
    const parts = compact(value).split(" ").filter(Boolean);
    if (parts.length < 2) return { givenNames: compact(value), surname: "" };
    return {
      givenNames: parts.slice(0, -1).join(" "),
      surname: parts.slice(-1).join("")
    };
  }

  function dateParts(value = "") {
    const strict = strictDobValidator()?.parseDate?.(value);
    if (strict?.display) {
      const [day, month, year] = strict.display.split("/");
      return { day, month, year };
    }
    const source = compact(value);
    if (!source) return null;
    const iso = source.match(/^(\d{4})-(\d{2})-(\d{2})$/);
    if (iso) return { day: iso[3], month: iso[2], year: iso[1] };
    const date = source.match(/^(\d{1,2})[\/-](\d{1,2})[\/-](\d{4})$/);
    if (!date) return null;
    return {
      day: date[1].padStart(2, "0"),
      month: date[2].padStart(2, "0"),
      year: date[3]
    };
  }

  function normalizeDateValue(value = "") {
    const strict = strictDobValidator()?.normalizeDate?.(value);
    if (strict) return strict;
    const parsed = dateParts(value);
    if (!parsed) return compact(value);
    return `${parsed.day}/${parsed.month}/${parsed.year}`;
  }

  function isoDateValue(value = "") {
    const parsed = dateParts(value);
    if (!parsed) return compact(value);
    return `${parsed.year}-${parsed.month}-${parsed.day}`;
  }

  function profileNormalizerOptions(source = {}) {
    return {
      ...source,
      siteUrl: location.href,
      allowDefaultCountry: /indianvisa-bangladesh\.nic\.in/i.test(location.hostname),
      defaultCountry: "BANGLADESH",
      currentUploadOnly: true
    };
  }

  function standardProfileForLog(profile = {}, source = {}) {
    const strictNormalizer = strictProfileNormalizer();
    if (strictNormalizer?.normalizeParsedData) {
      return strictNormalizer.normalizeParsedData(profile, profileNormalizerOptions(source));
    }
    const normalizer = profileNormalizer();
    return normalizer?.normalizeProfile
      ? normalizer.normalizeProfile(profile, profileNormalizerOptions(source))
      : {};
  }

  function buildAutofillProfile(profile = {}, source = {}) {
    const options = profileNormalizerOptions(source);
    const smartProfile = global.FIVA?.SmartVisaProfileEngine?.normalizeProfile
      ? global.FIVA.SmartVisaProfileEngine.normalizeProfile(profile, options).profile
      : profile;
    const sourceProfile = smartProfile && typeof smartProfile === "object" ? smartProfile : profile;
    const strictNormalizer = strictProfileNormalizer();
    const normalizer = strictNormalizer?.toQueueProfile ? strictNormalizer : profileNormalizer();
    const next = normalizer?.toQueueProfile
      ? normalizer.toQueueProfile(sourceProfile, options)
      : { ...sourceProfile };
    if (!next.country && /indianvisa-bangladesh\.nic\.in/i.test(location.hostname)) next.country = "BANGLADESH";
    if (!next.mission && next.country === "BANGLADESH") next.mission = "BANGLADESH-DHAKA";
    if (!next.dateOfBirth && next.dob) next.dateOfBirth = next.dob;
    if (!next.expectedArrivalDate && next.arrivalDate) next.expectedArrivalDate = next.arrivalDate;
    if (!next.expectedArrivalDate && next.expectedArrival) next.expectedArrivalDate = next.expectedArrival;
    if (!next.givenNames && next.givenName) next.givenNames = next.givenName;
    if (next.fullName && (!next.givenNames || !next.surname)) {
      const split = splitFullName(next.fullName);
      if (!next.givenNames && split.givenNames) next.givenNames = split.givenNames;
      if (!next.surname && split.surname) next.surname = split.surname;
    }
    if (next.email && !next.reEnterEmail) {
      next.reEnterEmail = next.email;
    }
    ["dateOfBirth", "expectedArrivalDate", "passportIssueDate", "passportExpiryDate"].forEach((key) => {
      if (next[key]) next[key] = normalizeDateValue(next[key]);
      if (next[key] && strictDobValidator()?.validateDob && !strictDobValidator().validateDob(next[key]).ok) delete next[key];
    });
    const validators = validatorsEngine();
    const sanitized = validators?.sanitizeProfile ? validators.sanitizeProfile(next, source) : next;
    return Object.fromEntries(Object.entries(sanitized).filter(([, value]) => Boolean(compact(value))));
  }

  function normalizedFieldValue(fieldKey, value, control) {
    const source = compact(value);
    if (!source) return "";
    if (fieldKey === "email") return source.toLowerCase();
    if (fieldKey === "passportNumber") return source.toUpperCase().replace(/[^A-Z0-9]/g, "");
    if (fieldKey.includes("Date") || fieldKey === "dateOfBirth") return normalizeDateForControl(source, control);
    if (UPPERCASE_FIELDS.has(fieldKey)) return source.toUpperCase();
    return source;
  }

  function titleForControl(control) {
    const parts = [
      control.name,
      control.id,
      control.className,
      control.placeholder,
      control.getAttribute("aria-label"),
      control.getAttribute("title"),
      control.closest("label")?.innerText
    ];

    if (control.id) {
      const explicit = document.querySelector(`label[for="${CSS.escape(control.id)}"]`);
      if (explicit) parts.push(explicit.innerText);
    }

    const row = control.closest("tr, .form-group, .form-row, .row, .mb-3, .field, .control-group");
    if (row) parts.push(row.innerText);

    const previous = control.previousElementSibling;
    const next = control.nextElementSibling;
    if (previous) parts.push(previous.innerText || previous.textContent);
    if (next) parts.push(next.innerText || next.textContent);

    return normalize(parts.filter(Boolean).join(" "));
  }

  function isFillable(control) {
    if (!control || control.disabled) return false;
    if (control.type && ["hidden", "submit", "button", "reset", "file", "password"].includes(control.type)) return false;
    return ["INPUT", "SELECT", "TEXTAREA"].includes(control.tagName);
  }

  function detectControlType(control) {
    return fieldTypeDetector()?.detectFieldType?.(control) || "";
  }

  function controlDescriptor(control) {
    return {
      tagName: String(control?.tagName || "").toUpperCase(),
      type: String(control?.type || "").toLowerCase(),
      role: String(control?.getAttribute?.("role") || "").toLowerCase()
    };
  }

  function isVisible(element) {
    if (!element || element.hidden) return false;
    const style = global.getComputedStyle(element);
    if (style.display === "none" || style.visibility === "hidden" || Number(style.opacity) === 0) return false;
    const rect = element.getBoundingClientRect();
    return rect.width > 0 && rect.height > 0;
  }

  function controls() {
    return Array.from(document.querySelectorAll("input, select, textarea")).filter((control) => isFillable(control) && isVisible(control));
  }

  function detectPage() {
    const url = location.href.toLowerCase();
    const text = normalize([
      document.title,
      document.querySelector("h1,h2,h3,.title,.page-title")?.textContent,
      document.body?.innerText?.slice(0, 2500)
    ].filter(Boolean).join(" "));

    if (/basicdetails|basic-details|applicantdetails|applicant-details/.test(url) || /basic details|applicant details/.test(text)) return "basicDetails";
    if (/passport/.test(url) || /passport details|passport information/.test(text)) return "passport";
    if (/address/.test(url) || /address details|present address|permanent address/.test(text)) return "address";
    if (/family/.test(url) || /family details|father|mother|spouse/.test(text)) return "family";
    if (/occupation/.test(url) || /occupation|profession|employment/.test(text)) return "occupation";
    if (/reference/.test(url) || /reference|indian reference/.test(text)) return "reference";
    if (/review|confirm|final/.test(url) || /final review|review application|confirm details/.test(text)) return "finalReview";
    console.log(LOG, "Registration page detected");
    return "registration";
  }

  function pageFieldOrder(profile = {}) {
    const page = detectPage();
    const pageFields = PAGE_FIELD_GROUPS[page] || [];
    const fallbackFields = page === "registration" || !PAGE_FIELD_GROUPS[page] ? FIELD_ORDER : [];
    return {
      page,
      order: [...pageFields, ...fallbackFields].filter((key, index, list) => list.indexOf(key) === index && profile[key])
    };
  }

  function fieldName(fieldKey) {
    return String(fieldKey || "")
      .replace(/([A-Z])/g, " $1")
      .replace(/^./, (letter) => letter.toUpperCase())
      .trim();
  }

  function logField(fieldKey, message) {
    console.log(LOG, `${fieldName(fieldKey)} ${message}`);
  }

  function waitLogMessage(fieldKey) {
    if (fieldKey === "nationality") return "Waiting nationality options...";
    if (fieldKey === "visaType") return "Waiting visa type options...";
    if (fieldKey === "purpose") return "Waiting purpose options...";
    if (fieldKey === "mission") return "Waiting mission options...";
    return `Waiting ${fieldName(fieldKey).toLowerCase()} options...`;
  }

  function querySelectorCandidates(fieldKey) {
    const seen = new Set();
    const matches = [];
    (FIELD_SELECTORS[fieldKey] || []).forEach((selector) => {
      try {
        document.querySelectorAll(selector).forEach((control) => {
          if (!seen.has(control) && isFillable(control) && isVisible(control)) {
            seen.add(control);
            matches.push(control);
          }
        });
      } catch (_) {
        // Keep selector fallbacks best-effort across older Chromium versions.
      }
    });
    return matches;
  }

  function scoreControl(fieldKey, control, selectorBoost = 0) {
    const title = titleForControl(control);
    const aliases = FIELD_ALIASES[fieldKey] || [fieldKey];
    let score = selectorBoost;

    aliases.forEach((alias) => {
      const cleanAlias = normalize(alias);
      if (!cleanAlias) return;
      if (title === cleanAlias) score = Math.max(score, 120 + selectorBoost);
      if (title.includes(cleanAlias)) score = Math.max(score, 88 + selectorBoost);

      const aliasParts = cleanAlias.split(" ").filter((part) => part.length > 2);
      const matches = aliasParts.filter((part) => title.includes(part)).length;
      if (matches) score = Math.max(score, 42 + selectorBoost + (matches * 12));
    });

    if (control.tagName === "SELECT" && ["country", "nationality", "mission", "gender", "visaType", "purpose"].includes(fieldKey)) {
      score += NATIVE_SELECT_REQUIRED_FIELDS.has(fieldKey) ? 120 : 12;
    }

    return score;
  }

  function emailLikeControls() {
    return controls().filter((control) => {
      if (control.tagName === "SELECT") return false;
      if (control.type === "email") return true;
      return /email|mail/.test(titleForControl(control));
    });
  }

  function findEmailControl(fieldKey, usedControls = new Set()) {
    const candidates = emailLikeControls().filter((control) => !usedControls.has(control));
    if (!candidates.length) return null;

    const isReEnter = (control) => /re enter|reenter|confirm|confirmation|again|verify/.test(titleForControl(control));
    if (fieldKey === "reEnterEmail") {
      return candidates.find(isReEnter) || candidates[1] || candidates[0] || null;
    }

    return candidates.find((control) => !isReEnter(control)) || candidates[0] || null;
  }

  function findControlForField(fieldKey, usedControls) {
    if (NATIVE_SELECT_REQUIRED_FIELDS.has(fieldKey)) {
      return findSelectForField(fieldKey, usedControls);
    }

    if (fieldKey === "email" || fieldKey === "reEnterEmail") {
      const emailControl = findEmailControl(fieldKey, usedControls);
      if (emailControl) return emailControl;
    }

    const ranked = [];
    querySelectorCandidates(fieldKey).forEach((control) => {
      if (!usedControls.has(control)) ranked.push({ control, score: scoreControl(fieldKey, control, 28) });
    });
    controls().forEach((control) => {
      if (!usedControls.has(control)) ranked.push({ control, score: scoreControl(fieldKey, control) });
    });

    ranked.sort((left, right) => right.score - left.score);
    const best = ranked[0];
    return best && best.score >= 58 ? best.control : null;
  }

  function findSelectForField(fieldKey, usedControls = new Set()) {
    const ranked = [];
    querySelectorCandidates(fieldKey).forEach((control) => {
      if (control.tagName === "SELECT" && !usedControls.has(control)) {
        ranked.push({ control, score: scoreControl(fieldKey, control, 48) });
      }
    });
    controls().forEach((control) => {
      if (control.tagName === "SELECT" && !usedControls.has(control)) {
        ranked.push({ control, score: scoreControl(fieldKey, control) });
      }
    });
    ranked.sort((left, right) => right.score - left.score);
    const best = ranked[0];
    return best && best.score >= 58 ? best.control : null;
  }

  function validOptions(select) {
    const humanDropdown = humanDropdownSelect();
    if (humanDropdown?.validOptions) return humanDropdown.validOptions(select);
    const human = humanSelectOption();
    if (human?.validOptions) return human.validOptions(select);
    const smart = selectSmartOption();
    if (smart?.validOptions) return smart.validOptions(select);
    return Array.from(select.options || []).filter((option) => !isPlaceholderOption(option));
  }

  function selectedControlForField(fieldKey, value, usedControls = new Set()) {
    const control = findControlForField(fieldKey, usedControls);
    if (!control) return null;
    if (NATIVE_SELECT_REQUIRED_FIELDS.has(fieldKey) && control.tagName !== "SELECT") return null;
    if (control.tagName !== "SELECT") return control;
    return validOptions(control).length ? control : null;
  }

  function dependentFieldFor(fieldKey) {
    if (fieldKey === "country") return "mission";
    if (fieldKey === "mission") return "nationality";
    if (fieldKey === "visaType") return "purpose";
    return "";
  }

  function dependentSelectFor(fieldKey) {
    const dependentField = dependentFieldFor(fieldKey);
    if (!dependentField) return null;
    const control = NATIVE_SELECT_REQUIRED_FIELDS.has(dependentField)
      ? findSelectForField(dependentField, new Set())
      : findControlForField(dependentField, new Set());
    return control?.tagName === "SELECT" ? control : null;
  }

  function currentDomSignature() {
    return Array.from(document.querySelectorAll("select"))
      .map((select) => `${select.name || select.id || ""}:${select.options?.length || 0}:${select.value || ""}`)
      .join("|");
  }

  async function waitForDomStable(timeout = 1800, quiet = 320) {
    if (isStopped()) return false;
    const startedAt = Date.now();
    let lastMutationAt = Date.now();
    let lastSignature = currentDomSignature();

    const observer = new MutationObserver(() => {
      lastMutationAt = Date.now();
      lastSignature = currentDomSignature();
    });

    observer.observe(document.documentElement, {
      attributes: true,
      childList: true,
      subtree: true
    });

    try {
      while (Date.now() - startedAt < timeout) {
        if (isStopped()) return false;
        await wait(90);
        const signature = currentDomSignature();
        if (signature !== lastSignature) {
          lastSignature = signature;
          lastMutationAt = Date.now();
        }
        if (Date.now() - lastMutationAt >= quiet) return true;
      }
      return false;
    } finally {
      observer.disconnect();
    }
  }

  async function waitForFieldReady(fieldKey, value, usedControls = new Set(), timeout = 4200) {
    const startedAt = Date.now();
    let lastOptionCount = -1;
    let stableSince = Date.now();
    let detectedLogged = false;
    let loadingLogged = false;
    let foundCountLogged = 0;

    while (Date.now() - startedAt < timeout) {
      if (isStopped()) return null;
      const control = findControlForField(fieldKey, usedControls);
      if (control && !control.disabled) {
        if (NATIVE_SELECT_REQUIRED_FIELDS.has(fieldKey) && control.tagName !== "SELECT") {
          await wait(160);
          continue;
        }
        if (control.tagName !== "SELECT") return control;

        const optionCount = validOptions(control).length;
        if (optionCount !== lastOptionCount) {
          lastOptionCount = optionCount;
          stableSince = Date.now();
        }

        if (!detectedLogged) {
          const detectedMessage = `${fieldName(fieldKey)} dropdown detected`;
          console.log(LOG, detectedMessage);
          emitActivity(detectedMessage, "info", {
            state: stateMachine()?.STATES?.RUNNING,
            status: "WAITING FOR DROPDOWN"
          });
          detectedLogged = true;
        }

        if (!loadingLogged) {
          const loadingMessage = `Loading ${fieldName(fieldKey).toLowerCase()} options`;
          console.log(LOG, loadingMessage);
          emitActivity(loadingMessage, "info", {
            state: stateMachine()?.STATES?.RUNNING,
            status: "WAITING FOR DROPDOWN"
          });
          loadingLogged = true;
        }

        const optionsStable = Date.now() - stableSince >= 280;
        if (optionCount > 0 && foundCountLogged !== optionCount) {
          const foundMessage = `Found ${optionCount} ${fieldName(fieldKey).toLowerCase()} options`;
          console.log(LOG, foundMessage);
          emitActivity(foundMessage, "info", {
            state: stateMachine()?.STATES?.RUNNING,
            status: "WAITING FOR DROPDOWN"
          });
          foundCountLogged = optionCount;
        }
        if (optionCount > 0 && optionsStable) return control;
      }

      await wait(160);
    }

    if (fieldKey === "mission") {
      console.warn(LOG, "Mission dropdown failed to load");
      emitActivity("Mission dropdown failed to load", "warn", {
        state: stateMachine()?.STATES?.RETRYING,
        status: "WAITING FOR DROPDOWN"
      });
    }

    return selectedControlForField(fieldKey, value, usedControls);
  }

  function fire(control, type) {
    control.dispatchEvent(new Event(type, { bubbles: true, cancelable: true }));
  }

  function keyEvent(control, type, key, options = {}) {
    control.dispatchEvent(new KeyboardEvent(type, {
      bubbles: true,
      cancelable: true,
      key,
      code: options.code || key,
      ctrlKey: options.ctrlKey === true,
      metaKey: options.metaKey === true
    }));
  }

  function simulateKey(control, key, options = {}) {
    keyEvent(control, "keydown", key, options);
    keyEvent(control, "keypress", key, options);
    keyEvent(control, "keyup", key, options);
  }

  function fireInput(control, value) {
    try {
      control.dispatchEvent(new InputEvent("beforeinput", {
        bubbles: true,
        cancelable: true,
        data: value,
        inputType: "insertFromPaste"
      }));
    } catch (_) {
      fire(control, "beforeinput");
    }
    fire(control, "input");
  }

  function setNativeValue(control, value) {
    const proto = control.tagName === "TEXTAREA"
      ? HTMLTextAreaElement.prototype
      : control.tagName === "SELECT"
        ? HTMLSelectElement.prototype
        : HTMLInputElement.prototype;
    const descriptor = Object.getOwnPropertyDescriptor(proto, "value");
    if (descriptor?.set) descriptor.set.call(control, value);
    else control.value = value;
  }

  async function activateControl(control) {
    control.scrollIntoView({ block: "center", inline: "nearest" });
    control.dispatchEvent(new MouseEvent("mouseover", { bubbles: true, cancelable: true }));
    control.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, cancelable: true }));
    control.focus({ preventScroll: true });
    control.click();
    control.dispatchEvent(new MouseEvent("mouseup", { bubbles: true, cancelable: true }));
    await randomDelay(90, 180);
  }

  async function hardClear(control) {
    simulateKey(control, "a", { ctrlKey: true, code: "KeyA" });
    await wait(25);
    simulateKey(control, "Backspace", { code: "Backspace" });
    simulateKey(control, "Delete", { code: "Delete" });
    setNativeValue(control, "");
    fireInput(control, "");
    fire(control, "change");
    await randomDelay(60, 140);
  }

  async function clearTextControl(control) {
    setNativeValue(control, "");
    fireInput(control, "");
    fire(control, "change");
    await randomDelay(60, 140);
  }

  function blurControl(control) {
    control.blur();
    fire(control, "blur");
  }

  function normalizeDateForControl(value, control) {
    if (!value) return "";
    if (control?.type === "date") return isoDateValue(value);
    return normalizeDateValue(value);
  }

  function optionCandidates(fieldKey, value) {
    const source = normalize(value);
    const variants = new Set([source]);

    if (fieldKey === "nationality" && source === "bangladesh") variants.add("bangladeshi");
    if (/bangladesh|bangladeshi/.test(source)) {
      variants.add("bangladesh");
      variants.add("bangladeshi");
    }
    if (/male|^m$/.test(source)) variants.add("male");
    if (/female|^f$/.test(source)) variants.add("female");
    if (/tourist|tourism|travel/.test(source)) {
      variants.add("tourist");
      variants.add("tourist visa");
      variants.add("e tourist visa");
      variants.add("e-tourist visa");
      variants.add("tourism");
    }
    if (/business/.test(source)) {
      variants.add("business");
      variants.add("business visa");
      variants.add("e business visa");
      variants.add("e-business visa");
    }
    if (/medical/.test(source)) {
      variants.add("medical");
      variants.add("medical visa");
      variants.add("medical treatment");
    }
    if (/study|student/.test(source)) {
      variants.add("student");
      variants.add("student visa");
      variants.add("study");
    }
    if (fieldKey === "visaType" && /entry/.test(source)) variants.add("entry visa");
    if (fieldKey === "purpose" && /tourism|tourist/.test(source)) variants.add("tourism");
    if ((fieldKey === "religion" || fieldKey === "education") && source) variants.add(source.replace(/\s+/g, " "));
    if (fieldKey === "mission" && /dhaka/.test(source)) {
      variants.add("dhaka");
      variants.add("bangladesh dhaka");
      variants.add("bangladesh-dhaka");
      variants.add("indian mission dhaka");
      variants.add("ivac dhaka");
    }

    return Array.from(variants).filter(Boolean);
  }

  function isPlaceholderOption(option) {
    const text = normalize(option.text || option.textContent || option.label || option.innerText || "");
    const value = normalize(option.value || "");
    return (!value && !text)
      || /^(select|choose|loading|wait|please wait|please select|none)\b/.test(text)
      || /^(select|choose|loading|wait|0|-1)$/.test(value);
  }

  function findMatchingOption(select, fieldKey, value) {
    const humanDropdown = humanDropdownSelect();
    const dropdownMatch = humanDropdown?.matchOption?.(select, { fieldKey, value });
    if (dropdownMatch?.option) return dropdownMatch.option;
    const human = humanSelectOption();
    const humanMatch = human?.matchOption?.(select, { fieldKey, value });
    if (humanMatch?.option) return humanMatch.option;
    const smart = selectSmartOption();
    const smartMatch = smart?.matchOption?.(select, { fieldKey, value });
    if (smartMatch?.option) return smartMatch.option;
    const candidates = optionCandidates(fieldKey, value);
    const options = Array.from(select.options || []).filter((option) => !isPlaceholderOption(option));

    const ranked = options.map((option) => ({
      option,
      score: scoreOption(option, candidates)
    })).sort((left, right) => right.score - left.score);

    return ranked[0]?.score >= 45 ? ranked[0].option : null;
  }

  function scoreOption(option, candidates) {
    const text = normalize(option.text || option.textContent || option.label || option.innerText || "");
    const optionValue = normalize(option.value || "");
    const haystack = `${text} ${optionValue}`.trim();
    const tightText = tightNormalize(option.text || option.textContent || option.label || option.innerText || "");
    const tightValue = tightNormalize(option.value || "");
    const optionTokens = new Set(haystack.split(" ").filter(Boolean));
    let score = 0;

    candidates.forEach((candidate) => {
      if (!candidate) return;
      const tightCandidate = tightNormalize(candidate);
      if ((text && text === candidate) || (optionValue && optionValue === candidate)) score = Math.max(score, 120);
      if ((tightText && tightText === tightCandidate) || (tightValue && tightValue === tightCandidate)) score = Math.max(score, 118);
      if ((text && text.includes(candidate)) || (optionValue && optionValue.includes(candidate))) score = Math.max(score, 92);
      if ((tightText && tightText.includes(tightCandidate)) || (tightValue && tightValue.includes(tightCandidate))) score = Math.max(score, 90);
      if ((text && candidate.includes(text)) || (optionValue && candidate.includes(optionValue))) score = Math.max(score, 78);
      if ((tightText && tightCandidate.includes(tightText)) || (tightValue && tightCandidate.includes(tightValue))) score = Math.max(score, 76);

      const candidateTokens = candidate.split(" ").filter(Boolean);
      const overlap = candidateTokens.filter((token) => optionTokens.has(token)).length;
      if (overlap) score = Math.max(score, 45 + (overlap * 18));

      if (text && candidate.length > 4 && levenshteinRatio(candidate, text) > 0.72) score = Math.max(score, 74);
      if (optionValue && candidate.length > 4 && levenshteinRatio(candidate, optionValue) > 0.72) score = Math.max(score, 74);
    });

    return score;
  }

  function levenshteinRatio(left = "", right = "") {
    if (!left || !right) return 0;
    const a = left.slice(0, 48);
    const b = right.slice(0, 48);
    const rows = Array.from({ length: a.length + 1 }, () => []);
    for (let i = 0; i <= a.length; i += 1) rows[i][0] = i;
    for (let j = 0; j <= b.length; j += 1) rows[0][j] = j;
    for (let i = 1; i <= a.length; i += 1) {
      for (let j = 1; j <= b.length; j += 1) {
        rows[i][j] = Math.min(
          rows[i - 1][j] + 1,
          rows[i][j - 1] + 1,
          rows[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1)
        );
      }
    }
    return 1 - (rows[a.length][b.length] / Math.max(a.length, b.length));
  }

  function selectedOptionMatches(select, fieldKey, value) {
    const option = select.options[select.selectedIndex];
    if (!option) return false;
    const normalizer = optionTextNormalizer();
    if (normalizer?.matchesOptionValue?.(option, value)) return select.selectedIndex > 0;
    if (fieldKey === "country" && /bangladesh/i.test(String(value || ""))) {
      const selected = `${option.text || option.textContent || option.label || option.innerText || ""} ${option.value || ""}`;
      return select.selectedIndex > 0 && normalize(selected).includes("bangladesh");
    }
    const candidates = optionCandidates(fieldKey, value);
    return scoreOption(option, candidates) >= 45;
  }

  async function waitForSelectOption(select, fieldKey, value, timeout = 4200) {
    const startedAt = Date.now();
    let lastOptionCount = validOptions(select).length;
    let stableSince = Date.now();

    while (Date.now() - startedAt < timeout) {
      if (isStopped()) return null;
      if (select.disabled) {
        await wait(160);
        continue;
      }

      const optionCount = validOptions(select).length;
      if (optionCount !== lastOptionCount) {
        lastOptionCount = optionCount;
        stableSince = Date.now();
      }

      const option = findMatchingOption(select, fieldKey, value);
      if (option && Date.now() - stableSince >= 260) return option;
      await wait(160);
    }

    return findMatchingOption(select, fieldKey, value);
  }

  function verifyFieldValue(fieldKey, value, control) {
    if (control && document.contains(control) && valueMatches(control, fieldKey, value)) return true;
    const freshControl = NATIVE_SELECT_REQUIRED_FIELDS.has(fieldKey)
      ? findSelectForField(fieldKey, new Set())
      : findControlForField(fieldKey, new Set());
    return Boolean(freshControl && valueMatches(freshControl, fieldKey, value));
  }

  async function forceSelectValue(select, fieldKey, value, options = {}) {
    if (isStopped()) return false;
    const dropdown = dropdownEngine();
    if (dropdown?.choose) {
      const dependentFieldKey = fieldKey === "country" || fieldKey === "mission" || fieldKey === "visaType"
        ? dependentFieldFor(fieldKey)
        : "";
      const result = await dropdown.choose(select, {
        attempts: MAX_DROPDOWN_RETRIES,
        dependentFieldKey,
        fieldKey,
        getDependentSelect: () => dependentFieldKey ? dependentSelectFor(fieldKey) : null,
        isPlaceholder: isPlaceholderOption,
        match: () => findMatchingOption(select, fieldKey, value),
        onTrace: (message, level) => emitActivity(message, level, {
          state: level === "warn" ? stateMachine()?.STATES?.RETRYING : stateMachine()?.STATES?.RUNNING,
          status: level === "warn" ? "WAITING FOR DROPDOWN" : "FILLING FORM"
        }),
        quiet: DYNAMIC_FIELDS.has(fieldKey) ? 320 : 220,
        resolveSelect: () => findSelectForField(fieldKey, new Set()),
        signal: currentSignal(),
        timeout: Math.max(400, Math.min(Number(options.timeout || MAX_WAIT_PER_FIELD), MAX_WAIT_PER_FIELD)),
        value,
        verify: (activeSelect) => verifyFieldValue(fieldKey, value, activeSelect || select)
      });
      select.dataset.fivaLastReason = result?.reason || "";
      if (result?.success) {
        if (fieldKey === "country") console.log(LOG, "country selected successfully");
        if (fieldKey === "mission") console.log(LOG, "Mission matched successfully");
        if (fieldKey === "mission") console.log(LOG, "mission selected successfully");
        if (fieldKey === "nationality") console.log(LOG, "Nationality selected");
        if (fieldKey === "visaType") console.log(LOG, "Visa type selected");
        return true;
      }
      return false;
    }

    const attempts = MAX_DROPDOWN_RETRIES;

    for (let attempt = 0; attempt < attempts; attempt += 1) {
      if (isStopped()) return false;
      await activateControl(select);
      const option = await waitForSelectOption(select, fieldKey, value, Math.max(400, Math.min(Number(options.timeout || MAX_WAIT_PER_FIELD), MAX_WAIT_PER_FIELD)));
      if (!option) {
        select.dataset.fivaLastReason = validOptions(select).length ? "option_not_found" : "dropdown_not_loaded";
        await randomDelay(260, 620);
        continue;
      }

      select.selectedIndex = option.index;
      option.selected = true;
      setNativeValue(select, option.value);
      fire(select, "input");
      fire(select, "change");
      await waitForDomStable(DYNAMIC_FIELDS.has(fieldKey) ? 2200 : 900, 320);
      await randomDelay(DYNAMIC_FIELDS.has(fieldKey) ? 320 : 180, DYNAMIC_FIELDS.has(fieldKey) ? 780 : 420);
      blurControl(select);

      if (verifyFieldValue(fieldKey, value, select)) {
        if (fieldKey === "country") console.log(LOG, "country selected successfully");
        if (fieldKey === "mission") console.log(LOG, "Mission matched successfully");
        if (fieldKey === "mission") console.log(LOG, "mission selected successfully");
        if (fieldKey === "nationality") console.log(LOG, "Nationality selected");
        if (fieldKey === "visaType") console.log(LOG, "Visa type selected");
        select.dataset.fivaLastReason = "";
        return true;
      }

      select.dataset.fivaLastReason = "verification_failed";
      await waitForDomStable(900, 220);
      await randomDelay(260, 620);
    }

    return false;
  }

  function valueMatches(control, fieldKey, expected) {
    if (control.tagName === "SELECT") return selectedOptionMatches(control, fieldKey, expected);
    const actual = normalize(control.value);
    const wanted = normalize(expected);
    if (!wanted) return false;
    return actual === wanted;
  }

  async function forceTextValue(control, fieldKey, value) {
    const nextValue = normalizedFieldValue(fieldKey, value, control);
    if (!nextValue) return false;
    if (isStopped()) return false;

    const validators = validatorsEngine();
    const validation = validators?.validateField?.(fieldKey, nextValue, {}) || { ok: true, value: nextValue };
    if (!validation.ok) {
      console.log(LOG, `${fieldName(fieldKey)} skipped: ${validation.reason}`);
      return false;
    }

    const primaryPaste = hardPaste();
    if (primaryPaste?.fill) {
      emitActivity(`Textbox detected: ${fieldName(fieldKey)}`);
      const pasted = await primaryPaste.fill(control, nextValue, {
        attempts: 2,
        onTrace: (message, level) => emitActivity(`${fieldName(fieldKey)} ${message}`, level, {
          state: level === "warn" ? stateMachine()?.STATES?.RETRYING : stateMachine()?.STATES?.RUNNING,
          status: level === "warn" ? "RETRYING" : "FILLING FORM"
        }),
        signal: currentSignal(),
        verify: () => verifyFieldValue(fieldKey, nextValue, control)
      });
      if (pasted && !isStopped()) return true;
    }

    const legacyHardPaste = hardPasteEngine();
    if (legacyHardPaste?.fillText) {
      const hardPasted = await legacyHardPaste.fillText(control, nextValue, {
        attempts: 2,
        onTrace: (message, level) => emitActivity(`${fieldName(fieldKey)} ${message}`, level, {
          state: level === "warn" ? stateMachine()?.STATES?.RETRYING : stateMachine()?.STATES?.RUNNING,
          status: level === "warn" ? "RETRYING" : "FILLING FORM"
        }),
        signal: currentSignal(),
        verify: () => verifyFieldValue(fieldKey, nextValue, control)
      });
      return hardPasted && !isStopped();
    }

    const wasReadOnly = control.readOnly === true;
    if (wasReadOnly) {
      control.readOnly = false;
      control.removeAttribute("readonly");
    }

    try {
      await activateControl(control);
      await clearTextControl(control);
      fireInput(control, nextValue);
      setNativeValue(control, nextValue);
      fireInput(control, nextValue);
      fire(control, "change");
      await randomDelay(180, 360);
      blurControl(control);
      return verifyFieldValue(fieldKey, nextValue, control);
    } finally {
      if (wasReadOnly) {
        control.readOnly = true;
        control.setAttribute("readonly", "readonly");
      }
    }
  }

  async function forceRadioValue(fieldKey, value, usedControls) {
    if (isStopped()) return null;
    if (!RADIO_FIELDS.has(fieldKey)) return null;
    const candidates = optionCandidates(fieldKey, value);
    const radios = controls().filter((control) => control.type === "radio" && !usedControls.has(control));

    for (const radio of radios) {
      const title = titleForControl(radio);
      const optionValue = normalize(radio.value);
      const matches = candidates.some((candidate) => title.includes(candidate) || optionValue.includes(candidate));
      if (!matches) continue;
      if (isStopped()) return null;

      await activateControl(radio);
      radio.checked = true;
      fire(radio, "input");
      fire(radio, "change");
      await randomDelay(180, 360);
      blurControl(radio);
      return radio.checked ? radio : null;
    }

    return null;
  }

  async function setControlValue(control, fieldKey, value, options = {}) {
    const type = detectControlType(control);
    if (NATIVE_SELECT_REQUIRED_FIELDS.has(fieldKey) && type !== "dropdown") {
      control.dataset.fivaLastReason = "field_blocked";
      return false;
    }
    if (type === "dropdown") return forceSelectValue(control, fieldKey, value, options);
    if (type === "radio") {
      await activateControl(control);
      control.checked = true;
      fire(control, "input");
      fire(control, "change");
      await randomDelay(180, 360);
      blurControl(control);
      return control.checked === true;
    }
    if (type === "checkbox") {
      await activateControl(control);
      control.checked = !/^(false|no|0)$/i.test(String(value || ""));
      fire(control, "input");
      fire(control, "change");
      await randomDelay(180, 360);
      blurControl(control);
      return control.checked === true;
    }
    if (type === "textbox" || type === "textarea") return forceTextValue(control, fieldKey, value);
    return false;
  }

  function mark(control) {
    control.classList.remove(FILLED_CLASS);
    control.classList.add(FILLED_CLASS);
    const timer = setTimeout(() => {
      activeTimers.delete(timer);
      control.classList.remove(FILLED_CLASS);
    }, 8000);
    activeTimers.add(timer);
  }

  function ensureStyles() {
    if (document.getElementById("fiva-form-engine-style")) return;
    const style = document.createElement("style");
    style.id = "fiva-form-engine-style";
    style.textContent = `
      .${FILLED_CLASS} {
        outline: 3px solid rgba(52, 211, 153, .9) !important;
        outline-offset: 2px !important;
        box-shadow: 0 0 0 5px rgba(52, 211, 153, .18) !important;
      }
      .fiva-autofill-toast {
        position: fixed;
        z-index: 2147483647;
        right: 18px;
        bottom: 18px;
        padding: 10px 12px;
        border-radius: 8px;
        border: 1px solid rgba(52, 211, 153, .42);
        background: rgba(6, 78, 59, .96);
        color: #ecfdf5;
        font: 13px/1.35 system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
        box-shadow: 0 14px 30px rgba(0, 0, 0, .24);
      }
    `;
    document.documentElement.appendChild(style);
  }

  function showAutofillToast() {
    document.querySelector(".fiva-autofill-toast")?.remove();
    const toast = document.createElement("div");
    toast.className = "fiva-autofill-toast";
    toast.textContent = "Autofill complete";
    document.body.appendChild(toast);
    const timer = setTimeout(() => {
      activeTimers.delete(timer);
      toast.remove();
    }, 2400);
    activeTimers.add(timer);
  }

  function cleanupTimers() {
    activeTimers.forEach((timer) => clearTimeout(timer));
    activeTimers.clear();
  }

  async function stopAutofill(reason = "manual") {
    fivaRunning = false;
    fivaRunActive = false;
    globalAbortController?.abort?.();
    cleanupTimers();
    emitActivity("FIVA stopped", "warn", { state: stateMachine()?.STATES?.STOPPED, status: "STOPPED" });
    await storageRemove(FIVA_SESSION_KEY).catch(() => {});
    return { ok: true, stopped: true, reason };
  }

  function isCaptchaControl(control) {
    const title = titleForControl(control);
    return /captcha|verification code|enter above text|security code/.test(title);
  }

  function captchaControls() {
    return controls().filter(isCaptchaControl);
  }

  function hasPendingManualGate() {
    return captchaControls().some((control) => !compact(control.value));
  }

  function isRequiredControl(control) {
    if (!isVisible(control) || !isFillable(control)) return false;
    if (isCaptchaControl(control)) return false;
    if (control.required || control.getAttribute("aria-required") === "true") return true;
    const rowText = compact(control.closest("tr, .form-group, .form-row, .row, .mb-3, .field, .control-group, label")?.innerText || "");
    return /\*/.test(rowText) || /required/i.test(rowText);
  }

  function controlHasValue(control) {
    if (control.type === "checkbox" || control.type === "radio") return control.checked;
    if (control.tagName === "SELECT") return Boolean(validOptions(control).find((option) => option.selected));
    return Boolean(compact(control.value));
  }

  function validateCurrentPage() {
    const missing = controls().filter((control) => isRequiredControl(control) && !controlHasValue(control));
    return {
      ok: missing.length === 0,
      missing
    };
  }

  function findValidationControl(fieldKey, fieldControls = new Map()) {
    const tracked = fieldControls.get(fieldKey);
    if (tracked && document.contains(tracked)) return tracked;
    if (fieldKey === "reEnterEmail") {
      const used = new Set();
      const emailControl = fieldControls.get("email") || findControlForField("email", new Set());
      if (emailControl) used.add(emailControl);
      return findControlForField("reEnterEmail", used);
    }
    return findControlForField(fieldKey, new Set());
  }

  function validateRegistrationFields(profile = {}, fieldControls = new Map()) {
    const missing = [];

    REGISTRATION_REQUIRED_FIELDS.forEach((fieldKey) => {
      const value = profile[fieldKey];
      if (!value) {
        missing.push(fieldKey);
        return;
      }

      const control = findValidationControl(fieldKey, fieldControls);
      const expectedValue = normalizedFieldValue(fieldKey, value, control);
      if (!control || !verifyFieldValue(fieldKey, expectedValue, control)) {
        missing.push(fieldKey);
      }
    });

    return {
      ok: missing.length === 0,
      missing
    };
  }

  function findContinueButton() {
    const candidates = Array.from(document.querySelectorAll("button, input[type='submit'], input[type='button'], a"))
      .filter(isVisible)
      .filter((element) => !element.disabled && element.getAttribute("aria-disabled") !== "true")
      .filter((element) => {
        const text = normalize([
          element.innerText,
          element.textContent,
          element.value,
          element.getAttribute("title"),
          element.getAttribute("aria-label"),
          element.id,
          element.name
        ].filter(Boolean).join(" "));
        return /continue|next|save and continue|proceed|submit/.test(text);
      });
    return candidates[0] || null;
  }

  async function clickContinue(profile, session, fieldControls = new Map()) {
    if (isStopped()) return { continued: false, stopped: true };
    if (hasPendingManualGate()) {
      console.log(LOG, "Waiting for manual captcha");
      await saveSession({
        ...session,
        active: true,
        awaitingManual: true,
        page: detectPage(),
        profile
      });
      waitForManualCaptcha(profile, session);
      return { continued: false, manual: true };
    }

    const validation = validateCurrentPage();
    const page = detectPage();
    const registrationValidation = page === "registration"
      ? validateRegistrationFields(profile, fieldControls)
      : { ok: true, missing: [] };

    if (!registrationValidation.ok) {
      console.log(LOG, `Registration verification blocked missing fields: ${registrationValidation.missing.join(", ")}`);
      await saveSession({
        ...session,
        active: true,
        blocked: true,
        blockedFields: registrationValidation.missing,
        page,
        profile
      });
      return { continued: false, blocked: true, missing: registrationValidation.missing };
    }

    if (!validation.ok) {
      console.log(LOG, `Page validation blocked missing fields: ${validation.missing.length}`);
      await saveSession({
        ...session,
        active: true,
        blocked: true,
        page,
        profile
      });
      return { continued: false, blocked: true };
    }

    const button = findContinueButton();
    if (!button) {
      await saveSession({ ...session, active: false, completedAt: Date.now(), page: detectPage(), profile });
      return { continued: false, complete: true };
    }

    console.log(LOG, "Page validation passed");
    await saveSession({
      ...session,
      active: true,
      awaitingManual: false,
      profile,
      page,
      stepCount: Number(session.stepCount || 0) + 1,
      updatedAt: Date.now()
    });
    console.log(LOG, "Continuing next step");
    await activateControl(button);
    if (isStopped()) return { continued: false, stopped: true };
    button.click();
    await waitForNavigationOrDomChange();
    return { continued: true };
  }

  function scheduleContinueAfterResponse(profile, session, fieldControls = new Map()) {
    const signal = currentSignal();
    const timer = setTimeout(async () => {
      activeTimers.delete(timer);
      if (signal?.aborted) return;
      fivaRunning = true;
      fivaRunActive = true;
      try {
        const continuation = await clickContinue(profile, session, fieldControls);
        if (continuation.continued) scheduleResume();
      } catch (error) {
        console.warn(LOG, error);
        emitActivity("Continue failed", "warn");
      } finally {
        fivaRunActive = false;
        fivaRunning = false;
      }
    }, 120);
    activeTimers.add(timer);
  }

  async function prepareContinueAfterResponse(profile, session, fieldControls = new Map()) {
    if (isStopped()) return { continued: false, stopped: true };
    if (hasPendingManualGate()) {
      console.log(LOG, "Waiting for manual captcha");
      await saveSession({
        ...session,
        active: true,
        awaitingManual: true,
        page: detectPage(),
        profile
      });
      waitForManualCaptcha(profile, session);
      return { continued: false, manual: true };
    }

    const validation = validateCurrentPage();
    const page = detectPage();
    const registrationValidation = page === "registration"
      ? validateRegistrationFields(profile, fieldControls)
      : { ok: true, missing: [] };

    if (!registrationValidation.ok) {
      console.log(LOG, `Registration verification blocked missing fields: ${registrationValidation.missing.join(", ")}`);
      await saveSession({
        ...session,
        active: true,
        blocked: true,
        blockedFields: registrationValidation.missing,
        page,
        profile
      });
      return { continued: false, blocked: true, missing: registrationValidation.missing };
    }

    if (!validation.ok) {
      console.log(LOG, `Page validation blocked missing fields: ${validation.missing.length}`);
      await saveSession({
        ...session,
        active: true,
        blocked: true,
        page,
        profile
      });
      return { continued: false, blocked: true };
    }

    if (!findContinueButton()) {
      await saveSession({ ...session, active: false, completedAt: Date.now(), page: detectPage(), profile });
      return { continued: false, complete: true };
    }

    console.log(LOG, "Page validation passed");
    await saveSession({
      ...session,
      active: true,
      awaitingManual: false,
      profile,
      page,
      stepCount: Number(session.stepCount || 0) + 1,
      updatedAt: Date.now()
    });
    console.log(LOG, "Continuing next step");
    scheduleContinueAfterResponse(profile, session, fieldControls);
    return { continued: true };
  }

  function scheduleResume(delayMs = 1200) {
    const timer = setTimeout(() => {
      activeTimers.delete(timer);
      if (currentSignal()?.aborted) return;
      resumeSessionIfActive().catch((error) => console.warn(LOG, error));
    }, delayMs);
    activeTimers.add(timer);
  }

  function waitForManualCaptcha(profile, session) {
    const controlsToWatch = captchaControls();
    controlsToWatch.forEach((control) => {
      const handler = async () => {
        if (currentSignal()?.aborted) return;
        if (!compact(control.value)) return;
        control.removeEventListener("input", handler);
        control.removeEventListener("change", handler);
        await randomDelay(500, 1000);
        if (currentSignal()?.aborted) return;
        fivaRunning = true;
        fivaRunActive = true;
        try {
          const continuation = await clickContinue(profile, session);
          if (continuation.continued) scheduleResume();
        } catch (error) {
          console.warn(LOG, error);
        } finally {
          fivaRunActive = false;
          fivaRunning = false;
        }
      };
      control.addEventListener("input", handler);
      control.addEventListener("change", handler);
    });
  }

  async function waitForNavigationOrDomChange() {
    const startUrl = location.href;
    const startSignature = currentDomSignature();
    const startedAt = Date.now();
    while (Date.now() - startedAt < 5000) {
      if (isStopped()) return false;
      await wait(180);
      if (location.href !== startUrl || currentDomSignature() !== startSignature || document.readyState === "loading") return true;
    }
    return false;
  }

  async function saveSession(session = {}) {
    await storageSet({
      [FIVA_SESSION_KEY]: {
        ...session,
        updatedAt: Date.now()
      }
    });
  }

  async function getSession() {
    const data = await storageGet({ [FIVA_SESSION_KEY]: null });
    return data[FIVA_SESSION_KEY] || null;
  }

  async function resumeSessionIfActive() {
    const session = await getSession().catch(() => null);
    if (!session?.active || session.blocked || session.stopped || !session.profile || Number(session.stepCount || 0) > 12) return;
    if (Date.now() - Number(session.updatedAt || session.startedAt || 0) > 120000) {
      await storageRemove(FIVA_SESSION_KEY).catch(() => {});
      return;
    }
    if (fivaRunActive) return;
    await randomDelay(600, 1200);
    await fillForm(session.profile, { resume: true, session });
  }

  function orderedEntries(profile = {}) {
    const { page, order } = pageFieldOrder(profile);
    const fallback = page === "registration" ? [...FIELD_ORDER, ...Object.keys(profile || {})] : [];
    const keys = new Set([...order, ...fallback]);
    return Array.from(keys)
      .filter((key) => !key.startsWith("__") && profile[key])
      .map((key) => [key, profile[key]]);
  }

  function nextFieldAfter(fieldKey, profile = {}) {
    const keys = orderedEntries(profile).map(([key]) => key);
    const index = keys.indexOf(fieldKey);
    if (index < 0) return "";
    return keys.slice(index + 1).find((key) => profile[key]) || "";
  }

  function logFilled(fieldKey) {
    if (fieldKey === "country") emitActivity("Country selected");
    else if (fieldKey === "mission") emitActivity("Mission selected");
    else if (fieldKey === "nationality") emitActivity("Nationality selected");
    else if (fieldKey === "dateOfBirth") emitActivity("DOB inserted");
    else if (fieldKey === "email") emitActivity("Email inserted");
    else if (fieldKey === "expectedArrivalDate") emitActivity("Arrival date inserted");
    else if (fieldKey === "visaType") emitActivity("Visa type selected");
    else if (fieldKey === "purpose") emitActivity("Purpose selected");
    else logField(fieldKey, "filled");
  }

  async function waitAfterField(fieldKey, profile, usedControls) {
    if (!DYNAMIC_FIELDS.has(fieldKey)) {
      await randomDelay(300, 520);
      return;
    }

    await waitForDomStable(2600, 420);
    const preferredTarget = DEPENDENT_WAIT_TARGETS[fieldKey];
    const nextField = preferredTarget && profile[preferredTarget]
      ? preferredTarget
      : nextFieldAfter(fieldKey, profile);

    if (nextField) {
      if (fieldKey === "country" && nextField === "mission") {
        emitActivity("Waiting mission dropdown load", "info", {
          state: stateMachine()?.STATES?.RUNNING,
          status: "WAITING FOR DROPDOWN"
        });
        console.log(LOG, "waiting mission load");
      }
      if (fieldKey === "mission" && nextField === "nationality") {
        emitActivity("Waiting nationality load", "info", {
          state: stateMachine()?.STATES?.RUNNING,
          status: "WAITING FOR DROPDOWN"
        });
      }
      await waitForFieldReady(nextField, profile[nextField], usedControls, nextField === "mission" ? 8000 : 5200);
    }

    await randomDelay(800, 1500);
  }

  function fieldResult(fieldKey, value, patch = {}) {
    return {
      success: false,
      field: fieldKey,
      value,
      controlFound: false,
      attempts: 0,
      reason: "verification_failed",
      control: null,
      controlType: null,
      ...patch
    };
  }

  function failureReasonForControl(control, fieldKey, value) {
    if (!control) return "selector_missing";
    if (control.isConnected === false || !document.contains(control)) return "stale_dom_reference";
    if (control.dataset?.fivaLastReason) return control.dataset.fivaLastReason;
    if (NATIVE_SELECT_REQUIRED_FIELDS.has(fieldKey) && control.tagName !== "SELECT") return "field_blocked";
    if (control.tagName === "SELECT") {
      if (validOptions(control).length < 1) return "dropdown_not_loaded";
      if (!findMatchingOption(control, fieldKey, value)) return "option_not_found";
      return "verification_failed";
    }
    return "hard_paste_failed";
  }

  async function fillFieldResult(fieldKey, value, usedControls) {
    if (isStopped()) return fieldResult(fieldKey, value, { reason: "stopped_manually" });
    if (!compact(value)) return fieldResult(fieldKey, value, { reason: "parser_missing_field" });
    const startedAt = Date.now();
    const attempts = MAX_DROPDOWN_RETRIES;
    let preparedControl = findControlForField(fieldKey, usedControls);
    if (!preparedControl && DYNAMIC_FIELDS.has(fieldKey)) {
      preparedControl = await waitForFieldReady(fieldKey, value, usedControls, 1800);
    }
    let lastReason = preparedControl ? "verification_failed" : (DYNAMIC_FIELDS.has(fieldKey) ? "dropdown_not_loaded" : "selector_missing");

    for (let attempt = 0; attempt < attempts; attempt += 1) {
      if (isStopped()) return fieldResult(fieldKey, value, { attempts: attempt, reason: "stopped_manually" });
      const elapsed = Date.now() - startedAt;
      const remaining = Math.max(0, MAX_WAIT_PER_FIELD - elapsed);
      if (remaining <= 0) break;
      const radio = await forceRadioValue(fieldKey, value, usedControls);
      if (radio) {
        emitActivity(`${fieldName(fieldKey)} verification success`);
        return fieldResult(fieldKey, value, { success: true, control: radio, controlFound: true, controlType: controlDescriptor(radio), attempts: attempt + 1, reason: "" });
      }

      const control = preparedControl && !usedControls.has(preparedControl)
        ? preparedControl
        : findControlForField(fieldKey, usedControls);
      if (control) emitActivity(`${fieldName(fieldKey)} selector found`);
      if (control && (control.isConnected === false || !document.contains(control))) {
        lastReason = "stale_dom_reference";
        preparedControl = null;
        await waitForDomStable(900, 220);
        continue;
      }
      if (control && await setControlValue(control, fieldKey, value, { timeout: remaining })) {
        emitActivity(`${fieldName(fieldKey)} verification success`);
        return fieldResult(fieldKey, value, { success: true, control, controlFound: true, controlType: controlDescriptor(control), attempts: attempt + 1, reason: "" });
      }

      lastReason = failureReasonForControl(control, fieldKey, value);
      emitActivity(`Retry attempt ${attempt + 1}: ${fieldName(fieldKey)}`, "warn", {
        state: stateMachine()?.STATES?.RETRYING,
        status: "RETRYING"
      });

      preparedControl = null;
      await waitForDomStable(900, 220);
      await randomDelay(DYNAMIC_FIELDS.has(fieldKey) ? 420 : 260, DYNAMIC_FIELDS.has(fieldKey) ? 980 : 520);
    }

    return fieldResult(fieldKey, value, {
      controlFound: lastReason !== "selector_missing",
      controlType: controlDescriptor(preparedControl),
      attempts,
      reason: lastReason
    });
  }

  async function fillField(fieldKey, value, usedControls) {
    const result = await fillFieldResult(fieldKey, value, usedControls);
    return result.success ? result.control : null;
  }

  function registrationEntries(profile = {}) {
    return REGISTRATION_QUEUE
      .map((fieldKey) => [fieldKey, profile[fieldKey]]);
  }

  function criticalMissingFields(fields = []) {
    return fields.filter((fieldKey) => CRITICAL_DEPENDENCY_FIELDS.has(fieldKey));
  }

  async function retryPageFields(profile, usedControls, filled, missing, fieldControls) {
    for (const [fieldKey, value] of orderedEntries(profile)) {
      const existingControl = findValidationControl(fieldKey, fieldControls);
      const expectedValue = normalizedFieldValue(fieldKey, value, existingControl);
      if (existingControl && verifyFieldValue(fieldKey, expectedValue, existingControl)) continue;
      const retryUsedControls = new Set(usedControls);
      if (existingControl) retryUsedControls.delete(existingControl);
      const control = await fillField(fieldKey, value, retryUsedControls);
      if (!control) continue;
      usedControls.add(control);
      fieldControls.set(fieldKey, control);
      mark(control);
      if (!filled.includes(fieldKey)) filled.push(fieldKey);
      const missingIndex = missing.indexOf(fieldKey);
      if (missingIndex >= 0) missing.splice(missingIndex, 1);
      logFilled(fieldKey);
      await waitAfterField(fieldKey, profile, usedControls);
    }
  }

  async function retryRegistrationFields(profile, usedControls, filled, missing, fieldControls, completedFields) {
    for (let pass = 0; pass < 2; pass += 1) {
      if (isStopped()) break;
      const validation = validateRegistrationFields(profile, fieldControls);
      if (validation.ok) return validation;

      for (const fieldKey of validation.missing) {
        if (isStopped()) break;
        const value = profile[fieldKey];
        if (!value) continue;

        const existingControl = findValidationControl(fieldKey, fieldControls);
        const retryUsedControls = new Set(usedControls);
        if (existingControl) retryUsedControls.delete(existingControl);

        const control = await fillField(fieldKey, value, retryUsedControls);
        if (!control) continue;

        usedControls.add(control);
        fieldControls.set(fieldKey, control);
        completedFields?.add(fieldKey);
        mark(control);
        if (!filled.includes(fieldKey)) filled.push(fieldKey);
        const missingIndex = missing.indexOf(fieldKey);
        if (missingIndex >= 0) missing.splice(missingIndex, 1);
        logFilled(fieldKey);
        await waitAfterField(fieldKey, profile, usedControls);
      }
    }

    return validateRegistrationFields(profile, fieldControls);
  }

  async function fillRegistrationPage(profile, session) {
    profile = buildAutofillProfile(profile, session?.source || {});
    const usedControls = new Set();
    const fieldControls = new Map();
    const completedFields = new Set();
    const filled = [];
    const missing = [];
    const results = [];

    console.log(LOG, "Registration page detected");
    emitActivity("Building autofill queue", "info", { state: stateMachine()?.STATES?.RUNNING, status: "FILLING FORM" });
    console.log(LOG, "queue built", REGISTRATION_QUEUE);

    for (const [fieldKey, value] of registrationEntries(profile)) {
      if (isStopped()) break;
      if (completedFields.has(fieldKey)) continue;
      const dependencyField = FIELD_DEPENDENCY_REQUIREMENTS[fieldKey];
      if (dependencyField && !completedFields.has(dependencyField)) {
        const result = fieldResult(fieldKey, value, {
          attempts: 0,
          reason: "dependency_not_completed"
        });
        results.push({
          success: result.success,
          field: result.field,
          value: result.value,
          controlFound: result.controlFound,
          attempts: result.attempts,
          reason: result.reason,
          controlType: result.controlType
        });
        if (!missing.includes(fieldKey)) missing.push(fieldKey);
        emitActivity(`Failed field: ${fieldName(fieldKey)} (${reasonLabel(result.reason)})`, "warn", {
          state: stateMachine()?.STATES?.RETRYING,
          status: "RETRYING"
        });
        continue;
      }
      emitActivity(`Executing field: ${fieldName(fieldKey)}`);
      const result = await fillFieldResult(fieldKey, value, usedControls);
      results.push({
        success: result.success,
        field: result.field,
        value: result.value,
        controlFound: result.controlFound,
        attempts: result.attempts,
        reason: result.reason,
        controlType: result.controlType
      });
      const control = result.control;
      if (result.success && control) {
        usedControls.add(control);
        fieldControls.set(fieldKey, control);
        completedFields.add(fieldKey);
        mark(control);
        filled.push(fieldKey);
        logFilled(fieldKey);
        await waitAfterField(fieldKey, profile, usedControls);
      } else {
        if (!missing.includes(fieldKey)) missing.push(fieldKey);
        logField(fieldKey, `not filled: ${result.reason}`);
        emitActivity(`Failed field: ${fieldName(fieldKey)} (${reasonLabel(result.reason)})`, "warn", {
          state: stateMachine()?.STATES?.RETRYING,
          status: "RETRYING"
        });
        if (CRITICAL_DEPENDENCY_FIELDS.has(fieldKey)) {
          emitActivity(`${fieldName(fieldKey)} is required before dependent fields`, "error", {
            state: stateMachine()?.STATES?.FAILED,
            status: "FAILED",
            failedFields: missing
          });
          break;
        }
        await randomDelay(300, 560);
      }
    }

    if (isStopped()) {
      return {
        ok: true,
        page: "registration",
        filled,
        missing,
        continued: false,
        manual: false,
        blocked: false,
        complete: false,
        stopped: true,
        review: [],
        failedFields: missing,
        results,
        message: "FIVA stopped"
      };
    }

    const criticalMissing = criticalMissingFields(missing);
    if (criticalMissing.length) {
      const message = `Required fields missing: ${criticalMissing.join(", ")}`;
      emitActivity(message, "error", {
        state: stateMachine()?.STATES?.FAILED,
        status: "FAILED",
        failedFields: criticalMissing
      });
      await saveSession({
        ...session,
        active: true,
        blocked: true,
        blockedFields: criticalMissing,
        page: "registration",
        profile
      });
      return {
        ok: true,
        page: "registration",
        filled,
        missing: criticalMissing,
        continued: false,
        manual: false,
        blocked: true,
        complete: false,
        review: [],
        failedFields: criticalMissing,
        results,
        message
      };
    }

    const registrationValidation = await retryRegistrationFields(profile, usedControls, filled, missing, fieldControls, completedFields);
    if (isStopped()) {
      return {
        ok: true,
        page: "registration",
        filled,
        missing,
        continued: false,
        manual: false,
        blocked: false,
        complete: false,
        stopped: true,
        review: [],
        failedFields: missing,
        results,
        message: "FIVA stopped"
      };
    }
    if (!registrationValidation.ok) {
      const message = `Required fields missing: ${registrationValidation.missing.join(", ")}`;
      const state = filled.length ? stateMachine()?.STATES?.PARTIAL_SUCCESS : stateMachine()?.STATES?.FAILED;
      emitActivity(message, filled.length ? "warn" : "error", {
        state,
        status: filled.length ? "PARTIAL SUCCESS" : "FAILED",
        failedFields: registrationValidation.missing
      });
      await saveSession({
        ...session,
        active: true,
        blocked: true,
        blockedFields: registrationValidation.missing,
        page: "registration",
        profile
      });
      return {
        ok: true,
        page: "registration",
        filled,
        missing: registrationValidation.missing,
        continued: false,
        manual: false,
        blocked: true,
        complete: false,
        review: [],
        failedFields: registrationValidation.missing,
        results,
        message
      };
    }

    emitActivity("Registration fields verified", "info", { state: stateMachine()?.STATES?.RUNNING, status: "FILLING FORM" });
    const continuation = await prepareContinueAfterResponse(profile, session, fieldControls);
    if (continuation.continued) {
      emitActivity("Registration page completed");
      emitActivity("Waiting for next page");
    }

    return {
      ok: true,
      page: "registration",
      filled,
      missing: continuation.missing || [],
      continued: continuation.continued === true,
      manual: continuation.manual === true,
      blocked: continuation.blocked === true,
      complete: continuation.complete === true,
      review: [],
      failedFields: continuation.missing || [],
      results,
      message: continuation.continued ? "Registration page completed" : (continuation.missing?.length ? `Required fields missing: ${continuation.missing.join(", ")}` : "Partial autofill completed")
    };
  }

  async function startFivaAutofill(profile = {}, options = {}) {
    if (fivaRunActive) return { ok: true, busy: true };
    globalAbortController?.abort?.();
    cleanupTimers();
    globalAbortController = new AbortController();
    fivaRunning = true;
    fivaRunActive = true;
    const globalTimeoutTimer = setTimeout(() => {
      activeTimers.delete(globalTimeoutTimer);
      globalAbortController?.abort?.();
      fivaRunning = false;
      emitActivity("Autofill timed out", "error", { state: stateMachine()?.STATES?.FAILED, status: "FAILED" });
    }, GLOBAL_AUTOFILL_TIMEOUT);
    activeTimers.add(globalTimeoutTimer);
    try {
      ensureStyles();
      emitActivity("Detecting Indian Visa form", "info", { state: stateMachine()?.STATES?.RUNNING, status: "FILLING FORM" });
      console.log(LOG, "parser output received", profile);
      const hasInputData = hasProfileInputData(profile);
      const standardProfile = hasInputData ? standardProfileForLog(profile, options.source || {}) : {};
      console.log(LOG, "normalized profile:", standardProfile);
      console.log(LOG, "profile normalized");
      if (standardProfile.country) console.log(LOG, `country mapped -> ${standardProfile.country}`);
      if (standardProfile.mission) console.log(LOG, `mission mapped -> ${standardProfile.mission}`);
      const normalizedProfile = hasInputData ? buildAutofillProfile(profile, options.source || {}) : {};
      console.log(LOG, "parser success", normalizedProfile);
      emitActivity("Autofill profile loaded", "info", { state: stateMachine()?.STATES?.RUNNING, status: "FILLING FORM" });
      if (!Object.keys(normalizedProfile).length) {
        await storageRemove(FIVA_SESSION_KEY).catch(() => {});
        emitActivity("No valid application data found.", "error", { state: stateMachine()?.STATES?.FAILED, status: "FAILED" });
        fivaRunActive = false;
        fivaRunning = false;
        return {
          ok: true,
          page: detectPage(),
          filled: [],
          missing: [],
          continued: false,
          manual: false,
          blocked: true,
          complete: false,
          review: [],
          failedFields: [],
          results: [],
          message: "No valid application data found."
        };
      }
      const page = detectPage();
      const session = {
        ...(options.session || {}),
        active: true,
        profile: normalizedProfile,
        source: options.source || {},
        page,
        startedAt: options.session?.startedAt || Date.now(),
        stepCount: Number(options.session?.stepCount || 0)
      };
      if (!options.resume) await storageRemove(FIVA_SESSION_KEY).catch(() => {});
      await saveSession(session);

      if (page === "registration") {
        return await fillRegistrationPage(normalizedProfile, session);
      }

      const usedControls = new Set();
      const fieldControls = new Map();
      const filled = [];
      const missing = [];

      for (const [fieldKey, value] of orderedEntries(normalizedProfile)) {
        if (isStopped()) break;
        const control = await fillField(fieldKey, value, usedControls);
        if (control) {
          usedControls.add(control);
          fieldControls.set(fieldKey, control);
          mark(control);
          filled.push(fieldKey);
          logFilled(fieldKey);
          await waitAfterField(fieldKey, normalizedProfile, usedControls);
        } else {
          missing.push(fieldKey);
          logField(fieldKey, "not filled");
          await randomDelay(320, 650);
        }
      }

      await retryPageFields(normalizedProfile, usedControls, filled, missing, fieldControls);
      if (isStopped()) {
        return {
          ok: true,
          page,
          filled,
          missing,
          continued: false,
          manual: false,
          blocked: false,
          complete: false,
          stopped: true,
          review: [],
          message: "FIVA stopped"
        };
      }
      const continuation = await prepareContinueAfterResponse(normalizedProfile, session, fieldControls);
      if (page === "registration" && continuation.continued) console.log(LOG, "Registration page completed");
      if (continuation.continued) console.log(LOG, "Moving to next page");
      if (continuation.complete) {
        showAutofillToast();
      }
      console.log(LOG, continuation.complete ? "Autofill completed successfully" : (continuation.blocked ? "Autofill waiting for required fields" : "Autofill step finished"));
      return {
        ok: true,
        page,
        filled,
        missing,
        continued: continuation.continued === true,
        manual: continuation.manual === true,
        blocked: continuation.blocked === true,
        complete: continuation.complete === true,
        review: [],
        message: continuation.complete ? "Autofill completed successfully" : (continuation.blocked ? "Autofill waiting for required fields" : "Autofill step finished")
      };
    } finally {
      clearTimeout(globalTimeoutTimer);
      activeTimers.delete(globalTimeoutTimer);
      fivaRunActive = false;
      fivaRunning = false;
    }
  }

  async function fillForm(profile = {}, options = {}) {
    return startFivaAutofill(profile, options);
  }

  chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
    if (message?.type === "FIVA_PING" || message?.type === "FIVA_PING_V2") {
      sendResponse({ ok: true, ready: true, version: ENGINE_VERSION, capabilities: fivaCapabilities(), url: location.href });
      return false;
    }
    if (message?.type === "FIVA_STOP_FORM" || message?.type === "FIVA_STOP_FORM_V2") {
      stopAutofill(message.reason || "runtime").then(sendResponse).catch((error) => sendResponse({ ok: false, error: error.message }));
      return true;
    }
    if (message?.type !== "FIVA_FILL_FORM" && message?.type !== "FIVA_FILL_FORM_V2") return false;
    Promise.resolve()
      .then(() => startFivaAutofill(message.profile || {}, {
        resume: message.resume === true,
        source: message.source || {}
      }))
      .then(sendResponse)
      .catch((error) => sendResponse({ ok: false, error: error.message }));
    return true;
  });

  chrome.runtime.sendMessage({ type: "FIVA_CONTENT_READY", version: ENGINE_VERSION, capabilities: fivaCapabilities(), url: location.href }).catch(() => {});
  setTimeout(() => resumeSessionIfActive().catch((error) => console.warn(LOG, error)), 700);
  window.addEventListener("pagehide", cleanupTimers, { once: true });
})(typeof globalThis !== "undefined" ? globalThis : this);
