const BRAND = window.__UI_PATCHER_BRAND__ || {};
const BRAND_ICON_URL = "/plugins/ui-whatsynaptor/assets/logo.svg";

function text(value) {
  return typeof value === "string" ? value.trim() : "";
}

function setDocumentBranding() {
  document.documentElement.setAttribute("data-ui-whatsynaptor", "active");
  const title = text(BRAND.browserTitle);
  if (title) {
    document.title = title;
  }
}

function updateFavicon() {
  const faviconUrl = text(BRAND.faviconUrl) || BRAND_ICON_URL;
  if (!faviconUrl) return;

  const selectors = [
    'link[rel="icon"][type="image/svg+xml"]',
    'link[rel="icon"][sizes="32x32"]',
    'link[rel="apple-touch-icon"]',
  ];

  for (const selector of selectors) {
    const node = document.querySelector(selector);
    if (node instanceof HTMLLinkElement) {
      node.href = faviconUrl;
    }
  }
}

function forceDarkTheme() {
  document.documentElement.setAttribute("data-theme-mode", "dark");
  document.documentElement.setAttribute("data-theme", "claw");
  document.documentElement.style.colorScheme = "dark";

  try {
    for (const key of Object.keys(window.localStorage)) {
      if (!key.includes("openclaw.control.settings.v1")) continue;
      const raw = window.localStorage.getItem(key);
      if (!raw) continue;
      const parsed = JSON.parse(raw);
      if (!parsed || typeof parsed !== "object") continue;
      let changed = false;
      if (parsed.themeMode !== "dark") {
        parsed.themeMode = "dark";
        changed = true;
      }
      if (parsed.theme !== "claw") {
        parsed.theme = "claw";
        changed = true;
      }
      if (!changed) continue;
      window.localStorage.setItem(key, JSON.stringify(parsed));
    }
  } catch {}
}

function ensureThemeOverrides() {
  let style = document.getElementById("ui-whatsynaptor-theme-overrides");
  if (!(style instanceof HTMLStyleElement)) {
    style = document.createElement("style");
    style.id = "ui-whatsynaptor-theme-overrides";
    document.head.append(style);
  }

  style.textContent = `
    html[data-ui-whatsynaptor="active"] {
      --bg: #12141a !important;
      --bg-accent: #14161d !important;
      --bg-elevated: #1a1d25 !important;
      --bg-hover: #262a35 !important;
      --bg-muted: #262a35 !important;
      --card: #181b22 !important;
      --card-foreground: #f4f4f5 !important;
      --popover: #181b22 !important;
      --popover-foreground: #f4f4f5 !important;
      --panel: #12141a !important;
      --panel-strong: #1a1d25 !important;
      --panel-hover: #262a35 !important;
      --chrome: rgba(18, 20, 26, 0.95) !important;
      --chrome-strong: rgba(18, 20, 26, 0.98) !important;
      --text: #e4e4e7 !important;
      --text-strong: #fafafa !important;
      --chat-text: #e4e4e7 !important;
      --muted: #71717a !important;
      --muted-strong: #52525b !important;
      --muted-foreground: #71717a !important;
      --border: #27272a !important;
      --border-strong: #3f3f46 !important;
      --border-hover: #52525b !important;
      --input: #27272a !important;
    }

    html[data-ui-whatsynaptor="active"] .nav-item__icon,
    html[data-ui-whatsynaptor="active"] .nav-collapse-toggle__icon,
    html[data-ui-whatsynaptor="active"] .nav-item__external-icon {
      color: var(--ui-brand-accent, #3d8f6e) !important;
      text-shadow: none !important;
    }
  `;
}

