(function () {
  const STYLE_ID = 'mishkalapka-theme-style';
  const CURSOR_OVERLAY_ID = 'mishka-cursor-overlay';
  const CURSOR_HIDE_ID = 'mishka-cursor-hide-style';
  const CURSOR_PX = 32;

  const SHELL_SEL = [
    'html', 'body', '#nav-bar', '#navigation', '#navigation-wrapper',
    '#navigation-background', '#left-navigation-background', '.rbx-left-col',
    '.left-col', '#left-column', '.rbx-navbar', 'nav.rbx-navbar',
    '.navbar-container', '.nav-content', '.navigation-container',
    '#header', '.rbx-header', '#container-main', '.container-main',
    '#main-container', '.main-container', '#content', '.content',
    '.rbx-content', 'main', '#home-page', '#page-container', '.page-content',
    '[data-testid="navigation"]', '[data-testid="home-page"]',
    '[class*="Navigation"]', '[class*="navigation-layout"]',
    '[class*="LeftNav"]', '[class*="left-nav"]', '[class*="Sidebar"]',
    'aside',
  ].join(', ');

  const LEFT_NAV_SEL = [
    '#navigation', '#navigation-wrapper', '#navigation-background',
    '#left-navigation-background', '.rbx-left-col', '.left-col',
    '#left-column', '#nav-bar', '.navigation-container',
    '[data-testid="navigation"]', '[class*="NavigationSidebar"]',
    '[class*="LeftNav"]', 'aside[class*="nav"]', 'aside',
  ].join(', ');

  const TOP_BAR_SEL = [
    '#header', '.rbx-header', '.navbar-container', '.nav-content',
    '.rbx-navbar', 'nav.rbx-navbar',
  ].join(', ');

  const ROBUX_SEL = [
    '#nav-robux-amount', '#navigation-robux-container', '.nav-robux-balance',
    '[data-testid="nav-robux"]', '[data-testid*="robux"]', '[data-testid*="Robux"]',
    'a[href*="/upgrades/robux"]', 'a[href*="robux"]',
    '[class*="robux-balance"]', '[class*="RobuxBalance"]', '[class*="icon-robux"]',
  ].join(', ');

  let cursorCleanup = null;
  let cachedSettings = null;
  let lastUrl = location.href;
  let applyPending = false;
  let applyForceNext = false;
  let applySettingsNext = null;
  let routeTimer = null;

  function normalizeSettings(raw) {
    const base = { ...MISHKA_DEFAULTS, ...(raw || {}) };
    for (const key of MISHKA_LOCAL_KEYS) {
      if (Array.isArray(raw?.[key]) || (raw?.[key] && typeof raw[key] === 'object')) {
        base[key] = raw[key];
      }
    }
    return base;
  }

  function getSettings() {
    return new Promise((resolve) => {
      chrome.storage.sync.get(MISHKA_DEFAULTS, (sync) => {
        chrome.storage.local.get(MISHKA_LOCAL_KEYS, (local) => {
          resolve({ ...MISHKA_DEFAULTS, ...sync, ...local });
        });
      });
    });
  }

  function cleanupAnimatedCursor() {
    if (cursorCleanup) {
      cursorCleanup();
      cursorCleanup = null;
    }
    document.getElementById(CURSOR_OVERLAY_ID)?.remove();
    document.getElementById(CURSOR_HIDE_ID)?.remove();
  }

  function wallpaperLayer(url, size, repeat) {
    return `
      html::before {
        content: "" !important;
        position: fixed !important;
        inset: 0 !important;
        width: 100vw !important;
        height: 100vh !important;
        height: 100dvh !important;
        min-width: 100vw !important;
        min-height: 100vh !important;
        min-height: 100dvh !important;
        z-index: -2147483647 !important;
        pointer-events: none !important;
        background-color: #0f0a12 !important;
        background-image: url("${url}") !important;
        background-size: ${size} !important;
        background-repeat: ${repeat} !important;
        background-position: center center !important;
      }
      html, body {
        background: transparent !important;
        min-height: 100vh !important;
        min-height: 100dvh !important;
      }
      ${SHELL_SEL} {
        background-color: transparent !important;
        background-image: none !important;
      }
      ${LEFT_NAV_SEL} {
        background: rgba(12, 8, 16, 0.58) !important;
        background-color: rgba(12, 8, 16, 0.58) !important;
        backdrop-filter: blur(12px) !important;
        -webkit-backdrop-filter: blur(12px) !important;
      }
      ${TOP_BAR_SEL}, ${TOP_BAR_SEL} > *, ${TOP_BAR_SEL} .rbx-navbar,
      ${TOP_BAR_SEL} .navbar-container, ${TOP_BAR_SEL} .nav-content {
        background: transparent !important;
        background-color: transparent !important;
        background-image: none !important;
        backdrop-filter: none !important;
        -webkit-backdrop-filter: none !important;
        border: none !important;
        box-shadow: none !important;
      }
      ${LEFT_NAV_SEL} li, ${LEFT_NAV_SEL} a, ${LEFT_NAV_SEL} div, ${LEFT_NAV_SEL} span {
        background-color: transparent !important;
      }
      ${LEFT_NAV_SEL} li:hover, ${LEFT_NAV_SEL} a:hover {
        background-color: rgba(200, 200, 212, 0.12) !important;
      }
    `;
  }

  function buildCursorCss(cursorUrl, hx, hy) {
    const cur = `url("${cursorUrl}") ${hx} ${hy}, auto`;
    const curPointer = `url("${cursorUrl}") ${hx} ${hy}, pointer`;
    return `
      html, html *, html *::before, html *::after,
      html *:hover, html *:active, html *:focus, html *:focus-visible {
        cursor: ${cur} !important;
      }
      html a, html button, html [role="button"], html [role="link"],
      html .game-card, html .game-card-container, html .game-card-link,
      html .rbx-menu-item, html .btn-primary, html .btn-control-md,
      html [class*="game-card"], html [class*="GameCard"] {
        cursor: ${curPointer} !important;
      }
      html input[type="text"], html input[type="search"], html input[type="email"],
      html input[type="password"], html textarea, html [contenteditable="true"] {
        cursor: text !important;
      }
    `;
  }

  function buildRobloxUiFixCss() {
    const glassActive = 'rgba(200, 200, 212, 0.22)';

    return `
      :root, .light-theme, .dark-theme {
        --background-default: transparent !important;
        --background-secondary: transparent !important;
        --background-tertiary: transparent !important;
        --surface-100: transparent !important;
        --surface-200: transparent !important;
        --surface-300: transparent !important;
        --color-surface-100: transparent !important;
        --color-surface-200: transparent !important;
        --color-surface-300: transparent !important;
      }

      .alert, .alert-info, .alert-warning, .alert-danger, .alert-success,
      .system-feedback, .interstitial-wrapper, .notification-blue,
      [class*="SystemFeedback"], [class*="system-feedback"],
      [class*="Interstitial"], [class*="interstitial"],
      [class*="AlertBanner"], [class*="alert-banner"],
      [class*="NotificationBar"], [class*="notification-bar"],
      [class*="GlobalAlert"], [class*="global-alert"],
      [class*="TopBanner"], [class*="top-banner"],
      [class*="CriticalBanner"], [class*="UrgentMessage"],
      [class*="PolicyBanner"], [class*="ExperienceGuidelines"],
      [data-testid*="system-feedback"], [data-testid*="alert-banner"],
      #global-message, .global-message, #GlobalMessage,
      #AccountSecurityPrompt, [class*="AccountSecurity"],
      #header [class*="alert"], #header [class*="Alert"],
      #header [class*="banner"], #header [class*="Banner"],
      #header [class*="feedback"], #header [class*="Feedback"],
      .rbx-header [class*="alert"], .rbx-header [class*="Alert"],
      .rbx-header [class*="banner"], .rbx-header [class*="Banner"],
      body > div[class*="interstitial"], body > div[id*="interstitial"] {
        display: none !important;
        height: 0 !important;
        min-height: 0 !important;
        max-height: 0 !important;
        overflow: hidden !important;
        opacity: 0 !important;
        pointer-events: none !important;
        margin: 0 !important;
        padding: 0 !important;
        border: none !important;
      }

      ${TOP_BAR_SEL}, ${TOP_BAR_SEL} a, ${TOP_BAR_SEL} button,
      ${TOP_BAR_SEL} span, ${TOP_BAR_SEL} div, ${TOP_BAR_SEL} p {
        color: #ececf0 !important;
      }

      ${ROBUX_SEL}, ${ROBUX_SEL} *, ${TOP_BAR_SEL} a[href*="robux"],
      ${TOP_BAR_SEL} a[href*="Robux"], ${TOP_BAR_SEL} [class*="robux"],
      ${TOP_BAR_SEL} [class*="Robux"] {
        opacity: 1 !important;
        visibility: visible !important;
        overflow: visible !important;
        color: #ffffff !important;
        -webkit-text-fill-color: #ffffff !important;
        text-shadow: 0 1px 4px rgba(0, 0, 0, 0.85) !important;
        background: transparent !important;
        background-color: transparent !important;
      }

      #navigation .rbx-highlight, #navigation li.rbx-highlight,
      #navigation .selected, #navigation [aria-current="page"],
      .rbx-left-col .rbx-highlight, .rbx-left-col li.rbx-highlight {
        background: ${glassActive} !important;
        background-color: ${glassActive} !important;
        color: #ececf0 !important;
        border-radius: 12px !important;
      }

      .game-card, .game-card-link, .game-card-container,
      [class*="GameCard"]:not(img), [class*="game-card"]:not(img),
      [class*="GameTile"]:not(img) {
        background: transparent !important;
        background-color: transparent !important;
        box-shadow: none !important;
      }

      .game-card:hover, .game-card-link:hover, .game-card-container:hover,
      .game-card:focus, .game-card-link:focus, .game-card-container:focus,
      .game-card:focus-within, .game-card-link:focus-within,
      .game-card-container:focus-within,
      [class*="game-card"]:not(img):hover,
      [class*="GameCard"]:not(img):hover,
      [class*="GameTile"]:not(img):hover {
        background: transparent !important;
        background-color: transparent !important;
        box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.18) !important;
      }

      .game-card *:not(img):not([class*="thumbnail"]),
      .game-card-link *:not(img):not([class*="thumbnail"]),
      [class*="GameCard"] *:not(img):not([class*="thumbnail"]) {
        background-color: transparent !important;
        background: transparent !important;
      }

      .game-card:hover *:not(img):not([class*="thumbnail"]),
      .game-card-link:hover *:not(img):not([class*="thumbnail"]),
      [class*="GameCard"]:hover *:not(img):not([class*="thumbnail"]) {
        background-color: transparent !important;
        background: transparent !important;
      }

      .game-card .game-card-name, .game-card-info,
      [class*="game-card-name"], [class*="GameCardFooter"],
      [class*="caption-container"], [class*="CaptionContainer"],
      [class*="metadata"], [class*="Metadata"], [class*="overlay"], [class*="Overlay"] {
        background-color: transparent !important;
        background: transparent !important;
      }

      .game-card img, .game-card-link img, .thumbnail-2d,
      img[src*="rbxcdn"], img[src*="roblox"] {
        background-color: transparent !important;
        opacity: 1 !important;
        visibility: visible !important;
      }

      .section, .section-content, .home-container, .feed-container,
      [class*="HomePage"], [class*="home-page"] {
        background-color: transparent !important;
        background: transparent !important;
      }
    `;
  }

  function resolveCursor(settings) {
    if (!settings.enabled || settings.cursorId === 'none') return null;

    if (settings.cursorId === MISHKA_CUSTOM.legacyCursorId && settings.customCursor?.dataUrl) {
      return {
        url: settings.customCursor.dataUrl,
        hx: settings.customCursor.hotspot?.[0] ?? 2,
        hy: settings.customCursor.hotspot?.[1] ?? 2,
        animated: Boolean(settings.customCursor.animated || /\.gif/i.test(settings.customCursor.dataUrl)),
      };
    }

    const customCursor = mishkaFindCustomCursor(settings);
    if (customCursor?.dataUrl) {
      return {
        url: customCursor.dataUrl,
        hx: customCursor.hotspot?.[0] ?? 2,
        hy: customCursor.hotspot?.[1] ?? 2,
        animated: Boolean(customCursor.animated || /\.gif/i.test(customCursor.dataUrl)),
      };
    }

    const cursor = MISHKA_THEMES.cursors[settings.cursorId];
    if (!cursor?.file) return null;

    return {
      url: chrome.runtime.getURL(cursor.file),
      hx: cursor.hotspot?.[0] ?? 2,
      hy: cursor.hotspot?.[1] ?? 2,
      animated: !!cursor.animated || /\.gif$/i.test(cursor.file),
    };
  }

  function setupAnimatedCursor(cur) {
    cleanupAnimatedCursor();

    const hide = document.createElement('style');
    hide.id = CURSOR_HIDE_ID;
    hide.textContent = `
      html, html *, html *::before, html *::after,
      html *:hover, html *:active, html *:focus {
        cursor: none !important;
      }
    `;
    (document.head || document.documentElement).appendChild(hide);

    const img = document.createElement('img');
    img.id = CURSOR_OVERLAY_ID;
    img.src = cur.url;
    img.alt = '';
    img.draggable = false;
    img.width = CURSOR_PX;
    img.height = CURSOR_PX;
    img.style.cssText = `position:fixed;left:0;top:0;width:${CURSOR_PX}px;height:${CURSOR_PX}px;pointer-events:none;z-index:2147483646;`;
    document.documentElement.appendChild(img);

    let raf = 0;
    let x = 0;
    let y = 0;
    const hx = cur.hx;
    const hy = cur.hy;
    const paint = () => {
      raf = 0;
      img.style.transform = `translate(${x - hx}px,${y - hy}px)`;
    };
    const onMove = (e) => {
      x = e.clientX;
      y = e.clientY;
      if (!raf) raf = requestAnimationFrame(paint);
    };
    document.addEventListener('mousemove', onMove, { passive: true });

    cursorCleanup = () => {
      document.removeEventListener('mousemove', onMove);
      if (raf) cancelAnimationFrame(raf);
      img.remove();
      hide.remove();
    };
  }

  function buildCss(settings) {
    if (!settings.enabled) return '';

    let css = '';
    let hasBg = false;

    const customBg = mishkaFindCustomBackground(settings);
    if (customBg?.dataUrl) {
      const mode = settings.customBgMode || 'cover';
      css += wallpaperLayer(customBg.dataUrl, mode === 'tile' ? 'auto' : 'cover', mode === 'tile' ? 'repeat' : 'no-repeat');
      hasBg = true;
    } else if (settings.backgroundId === MISHKA_CUSTOM.legacyBackgroundId && settings.customBackground?.dataUrl) {
      const mode = settings.customBgMode || 'cover';
      css += wallpaperLayer(settings.customBackground.dataUrl, mode === 'tile' ? 'auto' : 'cover', mode === 'tile' ? 'repeat' : 'no-repeat');
      hasBg = true;
    } else if (settings.backgroundId !== 'none') {
      const bg = MISHKA_THEMES.backgrounds[settings.backgroundId];
      if (bg?.type === 'image' && bg.file) {
        css += wallpaperLayer(chrome.runtime.getURL(bg.file), 'cover', 'no-repeat');
        hasBg = true;
      }
    }

    const cur = resolveCursor(settings);
    if (cur && !cur.animated) {
      css += buildCursorCss(cur.url, cur.hx, cur.hy);
    }

    if (settings.enabled) css += buildRobloxUiFixCss();
    return css;
  }

  function apply(settings, force) {
    cachedSettings = settings;

    if (!settings.enabled) {
      cleanupAnimatedCursor();
      document.getElementById(STYLE_ID)?.remove();
      return;
    }

    const css = buildCss(settings);
    let el = document.getElementById(STYLE_ID);
    if (!el) {
      el = document.createElement('style');
      el.id = STYLE_ID;
      (document.head || document.documentElement).appendChild(el);
    }
    if (force || el.textContent !== css) el.textContent = css;

    const cur = resolveCursor(settings);
    if (cur?.animated) {
      if (force || !document.getElementById(CURSOR_OVERLAY_ID)) {
        setupAnimatedCursor(cur);
      }
    } else {
      cleanupAnimatedCursor();
    }
  }

  function queueApply(force, settings) {
    applyForceNext = applyForceNext || !!force;
    if (settings) applySettingsNext = normalizeSettings(settings);
    if (applyPending) return;
    applyPending = true;
    requestAnimationFrame(() => {
      const f = applyForceNext;
      const direct = applySettingsNext;
      applyForceNext = false;
      applySettingsNext = null;
      applyPending = false;
      if (direct) {
        apply(direct, f);
        return;
      }
      getSettings().then((s) => apply(s, f));
    });
  }

  function ensureTheme(force) {
    getSettings().then((s) => {
      if (!s.enabled) return;
      const el = document.getElementById(STYLE_ID);
      const cur = resolveCursor(s);
      const missingStyle = !el || !el.textContent;
      const missingCursor = cur?.animated && !document.getElementById(CURSOR_OVERLAY_ID);
      if (force || missingStyle || missingCursor) apply(s, true);
    });
  }

  function hookSpaNavigation() {
    const notify = () => {
      clearTimeout(routeTimer);
      routeTimer = setTimeout(() => {
        if (location.href !== lastUrl) {
          lastUrl = location.href;
          queueApply(true);
          return;
        }
        ensureTheme(true);
      }, 80);
    };

    const wrap = (fn) => function () {
      const r = fn.apply(this, arguments);
      notify();
      return r;
    };

    try {
      history.pushState = wrap(history.pushState);
      history.replaceState = wrap(history.replaceState);
    } catch (_) {}

    window.addEventListener('popstate', notify);
    window.addEventListener('pageshow', () => queueApply(true));
    document.addEventListener('visibilitychange', () => {
      if (document.visibilityState === 'visible') ensureTheme(true);
    });
    setInterval(() => {
      if (location.href !== lastUrl) {
        lastUrl = location.href;
        queueApply(true);
      }
    }, 700);
  }

  function watchThemeNodes() {
    const obs = new MutationObserver(() => ensureTheme(false));
    const start = () => {
      const head = document.head || document.documentElement;
      if (head) obs.observe(head, { childList: true, subtree: true });
      obs.observe(document.documentElement, { childList: true, subtree: false });
    };
    if (document.head) start();
    else document.addEventListener('DOMContentLoaded', start, { once: true });
  }

  queueApply(true);
  hookSpaNavigation();
  watchThemeNodes();

  chrome.storage.onChanged.addListener((_, area) => {
    if (area === 'sync' || area === 'local') queueApply(true);
  });

  chrome.runtime.onMessage.addListener((msg, _sender, sendResponse) => {
    if (msg?.type === 'APPLY_THEME') {
      queueApply(true, msg.settings || null);
      sendResponse({ ok: true });
      return true;
    }
  });
})();
