(() => {
  const $ = (id) => document.getElementById(id);
  const ENTRY_EDIT_FIELDS = ["number", "driver", "team", "car", "class", "notes"];

  const state = {
    overview: null,
    selectedScope: "official",
    selectedProjectId: "",
    selectedProject: null,
    installInfo: null,
    importSourcePaths: [],
    thumbnailCache: {},
    bridgeRetryTimer: 0,
    activeView: "installed",
    expandedInstalledPackId: "",
    projectDrafts: {},
    entryDrafts: {},
  };

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

  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 make(tag, className = "", text = "") {
    const node = document.createElement(tag);
    if (className) node.className = className;
    if (text) node.textContent = text;
    return node;
  }

  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 setDraftSaveState(dirty = false) {
    const node = $("onlineLeagueDraftSaveState");
    if (!node) return;
    node.textContent = dirty ? "Unsaved changes" : "Saved";
    node.classList.toggle("is-dirty", dirty);
  }

  function projectDraftKey(project = {}) {
    return `${String(project.workflowScope || "official")}::${String(project.id || "")}`;
  }

  function entryDraftKey(project = {}, entryId = "") {
    return `${projectDraftKey(project)}::${String(entryId || "")}`;
  }

  function projectFieldValues(source = {}) {
    return {
      name: String(source.name || ""),
      packVersion: String(source.packVersion || "1.0.0"),
      notes: String(source.notes || ""),
    };
  }

  function entryFieldValues(source = {}) {
    return Object.fromEntries(ENTRY_EDIT_FIELDS.map((field) => [field, String(source[field] || "")]));
  }

  function valuesDiffer(left = {}, right = {}, fields = []) {
    return fields.some((field) => String(left[field] || "") !== String(right[field] || ""));
  }

  function updateDraftSaveState() {
    const project = state.selectedProject;
    if (!project) {
      setDraftSaveState(false);
      return;
    }
    const metaKey = projectDraftKey(project);
    const metaDraft = state.projectDrafts[metaKey];
    const metaDirty = Boolean(metaDraft && valuesDiffer(metaDraft, projectFieldValues(project), ["name", "packVersion", "notes"]));
    if (metaDraft && !metaDirty) delete state.projectDrafts[metaKey];
    const entryDirty = (project.entries || []).some((entry) => {
      const key = entryDraftKey(project, entry.id);
      const draft = state.entryDrafts[key];
      const dirty = Boolean(draft && valuesDiffer(draft, entryFieldValues(entry), ENTRY_EDIT_FIELDS));
      if (draft && !dirty) delete state.entryDrafts[key];
      return dirty;
    });
    setDraftSaveState(metaDirty || entryDirty);
  }

  function captureProjectDraft() {
    const project = state.selectedProject;
    if (!project) return;
    const key = projectDraftKey(project);
    const values = {
      name: String($("onlineLeagueEditName")?.value || ""),
      packVersion: String($("onlineLeagueEditVersion")?.value || ""),
      notes: String($("onlineLeagueEditNotes")?.value || ""),
    };
    if (valuesDiffer(values, projectFieldValues(project), ["name", "packVersion", "notes"])) state.projectDrafts[key] = values;
    else delete state.projectDrafts[key];
    updateDraftSaveState();
  }

  function captureEntryDraft(entryId, row) {
    const project = state.selectedProject;
    const entry = (project?.entries || []).find((item) => String(item.id || "") === String(entryId || ""));
    if (!project || !entry || !row) return;
    const values = {};
    row.querySelectorAll("[data-entry-field]").forEach((input) => {
      values[input.dataset.entryField] = String(input.value || "");
    });
    const key = entryDraftKey(project, entryId);
    if (valuesDiffer(values, entryFieldValues(entry), ENTRY_EDIT_FIELDS)) state.entryDrafts[key] = values;
    else delete state.entryDrafts[key];
    updateDraftSaveState();
  }

  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 "";
    return [result.errorDetails, result.errorDetail, result.traceback].filter(Boolean).join("\n\n");
  }

  function placeholderSrc() {
    return "./assets/placeholder.png";
  }

  function clearImportSource() {
    state.importSourcePaths = [];
    if ($("onlineLeagueImportPath")) $("onlineLeagueImportPath").value = "";
  }

  function currentScope() {
    if (state.selectedScope !== "official") {
      state.selectedScope = "official";
      state.selectedProjectId = "";
      state.installInfo = null;
      if ($("importOnlineLeaguePack")) $("importOnlineLeaguePack").disabled = true;
    }
    return "official";
  }

  function workflowLabel() {
    return "Official";
  }

  function selectedProject() {
    const projects = Array.isArray(state.overview?.projects) ? state.overview.projects : [];
    return projects.find((project) => String(project.id || "") === state.selectedProjectId && String(project.workflowScope || "") === state.selectedScope) || null;
  }

  function setLeagueView(view) {
    state.activeView = view === "builder" ? "builder" : "installed";
    const installed = state.activeView === "installed";
    if ($("onlineLeagueInstalledView")) $("onlineLeagueInstalledView").hidden = !installed;
    if ($("onlineLeagueBuilderView")) $("onlineLeagueBuilderView").hidden = installed;
    if ($("onlineLeagueViewInstalled")) {
      $("onlineLeagueViewInstalled").classList.toggle("active", installed);
      $("onlineLeagueViewInstalled").setAttribute("aria-selected", String(installed));
    }
    if ($("onlineLeagueViewBuilder")) {
      $("onlineLeagueViewBuilder").classList.toggle("active", !installed);
      $("onlineLeagueViewBuilder").setAttribute("aria-selected", String(!installed));
    }
  }

  function projectThumbnailPath(project = {}) {
    return String(project.thumbnailPath || project.previewPngPath || "").trim();
  }

  function installedEntryThumbnailPath(pack = {}, entry = {}) {
    const raw = String(entry.thumbnailPath || entry.inspection?.thumbnailPath || "").trim();
    const root = String(pack.installedRoot || "").trim();
    if (!raw || !root) return "";
    const normalize = (value) => String(value || "").replaceAll("\\", "/").replace(/\/+$/, "");
    const normalizedRoot = normalize(root);
    const normalizedRaw = normalize(raw);
    const rootPrefix = `${normalizedRoot.toLowerCase()}/`;
    const absolute = /^[a-z]:\//i.test(normalizedRaw) || normalizedRaw.startsWith("/") || normalizedRaw.startsWith("//");
    if (absolute) {
      return normalizedRaw.toLowerCase().startsWith(rootPrefix) ? raw : "";
    }
    const parts = normalizedRaw.split("/");
    if (!parts.length || parts.some((part) => !part || part === "." || part === ".." || part.includes(":"))) return "";
    const separator = root.includes("\\") ? "\\" : "/";
    return `${root.replace(/[\\/]+$/, "")}${separator}${parts.join(separator)}`;
  }

  function projectMarkHtml(project = {}, options = {}) {
    const path = projectThumbnailPath(project);
    const classes = ["online-league-pack-mark"];
    if (options.large) classes.push("is-large");
    if (path) {
      return `<div class="${classes.join(" ")}"><img alt="" src="${placeholderSrc()}" data-online-league-pack-thumb-path="${escapeHtml(path)}" /></div>`;
    }
    return `<div class="${classes.join(" ")}"><span>LEAGUE</span></div>`;
  }

  async function loadImagePreview(path, image, namespace = "online_league") {
    if (!path || !image || !api()?.load_image_preview) return;
    if (state.thumbnailCache[path]) {
      image.src = state.thumbnailCache[path];
      return;
    }
    try {
      const result = await api().load_image_preview(path, namespace);
      const src = result?.ok ? (result.data?.data_url || result.data?.dataUrl || "") : "";
      if (src) {
        state.thumbnailCache[path] = src;
        image.src = src;
      }
    } catch (_error) {}
  }

  function loadProjectThumbnailImages(root = document) {
    root.querySelectorAll("[data-online-league-pack-thumb-path]").forEach((image) => {
      const path = image.getAttribute("data-online-league-pack-thumb-path") || "";
      loadImagePreview(path, image, "online_league_pack");
    });
  }

  function loadInstalledEntryThumbnailImages(root = document) {
    root.querySelectorAll("[data-online-league-installed-entry-thumb-path]").forEach((image) => {
      const path = image.getAttribute("data-online-league-installed-entry-thumb-path") || "";
      loadImagePreview(path, image, "online_league_installed_entry");
    });
  }

  function renderProjectList() {
    const list = $("onlineLeagueProjectList");
    if (!list) return;
    const scope = currentScope();
    const projects = (Array.isArray(state.overview?.projects) ? state.overview.projects : [])
      .filter((project) => String(project.workflowScope || "") === scope);
    list.innerHTML = "";
    if (!projects.length) {
      list.appendChild(make("div", "online-league-empty", `No ${workflowLabel(scope)} league packs yet.`));
      return;
    }
    projects.forEach((project) => {
      const button = make("button", "online-league-list-item", "");
      button.type = "button";
      button.classList.toggle("active", String(project.id || "") === state.selectedProjectId && String(project.workflowScope || "") === state.selectedScope);
      button.innerHTML = `
        ${projectMarkHtml(project)}
        <span class="online-league-item-copy">
          <strong>${escapeHtml(project.name || project.id || "League Pack")}</strong>
          <span>${Number(project.statusSummary?.total || 0)} entr${Number(project.statusSummary?.total || 0) === 1 ? "y" : "ies"} / ${escapeHtml(project.packVersion || "1.0.0")}</span>
          <small>${escapeHtml(project.updatedAt || "")}</small>
        </span>
      `;
      button.addEventListener("click", () => {
        state.selectedScope = String(project.workflowScope || scope);
        state.selectedProjectId = String(project.id || "");
        setLeagueView("builder");
        renderAll();
      });
      list.appendChild(button);
    });
    loadProjectThumbnailImages(list);
  }

  function renderInstalledList() {
    const list = $("onlineLeagueInstalledList");
    if (!list) return;
    const scope = currentScope();
    const packs = (Array.isArray(state.overview?.installedPacks) ? state.overview.installedPacks : [])
      .filter((pack) => String(pack.workflowScope || "") === scope);
    list.innerHTML = "";
    if ($("onlineLeagueInstalledCount")) $("onlineLeagueInstalledCount").textContent = `${packs.length} pack${packs.length === 1 ? "" : "s"}`;
    const activationAvailable = Boolean(api()?.preflight_online_league_pack_activation && api()?.activate_online_league_pack && api()?.preflight_online_league_pack_deactivation && api()?.deactivate_online_league_pack);
    const deletionAvailable = Boolean(api()?.preflight_online_league_pack_deletion && api()?.delete_online_league_pack);
    if ($("onlineLeagueRuntimeNotice")) $("onlineLeagueRuntimeNotice").hidden = activationAvailable;
    if (!packs.length) {
      state.expandedInstalledPackId = "";
      list.appendChild(make("div", "online-league-empty online-league-empty-card", "No League packs imported yet. Choose a League ZIP above to add one."));
      return;
    }
    if (!packs.some((pack) => String(pack.installedId || "") === state.expandedInstalledPackId)) {
      state.expandedInstalledPackId = "";
    }
    packs.forEach((pack, packIndex) => {
      const hasDeploymentSummary = Boolean(pack.deploymentSummary);
      const deployment = pack.deploymentSummary || {};
      const deploymentEntries = new Map(
        (Array.isArray(deployment.entries) ? deployment.entries : [])
          .map((entry) => [String(entry.entryId || "").toLowerCase(), entry]),
      );
      const activeCount = Number(deployment.activeCount || 0);
      const entryCount = Number(pack.entryCount || 0);
      const installedId = String(pack.installedId || "");
      const expanded = installedId === state.expandedInstalledPackId;
      const activationState = String(pack.activationState || deployment.state || "local_only");
      const statusText = activationState === "active"
        ? `Active · ${activeCount} of ${entryCount} liveries`
        : activationState === "partial"
          ? `Partially active · ${activeCount} of ${entryCount} liveries`
          : "Local only";
      const stateClass = activationState === "active" ? "is-active" : activationState === "partial" ? "is-partial" : "is-local";
      const detailId = `online-league-installed-detail-${packIndex}`;
      const entryCards = (Array.isArray(pack.entries) ? pack.entries : []).map((entry) => {
        const entryId = String(entry.id || "");
        const entryDeployment = deploymentEntries.get(entryId.toLowerCase()) || {};
        const isActive = Boolean(entryDeployment.active);
        const ownership = String(entryDeployment.ownership || "");
        const statusLabel = isActive
          ? ownership === "league_owned"
            ? "Active · League-owned"
            : ownership === "reused_existing"
              ? "Active · Existing livery reused"
              : "Active"
          : "Not active";
        const statusClass = isActive ? (ownership === "reused_existing" ? "is-reused" : "is-active") : "is-local";
        const thumbnailPath = installedEntryThumbnailPath(pack, entry);
        const number = String(entry.number || "").trim();
        const driver = String(entry.driver || entry.displayName || entry.id || "Livery").trim();
        const title = `${number ? `#${number} ` : ""}${driver}`;
        const team = String(entry.team || "").trim();
        const specification = [entry.car, entry.class].map((value) => String(value || "").trim()).filter(Boolean).join(" · ");
        const notes = String(entry.notes || "").trim();
        const fallback = String(entry.externalFolderName || "").trim();
        return `
          <article class="online-league-installed-livery" role="listitem">
            <div class="online-league-installed-livery-thumb">
              ${thumbnailPath
                ? `<img alt="" src="${placeholderSrc()}" data-online-league-installed-entry-thumb-path="${escapeHtml(thumbnailPath)}" />`
                : "<span>No preview</span>"}
            </div>
            <div class="online-league-installed-livery-copy">
              <div class="online-league-installed-livery-title">
                <strong title="${escapeHtml(title)}">${escapeHtml(title)}</strong>
                <span class="online-league-installed-livery-state ${statusClass}">${escapeHtml(statusLabel)}</span>
              </div>
              ${team ? `<span title="${escapeHtml(team)}">${escapeHtml(team)}</span>` : ""}
              ${specification ? `<small title="${escapeHtml(specification)}">${escapeHtml(specification)}</small>` : ""}
              ${!team && !specification && fallback ? `<small title="${escapeHtml(fallback)}">${escapeHtml(fallback)}</small>` : ""}
              ${notes ? `<p>${escapeHtml(notes)}</p>` : ""}
            </div>
          </article>
        `;
      }).join("");
      const row = make("article", `online-league-installed ${stateClass}${expanded ? " is-expanded" : ""}`, "");
      row.innerHTML = `
        ${projectMarkHtml(pack)}
        <span class="online-league-item-copy">
          <strong>${escapeHtml(pack.name || pack.installedId || "League Pack")}</strong>
          <span>Version ${escapeHtml(pack.packVersion || "-")} · ${entryCount} liver${entryCount === 1 ? "y" : "ies"}</span>
          <small class="online-league-pack-state">${escapeHtml(statusText)}</small>
        </span>
        <div class="online-league-installed-actions">
          <button type="button" class="primary" data-league-activate="${escapeHtml(installedId)}" ${activationAvailable && activationState !== "active" ? "" : "disabled"} title="${activationAvailable ? "Install this pack into ExternalLiveries" : "Activation requires an updated LiveryLab build"}">Activate</button>
          <button type="button" data-league-deactivate="${escapeHtml(installedId)}" ${activationAvailable && activeCount ? "" : "disabled"}>Deactivate</button>
          <button type="button" class="danger-outline" data-league-delete="${escapeHtml(installedId)}" ${deletionAvailable ? "" : "disabled"} title="${deletionAvailable ? "Permanently delete this installed pack and its exclusively owned ExternalLiveries" : "Pack deletion requires an updated LiveryLab build"}">Delete</button>
        </div>
        <button type="button" class="online-league-installed-toggle" data-league-toggle="${escapeHtml(installedId)}" aria-expanded="${expanded}" aria-controls="${detailId}">
          <span>${expanded ? "Hide liveries" : "Show liveries"} (${entryCount})</span>
          <span class="online-league-installed-toggle-icon" aria-hidden="true"></span>
        </button>
        <div id="${detailId}" class="online-league-installed-detail-panel" ${expanded ? "" : "hidden"}>
          <div class="online-league-installed-detail-head">
            <strong>Pack liveries</strong>
            <span>Read only · ${entryCount} entr${entryCount === 1 ? "y" : "ies"}</span>
          </div>
          ${hasDeploymentSummary ? `<div class="online-league-installed-facts">
            <span><strong>${Number(deployment.leagueOwnedCount || 0)}</strong> League-owned</span>
            <span><strong>${Number(deployment.reusedExistingCount || 0)}</strong> existing reused</span>
            <span><strong>${activeCount}</strong> active</span>
          </div>` : ""}
          <div class="online-league-installed-livery-scroll">
            <div class="online-league-installed-livery-grid" role="list">
              ${entryCards || '<div class="online-league-empty">No livery entries available.</div>'}
            </div>
          </div>
        </div>
      `;
      list.appendChild(row);
    });
    list.querySelectorAll("[data-league-activate]").forEach((button) => {
      button.addEventListener("click", () => activateInstalledPack(button.dataset.leagueActivate || ""));
    });
    list.querySelectorAll("[data-league-deactivate]").forEach((button) => {
      button.addEventListener("click", () => deactivateInstalledPack(button.dataset.leagueDeactivate || ""));
    });
    list.querySelectorAll("[data-league-delete]").forEach((button) => {
      button.addEventListener("click", () => deleteInstalledPack(button.dataset.leagueDelete || ""));
    });
    list.querySelectorAll("[data-league-toggle]").forEach((button) => {
      button.addEventListener("click", () => {
        const installedId = button.dataset.leagueToggle || "";
        state.expandedInstalledPackId = state.expandedInstalledPackId === installedId ? "" : installedId;
        renderInstalledList();
      });
    });
    loadProjectThumbnailImages(list);
    loadInstalledEntryThumbnailImages(list);
  }

  function activationPlanDetails(preflight = {}) {
    const lines = [];
    (preflight.plans || []).forEach((plan) => {
      const action = String(plan.action || "unknown").replaceAll("_", " ");
      lines.push(`${plan.displayName || plan.entryId || "Livery"}: ${action}`);
      (plan.errors || []).forEach((error) => lines.push(`  ${error}`));
    });
    return lines.join("\n");
  }

  async function confirmLeagueWrite(options = {}) {
    if (typeof window.showConfirmModal === "function") {
      return window.showConfirmModal(options);
    }
    return window.confirm([options.message, options.details].filter(Boolean).join("\n\n"));
  }

  async function activateInstalledPack(installedId) {
    if (!installedId || !api()?.preflight_online_league_pack_activation || !api()?.activate_online_league_pack) return;
    setStatus("onlineLeagueInstallStatus", "Checking League pack activation...", "warning");
    const checked = await api().preflight_online_league_pack_activation({ installedId });
    if (!checked?.ok) {
      showModal("error", "Activate League Pack", checked?.message || "Activation preflight failed.", resultDetails(checked));
      return;
    }
    const preflight = checked.data || {};
    if (!preflight.ready) {
      showModal("error", "Activate League Pack", "No files were changed. Resolve the activation conflicts first.", activationPlanDetails(preflight));
      setStatus("onlineLeagueInstallStatus", "Activation blocked by conflicts.", "error");
      return;
    }
    const counts = preflight.counts || {};
    const confirmed = await confirmLeagueWrite({
      type: Number(counts.reuseExisting || 0) ? "warning" : "info",
      title: "Activate League Pack",
      subtitle: preflight.name || installedId,
      message: `${Number(counts.install || 0)} liveries will be installed. ${Number(counts.reuseExisting || 0)} identical existing liveries will be reused and remain normally owned.`,
      details: activationPlanDetails(preflight),
      confirmLabel: "Activate Pack",
      loadingLabel: "Activating...",
    });
    if (!confirmed) {
      setStatus("onlineLeagueInstallStatus", "League activation cancelled.", "unknown");
      return;
    }
    const result = await api().activate_online_league_pack({ installedId, confirmToken: "ACTIVATE_LEAGUE_PACK" });
    if (!result?.ok) {
      showModal("error", "Activate League Pack", result?.message || "Activation failed.", resultDetails(result));
      setStatus("onlineLeagueInstallStatus", "League activation failed.", "error");
      return;
    }
    showModal("success", "Activate League Pack", result.message || "League pack activated.", "Existing normal liveries were left untouched.");
    await refresh();
    setStatus("onlineLeagueInstallStatus", "League pack active in ExternalLiveries.", "ok");
  }

  async function deactivateInstalledPack(installedId) {
    if (!installedId || !api()?.preflight_online_league_pack_deactivation || !api()?.deactivate_online_league_pack) return;
    setStatus("onlineLeagueInstallStatus", "Checking League pack deactivation...", "warning");
    const checked = await api().preflight_online_league_pack_deactivation({ installedId });
    if (!checked?.ok) {
      showModal("error", "Deactivate League Pack", checked?.message || "Deactivation preflight failed.", resultDetails(checked));
      return;
    }
    const preflight = checked.data || {};
    if (!preflight.ready) {
      showModal("error", "Deactivate League Pack", "No files were changed. Modified League-owned files cannot be removed automatically.", activationPlanDetails(preflight));
      setStatus("onlineLeagueInstallStatus", "Deactivation blocked to protect modified files.", "error");
      return;
    }
    const counts = preflight.counts || {};
    const confirmed = await confirmLeagueWrite({
      type: "warning",
      title: "Deactivate League Pack",
      subtitle: preflight.name || installedId,
      message: `${Number(counts.backup || 0)} League-owned liveries will be moved to a LiveryLab backup. ${Number(counts.reusedExisting || 0)} pre-existing liveries will remain untouched.`,
      details: activationPlanDetails(preflight),
      confirmLabel: "Deactivate Pack",
      loadingLabel: "Deactivating...",
    });
    if (!confirmed) {
      setStatus("onlineLeagueInstallStatus", "League deactivation cancelled.", "unknown");
      return;
    }
    const result = await api().deactivate_online_league_pack({ installedId, confirmToken: "DEACTIVATE_LEAGUE_PACK" });
    if (!result?.ok) {
      showModal("error", "Deactivate League Pack", result?.message || "Deactivation failed.", resultDetails(result));
      setStatus("onlineLeagueInstallStatus", "League deactivation failed.", "error");
      return;
    }
    showModal("success", "Deactivate League Pack", result.message || "League pack deactivated.", "League-owned files were preserved in the LeagueLibrary backup area.", result.data?.backupRoot || "");
    await refresh();
    setStatus("onlineLeagueInstallStatus", "League pack deactivated.", "ok");
  }

  async function deleteInstalledPack(installedId) {
    if (!installedId || !api()?.preflight_online_league_pack_deletion || !api()?.delete_online_league_pack) return;
    setStatus("onlineLeagueInstallStatus", "Checking permanent League pack deletion...", "warning");
    const checked = await api().preflight_online_league_pack_deletion({ installedId });
    if (!checked?.ok) {
      showModal("error", "Delete League Pack", checked?.message || "Deletion preflight failed.", resultDetails(checked));
      setStatus("onlineLeagueInstallStatus", "League pack deletion preflight failed.", "error");
      return;
    }
    const preflight = checked.data || {};
    if (!preflight.ready) {
      showModal("error", "Delete League Pack", "No files were changed. Resolve the deletion conflicts first.", activationPlanDetails(preflight));
      setStatus("onlineLeagueInstallStatus", "Deletion blocked to protect modified or unknown files.", "error");
      return;
    }
    const counts = preflight.counts || {};
    const deleteCount = Number(counts.deleteLeagueOwned || 0);
    const keepExisting = Number(counts.keepExisting || 0);
    const keepShared = Number(counts.keepShared || 0);
    const details = [
      `${keepExisting} pre-existing liveries will remain untouched.`,
      `${keepShared} League liveries still used by other packs will remain installed.`,
      "",
      activationPlanDetails(preflight),
    ].join("\n");
    const confirmed = await confirmLeagueWrite({
      type: "error",
      title: "Delete League Pack",
      subtitle: preflight.name || installedId,
      message: `The installed pack copy will be permanently deleted. ${deleteCount} exclusively owned liver${deleteCount === 1 ? "y" : "ies"} will also be permanently removed from ExternalLiveries. This cannot be undone.`,
      details,
      confirmLabel: "Delete Pack",
      loadingLabel: "Deleting...",
    });
    if (!confirmed) {
      setStatus("onlineLeagueInstallStatus", "League pack deletion cancelled.", "unknown");
      return;
    }
    const result = await api().delete_online_league_pack({ installedId, confirmToken: "DELETE_LEAGUE_PACK" });
    if (!result?.ok) {
      showModal("error", "Delete League Pack", result?.message || "Deletion failed.", resultDetails(result));
      setStatus("onlineLeagueInstallStatus", "League pack deletion failed.", "error");
      return;
    }
    state.expandedInstalledPackId = "";
    showModal(
      "success",
      "Delete League Pack",
      result.message || "League pack permanently deleted.",
      `${Number(result.data?.keptExistingCount || 0)} pre-existing and ${Number(result.data?.keptSharedCount || 0)} shared liveries were left untouched.`,
    );
    await refresh();
    setStatus("onlineLeagueInstallStatus", "League pack permanently deleted.", "ok");
  }

  function renderSummary(project) {
    const node = $("onlineLeagueSummary");
    if (!node) return;
    const summary = project?.statusSummary || {};
    const parts = [`${Number(summary.total || 0)} liver${Number(summary.total || 0) === 1 ? "y" : "ies"}`, `${Number(summary.ready || 0)} ready`];
    if (Number(summary.warning || 0)) parts.push(`${Number(summary.warning)} warnings`);
    if (Number(summary.error || 0)) parts.push(`${Number(summary.error)} errors`);
    node.textContent = parts.join(" · ");
  }

  function statusClass(status = "") {
    const key = String(status || "").toLowerCase();
    if (key === "ready") return "is-ready";
    if (key === "error") return "is-error";
    return "is-warning";
  }

  async function loadThumbnail(entry, image) {
    const path = String(entry.thumbnailPath || entry.inspection?.thumbnailPath || "").trim();
    await loadImagePreview(path, image, "online_league");
  }

  function entryIssues(entry = {}) {
    const lines = [];
    (entry.errors || []).forEach((item) => lines.push(`Error: ${item}`));
    (entry.warnings || []).forEach((item) => lines.push(`Warning: ${item}`));
    return lines;
  }

  function renderEntryList(project) {
    const list = $("onlineLeagueEntryList");
    if (!list) return;
    const entries = Array.isArray(project?.entries) ? project.entries : [];
    list.innerHTML = "";
    if (!entries.length) {
      list.appendChild(make("div", "online-league-empty", "No league liveries imported yet."));
      return;
    }
    entries.forEach((entry) => {
      const row = make("article", `online-league-entry ${statusClass(entry.status)}`, "");
      row.dataset.entryId = entry.id || "";
      const number = String(entry.number || "").trim();
      const driver = String(entry.driver || entry.displayName || "Unnamed livery").trim();
      const team = String(entry.team || "No team").trim();
      const carMeta = [entry.car, entry.class].filter(Boolean).join(" · ") || "Car not specified";
      const editValues = state.entryDrafts[entryDraftKey(project, entry.id)] || entryFieldValues(entry);
      row.innerHTML = `
        <div class="online-league-entry-media">
          <div class="online-league-thumb"><img alt="" hidden /><span>${escapeHtml(String(entry.status || "?").slice(0, 1).toUpperCase())}</span></div>
        </div>
        <div class="online-league-entry-copy">
          <strong>${number ? `#${escapeHtml(number)} · ` : ""}${escapeHtml(driver)}</strong>
          <span>${escapeHtml(team)}</span>
          <small>${escapeHtml(carMeta)}</small>
        </div>
        <div class="online-league-entry-side">
          <span class="online-league-entry-status ${statusClass(entry.status)}">${escapeHtml(entry.status || "warning")}</span>
          <button type="button" data-entry-edit="${escapeHtml(entry.id || "")}" aria-expanded="false">Edit</button>
        </div>
        <div class="online-league-entry-editor" hidden>
          <div class="online-league-entry-fields">
            <label>#<input data-entry-field="number" value="${escapeHtml(editValues.number)}" spellcheck="false" /></label>
            <label>Driver<input data-entry-field="driver" value="${escapeHtml(editValues.driver)}" spellcheck="false" /></label>
            <label>Team<input data-entry-field="team" value="${escapeHtml(editValues.team)}" spellcheck="false" /></label>
            <label>Car<input data-entry-field="car" value="${escapeHtml(editValues.car)}" spellcheck="false" /></label>
            <label>Class<input data-entry-field="class" value="${escapeHtml(editValues.class)}" spellcheck="false" /></label>
            <label>Notes<input data-entry-field="notes" value="${escapeHtml(editValues.notes)}" spellcheck="false" /></label>
          </div>
          <div class="online-league-entry-editor-actions">
            <button type="button" data-entry-cancel="${escapeHtml(entry.id || "")}">Cancel</button>
            <button type="button" class="primary" data-entry-save="${escapeHtml(entry.id || "")}" data-icon="save">Save</button>
          </div>
        </div>
        ${entryIssues(entry).length ? `<div class="online-league-entry-issues">${entryIssues(entry).map((line) => `<span>${escapeHtml(line)}</span>`).join("")}</div>` : ""}
      `;
      list.appendChild(row);
      const image = row.querySelector("img");
      loadThumbnail(entry, image).then(() => {
        if (image?.src) {
          image.hidden = false;
          row.querySelector(".online-league-thumb span")?.setAttribute("hidden", "");
        }
      });
    });
    list.querySelectorAll("[data-entry-save]").forEach((button) => {
      button.addEventListener("click", () => saveEntry(button.dataset.entrySave || ""));
    });
    list.querySelectorAll(".online-league-entry").forEach((row) => {
      row.querySelectorAll("[data-entry-field]").forEach((input) => {
        input.addEventListener("input", () => captureEntryDraft(row.dataset.entryId || "", row));
      });
    });
    list.querySelectorAll("[data-entry-edit]").forEach((button) => {
      button.addEventListener("click", () => {
        const row = button.closest(".online-league-entry");
        toggleEntryEditor(button.dataset.entryEdit || "", !row?.classList.contains("is-editing"));
      });
    });
    list.querySelectorAll("[data-entry-cancel]").forEach((button) => {
      button.addEventListener("click", () => cancelEntryEdit(button.dataset.entryCancel || ""));
    });
  }

  function toggleEntryEditor(entryId, open) {
    const row = document.querySelector(`.online-league-entry[data-entry-id="${cssEscape(entryId)}"]`);
    const editor = row?.querySelector(".online-league-entry-editor");
    if (editor) editor.hidden = !open;
    row?.classList.toggle("is-editing", Boolean(open));
    const button = row?.querySelector("[data-entry-edit]");
    if (button) {
      button.textContent = open ? "Close" : "Edit";
      button.setAttribute("aria-expanded", String(Boolean(open)));
    }
  }

  function cancelEntryEdit(entryId) {
    const project = state.selectedProject;
    const entry = (project?.entries || []).find((item) => String(item.id || "") === String(entryId || ""));
    const row = document.querySelector(`.online-league-entry[data-entry-id="${cssEscape(entryId)}"]`);
    if (project) delete state.entryDrafts[entryDraftKey(project, entryId)];
    if (entry && row) {
      const values = entryFieldValues(entry);
      row.querySelectorAll("[data-entry-field]").forEach((input) => {
        input.value = values[input.dataset.entryField] || "";
      });
    }
    toggleEntryEditor(entryId, false);
    updateDraftSaveState();
  }

  function renderDetail() {
    const project = selectedProject();
    state.selectedProject = project;
    const empty = $("onlineLeagueEmpty");
    const detail = $("onlineLeagueProjectDetail");
    if (!project) {
      if (empty) empty.hidden = false;
      if (detail) detail.hidden = true;
      setStatus("onlineLeagueStatus", "Create or select a league pack.", "unknown");
      setDraftSaveState(false);
      return;
    }
    if (empty) empty.hidden = true;
    if (detail) detail.hidden = false;
    if ($("onlineLeagueProjectTitle")) $("onlineLeagueProjectTitle").textContent = project.name || project.id || "League Pack";
    if ($("onlineLeagueProjectMeta")) $("onlineLeagueProjectMeta").textContent = `Version ${project.packVersion || "1.0.0"}`;
    const projectValues = state.projectDrafts[projectDraftKey(project)] || projectFieldValues(project);
    if ($("onlineLeagueEditName")) $("onlineLeagueEditName").value = projectValues.name;
    if ($("onlineLeagueEditVersion")) $("onlineLeagueEditVersion").value = projectValues.packVersion;
    if ($("onlineLeagueEditNotes")) $("onlineLeagueEditNotes").value = projectValues.notes;
    if ($("onlineLeagueProjectPreviewStage")) {
      $("onlineLeagueProjectPreviewStage").innerHTML = projectMarkHtml(project, { large: true });
      loadProjectThumbnailImages($("onlineLeagueProjectPreviewStage"));
    }
    renderSummary(project);
    renderEntryList(project);
    updateDraftSaveState();
    setStatus("onlineLeagueStatus", "Local draft ready. Build League Pack exports the ZIP.", "ok");
  }

  function renderAll() {
    currentScope();
    setLeagueView(state.activeView);
    renderProjectList();
    renderInstalledList();
    renderDetail();
    window.decorateIconButtons?.($("tab-online-league") || document);
  }

  async function refresh() {
    if (String(document.body?.dataset.workflowScope || "").toLowerCase() !== "official") return;
    const bridge = api();
    if (!bridge?.get_online_league_overview) {
      setStatus("onlineLeagueStatus", "Waiting for app bridge...", "warning");
      setStatus("onlineLeagueInstallStatus", "Waiting for app bridge...", "warning");
      window.clearTimeout(state.bridgeRetryTimer);
      state.bridgeRetryTimer = window.setTimeout(refresh, 500);
      return;
    }
    window.clearTimeout(state.bridgeRetryTimer);
    const result = await bridge.get_online_league_overview({ scope: "official" });
    if (!result?.ok) {
      setStatus("onlineLeagueStatus", "Could not load Online League data.", "error");
      setStatus("onlineLeagueInstallStatus", "Could not load Online League data.", "error");
      showModal("error", "Online League", result?.message || "Could not load Online League data.", resultDetails(result));
      return;
    }
    state.overview = result.data || {};
    if (!selectedProject()) {
      const scoped = (state.overview.projects || []).find((project) => String(project.workflowScope || "") === currentScope());
      state.selectedScope = scoped?.workflowScope || currentScope();
      state.selectedProjectId = scoped?.id || "";
    }
    renderAll();
  }

  async function createProject() {
    const bridge = api();
    let name = "New League Pack";
    if (typeof window.showInputModal === "function") {
      const value = await window.showInputModal({
        type: "info",
        title: "New League Pack",
        subtitle: "Official Pack Builder",
        message: "Create a local organizer draft. You can change its version and details afterwards.",
        label: "Pack name",
        value: name,
        confirmLabel: "Create Pack",
      });
      if (value === null) return;
      name = String(value || "").trim() || name;
    } else {
      const value = window.prompt("League pack name", name);
      if (value === null) return;
      name = String(value || "").trim() || name;
    }
    const payload = {
      workflowScope: currentScope(),
      name,
      packVersion: "1.0.0",
    };
    const result = await bridge.create_online_league_project(payload);
    if (!result?.ok) {
      showModal("error", "Create League Pack", result?.message || "Could not create league pack.", resultDetails(result));
      return;
    }
    state.selectedScope = result.data?.workflowScope || payload.workflowScope;
    state.selectedProjectId = result.data?.id || "";
    setLeagueView("builder");
    await refresh();
    setStatus("onlineLeagueStatus", "Local draft created.", "ok");
  }

  async function saveProject() {
    const project = state.selectedProject;
    if (!project) return;
    const result = await api().update_online_league_project({
      workflowScope: project.workflowScope,
      id: project.id,
      name: $("onlineLeagueEditName")?.value || "",
      packVersion: $("onlineLeagueEditVersion")?.value || "",
      notes: $("onlineLeagueEditNotes")?.value || "",
    });
    if (!result?.ok) {
      showModal("error", "Save League Pack", result?.message || "Could not save league pack.", resultDetails(result));
      return;
    }
    delete state.projectDrafts[projectDraftKey(project)];
    await refresh();
    setStatus("onlineLeagueStatus", "Local draft saved.", "ok");
  }

  async function chooseProjectThumbnail() {
    const project = state.selectedProject;
    if (!project) return;
    if (!api()?.choose_path || !api()?.update_online_league_project_thumbnail) {
      showModal("error", "League Thumbnail", "Thumbnail picker is not available in this build.");
      return;
    }
    const picked = await api().choose_path("file", ["PNG (*.png)", "All files (*.*)"], "");
    if (!picked?.ok || !picked.data?.path) return;
    const button = $("chooseOnlineLeagueThumbnail");
    const previousText = button?.textContent || "";
    if (button) {
      button.disabled = true;
      button.textContent = "Saving...";
    }
    try {
      const result = await api().update_online_league_project_thumbnail({
        workflowScope: project.workflowScope,
        projectId: project.id,
        thumbnailPng: picked.data.path,
      });
      if (!result?.ok) {
        showModal("error", "League Thumbnail", result?.message || "Could not save thumbnail.", resultDetails(result));
        return;
      }
      state.selectedProjectId = result.data?.id || project.id;
      await refresh();
      setStatus("onlineLeagueStatus", "League thumbnail saved.", "ok");
    } finally {
      if (button) {
        button.disabled = false;
        button.textContent = previousText || "Choose PNG";
      }
    }
  }

  async function saveEntry(entryId) {
    const project = state.selectedProject;
    const row = document.querySelector(`.online-league-entry[data-entry-id="${cssEscape(entryId)}"]`);
    if (!project || !row) return;
    const payload = { workflowScope: project.workflowScope, projectId: project.id, entryId };
    row.querySelectorAll("[data-entry-field]").forEach((input) => {
      payload[input.dataset.entryField] = input.value || "";
    });
    const result = await api().update_online_league_entry(payload);
    if (!result?.ok) {
      showModal("error", "Save League Entry", result?.message || "Could not save league entry.", resultDetails(result));
      return;
    }
    delete state.entryDrafts[entryDraftKey(project, entryId)];
    state.selectedProjectId = result.data?.id || project.id;
    await refresh();
    setStatus("onlineLeagueStatus", "Entry saved to local draft.", "ok");
  }

  async function pickImport(kind) {
    const bridge = api();
    const allowMultiple = kind === "zip";
    const initialDirectory = state.importSourcePaths[0] || $("onlineLeagueImportPath")?.value || "";
    const result = await bridge.choose_path(kind === "folder" ? "folder" : "file", kind === "folder" ? ["All files (*.*)"] : ["ZIP (*.zip)", "All files (*.*)"], "", initialDirectory, allowMultiple);
    if (result?.ok && $("onlineLeagueImportPath")) {
      const paths = Array.isArray(result.data?.paths) ? result.data.paths.filter(Boolean) : [];
      state.importSourcePaths = paths.length ? paths : (result.data?.path ? [result.data.path] : []);
      if (state.importSourcePaths.length > 1) {
        $("onlineLeagueImportPath").value = `${state.importSourcePaths.length} ZIP files selected`;
      } else {
        $("onlineLeagueImportPath").value = state.importSourcePaths[0] || "";
      }
      if (state.importSourcePaths.length) await importEntry();
    }
    else if (result && !result.ok) showModal("error", "Choose import source", result.message || "Path selection failed.", resultDetails(result));
  }

  async function importEntry() {
    const project = state.selectedProject;
    const typedSource = $("onlineLeagueImportPath")?.value || "";
    const sourcePaths = state.importSourcePaths.length ? state.importSourcePaths : (typedSource.trim() ? [typedSource.trim()] : []);
    if (!project || !sourcePaths.length) {
      setStatus("onlineLeagueStatus", "Select a league pack and import source first.", "warning");
      return;
    }
    const failures = [];
    let imported = 0;
    for (const [index, sourcePath] of sourcePaths.entries()) {
      setStatus("onlineLeagueStatus", `Importing league livery ${index + 1} / ${sourcePaths.length}...`, "warning");
      const result = await api().import_online_league_entry({ workflowScope: project.workflowScope, projectId: project.id, sourcePath });
      if (!result?.ok) {
        failures.push(`${sourcePath}: ${result?.message || "Import failed."}`);
        continue;
      }
      imported += 1;
      state.selectedProjectId = result.data?.id || project.id;
    }
    clearImportSource();
    await refresh();
    if (failures.length) {
      setStatus("onlineLeagueStatus", `${imported} imported, ${failures.length} failed.`, imported ? "warning" : "error");
      showModal(imported ? "warning" : "error", "Import League Liveries", `${imported} of ${sourcePaths.length} imports completed.`, failures.join("\n"));
      return;
    }
    setStatus("onlineLeagueStatus", `${imported} league livery${imported === 1 ? "" : "ies"} imported.`, "ok");
  }

  async function runPreflight() {
    const project = state.selectedProject;
    if (!project) return;
    const result = await api().run_online_league_preflight({ workflowScope: project.workflowScope, projectId: project.id });
    if (!result?.ok) {
      showModal("error", "Online League Preflight", result?.message || "Preflight failed.", resultDetails(result));
      return;
    }
    await refresh();
  }

  async function pickExportDir() {
    const result = await api().choose_path("folder", ["All files (*.*)"], "", $("onlineLeagueExportDir")?.value || "");
    if (result?.ok && result.data?.path && $("onlineLeagueExportDir")) $("onlineLeagueExportDir").value = result.data.path;
  }

  async function buildPack() {
    const project = state.selectedProject;
    if (!project) return;
    const result = await api().build_online_league_pack({
      workflowScope: project.workflowScope,
      projectId: project.id,
      targetDir: $("onlineLeagueExportDir")?.value || "",
      includeWarnings: Boolean($("onlineLeagueIncludeWarnings")?.checked),
    });
    if (!result?.ok) {
      showModal("error", "Build League Pack", result?.message || "Export failed.", resultDetails(result));
      return;
    }
    showModal("success", "Build League Pack", result.message || "League pack exported.", "", result.data?.zipPath || result.data?.bundlePath || "");
    await refresh();
  }

  async function pickInstallZip() {
    const result = await api().choose_path("file", ["LiveryLab League ZIP (*.zip)", "ZIP (*.zip)", "All files (*.*)"], "", $("onlineLeagueInstallPath")?.value || "");
    if (result?.ok && result.data?.path && $("onlineLeagueInstallPath")) {
      $("onlineLeagueInstallPath").value = result.data.path;
      state.installInfo = null;
      $("importOnlineLeaguePack").disabled = true;
      await inspectInstallZip();
    }
  }

  async function inspectInstallZip() {
    const path = $("onlineLeagueInstallPath")?.value || "";
    if (!path.trim()) {
      setStatus("onlineLeagueInstallStatus", "Choose a league pack ZIP.", "warning");
      return;
    }
    const result = await api().inspect_online_league_pack(path);
    if (!result?.ok) {
      state.installInfo = null;
      $("importOnlineLeaguePack").disabled = true;
      setStatus("onlineLeagueInstallStatus", result?.message || "Inspection failed.", "error");
      return;
    }
    state.installInfo = result.data || {};
    const packageScope = String(state.installInfo.workflowScope || "");
    const activeScope = currentScope();
    if (packageScope !== activeScope) {
      $("importOnlineLeaguePack").disabled = true;
      setStatus("onlineLeagueInstallStatus", `${workflowLabel(packageScope)} pack cannot be imported while ${workflowLabel(activeScope)} is active.`, "warning");
      return;
    }
    $("importOnlineLeaguePack").disabled = false;
    setStatus("onlineLeagueInstallStatus", `${workflowLabel(packageScope)} pack: ${state.installInfo.entryCount || 0} entries.`, "ok");
  }

  async function importLeaguePack() {
    const path = $("onlineLeagueInstallPath")?.value || "";
    if (!path.trim() || !state.installInfo) {
      setStatus("onlineLeagueInstallStatus", "Inspect a league pack ZIP first.", "warning");
      return;
    }
    const result = await api().import_online_league_pack({ packagePath: path, expectedWorkflowScope: currentScope() });
    if (!result?.ok) {
      showModal("error", "Import League Pack", result?.message || "Import failed.", resultDetails(result));
      return;
    }
    showModal("success", "Import League Pack", result.message || "League pack imported locally.", "", result.data?.installedRoot || "");
    state.installInfo = null;
    if ($("onlineLeagueInstallPath")) $("onlineLeagueInstallPath").value = "";
    if ($("importOnlineLeaguePack")) $("importOnlineLeaguePack").disabled = true;
    setLeagueView("installed");
    await refresh();
  }

  function bind() {
    if (!$("tab-online-league")) return;
    $("refreshOnlineLeague")?.addEventListener("click", refresh);
    $("onlineLeagueViewInstalled")?.addEventListener("click", () => setLeagueView("installed"));
    $("onlineLeagueViewBuilder")?.addEventListener("click", () => setLeagueView("builder"));
    $("createOnlineLeagueProject")?.addEventListener("click", createProject);
    $("saveOnlineLeagueProject")?.addEventListener("click", saveProject);
    ["onlineLeagueEditName", "onlineLeagueEditVersion", "onlineLeagueEditNotes"].forEach((id) => {
      $(id)?.addEventListener("input", captureProjectDraft);
    });
    $("chooseOnlineLeagueThumbnail")?.addEventListener("click", chooseProjectThumbnail);
    $("pickOnlineLeagueEntryZip")?.addEventListener("click", () => pickImport("zip"));
    $("pickOnlineLeagueEntryFolder")?.addEventListener("click", () => pickImport("folder"));
    $("runOnlineLeaguePreflight")?.addEventListener("click", runPreflight);
    $("pickOnlineLeagueExportDir")?.addEventListener("click", pickExportDir);
    $("buildOnlineLeaguePack")?.addEventListener("click", buildPack);
    $("pickOnlineLeagueInstallZip")?.addEventListener("click", pickInstallZip);
    $("importOnlineLeaguePack")?.addEventListener("click", importLeaguePack);
    const refreshWhenOfficial = () => {
      if (String(document.body?.dataset.workflowScope || "").toLowerCase() === "official") refresh();
    };
    if (document.body) {
      new MutationObserver(refreshWhenOfficial).observe(document.body, { attributes: true, attributeFilter: ["data-workflow-scope"] });
    }
    refreshWhenOfficial();
  }

  window.LiveryLabOnlineLeague = { refresh };

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