(() => {
  const CATEGORY_META = {
    app_settings: "App settings",
    my_liveries: "My Liveries",
    driver_profiles: "Driver profiles",
    tyre_brands: "Tyre brands",
    custom_grids: "Custom grids",
    numberplates: "Numberplates",
    layer_studio: "Layer Studio Library",
    project_files: "Project files",
  };

  const $ = (id) => document.getElementById(id);

  const state = {
    overview: null,
    importInfo: null,
    transferProgress: null,
    transferImportProgress: null,
    importInspecting: false,
    importRunning: false,
    overviewRefreshing: false,
    skinPackImportInfo: null,
    skinPackImportInspecting: false,
    skinPackImportRunning: false,
  };

  const previousBackendProgress = window.handleBackendProgress;

  function api() {
    return window.pywebview && window.pywebview.api ? window.pywebview.api : null;
  }

  function setStatus(id, message, kind = "unknown") {
    const node = $(id);
    if (!node) return;
    node.textContent = message || "";
    node.classList.remove("is-ok", "is-warning", "is-error", "is-unknown");
    node.classList.add(`is-${kind}`);
  }

  function setWorking(button, working, label) {
    if (!button) return;
    if (working) {
      if (!button.dataset.idleText) button.dataset.idleText = button.textContent;
      button.innerHTML = `<span class="button-spinner" aria-hidden="true"></span><span>${escapeHtml(label || "Working...")}</span>`;
      button.disabled = true;
      return;
    }
    button.textContent = button.dataset.idleText || button.textContent;
    delete button.dataset.idleText;
    button.disabled = false;
    window.decorateIconButtons?.(button.parentElement || document);
  }

  function escapeHtml(value) {
    return String(value ?? "")
      .replaceAll("&", "&amp;")
      .replaceAll("<", "&lt;")
      .replaceAll(">", "&gt;")
      .replaceAll('"', "&quot;")
      .replaceAll("'", "&#39;");
  }

  function cssEscape(value) {
    if (window.CSS && typeof window.CSS.escape === "function") return window.CSS.escape(String(value || ""));
    return String(value || "").replace(/["\\]/g, "\\$&");
  }

  function showModal(type, title, message, details = "", openFolderPath = "") {
    if (typeof window.showStatusModal === "function") {
      window.showStatusModal({ type, title, message, details, openFolderPath });
      return;
    }
    window.alert([title, message, details].filter(Boolean).join("\n\n"));
  }

  function resultDetails(result) {
    if (!result) return "";
    const parts = [];
    if (result.errorDetail) parts.push(result.errorDetail);
    if (result.traceback) parts.push(result.traceback);
    return parts.join("\n\n");
  }

  function dependencyDetails(data = {}) {
    const rows = Array.isArray(data.requiredDependencies) ? data.requiredDependencies : [];
    if (!rows.length) return "";
    const lines = ["Automatically included dependencies:"];
    rows.forEach((row) => {
      const requiredBy = Array.isArray(row.requiredBy) && row.requiredBy.length
        ? ` for ${row.requiredBy.join(", ")}`
        : "";
      lines.push(`- ${CATEGORY_META[row.category] || row.category}: ${row.label || row.id}${requiredBy}`);
    });
    return lines.join("\n");
  }

  function fmtBytes(bytes) {
    const value = Number(bytes || 0);
    if (!value) return "0 B";
    const units = ["B", "KB", "MB", "GB"];
    let current = value;
    let index = 0;
    while (current >= 1024 && index < units.length - 1) {
      current /= 1024;
      index += 1;
    }
    return index === 0 ? `${current.toFixed(0)} ${units[index]}` : `${current.toFixed(1)} ${units[index]}`;
  }

  function make(tag, className = "", text = "") {
    const node = document.createElement(tag);
    if (className) node.className = className;
    if (text) node.textContent = text;
    return node;
  }

  function categorySummary(category) {
    const files = Number(category.fileCount || 0);
    const items = Array.isArray(category.items) ? category.items.length : 0;
    if (category.itemized) return `${items} item${items === 1 ? "" : "s"} / ${files} file${files === 1 ? "" : "s"} / ${fmtBytes(category.bytes)}`;
    return `${files} file${files === 1 ? "" : "s"} / ${fmtBytes(category.bytes)}`;
  }

  function categoryHint(category = {}) {
    const id = String(category.id || "");
    if (id === "my_liveries") {
      return "Includes local skin files, LiveryLab-managed project files, custom rear plates and needed Layer Studio PNG dependencies. Editable source files such as PSD, PSB, XCF, AI or SVG are not included.";
    }
    if (id === "layer_studio") {
      return "Exports the full shared Layer Studio PNG Library.";
    }
    return "";
  }

  function liveryCategoryGroups(category = {}) {
    if (String(category.id || "") !== "my_liveries") return [];
    const items = new Set((Array.isArray(category.items) ? category.items : []).map((item) => String(item.id || "")).filter(Boolean));
    return (Array.isArray(category.liveryCategories) ? category.liveryCategories : [])
      .map((group) => ({
        id: String(group.id || "").trim(),
        name: String(group.name || group.id || "").trim(),
        itemIds: (Array.isArray(group.itemIds) ? group.itemIds : []).map((id) => String(id || "").trim()).filter((id) => id && items.has(id)),
      }))
      .filter((group) => group.id && group.name && group.itemIds.length);
  }

  function workspaceLiveryGroups(category = {}) {
    const items = Array.isArray(category.items) ? category.items : [];
    const itemsById = new Map(items.map((item) => [String(item.id || ""), item]).filter(([id]) => Boolean(id)));
    const assigned = new Set();
    const groups = liveryCategoryGroups(category).map((group) => {
      group.itemIds.forEach((id) => assigned.add(id));
      return {
        ...group,
        items: group.itemIds.map((id) => itemsById.get(id)).filter(Boolean),
      };
    }).filter((group) => group.items.length);
    const uncategorizedItems = items.filter((item) => {
      const id = String(item.id || "");
      return id && !assigned.has(id);
    });
    if (uncategorizedItems.length) {
      groups.push({
        id: "uncategorized",
        name: "Uncategorized",
        itemIds: uncategorizedItems.map((item) => String(item.id || "")).filter(Boolean),
        items: uncategorizedItems,
      });
    }
    return groups;
  }

  function selectedSkinPackGroup() {
    const checked = document.querySelector("#skinPackCategoryList .skin-pack-category-check:checked");
    if (!checked || !state.overview) return null;
    const myLiveries = (Array.isArray(state.overview.categories) ? state.overview.categories : [])
      .find((category) => String(category.id || "") === "my_liveries");
    return liveryCategoryGroups(myLiveries).find((group) => group.id === checked.value) || null;
  }

  function updateSkinPackExportActionState() {
    const button = $("exportSkinPack");
    if (button) button.disabled = !selectedSkinPackGroup();
  }

  function renderSkinPackCategories(data) {
    const list = $("skinPackCategoryList");
    if (!list) return;
    list.innerHTML = "";
    const myLiveries = (Array.isArray(data?.categories) ? data.categories : [])
      .find((category) => String(category.id || "") === "my_liveries");
    const groups = liveryCategoryGroups(myLiveries);
    if (!groups.length) {
      list.appendChild(make("div", "transfer-empty", "No custom My Liveries categories with entries found."));
      updateSkinPackExportActionState();
      return;
    }
    groups.forEach((group, index) => {
      const label = make("label", "skin-pack-category-row");
      const input = document.createElement("input");
      input.type = "radio";
      input.name = "skinPackCategory";
      input.className = "skin-pack-category-check";
      input.value = group.id;
      input.checked = index === 0;
      const copy = make("span", "transfer-category-copy");
      copy.appendChild(make("strong", "", group.name));
      copy.appendChild(make("small", "", `${group.itemIds.length} livery${group.itemIds.length === 1 ? "" : "ies"}`));
      label.appendChild(input);
      label.appendChild(copy);
      list.appendChild(label);
      input.addEventListener("change", updateSkinPackExportActionState);
    });
    updateSkinPackExportActionState();
  }

  function setTransferProgressVisible(visible) {
    const node = $("transferExportProgress");
    if (node) node.hidden = !visible;
  }

  function renderTransferProgress(payload = {}) {
    state.transferProgress = { ...(state.transferProgress || {}), ...payload };
    const info = state.transferProgress || {};
    const total = Math.max(0, Number(info.totalFiles || 0));
    const processed = Math.max(0, Number(info.processedFiles || 0));
    const explicitPercent = Number(info.percent);
    const percent = Number.isFinite(explicitPercent)
      ? Math.max(0, Math.min(100, explicitPercent))
      : total > 0
        ? Math.max(0, Math.min(100, Math.round((processed / total) * 100)))
        : info.phase === "done"
          ? 100
          : 0;
    const fill = $("transferExportProgressFill");
    const label = $("transferExportProgressLabel");
    const text = $("transferExportProgressText");
    const path = $("transferExportProgressPath");
    if (fill) fill.style.width = `${percent}%`;
    if (label) label.textContent = `${Math.round(percent)}%`;
    const category = info.label || CATEGORY_META[info.category] || info.category || "Transfer export";
    const message = info.message || (total > 0 ? `${processed} / ${total} files` : "Preparing...");
    if (text) text.textContent = `${category} / ${message}`;
    if (path) path.textContent = info.path || info.currentFile || "Waiting for files...";
    setTransferProgressVisible(true);
  }

  function resetTransferProgress() {
    state.transferProgress = null;
    const fill = $("transferExportProgressFill");
    const label = $("transferExportProgressLabel");
    const text = $("transferExportProgressText");
    const path = $("transferExportProgressPath");
    if (fill) fill.style.width = "0%";
    if (label) label.textContent = "0%";
    if (text) text.textContent = "Preparing transfer export...";
    if (path) path.textContent = "Waiting for files...";
    setTransferProgressVisible(false);
  }

  function setTransferImportProgressVisible(visible) {
    const node = $("transferImportProgress");
    if (node) node.hidden = !visible;
  }

  function renderTransferImportProgress(payload = {}) {
    state.transferImportProgress = { ...(state.transferImportProgress || {}), ...payload };
    const info = state.transferImportProgress || {};
    const total = Math.max(0, Number(info.totalFiles || 0));
    const processed = Math.max(0, Number(info.processedFiles || 0));
    const explicitPercent = Number(info.percent);
    const percent = Number.isFinite(explicitPercent)
      ? Math.max(0, Math.min(100, explicitPercent))
      : total > 0
        ? Math.max(0, Math.min(100, Math.round((processed / total) * 100)))
        : info.phase === "done"
          ? 100
          : 0;
    const fill = $("transferImportProgressFill");
    const label = $("transferImportProgressLabel");
    const text = $("transferImportProgressText");
    const path = $("transferImportProgressPath");
    if (fill) fill.style.width = `${percent}%`;
    if (label) label.textContent = `${Math.round(percent)}%`;
    const category = info.label || CATEGORY_META[info.category] || info.category || "Transfer import";
    const message = info.message || (total > 0 ? `${processed} / ${total} files` : "Preparing...");
    if (text) text.textContent = `${category} / ${message}`;
    if (path) path.textContent = info.path || info.currentFile || "Waiting for transfer ZIP...";
    setTransferImportProgressVisible(true);
  }

  function resetTransferImportProgress() {
    state.transferImportProgress = null;
    const fill = $("transferImportProgressFill");
    const label = $("transferImportProgressLabel");
    const text = $("transferImportProgressText");
    const path = $("transferImportProgressPath");
    if (fill) fill.style.width = "0%";
    if (label) label.textContent = "0%";
    if (text) text.textContent = "Preparing transfer import...";
    if (path) path.textContent = "Waiting for transfer ZIP...";
    setTransferImportProgressVisible(false);
  }

  function updateImportActionState() {
    const button = $("importTransferBundle");
    if (!button || state.importRunning) return;
    button.disabled = !state.importInfo || state.importInspecting;
  }

  function updateExportParent(row) {
    const parent = row.querySelector(".transfer-category-check");
    const children = [...row.querySelectorAll(".transfer-item-check")];
    if (!parent || !children.length) return;
    const checked = children.filter((input) => input.checked && !input.disabled).length;
    parent.checked = checked === children.length && children.length > 0;
    parent.indeterminate = checked > 0 && checked < children.length;
    updateLiveryCategoryGroupChecks(row);
    renderExportSelectionSummary();
  }

  function updateLiveryCategoryGroupChecks(row) {
    row.querySelectorAll(".transfer-livery-category-check").forEach((input) => {
      const ids = String(input.dataset.itemIds || "").split("|").filter(Boolean);
      if (!ids.length) return;
      const checked = ids.filter((id) => {
        const item = row.querySelector(`.transfer-item-check[value="${cssEscape(id)}"]`);
        return item?.checked && !item.disabled;
      }).length;
      input.checked = checked === ids.length;
      input.indeterminate = checked > 0 && checked < ids.length;
    });
  }

  function renderTransferItem(item, selected, enabled, onChange) {
    const itemLabel = make("label", "transfer-item");
    const itemInput = document.createElement("input");
    itemInput.type = "checkbox";
    itemInput.className = "transfer-item-check";
    itemInput.value = item.id || "";
    itemInput.checked = Boolean(selected);
    itemInput.disabled = !enabled;
    const text = make("span", "transfer-item-copy");
    text.appendChild(make("strong", "", item.label || item.id || "Item"));
    const meta = [item.carModel, item.family, `${Number(item.fileCount || 0)} files`, fmtBytes(item.bytes)].filter(Boolean).join(" / ");
    text.appendChild(make("small", "", meta));
    itemLabel.appendChild(itemInput);
    itemLabel.appendChild(text);
    itemInput.addEventListener("change", onChange);
    return itemLabel;
  }

  function setExportSelection(selected) {
    document.querySelectorAll("#transferExportList .transfer-category").forEach((row) => {
      const parent = row.querySelector(".transfer-category-check");
      if (!parent || parent.disabled) return;
      parent.checked = Boolean(selected);
      parent.indeterminate = false;
      row.querySelectorAll(".transfer-item-check").forEach((child) => {
        if (!child.disabled) child.checked = Boolean(selected);
      });
      updateExportParent(row);
    });
    renderExportSelectionSummary();
  }

  function selectedExportRows() {
    const rows = [];
    document.querySelectorAll("#transferExportList .transfer-category").forEach((row) => {
      const category = row.dataset.category || "";
      const parent = row.querySelector(".transfer-category-check");
      if (!category || !parent || parent.disabled) return;
      const categoryLabel = row.querySelector(".transfer-category-copy strong")?.textContent || CATEGORY_META[category] || category;
      const childInputs = [...row.querySelectorAll(".transfer-item-check")];
      if (childInputs.length) {
        childInputs.filter((input) => input.checked && !input.disabled).forEach((input) => {
          const item = input.closest(".transfer-item");
          rows.push({
            category,
            categoryLabel,
            label: item?.querySelector(".transfer-item-copy strong")?.textContent || input.value,
            meta: item?.querySelector(".transfer-item-copy small")?.textContent || "",
            fileCount: Number((item?.querySelector(".transfer-item-copy small")?.textContent || "").match(/(\d+)\s+files?/)?.[1] || 0),
            bytes: parseTransferMetaBytes(item?.querySelector(".transfer-item-copy small")?.textContent || ""),
          });
        });
        return;
      }
      if (parent.checked) {
        rows.push({
          category,
          categoryLabel,
          label: categoryLabel,
          meta: row.querySelector(".transfer-category-copy small")?.textContent || "",
          fileCount: Number((row.querySelector(".transfer-category-copy small")?.textContent || "").match(/(\d+)\s+files?/)?.[1] || 0),
          bytes: parseTransferMetaBytes(row.querySelector(".transfer-category-copy small")?.textContent || ""),
        });
      }
    });
    return rows;
  }

  function parseTransferMetaBytes(meta = "") {
    const match = String(meta || "").match(/([\d.]+)\s*(B|KB|MB|GB)/i);
    if (!match) return 0;
    const value = Number(match[1] || 0);
    const unit = String(match[2] || "B").toUpperCase();
    const scale = unit === "GB" ? 1024 ** 3 : unit === "MB" ? 1024 ** 2 : unit === "KB" ? 1024 : 1;
    return Number.isFinite(value) ? Math.round(value * scale) : 0;
  }

  function renderExportSelectionSummary() {
    const node = $("transferExportSelectionSummary");
    if (!node) return;
    const rows = selectedExportRows();
    if (!rows.length) {
      node.innerHTML = `<strong>Selected export</strong><span>No export items selected.</span>`;
      return;
    }
    const categories = new Set(rows.map((row) => row.category));
    const files = rows.reduce((sum, row) => sum + Number(row.fileCount || 0), 0);
    const bytes = rows.reduce((sum, row) => sum + Number(row.bytes || 0), 0);
    node.innerHTML = `
      <strong>Selected export</strong>
      <span>${rows.length} item${rows.length === 1 ? "" : "s"} / ${categories.size} categor${categories.size === 1 ? "y" : "ies"}${files ? ` / ${files} file${files === 1 ? "" : "s"}` : ""}${bytes ? ` / ${fmtBytes(bytes)}` : ""}</span>
    `;
  }

  function renderExportOverview(data) {
    const list = $("transferExportList");
    if (!list) return;
    list.innerHTML = "";
    const categories = Array.isArray(data?.categories) ? data.categories : [];
    if (!categories.length) {
      list.appendChild(make("div", "transfer-empty", "No exportable data found."));
      return;
    }

    categories.forEach((category) => {
      const row = make("article", "transfer-category");
      row.dataset.category = category.id || "";
      if (!category.available) row.classList.add("is-disabled");

      const head = make("label", "transfer-category-head");
      const input = document.createElement("input");
      input.type = "checkbox";
      input.className = "transfer-category-check";
      input.value = category.id || "";
      input.checked = Boolean(category.available && category.selected);
      input.disabled = !category.available;
      const copy = make("span", "transfer-category-copy");
      copy.appendChild(make("strong", "", category.label || CATEGORY_META[category.id] || category.id || "Data"));
      copy.appendChild(make("small", "", category.available ? categorySummary(category) : "Nothing found"));
      const hint = categoryHint(category);
      if (hint) copy.appendChild(make("small", "", hint));
      head.appendChild(input);
      head.appendChild(copy);
      row.appendChild(head);

      if (category.itemized) {
        const items = make("div", "transfer-items");
        if (String(category.id || "") === "my_liveries") {
          const liveryGroups = workspaceLiveryGroups(category);
          liveryGroups.forEach((group) => {
            const groupSection = make("section", "transfer-livery-category-group");
            const label = make("label", "transfer-livery-category-head");
            const groupInput = document.createElement("input");
            groupInput.type = "checkbox";
            groupInput.className = "transfer-livery-category-check";
            groupInput.dataset.itemIds = group.itemIds.join("|");
            groupInput.disabled = !category.available;
            const groupCopy = make("span", "transfer-category-copy");
            groupCopy.appendChild(make("strong", "", group.name));
            groupCopy.appendChild(make("small", "", `${group.items.length} livery${group.items.length === 1 ? "" : "ies"}`));
            label.appendChild(groupInput);
            label.appendChild(groupCopy);
            const groupItems = make("div", "transfer-livery-category-items");
            group.items.forEach((item) => {
              groupItems.appendChild(renderTransferItem(item, input.checked, category.available, () => updateExportParent(row)));
            });
            groupSection.appendChild(label);
            groupSection.appendChild(groupItems);
            items.appendChild(groupSection);
            groupInput.addEventListener("change", () => {
              const selected = new Set(group.itemIds);
              row.querySelectorAll(".transfer-item-check").forEach((itemInput) => {
                if (!itemInput.disabled && selected.has(itemInput.value)) itemInput.checked = groupInput.checked;
              });
              groupInput.indeterminate = false;
              updateExportParent(row);
            });
          });
        } else {
          (category.items || []).forEach((item) => {
            items.appendChild(renderTransferItem(item, input.checked, category.available, () => updateExportParent(row)));
          });
        }
        row.appendChild(items);
        input.addEventListener("change", () => {
          row.querySelectorAll(".transfer-item-check").forEach((child) => {
            child.checked = input.checked;
          });
          input.indeterminate = false;
          updateExportParent(row);
        });
      }

      list.appendChild(row);
      updateExportParent(row);
    });
    renderExportSelectionSummary();
  }

  async function refreshOverview() {
    if (state.overviewRefreshing) return state.overview;
    const bridge = api();
    if (!bridge) {
      setStatus("transferExportStatus", "Waiting for app bridge...", "warning");
      setTimeout(refreshOverview, 800);
      return;
    }
    const button = $("refreshTransferOverview");
    state.overviewRefreshing = true;
    setWorking(button, true, "Refreshing...");
    try {
      const result = await bridge.get_transfer_bundle_overview();
      if (!result?.ok) {
        setStatus("transferExportStatus", result?.message || "Could not load transfer overview.", "error");
        showModal("error", "Workspace Transfer", result?.message || "Could not load transfer overview.", resultDetails(result));
        return;
      }
      state.overview = result.data || {};
      renderExportOverview(state.overview);
      renderSkinPackCategories(state.overview);
      setStatus("transferExportStatus", "Transfer export list is ready.", "ok");
      return state.overview;
    } finally {
      state.overviewRefreshing = false;
      setWorking(button, false);
    }
  }

  function collectExportSelection() {
    const categories = [];
    const items = {};
    document.querySelectorAll("#transferExportList .transfer-category").forEach((row) => {
      const category = row.dataset.category || "";
      const parent = row.querySelector(".transfer-category-check");
      if (!category || !parent || parent.disabled) return;
      const childInputs = [...row.querySelectorAll(".transfer-item-check")];
      if (childInputs.length) {
        const selectedItems = childInputs.filter((input) => input.checked && !input.disabled).map((input) => input.value).filter(Boolean);
        if (selectedItems.length) {
          categories.push(category);
          items[category] = selectedItems;
        }
        return;
      }
      if (parent.checked) categories.push(category);
    });
    return { categories, items };
  }

  async function pickExportDir() {
    const bridge = api();
    if (!bridge) return;
    const current = $("transferExportDir")?.value || "";
    const result = await bridge.choose_path("folder", ["All files (*.*)"], "", current);
    if (result?.ok && result.data?.path) {
      $("transferExportDir").value = result.data.path;
    } else if (result && !result.ok) {
      showModal("error", "Choose export folder", result.message || "Folder selection failed.", resultDetails(result));
    }
  }

  async function exportSelected() {
    const bridge = api();
    if (!bridge) return;
    const selection = collectExportSelection();
    if (!selection.categories.length) {
      setStatus("transferExportStatus", "Select at least one export item.", "warning");
      return;
    }
    const button = $("exportTransferBundle");
    setWorking(button, true, "Exporting...");
    resetTransferProgress();
    renderTransferProgress({ phase: "start", message: "Preparing transfer ZIP..." });
    setStatus("transferExportStatus", "Creating transfer bundle...", "warning");
    try {
      const result = await bridge.export_transfer_bundle({
        targetDir: $("transferExportDir")?.value || "",
        root: $("rootPath")?.value || "",
        categories: selection.categories,
        items: selection.items,
      });
      if (!result?.ok) {
        setStatus("transferExportStatus", result?.message || "Transfer export failed.", "error");
        renderTransferProgress({ phase: "error", message: result?.message || "Transfer export failed." });
        showModal("error", "Transfer Export", result?.message || "Transfer export failed.", resultDetails(result));
        return;
      }
      const depCount = Number(result.data?.requiredDependencyCount || 0);
      const depNote = depCount ? ` ${depCount} required dependenc${depCount === 1 ? "y was" : "ies were"} included.` : "";
      renderTransferProgress({ phase: "done", percent: 100, message: `Exported transfer ZIP.${depNote}`, path: result.data?.bundlePath || result.data?.bundleRoot || "" });
      setStatus("transferExportStatus", `Exported transfer ZIP.${depNote}`, "ok");
      showModal("success", "Transfer Export", result.message || "Transfer ZIP exported.", dependencyDetails(result.data), result.data?.bundlePath || result.data?.bundleRoot || "");
      await refreshOverview();
    } finally {
      setWorking(button, false);
    }
  }

  async function pickSkinPackExportDir() {
    const bridge = api();
    if (!bridge) return;
    const current = $("skinPackExportDir")?.value || $("transferExportDir")?.value || "";
    const result = await bridge.choose_path("folder", ["All files (*.*)"], "", current);
    if (result?.ok && result.data?.path) {
      $("skinPackExportDir").value = result.data.path;
    } else if (result && !result.ok) {
      showModal("error", "Choose export folder", result.message || "Folder selection failed.", resultDetails(result));
    }
  }

  async function exportSkinPack() {
    const bridge = api();
    const group = selectedSkinPackGroup();
    if (!bridge || !group) {
      setStatus("skinPackExportStatus", "Choose a My Liveries category first.", "warning");
      return;
    }
    const button = $("exportSkinPack");
    setWorking(button, true, "Exporting...");
    setStatus("skinPackExportStatus", "Creating skin pack transfer ZIP...", "warning");
    try {
      const result = await bridge.export_transfer_bundle({
        targetDir: $("skinPackExportDir")?.value || $("transferExportDir")?.value || "",
        root: $("rootPath")?.value || "",
        categories: ["my_liveries"],
        items: { my_liveries: group.itemIds },
      });
      if (!result?.ok) {
        setStatus("skinPackExportStatus", result?.message || "Skin pack export failed.", "error");
        showModal("error", "Skin Pack Export", result?.message || "Skin pack export failed.", resultDetails(result));
        return;
      }
      const depCount = Number(result.data?.requiredDependencyCount || 0);
      const depNote = depCount ? ` ${depCount} dependenc${depCount === 1 ? "y was" : "ies were"} included.` : "";
      setStatus("skinPackExportStatus", `Exported "${group.name}" skin pack.${depNote}`, "ok");
      showModal("success", "Skin Pack Export", result.message || "Skin pack exported.", dependencyDetails(result.data), result.data?.bundlePath || result.data?.bundleRoot || "");
      await refreshOverview();
    } finally {
      setWorking(button, false);
      updateSkinPackExportActionState();
    }
  }

  async function pickSkinPackImportDir() {
    const bridge = api();
    if (!bridge) return;
    const current = $("skinPackImportDir")?.value || "";
    const result = await bridge.choose_path("file", ["LiveryLab Transfer ZIP (*.zip)", "ZIP (*.zip)", "All files (*.*)"], "", current);
    if (result?.ok && result.data?.path) {
      $("skinPackImportDir").value = result.data.path;
      state.skinPackImportInfo = null;
      renderSkinPackImportInfo(null);
      updateSkinPackImportActionState();
      await inspectSkinPack();
    } else if (result && !result.ok) {
      showModal("error", "Choose skin pack ZIP", result.message || "File selection failed.", resultDetails(result));
    }
  }

  function skinPackInspectionError(data = {}) {
    const packages = Array.isArray(data?.packages) ? data.packages : [];
    if (packages.length !== 1 || String(packages[0]?.kind || "") !== "my_liveries") {
      return "This ZIP is not a skin pack. Skin packs must contain My Liveries only. Use Workspace Transfer for full transfer ZIPs.";
    }
    return "";
  }

  function renderSkinPackImportInfo(data) {
    const list = $("skinPackImportList");
    if (!list) return;
    list.innerHTML = "";
    if (!data) {
      list.appendChild(make("div", "transfer-empty", "Choose a skin pack ZIP and inspect it."));
      return;
    }
    const error = skinPackInspectionError(data);
    if (error) {
      list.appendChild(make("div", "transfer-empty is-warning", error));
      return;
    }
    const pkg = (Array.isArray(data.packages) ? data.packages : [])[0] || {};
    const row = make("div", "transfer-category-head transfer-import-package");
    const copy = make("span", "transfer-category-copy");
    const itemCount = Number(pkg.itemCount || 0);
    const fileCount = Number(pkg.fileCount || 0);
    copy.appendChild(make("strong", "", "My Liveries skin pack"));
    copy.appendChild(make("small", "", `${itemCount} livery item${itemCount === 1 ? "" : "s"} / ${fileCount} file${fileCount === 1 ? "" : "s"}`));
    const liveryCategories = Array.isArray(pkg.liveryCategories) ? pkg.liveryCategories : [];
    if (liveryCategories.length) {
      copy.appendChild(make("small", "", `Restores ${liveryCategories.length} categor${liveryCategories.length === 1 ? "y" : "ies"}.`));
    }
    row.appendChild(copy);
    list.appendChild(row);
  }

  function updateSkinPackImportActionState() {
    const button = $("importSkinPack");
    if (!button || state.skinPackImportRunning) return;
    button.disabled = !state.skinPackImportInfo || state.skinPackImportInspecting || Boolean(skinPackInspectionError(state.skinPackImportInfo));
  }

  async function inspectSkinPack() {
    const bridge = api();
    if (!bridge) return;
    const bundleDir = $("skinPackImportDir")?.value || "";
    if (!bundleDir.trim()) {
      state.skinPackImportInfo = null;
      renderSkinPackImportInfo(null);
      updateSkinPackImportActionState();
      setStatus("skinPackImportStatus", "Choose a skin pack ZIP first.", "warning");
      return;
    }
    const button = $("inspectSkinPack");
    state.skinPackImportInspecting = true;
    state.skinPackImportInfo = null;
    renderSkinPackImportInfo(null);
    updateSkinPackImportActionState();
    setWorking(button, true, "Inspecting...");
    try {
      const result = await bridge.inspect_transfer_bundle(bundleDir);
      if (!result?.ok) {
        setStatus("skinPackImportStatus", result?.message || "Skin pack inspection failed.", "error");
        showModal("error", "Skin Pack Import", result?.message || "Skin pack inspection failed.", resultDetails(result));
        return;
      }
      state.skinPackImportInfo = result.data || {};
      renderSkinPackImportInfo(state.skinPackImportInfo);
      const error = skinPackInspectionError(state.skinPackImportInfo);
      setStatus("skinPackImportStatus", error || "Skin pack is ready to import.", error ? "warning" : "ok");
    } finally {
      state.skinPackImportInspecting = false;
      setWorking(button, false);
      updateSkinPackImportActionState();
    }
  }

  async function importSkinPack() {
    const bridge = api();
    if (!bridge) return;
    const bundleDir = $("skinPackImportDir")?.value || "";
    const root = $("rootPath")?.value || "";
    const error = skinPackInspectionError(state.skinPackImportInfo || {});
    if (error) {
      setStatus("skinPackImportStatus", error, "warning");
      return;
    }
    if (!root.trim()) {
      setStatus("skinPackImportStatus", "Choose a document root before importing a skin pack.", "warning");
      return;
    }
    const button = $("importSkinPack");
    state.skinPackImportRunning = true;
    updateSkinPackImportActionState();
    setWorking(button, true, "Importing...");
    setStatus("skinPackImportStatus", "Importing skin pack...", "warning");
    try {
      const result = await bridge.import_transfer_bundle({ bundleDir, categories: ["my_liveries"], root });
      if (!result?.ok) {
        setStatus("skinPackImportStatus", result?.message || "Skin pack import failed.", "error");
        showModal("error", "Skin Pack Import", result?.message || "Skin pack import failed.", resultDetails(result));
        return;
      }
      setStatus("skinPackImportStatus", "Skin pack imported.", "ok");
      showModal("success", "Skin Pack Import", result.message || "Skin pack imported.", `Backup folder:\n${result.data?.backupFolder || "-"}`, result.data?.backupFolder || "");
      if (typeof window.LiveryLabAppRefresh?.afterLibraryImport === "function") {
        await window.LiveryLabAppRefresh.afterLibraryImport();
      }
      await refreshOverview();
    } finally {
      state.skinPackImportRunning = false;
      setWorking(button, false);
      updateSkinPackImportActionState();
    }
  }

  function setTab(name) {
    const exportActive = name === "export";
    $("transferExportTab")?.classList.toggle("active", exportActive);
    $("transferImportTab")?.classList.toggle("active", !exportActive);
    $("transferExportTab")?.setAttribute("aria-selected", exportActive ? "true" : "false");
    $("transferImportTab")?.setAttribute("aria-selected", exportActive ? "false" : "true");
    if ($("transferExportPanel")) $("transferExportPanel").hidden = !exportActive;
    if ($("transferImportPanel")) $("transferImportPanel").hidden = exportActive;
    if ($("transferExportSelectionActions")) $("transferExportSelectionActions").hidden = !exportActive;
  }

  async function pickImportDir() {
    const bridge = api();
    if (!bridge) return;
    const current = $("transferImportDir")?.value || "";
    const result = await bridge.choose_path("file", ["LiveryLab Transfer ZIP (*.zip)", "ZIP (*.zip)", "All files (*.*)"], "", current);
    if (result?.ok && result.data?.path) {
      $("transferImportDir").value = result.data.path;
      state.importInfo = null;
      renderImportInfo(null);
      resetTransferImportProgress();
      updateImportActionState();
      await inspectImportBundle();
    } else if (result && !result.ok) {
      showModal("error", "Choose transfer ZIP", result.message || "File selection failed.", resultDetails(result));
    }
  }

  function renderImportInfo(data) {
    const list = $("transferImportList");
    if (!list) return;
    list.innerHTML = "";
    const packages = Array.isArray(data?.packages) ? data.packages : [];
    if (!packages.length) {
      list.appendChild(make("div", "transfer-empty", "No importable categories found in this transfer ZIP."));
      return;
    }
    packages.forEach((pkg) => {
      const label = make("label", "transfer-category-head transfer-import-package");
      const input = document.createElement("input");
      input.type = "checkbox";
      input.className = "transfer-import-check";
      input.value = pkg.kind || "";
      input.checked = true;
      const copy = make("span", "transfer-category-copy");
      copy.appendChild(make("strong", "", pkg.label || CATEGORY_META[pkg.kind] || pkg.kind || "Package"));
      copy.appendChild(make("small", "", `${Number(pkg.itemCount || 0)} item${Number(pkg.itemCount || 0) === 1 ? "" : "s"} / ${Number(pkg.fileCount || 0)} file${Number(pkg.fileCount || 0) === 1 ? "" : "s"}`));
      label.appendChild(input);
      label.appendChild(copy);
      list.appendChild(label);
    });
    if (data.missingCount) {
      list.appendChild(make("div", "transfer-empty is-warning", `${data.missingCount} bundle reference${data.missingCount === 1 ? "" : "s"} missing or invalid.`));
    }
  }

  async function inspectImportBundle() {
    const bridge = api();
    if (!bridge) return;
    const bundleDir = $("transferImportDir")?.value || "";
    if (!bundleDir.trim()) {
      state.importInfo = null;
      renderImportInfo(null);
      updateImportActionState();
      setStatus("transferImportStatus", "Choose a transfer ZIP first.", "warning");
      return;
    }
    const button = $("inspectTransferBundle");
    state.importInspecting = true;
    state.importInfo = null;
    renderImportInfo(null);
    updateImportActionState();
    resetTransferImportProgress();
    setWorking(button, true, "Inspecting...");
    try {
      const result = await bridge.inspect_transfer_bundle(bundleDir);
      if (!result?.ok) {
        state.importInfo = null;
        renderImportInfo(null);
        resetTransferImportProgress();
        setStatus("transferImportStatus", result?.message || "Transfer bundle inspection failed.", "error");
        showModal("error", "Transfer Import", result?.message || "Transfer bundle inspection failed.", resultDetails(result));
        return;
      }
      state.importInfo = result.data || {};
      renderImportInfo(state.importInfo);
      renderTransferImportProgress({ phase: "inspect_done", percent: 100, message: "Inspection complete.", path: bundleDir });
      setStatus("transferImportStatus", `Found ${state.importInfo.categoryCount || 0} import categor${state.importInfo.categoryCount === 1 ? "y" : "ies"}.`, "ok");
    } finally {
      state.importInspecting = false;
      setWorking(button, false);
      updateImportActionState();
    }
  }

  function collectImportCategories() {
    return [...document.querySelectorAll("#transferImportList .transfer-import-check")]
      .filter((input) => input.checked && !input.disabled)
      .map((input) => input.value)
      .filter(Boolean);
  }

  async function importSelected() {
    const bridge = api();
    if (!bridge) return;
    const bundleDir = $("transferImportDir")?.value || "";
    const root = $("rootPath")?.value || "";
    const categories = collectImportCategories();
    if (state.importInspecting) {
      setStatus("transferImportStatus", "Wait until transfer ZIP inspection is complete.", "warning");
      return;
    }
    if (!root.trim()) {
      setStatus("transferImportStatus", "Choose a document root before importing a transfer ZIP.", "warning");
      showModal(
        "error",
        "Transfer Import",
        "Document root required",
        "Set the Assetto Corsa EVO document root first. Imported My Liveries entries are assigned to that root, but no game files are written during import.",
      );
      return;
    }
    if (!bundleDir.trim()) {
      setStatus("transferImportStatus", "Choose a transfer ZIP first.", "warning");
      return;
    }
    if (!state.importInfo) {
      setStatus("transferImportStatus", "Inspect the selected transfer ZIP before importing.", "warning");
      return;
    }
    if (!categories.length) {
      setStatus("transferImportStatus", "Select at least one category to import.", "warning");
      return;
    }
    const button = $("importTransferBundle");
    state.importRunning = true;
    updateImportActionState();
    setWorking(button, true, "Importing...");
    resetTransferImportProgress();
    renderTransferImportProgress({ phase: "start", message: "Preparing transfer import...", path: bundleDir });
    setStatus("transferImportStatus", "Importing selected transfer categories...", "warning");
    try {
      const result = await bridge.import_transfer_bundle({ bundleDir, categories, root });
      if (!result?.ok) {
        setStatus("transferImportStatus", result?.message || "Transfer import failed.", "error");
        renderTransferImportProgress({ phase: "error", message: result?.message || "Transfer import failed.", path: bundleDir });
        showModal("error", "Transfer Import", result?.message || "Transfer import failed.", resultDetails(result));
        return;
      }
      renderTransferImportProgress({ phase: "done", percent: 100, message: "Transfer import complete.", path: result.data?.backupFolder || "" });
      setStatus("transferImportStatus", `Imported ${result.data?.importedCount || 0} categor${result.data?.importedCount === 1 ? "y" : "ies"}.`, "ok");
      showModal("success", "Transfer Import", result.message || "Transfer import complete.", `Backup folder:\n${result.data?.backupFolder || "-"}`, result.data?.backupFolder || "");
      if (typeof window.LiveryLabAppRefresh?.afterLibraryImport === "function") {
        await window.LiveryLabAppRefresh.afterLibraryImport();
      }
      await refreshOverview();
    } finally {
      state.importRunning = false;
      setWorking(button, false);
      updateImportActionState();
    }
  }

  function bind() {
    if (!$("transferExportTab")) return;
    $("transferExportTab").addEventListener("click", () => setTab("export"));
    $("transferImportTab")?.addEventListener("click", () => setTab("import"));
    $("refreshTransferOverview")?.addEventListener("click", refreshOverview);
    $("refreshSkinPackCategories")?.addEventListener("click", refreshOverview);
    $("pickSkinPackExportDir")?.addEventListener("click", pickSkinPackExportDir);
    $("exportSkinPack")?.addEventListener("click", exportSkinPack);
    $("pickSkinPackImportDir")?.addEventListener("click", pickSkinPackImportDir);
    $("inspectSkinPack")?.addEventListener("click", inspectSkinPack);
    $("importSkinPack")?.addEventListener("click", importSkinPack);
    $("selectAllTransferExport")?.addEventListener("click", () => setExportSelection(true));
    $("deselectAllTransferExport")?.addEventListener("click", () => setExportSelection(false));
    $("pickTransferExportDir")?.addEventListener("click", pickExportDir);
    $("exportTransferBundle")?.addEventListener("click", exportSelected);
    $("pickTransferImportDir")?.addEventListener("click", pickImportDir);
    $("inspectTransferBundle")?.addEventListener("click", inspectImportBundle);
    $("importTransferBundle")?.addEventListener("click", importSelected);
    $("transferImportDir")?.addEventListener("input", () => {
      state.importInfo = null;
      renderImportInfo(null);
      resetTransferImportProgress();
      setStatus("transferImportStatus", "Transfer ZIP changed. Inspect it before importing.", "warning");
      updateImportActionState();
    });
    $("skinPackImportDir")?.addEventListener("input", () => {
      state.skinPackImportInfo = null;
      renderSkinPackImportInfo(null);
      setStatus("skinPackImportStatus", "Skin pack ZIP changed. Inspect it before importing.", "warning");
      updateSkinPackImportActionState();
    });
    updateImportActionState();
    updateSkinPackImportActionState();
    refreshOverview();
  }

  window.handleBackendProgress = function handleBackendProgress(eventName, payload) {
    if (eventName === "transfer_export") {
      renderTransferProgress(payload || {});
      return;
    }
    if (eventName === "transfer_import") {
      renderTransferImportProgress(payload || {});
      return;
    }
    if (typeof previousBackendProgress === "function") {
      previousBackendProgress(eventName, payload);
    }
  };

  window.LiveryLabTransferBundle = {
    refresh: refreshOverview,
  };

  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", bind, { once: true });
  } else {
    bind();
  }
})();
