(() => {
  const initializedForms = new WeakSet();
  const initializedExpandables = new WeakSet();
  const REFRESH_COOLDOWN_MS = 3000;
  let saveBar = null;
  let stream = null;
  let lastScrollY = window.scrollY;

  const init = (root = document) => {
    initSettingsDirty(root);
    initExpandables(root);
    initSoftNavigation(root);
  };

  const ensureSaveBar = () => {
    if (saveBar) return saveBar;
    saveBar = document.createElement("div");
    saveBar.className = "lumi-savebar";
    saveBar.hidden = true;
    saveBar.innerHTML = `
      <div>
        <strong data-savebar-count>Unsaved changes</strong>
        <span class="hint" data-savebar-status>Review and save changed settings on this page.</span>
      </div>
      <button type="button" class="button" data-savebar-submit>Save changes</button>
    `;
    document.body.append(saveBar);
    saveBar.querySelector("[data-savebar-submit]").addEventListener("click", saveDirtyForms);
    window.addEventListener("scroll", updateSaveBarScroll, { passive: true });
    return saveBar;
  };

  const formFields = (form) => Array.from(form.elements).filter((field) =>
    field.name && !field.disabled && !["submit", "button", "reset", "file"].includes(field.type)
  );

  const fieldValue = (field) => {
    if (field.type === "checkbox") return field.checked ? "on" : "";
    if (field.type === "radio") return field.checked ? field.value : "";
    return field.value;
  };

  const snapshotForm = (form) => {
    const snapshot = new Map();
    for (const field of formFields(form)) {
      if (field.type === "radio") {
        if (!snapshot.has(field.name)) snapshot.set(field.name, "");
        if (field.checked) snapshot.set(field.name, field.value);
      } else {
        snapshot.set(field.name, fieldValue(field));
      }
    }
    return snapshot;
  };

  const isFieldDirty = (field, snapshot) => {
    const original = snapshot.get(field.name) || "";
    if (field.type === "radio") {
      return field.checked && field.value !== original;
    }
    return fieldValue(field) !== original;
  };

  const updateDirtyState = () => {
    const forms = Array.from(document.querySelectorAll("form[data-lumi-settings-form]"));
    let dirtyCount = 0;
    for (const form of forms) {
      const snapshot = form._lumiSnapshot || snapshotForm(form);
      let formDirty = false;
      for (const field of formFields(form)) {
        const dirty = isFieldDirty(field, snapshot);
        const container = field.closest(".field, .theme-color-control, .theme-range-control, .theme-select-control, fieldset");
        container?.classList.toggle("is-unsaved", dirty);
        formDirty = formDirty || dirty;
        if (dirty) dirtyCount += 1;
      }
      form.classList.toggle("has-unsaved-settings", formDirty);
    }
    const bar = ensureSaveBar();
    bar.hidden = dirtyCount === 0;
    bar.classList.toggle("is-visible", dirtyCount > 0);
    bar.querySelector("[data-savebar-count]").textContent =
      dirtyCount === 1 ? "1 unsaved setting" : `${dirtyCount} unsaved settings`;
    if (dirtyCount === 0) bar.querySelector("[data-savebar-status]").textContent = "Saved.";
    updateSaveBarScroll();
  };

  function initSettingsDirty(root) {
    root.querySelectorAll?.("form[data-lumi-settings-form]").forEach((form) => {
      if (initializedForms.has(form)) return;
      initializedForms.add(form);
      form._lumiSnapshot = snapshotForm(form);
      form.addEventListener("input", updateDirtyState);
      form.addEventListener("change", updateDirtyState);
      form.addEventListener("submit", () => {
        form._lumiSnapshot = snapshotForm(form);
        window.setTimeout(updateDirtyState, 0);
      });
    });
    if (document.querySelector("form[data-lumi-settings-form]")) {
      ensureSaveBar();
      updateDirtyState();
      window.addEventListener("beforeunload", warnDirtyNavigation);
    }
  }

  async function saveDirtyForms() {
    const bar = ensureSaveBar();
    const button = bar.querySelector("[data-savebar-submit]");
    const status = bar.querySelector("[data-savebar-status]");
    const forms = Array.from(document.querySelectorAll("form[data-lumi-settings-form].has-unsaved-settings"));
    if (!forms.length) return;
    button.disabled = true;
    status.textContent = "Saving...";
    try {
      for (const form of forms) {
        const body = new URLSearchParams();
        for (const [key, value] of new FormData(form).entries()) {
          if (typeof value === "string") body.append(key, value);
        }
        const response = await fetch(form.action || window.location.href, {
          method: form.method || "POST",
          body,
          headers: {
            Accept: "text/html,application/json",
            "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
          },
          redirect: "follow"
        });
        if (!response.ok) throw new Error(`Save failed for ${form.action || "settings form"}.`);
        form._lumiSnapshot = snapshotForm(form);
      }
      status.textContent = "Saved. Reloading...";
      window.removeEventListener("beforeunload", warnDirtyNavigation);
      window.setTimeout(() => window.location.reload(), 75);
    } catch (error) {
      status.textContent = error.message || "Save failed.";
      bar.classList.add("has-error");
    } finally {
      button.disabled = false;
      window.setTimeout(() => bar.classList.remove("has-error"), 2500);
    }
  }

  function warnDirtyNavigation(event) {
    if (!document.querySelector("form[data-lumi-settings-form].has-unsaved-settings")) return;
    event.preventDefault();
    event.returnValue = "";
  }

  function updateSaveBarScroll() {
    if (!saveBar || saveBar.hidden) return;
    const canScroll = document.documentElement.scrollHeight > window.innerHeight + 12;
    const next = window.scrollY;
    saveBar.classList.toggle("is-hidden-by-scroll", canScroll && next > lastScrollY + 4);
    lastScrollY = next;
  }

  function initExpandables(root) {
    root.querySelectorAll?.("[data-lumi-expandable-settings]").forEach((item) => {
      if (initializedExpandables.has(item)) return;
      initializedExpandables.add(item);
      item.querySelectorAll("[data-placeholder-preview]").forEach(updatePlaceholderPreview);
      item.addEventListener("input", () => {
        item.querySelectorAll("[data-placeholder-preview]").forEach(updatePlaceholderPreview);
      });
    });
  }

  function updatePlaceholderPreview(target) {
    const source = target.closest("[data-lumi-expandable-settings]")?.querySelector(target.dataset.placeholderPreview);
    const text = source?.value || target.dataset.fallback || "";
    const replacements = {
      gifter_username: "SomeUser123",
      item_name: "Cool Item",
      creator_username: "CreatorName",
      amount_display: "$12.34",
      username: "SomeUser123",
      platform: "Twitch"
    };
    target.textContent = text.replace(/\{([^{}]+)\}/g, (full, key) => replacements[key] || full);
  }

  function connectEvents() {
    if (!window.EventSource || stream) return;
    stream = new EventSource("/api/events");
    stream.addEventListener("server:warning", (event) => showEventNotice(readEvent(event), "warning"));
    stream.addEventListener("server:status", (event) => {
      const data = readEvent(event);
      if (data.status === "connected") document.body.dataset.eventStream = "connected";
    });
    stream.addEventListener("ai:model_status", (event) => showEventNotice(readEvent(event), "danger"));
    stream.addEventListener("data:new_available", (event) => showRefreshPrompt(readEvent(event)));
    stream.onerror = () => {
      document.body.dataset.eventStream = "disconnected";
    };
  }

  function readEvent(event) {
    try { return JSON.parse(event.data || "{}"); } catch { return {}; }
  }

  function noticeRoot() {
    let root = document.querySelector("[data-lumi-event-notices]");
    if (!root) {
      root = document.createElement("div");
      root.className = "lumi-event-notices";
      root.dataset.lumiEventNotices = "";
      document.body.append(root);
    }
    return root;
  }

  function showEventNotice(data, tone = "info") {
    const item = document.createElement("div");
    item.className = `lumi-event-notice ${tone}`;
    item.setAttribute("role", tone === "danger" ? "alert" : "status");
    item.textContent = data.message || data.status || "Lumi status changed.";
    noticeRoot().append(item);
    window.setTimeout(() => item.remove(), 9000);
  }

  function showRefreshPrompt(data) {
    const item = document.createElement("div");
    item.className = "lumi-refresh-prompt";
    item.setAttribute("role", "status");
    const label = document.createElement("span");
    label.textContent = data.message || "New data is available.";
    const button = document.createElement("button");
    button.type = "button";
    button.className = "button subtle";
    button.textContent = "Refresh";
    button.addEventListener("click", () => {
      button.disabled = true;
      window.setTimeout(() => { button.disabled = false; }, REFRESH_COOLDOWN_MS);
      if (data.url) window.location.assign(data.url);
      else window.location.reload();
    });
    item.append(label, button);
    noticeRoot().append(item);
  }

  function initSoftNavigation(root) {
    root.querySelectorAll?.("a[href]").forEach((link) => {
      if (link.dataset.softNavBound || link.target || link.hasAttribute("download")) return;
      const url = new URL(link.href, window.location.href);
      if (url.origin !== window.location.origin || url.pathname.startsWith("/auth/")) return;
      link.dataset.softNavBound = "true";
      link.addEventListener("click", (event) => {
        if (event.defaultPrevented || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
        const main = document.querySelector("main.content");
        if (!main || document.querySelector("form[data-lumi-settings-form].has-unsaved-settings")) return;
        event.preventDefault();
        softNavigate(url.href);
      });
    });
  }

  async function softNavigate(url, push = true) {
    const main = document.querySelector("main.content");
    if (!main) return window.location.assign(url);
    main.classList.add("is-soft-loading");
    try {
      const response = await fetch(url, { headers: { "X-Lumi-Soft-Navigation": "1" } });
      if (!response.ok) throw new Error("Navigation failed.");
      const html = await response.text();
      const doc = new DOMParser().parseFromString(html, "text/html");
      const nextMain = doc.querySelector("main.content");
      if (!nextMain) throw new Error("Navigation target did not contain page content.");
      document.title = doc.title || document.title;
      main.replaceChildren(...Array.from(nextMain.childNodes));
      main.classList.remove("is-soft-loading");
      main.classList.add("is-soft-loaded");
      window.setTimeout(() => main.classList.remove("is-soft-loaded"), 180);
      updateActiveNavigation(new URL(url, window.location.href).pathname);
      if (push) history.pushState({}, "", url);
      init(main);
      executePageScripts(main);
      window.scrollTo({ top: 0, behavior: "auto" });
    } catch {
      window.location.assign(url);
    }
  }

  function updateActiveNavigation(pathname) {
    document.querySelectorAll(".nav-link").forEach((link) => {
      const url = new URL(link.href, window.location.href);
      link.classList.toggle("active", url.pathname === pathname || (url.pathname !== "/" && pathname.startsWith(`${url.pathname}/`)));
    });
  }

  function executePageScripts(root) {
    root.querySelectorAll("script").forEach((script) => {
      const next = document.createElement("script");
      for (const attr of script.attributes) next.setAttribute(attr.name, attr.value);
      next.textContent = script.textContent;
      script.replaceWith(next);
    });
  }

  window.addEventListener("popstate", () => softNavigate(window.location.href, false));
  window.LumiInteractions = { init, connectEvents, showEventNotice, showRefreshPrompt };
  document.addEventListener("DOMContentLoaded", () => {
    init(document);
    connectEvents();
  });
})();