function patchKnownBrandSurfaces() {
  const brandName = text(BRAND.appName);
  const logoUrl = text(BRAND.logoUrl);
  const labelSelectors = [
    ".sidebar-brand__title",
    ".dashboard-header__breadcrumb-link",
    ".sidebar-title",
    ".sidebar-brand-title",
    ".nav-brand-title",
    ".app-brand-title",
  ];
  const eyebrowSelectors = [
    ".sidebar-brand__eyebrow",
    ".sidebar-kicker",
    ".sidebar-brand-kicker",
    ".nav-brand-kicker",
    ".app-brand-kicker",
  ];
  const logoSelectors = [
    ".sidebar-brand__logo",
    ".agent-chat__avatar--logo",
    ".sidebar-logo img",
    ".sidebar-brand img",
    ".nav-brand img",
    ".app-brand img",
  ];

  if (brandName) {
    for (const selector of labelSelectors) {
      for (const node of document.querySelectorAll(selector)) {
        if (node instanceof HTMLElement) {
          node.textContent = brandName;
        }
      }
    }
  }

  const eyebrow = text(BRAND.sidebarEyebrow);
  if (eyebrow) {
    for (const selector of eyebrowSelectors) {
      for (const node of document.querySelectorAll(selector)) {
        if (node instanceof HTMLElement) {
          node.textContent = eyebrow;
        }
      }
    }
  }

  if (logoUrl) {
    for (const selector of logoSelectors) {
      for (const node of document.querySelectorAll(selector)) {
        if (node instanceof HTMLImageElement) {
          node.src = logoUrl;
          node.alt = brandName || "Brand";
        } else if (node instanceof HTMLElement) {
          node.style.backgroundImage = `url("${logoUrl}")`;
          node.style.backgroundSize = "contain";
          node.style.backgroundPosition = "center";
          node.style.backgroundRepeat = "no-repeat";
        }
      }
    }
  }

  for (const node of document.querySelectorAll(".agent-chat__avatar--logo")) {
    if (node instanceof HTMLImageElement) {
      node.src = BRAND_ICON_URL;
      node.alt = brandName || "Whatsynaptic";
    } else if (node instanceof HTMLElement) {
      node.style.backgroundImage = `url("${BRAND_ICON_URL}")`;
      node.style.backgroundSize = "contain";
      node.style.backgroundPosition = "center";
      node.style.backgroundRepeat = "no-repeat";
    }
  }
}

function patchTopbarVideo() {
  const topbarVideoUrl = text(BRAND.topbarVideoUrl);
  if (!topbarVideoUrl) return;

  const topbar =
    document.querySelector(".topbar") ||
    document.querySelector('[class*="topbar"]') ||
    document.querySelector("header") ||
    document.querySelector("nav");
  if (!(topbar instanceof HTMLElement)) {
    // Not mounted yet — MutationObserver will retry
    return;
  }

  // Avoid duplicate layers
  let layer = topbar.querySelector(".ui-whatsynaptor-topbar-video-layer");
  if (!(layer instanceof HTMLDivElement)) {
    layer = document.createElement("div");
    layer.className = "ui-whatsynaptor-topbar-video-layer";
    layer.innerHTML =
      '<video class="ui-whatsynaptor-topbar-video" autoplay muted loop playsinline></video><div class="ui-whatsynaptor-topbar-video-scrim"></div>';
    topbar.prepend(layer);
  }

  const video = layer.querySelector(".ui-whatsynaptor-topbar-video");
  if (video instanceof HTMLVideoElement) {
    const resolved = new URL(topbarVideoUrl, location.href).href;
    if (video.src !== resolved) {
      video.src = resolved;
      video.load();
      video.play().catch(() => {});
    }
  }
}

function patchLoginGate() {
  const header = document.querySelector(".login-gate__header");
  if (!(header instanceof HTMLElement)) {
    return;
  }

  const brandName = text(BRAND.appName) || "OpenClaw Custom";

  const logo = header.querySelector(".login-gate__logo");
  if (logo instanceof HTMLImageElement) {
    logo.src = BRAND_ICON_URL;
    logo.alt = brandName;
  }

  const title = header.querySelector(".login-gate__title");
  if (title instanceof HTMLElement) {
    title.textContent = brandName;
  }

  const sub = header.querySelector(".login-gate__sub");
  if (sub instanceof HTMLElement) {
    sub.textContent = text(BRAND.sidebarEyebrow) || "Dashboard Login";
  }

  const help = document.querySelector(".login-gate__help");
  if (help instanceof HTMLElement) {
    help.hidden = true;
  }
}

function removeLegacyLoader() {
  const loader = document.querySelector(".ui-whatsynaptor-loader");
  if (loader instanceof HTMLElement) {
    loader.remove();
  }
}

let rafId = 0;
function runPatch() {
  rafId = 0;
  setDocumentBranding();
  updateFavicon();
  forceDarkTheme();
  ensureThemeOverrides();
  patchKnownBrandSurfaces();
  patchLoginGate();
  patchTopbarVideo();
  removeLegacyLoader();
}

function queuePatch() {
  if (rafId) return;
  rafId = window.requestAnimationFrame(runPatch);
}

queuePatch();
document.addEventListener("readystatechange", queuePatch);

const observer = new MutationObserver(() => {
  queuePatch();
  });
observer.observe(document.documentElement, {
  childList: true,
  subtree: true,
});
