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

  if (global.__FIVAUiReady) return;
  global.__FIVAUiReady = true;

  const UI_STATE_KEY = "vfx.uiState";
  const loadedScripts = new Map();
  const $ = (id) => document.getElementById(id);

  const elements = {
    automationTab: $("automationTab"),
    automationView: $("automationView"),
    activityList: $("fivaActivityList"),
    clearBtn: $("fivaClearBtn"),
    dropZone: $("fivaDropZone"),
    fileInput: $("fivaFileInput"),
    fileLabel: $("fivaFileLabel"),
    fillBtn: $("fivaFillBtn"),
    fivaTab: $("fivaTab"),
    fivaView: $("fivaView"),
    pasteClearBtn: $("fivaClearPasteBtn"),
    pastePanel: $("fivaPastePanel"),
    pasteParseBtn: $("fivaParsePasteBtn"),
    pasteText: $("fivaPasteText"),
    pasteToggleBtn: $("fivaPasteToggleBtn"),
    statusLine: $("fivaStatusLine"),
    stopBtn: $("fivaStopBtn"),
    toastViewport: $("toastViewport")
  };

  let selectedFile = null;
  let analysis = null;
  let fivaInitialized = false;
  let analyzeToken = 0;
  let currentUploadId = "";
  let ocrIdleTimer = null;
  let activity = [];
  let runtime = null;
  let runtimeStore = null;

  function runtimeUrl(path) {
    return chrome.runtime.getURL(path);
  }

  function module(name) {
    const value = global.FIVA?.[name];
    if (!value) throw new Error(`FIVA module not loaded: ${name}`);
    return value;
  }

  function toast(message, kind = "success") {
    if (!elements.toastViewport) return;
    const item = document.createElement("div");
    item.className = `toast ${kind}`;
    item.textContent = message;
    elements.toastViewport.appendChild(item);
    requestAnimationFrame(() => item.classList.add("is-visible"));
    setTimeout(() => {
      item.classList.remove("is-visible");
      setTimeout(() => item.remove(), 240);
    }, 2200);
  }

  function clearToasts(kind = "") {
    const selector = kind ? `.toast.${kind}` : ".toast";
    elements.toastViewport?.querySelectorAll(selector).forEach((item) => item.remove());
  }

  function clearRuntimeErrors() {
    clearToasts("error");
  }

  function showRuntimeToast(type, source = {}) {
    if (type === "UPLOAD_REQUIRED" && hasReadyStoreProfile(runtimeStore)) return;
    const message = source.message || (type === "UPLOAD_REQUIRED" ? "Document is not ready yet." : "FIVA could not start");
    toast(message, source.kind || "error");
  }

  function loadScript(path) {
    if (loadedScripts.has(path)) return loadedScripts.get(path);
    const promise = new Promise((resolve, reject) => {
      const existing = document.querySelector(`script[data-fiva-src="${path}"]`);
      if (existing?.dataset.loaded === "true") {
        resolve();
        return;
      }

      const script = existing || document.createElement("script");
      script.src = runtimeUrl(path);
      script.dataset.fivaSrc = path;
      script.onload = () => {
        script.dataset.loaded = "true";
        resolve();
      };
      script.onerror = () => reject(new Error(`Failed to load ${path}`));
      if (!existing) document.head.appendChild(script);
    });
    loadedScripts.set(path, promise);
    return promise;
  }

  async function ensureMapper() {
    await loadScript("fiva/utils/fivaStateMachine.js");
    await loadScript("fiva/runtime/fivaRuntimeStore.js");
    await loadScript("fiva/utils/cleanOCRText.js");
    await loadScript("fiva/utils/normalizeOptionText.js");
    await loadScript("fiva/utils/strictDobValidator.js");
    await loadScript("fiva/utils/normalizeParsedData.js");
    await loadScript("fiva/utils/normalizeProfile.js");
    await loadScript("fiva/form-engine/validators.js");
    await loadScript("fiva/parsers/fivaFieldMap.js");
    await loadScript("fiva/parsers/passportParser.js");
    await loadScript("fiva/parsers/passportProfileExtractor.js");
    await loadScript("fiva/utils/fieldIntentResolver.js");
    await loadScript("fiva/utils/smartVisaProfileEngine.js");
    await loadScript("fiva/parsers/fieldMapper.js");
  }

  async function ensureFileModules() {
    await ensureMapper();
    await loadScript("fiva/utils/fileUtils.js");
    await loadScript("fiva/parsers/passportParser.js");
  }

  async function ensurePdfModules() {
    await ensureFileModules();
    await loadScript("fiva/parsers/pdfParser.js");
  }

  async function ensureOcrModules() {
    await ensureFileModules();
    await loadScript("fiva/vendor/tesseract/tesseract.min.js");
    await loadScript("fiva/ocr/ocrEngine.js");
  }

  function readUiState() {
    try {
      return JSON.parse(localStorage.getItem(UI_STATE_KEY) || "{}");
    } catch (_) {
      return {};
    }
  }

  function saveUiState(patch = {}) {
    const current = readUiState();
    localStorage.setItem(UI_STATE_KEY, JSON.stringify({
      ...current,
      ...patch,
      updatedAt: new Date().toISOString()
    }));
  }

  function stateMachine() {
    return global.FIVA?.FivaStateMachine || {
      STATES: { IDLE: "IDLE", READY: "READY", RUNNING: "RUNNING", FAILED: "FAILED", STOPPED: "STOPPED" },
      createRuntime: (patch = {}) => ({
        state: patch.state || "IDLE",
        status: patch.status || patch.state || "READY",
        failedFields: Array.isArray(patch.failedFields) ? patch.failedFields : [],
        updatedAt: Date.now()
      }),
      statusFor: (state, status) => status || state || "READY",
      uploadLabelFor: (state, fallback) => fallback || (state === "FAILED" ? "Document parsing failed" : state === "READY" ? "Document analyzed successfully" : "Upload PDF or Passport")
    };
  }

  function normalizeCommandError(error = {}) {
    const raw = String(error.message || error || "");
    if (/message channel closed|receiving end does not exist|could not establish connection|extension context invalidated/i.test(raw)) {
      return new Error("FIVA command did not receive a response. Reload the Indian Visa page and try again.");
    }
    return error instanceof Error ? error : new Error(raw || "FIVA command failed.");
  }

  function send(type, payload = {}) {
    return chrome.runtime.sendMessage({ type, ...payload }).catch((error) => {
      throw normalizeCommandError(error);
    }).then((response) => {
      if (!response?.ok) throw new Error(response?.error || "FIVA command failed.");
      return response;
    });
  }

  async function sendWithUnsupportedConfirmation(type, payload = {}) {
    const response = await send(type, payload);
    if (!response?.needsConfirmation) return response;

    const confirmed = window.confirm(response.message || "Open the Indian Visa form from this tab?");
    if (!confirmed) return { ...response, cancelled: true };
    return send(type, { ...payload, confirmedUnsupported: true });
  }

  function isAcceptedFile(file) {
    if (!file) return false;
    const name = String(file.name || "").toLowerCase();
    const type = String(file.type || "").toLowerCase();
    return type === "application/pdf"
      || type === "image/png"
      || type === "image/jpeg"
      || /\.(pdf|png|jpe?g)$/i.test(name);
  }

  function setTab(tabName) {
    const isFiva = tabName === "fiva";
    elements.automationTab?.classList.toggle("is-active", !isFiva);
    elements.fivaTab?.classList.toggle("is-active", isFiva);
    elements.automationView.hidden = isFiva;
    elements.automationView.classList.toggle("is-active", !isFiva);
    elements.fivaView.hidden = !isFiva;
    elements.fivaView.classList.toggle("is-active", isFiva);
    const activeContext = isFiva ? "FIVA" : "AUTOMATION";
    global.VisaFlowX?.ActiveContextManager?.setContext(activeContext);
    saveUiState({ activeSection: tabName, activeContext });
    if (isFiva) initializeFiva().catch((error) => {
      console.warn("[FIVA]", error);
      toast("FIVA could not load", "error");
    });
  }

  function setBusy(isBusy) {
    elements.fivaView?.classList.toggle("fiva-busy", isBusy);
    if (elements.fillBtn) elements.fillBtn.disabled = isBusy;
  }

  function renderActivity(items = activity) {
    activity = Array.isArray(items) ? items.slice(0, 8) : [];
    if (!elements.activityList) return;
    elements.activityList.innerHTML = "";
    activity.forEach((item) => {
      const row = document.createElement("li");
      row.className = item.level === "warn" || item.level === "error" ? item.level : "";
      row.textContent = item.message || "";
      elements.activityList.appendChild(row);
    });
  }

  function setRuntime(patch = {}) {
    const machine = stateMachine();
    runtime = machine.createRuntime({ ...(runtime || {}), ...patch });
    if (elements.statusLine) elements.statusLine.textContent = machine.statusFor(runtime.state, runtime.status);
    if (elements.dropZone) elements.dropZone.dataset.state = runtime.state;
    if (["IDLE", "UPLOADING", "PARSING", "READY"].includes(runtime.state)) {
      setUploadLabel(machine.uploadLabelFor(runtime.state, elements.fileLabel?.textContent || ""));
    }
    if (elements.fillBtn) elements.fillBtn.disabled = !hasReadyStoreProfile(runtimeStore) || runtime.state === "RUNNING" || runtime.state === "RETRYING";
    elements.fivaView?.classList.toggle("fiva-running", runtime.state === "RUNNING" || runtime.state === "RETRYING");
    return runtime;
  }

  function renderRuntime(nextRuntime = null, items = null, store = null) {
    if (store) {
      runtimeStore = store;
      if (store.parsedProfile?.profile) {
        analysis = store.parsedProfile;
        currentUploadId = store.uploadId || store.parsedProfile.source?.uploadId || currentUploadId;
      }
    }
    if (nextRuntime) setRuntime(nextRuntime);
    if (items) renderActivity(items);
    if (store && typeof global.dispatchEvent === "function" && typeof global.CustomEvent === "function") {
      global.dispatchEvent(new CustomEvent("FIVA_RUNTIME_LOCAL_UPDATE", {
        detail: { store, runtime: store.runtimeState, activity: store.lastActivity || [] }
      }));
    }
  }

  async function addActivity(message, level = "info", patch = {}) {
    return send("FIVA_ACTIVITY", { message, level, ...patch }).then((response) => {
      renderRuntime(response.runtime || response.store?.runtimeState || null, response.activity || response.store?.lastActivity || [], response.store || null);
    }).catch(() => {});
  }

  function setUploadLabel(label = "Upload PDF or Passport") {
    if (elements.fileLabel) elements.fileLabel.textContent = label;
  }

  function scheduleOcrIdleCleanup() {
    if (ocrIdleTimer) clearTimeout(ocrIdleTimer);
    ocrIdleTimer = setTimeout(() => {
      ocrIdleTimer = null;
      global.FIVA?.OcrEngine?.terminate?.().catch(() => {});
    }, 60000);
  }

  function createAnalysis(fields, source) {
    return module("FieldMapper").map(fields, {
      ...source,
      textLength: source.textLength || 0
    });
  }

  function hasProfileData(candidate) {
    const profile = candidate?.profile || {};
    return Object.entries(profile).some(([key, value]) => !key.startsWith("__") && String(value || "").trim());
  }

  function parseDocumentText(text = "", source = {}) {
    const smartProfile = global.FIVA?.SmartVisaProfileEngine?.parseText?.(text, {
      ...source,
      siteUrl: "https://indianvisa-bangladesh.nic.in/visa/Registration",
      allowDefaultCountry: true
    });
    if (smartProfile?.fields) return smartProfile.fields;
    const { FivaFieldMap, PassportParser } = global.FIVA;
    return FivaFieldMap.mergeFields(
      FivaFieldMap.parseStructured(text),
      PassportParser.parse(text)
    );
  }

  async function analyzePdf(file, uploadId) {
    await ensurePdfModules();
    const { FileUtils, PdfParser } = global.FIVA;
    const buffer = await FileUtils.readAsArrayBuffer(file);
    const parsed = await PdfParser.extractText(buffer);
    let text = parsed.text || "";
    let confidence = parsed.confidence || 0;

    if (text.trim().length < 40) {
      await ensureOcrModules();
      const { OcrEngine } = global.FIVA;
      const pages = await PdfParser.renderPages(buffer, { maxPages: 2 });
      const ocr = await OcrEngine.recognizeMany(pages);
      scheduleOcrIdleCleanup();
      text = [text, ocr.text].filter(Boolean).join("\n\n");
      confidence = Math.max(confidence, ocr.confidence || 0);
    }

    const source = {
      type: "pdf",
      fileName: file.name,
      fileSize: Number(file.size || 0),
      fileLastModified: Number(file.lastModified || 0),
      uploadId,
      confidence,
      textLength: text.length
    };

    return {
      fields: parseDocumentText(text, source),
      source
    };
  }

  async function analyzeImage(file, uploadId) {
    await ensureOcrModules();
    const { FileUtils, OcrEngine } = global.FIVA;
    const dataUrl = await FileUtils.readAsDataUrl(file);
    const prepared = await OcrEngine.preprocess(dataUrl);
    const ocr = await OcrEngine.recognize(prepared);
    scheduleOcrIdleCleanup();
    const source = {
      type: "image",
      fileName: file.name,
      fileSize: Number(file.size || 0),
      fileLastModified: Number(file.lastModified || 0),
      uploadId,
      confidence: ocr.confidence || 0,
      textLength: ocr.text.length
    };

    return {
      fields: parseDocumentText(ocr.text, source),
      source
    };
  }

  async function analyzePastedText({ notify = true } = {}) {
    await ensureFileModules();
    const text = String(elements.pasteText?.value || "").replace(/\r\n/g, "\n").trim();
    if (!text) throw new Error("Paste valid passport or visa text first.");

    selectedFile = null;
    analysis = null;
    runtimeStore = null;
    currentUploadId = `paste-${Date.now()}-${text.length}`;
    analyzeToken += 1;
    const token = analyzeToken;

    setBusy(true);
    setRuntime({ state: "PARSING", status: "PARSING" });
    setUploadLabel("Analyzing document...");
    console.log("[FIVA]", "pasted text parse started");
    await send("FIVA_CLEAR_PROFILE").catch(() => {});
    renderActivity([]);
    await addActivity("Pasted text detected", "info", { state: "PARSING", status: "PARSING" });
    await addActivity("Extracting passport fields", "info", { state: "PARSING", status: "PARSING" });

    try {
      const source = {
        type: "pasted_text",
        fileName: "Pasted text",
        uploadId: currentUploadId,
        confidence: 95,
        textLength: text.length
      };
      const fields = parseDocumentText(text, source);
      const nextAnalysis = createAnalysis(fields, source);
      if (token !== analyzeToken) return null;
      if (!hasProfileData(nextAnalysis)) throw new Error("No valid application data found.");

      analysis = nextAnalysis;
      const saveResponse = await send("FIVA_SAVE_PROFILE", { profile: analysis });
      renderRuntime(saveResponse.runtime, saveResponse.activity, saveResponse.store);
      clearRuntimeErrors();
      console.log("[FIVA]", "parser success", analysis.profile || {});
      await addActivity("Profile normalized", "info", { state: "PARSING", status: "PARSING" });
      await addActivity("Runtime store updated", "info", { state: "READY", status: "READY" });
      await addActivity("Document analyzed successfully", "info", { state: "READY", status: "READY" });
      setUploadLabel("Document analyzed successfully");
      if (notify) toast("Pasted text parsed");
      return analysis;
    } finally {
      if (token === analyzeToken) setBusy(false);
    }
  }

  async function analyzeSelectedFile({ notify = true } = {}) {
    await ensureFileModules();
    const { FileUtils } = global.FIVA;
    if (!selectedFile) throw new Error("Upload a PDF, JPG, or PNG first.");
    if (!FileUtils.isAccepted(selectedFile)) throw new Error("Use a PDF, JPG, or PNG file.");

    const token = analyzeToken + 1;
    analyzeToken = token;
    const uploadId = currentUploadId;
    setBusy(true);
    setRuntime({ state: "PARSING", status: "PARSING" });
    await addActivity(FileUtils.isPdf(selectedFile) ? "Parsing PDF" : "Parsing image", "info", { state: "PARSING", status: "PARSING" });
    console.log("[FIVA]", "parser started");

    try {
      const result = FileUtils.isPdf(selectedFile)
        ? await analyzePdf(selectedFile, uploadId)
        : await analyzeImage(selectedFile, uploadId);
      if (token !== analyzeToken || uploadId !== currentUploadId) return null;

      await addActivity("Extracting visa profile", "info", { state: "PARSING", status: "PARSING" });
      const nextAnalysis = createAnalysis(result.fields, result.source);
      if (!hasProfileData(nextAnalysis)) {
        if (hasProfileData(analysis)) return analysis;
        throw new Error("Could not extract document data.");
      }

      analysis = nextAnalysis;
      const saveResponse = await send("FIVA_SAVE_PROFILE", { profile: analysis });
      renderRuntime(saveResponse.runtime, saveResponse.activity, saveResponse.store);
      console.log("[FIVA]", "parser success", analysis.profile || {});
      clearRuntimeErrors();
      await addActivity("Profile normalized", "info", { state: "PARSING", status: "PARSING" });
      await addActivity("Runtime store updated", "info", { state: "READY", status: "READY" });
      await addActivity("Document analyzed successfully", "info", { state: "READY", status: "READY" });
      if (notify) toast("Document analyzed");
      return analysis;
    } finally {
      if (token === analyzeToken) setBusy(false);
    }
  }

  async function setFile(file) {
    if (!file) return;
    if (!isAcceptedFile(file)) {
      toast("Use PDF, JPG, or PNG", "error");
      return;
    }

    selectedFile = file;
    analysis = null;
    runtimeStore = null;
    if (elements.pasteText) elements.pasteText.value = "";
    currentUploadId = `${Date.now()}-${String(file.name || "document")}-${Number(file.size || 0)}-${Number(file.lastModified || 0)}`;
    analyzeToken += 1;
    setRuntime({ state: "UPLOADING", status: "UPLOADING" });
    setUploadLabel("Uploading document...");
    console.log("[FIVA]", "upload started");
    await send("FIVA_CLEAR_PROFILE").catch(() => {});
    renderActivity([]);
    await addActivity("Document selected", "info", { state: "UPLOADING", status: "UPLOADING" });
    await addActivity("Uploading document", "info", { state: "UPLOADING", status: "UPLOADING" });
    await addActivity("Upload complete", "info", { state: "PARSING", status: "PARSING" });
    analyzeSelectedFile().catch((error) => {
      console.warn("[FIVA]", error);
      setBusy(false);
      setUploadLabel("Document parsing failed");
      addActivity("Document parsing failed", "error", { state: "FAILED", status: "FAILED" });
      toast("Could not analyze document", "error");
    });
  }

  function storeProfile() {
    return runtimeStore?.parsedProfile || null;
  }

  function hasReadyStoreProfile(store = runtimeStore) {
    return Boolean(store?.ready === true && store?.parsedProfile?.profile && store.parserStatus === "SUCCESS");
  }

  async function syncRuntimeSnapshot() {
    const response = await send("FIVA_GET_RUNTIME");
    renderRuntime(response.runtime || response.store?.runtimeState || null, response.activity || response.store?.lastActivity || [], response.store || null);
    return response.store || runtimeStore;
  }

  async function waitForRuntimeSync({ requireProfile = false, timeoutMs = 3500 } = {}) {
    const started = Date.now();
    let snapshot = runtimeStore;
    while (Date.now() - started < timeoutMs) {
      snapshot = await syncRuntimeSnapshot().catch(() => runtimeStore);
      if (!requireProfile || hasReadyStoreProfile(snapshot)) return snapshot;
      const state = snapshot?.runtimeState?.state || runtime?.state || "";
      if (state !== "UPLOADING" && state !== "PARSING") break;
      await new Promise((resolve) => setTimeout(resolve, 160));
    }
    return snapshot;
  }

  async function saveProfile() {
    const activeProfile = storeProfile() || analysis;
    if (!activeProfile) throw new Error("FIVA document is not ready.");
    const response = await send("FIVA_SAVE_PROFILE", { profile: activeProfile });
    renderRuntime(response.runtime, response.activity, response.store);
  }

  async function fillForm() {
    await ensureMapper();
    await waitForRuntimeSync({ requireProfile: false });
    if (!storeProfile() && selectedFile) await analyzeSelectedFile({ notify: false });
    const syncedStore = await waitForRuntimeSync({ requireProfile: true });
    const activeAnalysis = hasReadyStoreProfile(syncedStore) ? syncedStore.parsedProfile : null;
    if (!activeAnalysis?.profile) throw new Error("FIVA document is not ready.");

    const gate = module("FieldMapper").autofillGate(activeAnalysis);
    if (!gate.ok) throw new Error("FIVA document is not ready.");

    setBusy(true);
    try {
      await addActivity("Starting autofill", "info", { state: "RUNNING", status: "FILLING FORM" });
      await addActivity("Building autofill queue", "info", { state: "RUNNING", status: "FILLING FORM" });
      const response = await sendWithUnsupportedConfirmation("FIVA_FILL_ACTIVE_FORM", {
        profile: activeAnalysis
      });
      if (response.cancelled) return;
      if (response.continued && response.page === "registration") {
        addActivity("Waiting for next page", "info", { state: "SUCCESS", status: "AUTOFILL COMPLETE" });
        toast("Registration page completed");
      } else if (response.blocked) {
        addActivity(response.message || "Required fields missing", "warn", {
          state: response.filled?.length ? "PARTIAL_SUCCESS" : "FAILED",
          status: response.filled?.length ? "PARTIAL SUCCESS" : "FAILED",
          failedFields: response.failedFields || response.missing || []
        });
        toast("Partial autofill completed", "error");
      } else if (response.stopped) {
        addActivity("FIVA stopped", "warn", { state: "STOPPED", status: "STOPPED" });
      } else if (response.complete) {
        addActivity("Autofill complete", "info", { state: "SUCCESS", status: "AUTOFILL COMPLETE" });
        toast("Autofill complete");
      }
    } finally {
      setBusy(false);
    }
  }

  async function stopFiva() {
    await send("FIVA_STOP_AUTOFILL", { reason: "popup" });
    addActivity("FIVA stopped", "warn", { state: "STOPPED", status: "STOPPED" });
    setBusy(false);
    toast("FIVA stopped");
  }

  async function clearData() {
    selectedFile = null;
    analysis = null;
    runtimeStore = null;
    currentUploadId = "";
    analyzeToken += 1;
    elements.fileInput.value = "";
    if (elements.pasteText) elements.pasteText.value = "";
    if (elements.pastePanel) elements.pastePanel.hidden = true;
    if (elements.pasteToggleBtn) elements.pasteToggleBtn.textContent = "Paste Text";
    setUploadLabel();
    if (ocrIdleTimer) clearTimeout(ocrIdleTimer);
    ocrIdleTimer = null;
    await global.FIVA?.OcrEngine?.terminate?.().catch(() => {});
    const response = await send("FIVA_CLEAR_PROFILE");
    renderRuntime(response.runtime || response.store?.runtimeState || { state: "IDLE", status: "READY", failedFields: [] }, response.activity || [], response.store || null);
  }

  function bindUpload() {
    elements.fileInput.addEventListener("change", () => setFile(elements.fileInput.files?.[0]).catch((error) => {
      console.warn("[FIVA]", error);
      toast("Could not load document", "error");
    }));

    ["dragenter", "dragover"].forEach((eventName) => {
      elements.dropZone.addEventListener(eventName, (event) => {
        event.preventDefault();
        elements.dropZone.classList.add("is-dragging");
      });
    });

    ["dragleave", "drop"].forEach((eventName) => {
      elements.dropZone.addEventListener(eventName, (event) => {
        event.preventDefault();
        elements.dropZone.classList.remove("is-dragging");
      });
    });

    elements.dropZone.addEventListener("drop", (event) => {
      setFile(event.dataTransfer?.files?.[0]).catch((error) => {
        console.warn("[FIVA]", error);
        toast("Could not load document", "error");
      });
    });
  }

  function bindActions() {
    elements.automationTab.addEventListener("click", () => setTab("automation"));
    elements.fivaTab.addEventListener("click", () => setTab("fiva"));
    elements.pasteToggleBtn?.addEventListener("click", () => {
      const nextHidden = !elements.pastePanel?.hidden;
      if (elements.pastePanel) elements.pastePanel.hidden = nextHidden;
      if (elements.pasteToggleBtn) elements.pasteToggleBtn.textContent = nextHidden ? "Paste Text" : "Hide Pasted Text";
    });
    elements.pasteParseBtn?.addEventListener("click", () => analyzePastedText().catch((error) => {
      console.warn("[FIVA]", error);
      setBusy(false);
      setUploadLabel("Document parsing failed");
      addActivity(error.message || "Document parsing failed", "error", { state: "FAILED", status: "FAILED" });
      toast("Could not parse pasted text", "error");
    }));
    elements.pasteClearBtn?.addEventListener("click", () => {
      if (elements.pasteText) elements.pasteText.value = "";
    });
    elements.fillBtn?.addEventListener("click", () => fillForm().catch((error) => {
      const normalized = normalizeCommandError(error);
      console.info("[FIVA]", normalized.message);
      addActivity(normalized.message, "error", { state: "FAILED", status: "FAILED" });
      showRuntimeToast(/document is not ready|upload/i.test(normalized.message || "") ? "UPLOAD_REQUIRED" : "FIVA_FAILED", {
        message: "Autofill could not start",
        kind: "error"
      });
    }));
    elements.clearBtn.addEventListener("click", () => clearData().catch((error) => {
      console.warn("[FIVA]", error);
      toast("Could not clear data", "error");
    }));
    elements.stopBtn?.addEventListener("click", () => stopFiva().catch((error) => {
      console.warn("[FIVA]", error);
      toast("Could not stop FIVA", "error");
    }));
  }

  async function restoreProfile() {
    await ensureMapper();
    const response = await send("FIVA_GET_RUNTIME").catch(() => null);
    renderRuntime(response?.runtime || response?.store?.runtimeState || { state: "IDLE", status: "READY" }, response?.activity || response?.store?.lastActivity || [], response?.store || null);
    if (!response?.runtime) setUploadLabel();
  }

  async function initializeFiva() {
    if (fivaInitialized) return;
    fivaInitialized = true;
    await restoreProfile();
  }

  global.FIVA = Object.assign(global.FIVA || {}, {
    UiController: {
      clear: () => clearData(),
      getStore: () => runtimeStore,
      start: async () => {
        await initializeFiva();
        return fillForm();
      },
      stop: async () => {
        await initializeFiva();
        return stopFiva();
      }
    }
  });

  document.addEventListener("DOMContentLoaded", () => {
    bindUpload();
    bindActions();
    chrome.runtime.onMessage.addListener((message) => {
      if (message?.type === "FIVA_RUNTIME_UPDATE" || message?.type === "FIVA_RUNTIME_UPDATED") {
        renderRuntime(message.runtime || message.store?.runtimeState || null, message.activity || message.store?.lastActivity || null, message.store || null);
      }
      if (message?.type === "FIVA_ACTIVITY_UPDATE") renderRuntime(message.runtime || message.store?.runtimeState || null, message.activity || message.store?.lastActivity || [], message.store || null);
    });
    const uiState = readUiState();
    setTab(uiState.activeSection === "fiva" ? "fiva" : "automation");
  });
})(typeof globalThis !== "undefined" ? globalThis : this);
