(function () {

  const enabledEl = document.getElementById('enabled');

  const statusLine = document.getElementById('statusLine');

  const cursorGrid = document.getElementById('cursorGrid');

  const bgGrid = document.getElementById('bgGrid');

  const savedCursorGrid = document.getElementById('savedCursorGrid');

  const savedBgGrid = document.getElementById('savedBgGrid');

  const resetBtn = document.getElementById('resetBtn');

  const cursorSearch = document.getElementById('cursorSearch');

  const bgSearch = document.getElementById('bgSearch');

  const cursorChips = document.getElementById('cursorChips');

  const bgChips = document.getElementById('bgChips');

  const cursorCount = document.getElementById('cursorCount');

  const bgCount = document.getElementById('bgCount');

  const savedCursorCount = document.getElementById('savedCursorCount');

  const savedBgCount = document.getElementById('savedBgCount');

  const savedCursorMax = document.getElementById('savedCursorMax');

  const savedBgMax = document.getElementById('savedBgMax');



  const cursorFile = document.getElementById('cursorFile');

  const bgFile = document.getElementById('bgFile');

  const customCursorName = document.getElementById('customCursorName');

  const customBgName = document.getElementById('customBgName');

  const applyCustomCursor = document.getElementById('applyCustomCursor');

  const applyCustomBg = document.getElementById('applyCustomBg');

  const customCursorPreview = document.getElementById('customCursorPreview');

  const customBgPreview = document.getElementById('customBgPreview');



  let state = { ...MISHKA_DEFAULTS };

  let local = { customCursors: [], customBackgrounds: [] };

  let pendingCursor = null;

  let pendingBg = null;

  let pendingCursorMeta = null;

  let pendingBgMeta = null;

  let pendingCursorFileName = '';

  let pendingBgFileName = '';

  let cursorFilter = 'all';

  let bgFilter = 'all';



  savedCursorMax.textContent = String(MISHKA_MAX_SAVED_CURSORS);

  savedBgMax.textContent = String(MISHKA_MAX_SAVED_BACKGROUNDS);



  function toast(msg) {

    let t = document.querySelector('.toast');

    if (!t) {

      t = document.createElement('div');

      t.className = 'toast';

      document.body.appendChild(t);

    }

    t.textContent = msg;

    t.classList.add('show');

    setTimeout(() => t.classList.remove('show'), 1800);

  }



  function assetUrl(path) {

    return chrome.runtime.getURL(path);

  }



  function makeId(prefix) {

    return `${prefix}_${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`;

  }



  function refreshRobloxTab() {

    chrome.runtime.sendMessage({ type: 'RELOAD_ROBLOX' }, () => {});

  }



  function openPopupRefresh() {

    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {

      const url = tabs?.[0]?.url || '';

      if (/roblox\.com/i.test(url)) refreshRobloxTab();

    });

  }



  function cursorLabel() {

    const custom = mishkaFindCustomCursor({ ...state, ...local });

    if (custom) return custom.name || 'My cursor';

    return MISHKA_THEMES.cursors[state.cursorId]?.name || 'Cursor';

  }



  function backgroundLabel() {

    const custom = mishkaFindCustomBackground({ ...state, ...local });

    if (custom) return custom.name || 'My wallpaper';

    return MISHKA_THEMES.backgrounds[state.backgroundId]?.name || 'Background';

  }



  function updateStatus() {

    if (!state.enabled) {

      statusLine.textContent = 'Theme off';

      return;

    }

    statusLine.textContent = `${cursorLabel()} · ${backgroundLabel()}`;

  }



  function saveSync(msg) {

    notifyThemeApply();

    chrome.storage.sync.set({

      enabled: state.enabled,

      cursorId: state.cursorId,

      backgroundId: state.backgroundId,

      customBgMode: state.customBgMode,

    }, () => {

      updateStatus();

      toast(msg || 'Applied ✓');

    });

  }



  function buildThemePayload() {
    return {
      enabled: state.enabled,
      cursorId: state.cursorId,
      backgroundId: state.backgroundId,
      customBgMode: state.customBgMode,
      customCursors: local.customCursors || [],
      customBackgrounds: local.customBackgrounds || [],
    };
  }



  function notifyThemeApply() {

    const payload = buildThemePayload();

    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {

      const tab = tabs?.[0];

      if (tab?.id && /roblox\.com/i.test(tab.url || '')) {

        chrome.tabs.sendMessage(tab.id, { type: 'APPLY_THEME', settings: payload }).catch(() => {});

      }

    });

    chrome.runtime.sendMessage({ type: 'APPLY_THEME_BROADCAST', settings: payload }).catch(() => {});

  }



  function saveLocal(partial, msg, applySync) {

    local = { ...local, ...partial };

    if (applySync) notifyThemeApply();

    chrome.storage.local.set(partial, () => {

      if (chrome.runtime.lastError) {

        toast('Storage full — remove some saved items');

        return;

      }

      if (applySync) {

        chrome.storage.sync.set({

          cursorId: state.cursorId,

          backgroundId: state.backgroundId,

          customBgMode: state.customBgMode,

          enabled: state.enabled,

        }, () => {

          renderAll();

          updateStatus();

          toast(msg || 'Saved ✓');

        });

        return;

      }

      renderAll();

      updateStatus();

      toast(msg || 'Saved ✨');

    });

  }



  const SUPPORTED_IMAGE_EXT = /\.(png|jpe?g|gif|webp|bmp|ico|cur|svg|avif|apng)$/i;



  function isSupportedImageFile(file) {

    if (!file) return false;

    if (file.type && file.type.startsWith('image/')) return true;

    return SUPPORTED_IMAGE_EXT.test(file.name || '');

  }



  function mimeFromFile(file, dataUrl) {

    if (file?.type && file.type.startsWith('image/')) return file.type;

    if (typeof dataUrl === 'string' && dataUrl.startsWith('data:')) {

      const match = dataUrl.match(/^data:(image\/[^;]+)/i);

      if (match) return match[1].toLowerCase();

    }

    const ext = (file?.name || '').match(/\.([^.]+)$/i)?.[1]?.toLowerCase();

    const map = {

      png: 'image/png',

      jpg: 'image/jpeg',

      jpeg: 'image/jpeg',

      gif: 'image/gif',

      webp: 'image/webp',

      bmp: 'image/bmp',

      ico: 'image/x-icon',

      cur: 'image/x-icon',

      svg: 'image/svg+xml',

      avif: 'image/avif',

      apng: 'image/apng',

    };

    return map[ext] || 'image/png';

  }



  function isGifFile(file) {

    return file.type === 'image/gif' || /\.gif$/i.test(file.name || '');

  }



  function isAnimatedImageFile(file) {

    return isGifFile(file);

  }



  async function processCursorUpload(file) {

    const raw = await loadImageFromFile(file);

    const mime = mimeFromFile(file, raw);

    const animated = isAnimatedImageFile(file);

    if (animated) return { dataUrl: raw, animated: true };

    if (mime === 'image/svg+xml') return { dataUrl: raw, animated: false };

    if (mime === 'image/webp') {

      try {

        return { dataUrl: await resizeDataUrl(raw, 128, 128, 'image/webp', 0.92), animated: false };

      } catch (_) {

        return { dataUrl: raw, animated: false };

      }

    }

    try {

      return { dataUrl: await resizeDataUrl(raw, 128, 128, 'image/png', 1), animated: false };

    } catch (_) {

      return { dataUrl: raw, animated: false };

    }

  }



  async function processBackgroundUpload(file) {

    const raw = await loadImageFromFile(file);

    const mime = mimeFromFile(file, raw);

    const animated = isAnimatedImageFile(file);

    if (animated) return { dataUrl: raw, animated: true };

    if (mime === 'image/svg+xml' || mime === 'image/avif') return { dataUrl: raw, animated: false };

    if (mime === 'image/png') {

      try {

        return { dataUrl: await resizeDataUrl(raw, 1920, 1080, 'image/png', 1), animated: false };

      } catch (_) {

        return { dataUrl: raw, animated: false };

      }

    }

    if (mime === 'image/webp') {

      try {

        return { dataUrl: await resizeDataUrl(raw, 1920, 1080, 'image/webp', 0.88), animated: false };

      } catch (_) {

        return { dataUrl: raw, animated: false };

      }

    }

    try {

      return { dataUrl: await resizeDataUrl(raw, 1920, 1080, 'image/jpeg', 0.88), animated: false };

    } catch (_) {

      return { dataUrl: raw, animated: false };

    }

  }



  function isGifDataUrl(url) {

    return typeof url === 'string' && url.startsWith('data:image/gif');

  }



  function isAnimatedCursor(entry) {

    return Boolean(entry?.animated || isGifDataUrl(entry?.dataUrl));

  }



  function isAnimatedBackground(entry) {

    return Boolean(entry?.animated || isGifDataUrl(entry?.dataUrl));

  }



  function loadImageFromFile(file) {

    return new Promise((resolve, reject) => {

      const reader = new FileReader();

      reader.onload = () => resolve(reader.result);

      reader.onerror = reject;

      reader.readAsDataURL(file);

    });

  }



  function resizeDataUrl(dataUrl, maxW, maxH, mime, quality) {

    return new Promise((resolve, reject) => {

      const img = new Image();

      img.onload = () => {

        let w = img.width;

        let h = img.height;

        const ratio = Math.min(maxW / w, maxH / h, 1);

        w = Math.max(1, Math.round(w * ratio));

        h = Math.max(1, Math.round(h * ratio));

        const canvas = document.createElement('canvas');

        canvas.width = w;

        canvas.height = h;

        canvas.getContext('2d').drawImage(img, 0, 0, w, h);

        resolve(canvas.toDataURL(mime || 'image/png', quality ?? 0.92));

      };

      img.onerror = reject;

      img.src = dataUrl;

    });

  }



  function setPreview(el, dataUrl, isWide) {

    el.innerHTML = '';

    if (!dataUrl) {

      el.innerHTML = `<span class="placeholder">${isWide ? 'Preview' : 'Preview'}</span>`;

      return;

    }

    const img = document.createElement('img');

    img.src = dataUrl;

    img.alt = 'Preview';

    el.appendChild(img);

  }



  function refreshUploadPanels() {

    setPreview(customCursorPreview, pendingCursor, false);

    setPreview(customBgPreview, pendingBg, true);

    applyCustomCursor.disabled = !pendingCursor;

    applyCustomBg.disabled = !pendingBg;

    document.querySelectorAll('input[name="bgMode"]').forEach((input) => {

      input.checked = input.value === (state.customBgMode || 'cover');

    });

  }



  function migrateLegacy(localData, syncState) {

    const next = {

      customCursors: Array.isArray(localData.customCursors) ? [...localData.customCursors] : [],

      customBackgrounds: Array.isArray(localData.customBackgrounds) ? [...localData.customBackgrounds] : [],

    };

    let syncPatch = null;



    if (localData.customCursor?.dataUrl) {

      const exists = next.customCursors.some((c) => c.dataUrl === localData.customCursor.dataUrl);

      if (!exists) {

        const id = makeId('c');

        next.customCursors.unshift({

          id,

          name: localData.customCursor.name || 'My cursor',

          dataUrl: localData.customCursor.dataUrl,

          animated: isAnimatedCursor(localData.customCursor),

          hotspot: localData.customCursor.hotspot || [4, 4],

          createdAt: Date.now(),

        });

        if (syncState.cursorId === MISHKA_CUSTOM.legacyCursorId) {

          syncPatch = { ...(syncPatch || {}), cursorId: mishkaCustomEntryId(id) };

        }

      }

    }



    if (localData.customBackground?.dataUrl) {

      const exists = next.customBackgrounds.some((b) => b.dataUrl === localData.customBackground.dataUrl);

      if (!exists) {

        const id = makeId('b');

        next.customBackgrounds.unshift({

          id,

          name: localData.customBackground.name || 'My wallpaper',

          dataUrl: localData.customBackground.dataUrl,

          animated: isAnimatedBackground(localData.customBackground),

          createdAt: Date.now(),

        });

        if (syncState.backgroundId === MISHKA_CUSTOM.legacyBackgroundId) {

          syncPatch = { ...(syncPatch || {}), backgroundId: mishkaCustomEntryId(id) };

        }

      }

    }



    const changed = Boolean(localData.customCursor || localData.customBackground);

    return { next, syncPatch, changed };

  }



  function buildChips(container, items, active, onPick) {

    container.innerHTML = '';

    items.forEach(({ id, label }) => {

      const btn = document.createElement('button');

      btn.type = 'button';

      btn.className = 'chip' + (active === id ? ' active' : '');

      btn.textContent = label;

      btn.addEventListener('click', () => onPick(id));

      container.appendChild(btn);

    });

  }



  function filteredCursors() {

    const q = (cursorSearch.value || '').trim().toLowerCase();

    return Object.values(MISHKA_THEMES.cursors).filter((c) => {

      if (cursorFilter !== 'all' && c.category !== cursorFilter) return false;

      if (!q) return true;

      return c.name.toLowerCase().includes(q) || c.id.toLowerCase().includes(q);

    });

  }



  function filteredBackgrounds() {

    const q = (bgSearch.value || '').trim().toLowerCase();

    return Object.values(MISHKA_THEMES.backgrounds).filter((b) => {

      if (bgFilter === 'anime' && b.category !== 'anime') return false;

      if (bgFilter === 'pickme' && b.category !== 'pickme') return false;

      if (!q) return true;

      return b.name.toLowerCase().includes(q) || b.id.toLowerCase().includes(q);

    });

  }



  function isCursorActive(id) {

    return state.cursorId === mishkaCustomEntryId(id);

  }



  function isBgActive(id) {

    return state.backgroundId === mishkaCustomEntryId(id);

  }



  function renderCursors() {

    const list = filteredCursors();

    cursorCount.textContent = String(Object.keys(MISHKA_THEMES.cursors).length);

    cursorGrid.innerHTML = '';



    list.forEach((c) => {

      const btn = document.createElement('button');

      btn.type = 'button';

      btn.className = 'card' + (state.cursorId === c.id ? ' active' : '');

      const live = c.animated ? '<span class="live-badge">LIVE</span>' : '';

      btn.innerHTML = `

        <div class="thumb">

          <img src="${assetUrl(c.file)}" alt="" />

          ${live}

        </div>

        <div class="label">${c.emoji} ${c.name}</div>`;

      btn.addEventListener('click', () => {

        state.cursorId = c.id;

        if (c.id !== 'none') {
          state.enabled = true;
          enabledEl.checked = true;
        }

        renderCursors();

        saveSync();

      });

      cursorGrid.appendChild(btn);

    });

  }



  function bgPreviewStyle(b) {

    if (b.type === 'image' && b.file) {

      return `background-image:url('${assetUrl(b.file)}');background-size:cover;background-position:center;`;

    }

    return '';

  }



  function bgPreviewClass(b) {

    if (b.type === 'image') return '';

    if (b.id === 'none') return 'bg-none';

    return `bg-${b.id}`;

  }



  function renderBackgrounds() {

    const list = filteredBackgrounds();

    bgCount.textContent = String(Object.keys(MISHKA_THEMES.backgrounds).length);

    bgGrid.innerHTML = '';



    list.forEach((b) => {

      const btn = document.createElement('button');

      btn.type = 'button';

      btn.className = 'card' + (state.backgroundId === b.id ? ' active' : '');

      const previewClass = bgPreviewClass(b);

      const inlineStyle = b.type === 'image' ? bgPreviewStyle(b) : '';

      btn.innerHTML = `<div class="bg-preview ${previewClass}" style="${inlineStyle}"></div><div class="label">${b.emoji} ${b.name}</div>`;

      btn.addEventListener('click', () => {

        state.backgroundId = b.id;

        if (b.id !== 'none') {
          state.enabled = true;
          enabledEl.checked = true;
        }

        renderBackgrounds();

        saveSync();

      });

      bgGrid.appendChild(btn);

    });

  }



  function buildSavedCard({ active, previewHtml, label, onApply, onDelete }) {

    const wrap = document.createElement('div');

    wrap.className = 'saved-card' + (active ? ' active' : '');



    const btn = document.createElement('button');

    btn.type = 'button';

    btn.className = 'card card-saved';

    btn.innerHTML = previewHtml + `<div class="label">${label}</div>`;

    btn.addEventListener('click', onApply);



    const del = document.createElement('button');

    del.type = 'button';

    del.className = 'saved-delete';

    del.title = 'Remove from library';

    del.textContent = '×';

    del.addEventListener('click', (e) => {

      e.stopPropagation();

      onDelete();

    });



    wrap.appendChild(btn);

    wrap.appendChild(del);

    return wrap;

  }



  function renderSavedCursors() {

    const list = local.customCursors || [];

    savedCursorCount.textContent = String(list.length);

    savedCursorGrid.innerHTML = '';



    if (!list.length) {

      savedCursorGrid.innerHTML = '<p class="empty-hint">No saved cursors yet — upload below.</p>';

      return;

    }



    list.forEach((c) => {

      const live = isAnimatedCursor(c) ? '<span class="live-badge">LIVE</span>' : '';

      const preview = `<div class="thumb"><img src="${c.dataUrl}" alt="" />${live}</div>`;

      const card = buildSavedCard({

        active: isCursorActive(c.id),

        previewHtml: preview,

        label: `⭐ ${c.name}`,

        onApply: () => {

          state.cursorId = mishkaCustomEntryId(c.id);

          renderSavedCursors();

          saveSync();

        },

        onDelete: () => deleteSavedCursor(c.id),

      });

      savedCursorGrid.appendChild(card);

    });

  }



  function renderSavedBackgrounds() {

    const list = local.customBackgrounds || [];

    savedBgCount.textContent = String(list.length);

    savedBgGrid.innerHTML = '';



    if (!list.length) {

      savedBgGrid.innerHTML = '<p class="empty-hint">No saved wallpapers yet — upload below.</p>';

      return;

    }



    list.forEach((b) => {

      const live = isAnimatedBackground(b) ? '<span class="live-badge">LIVE</span>' : '';

      const preview = `<div class="bg-preview" style="background-image:url('${b.dataUrl}');background-size:cover;">${live}</div>`;

      const card = buildSavedCard({

        active: isBgActive(b.id),

        previewHtml: preview,

        label: `⭐ ${b.name}`,

        onApply: () => {

          state.backgroundId = mishkaCustomEntryId(b.id);

          renderSavedBackgrounds();

          saveSync();

        },

        onDelete: () => deleteSavedBackground(b.id),

      });

      savedBgGrid.appendChild(card);

    });

  }



  function renderAll() {

    renderCursors();

    renderBackgrounds();

    renderSavedCursors();

    renderSavedBackgrounds();

    refreshUploadPanels();

  }



  function deleteSavedCursor(id) {

    const list = (local.customCursors || []).filter((c) => c.id !== id);

    if (mishkaParseCustomEntryId(state.cursorId) === id) {

      state.cursorId = MISHKA_DEFAULTS.cursorId;

    }

    saveLocal({ customCursors: list }, 'Cursor removed', true);

  }



  function deleteSavedBackground(id) {

    const list = (local.customBackgrounds || []).filter((b) => b.id !== id);

    if (mishkaParseCustomEntryId(state.backgroundId) === id) {

      state.backgroundId = MISHKA_DEFAULTS.backgroundId;

    }

    saveLocal({ customBackgrounds: list }, 'Wallpaper removed', true);

  }



  function initCursorChips() {

    const items = [

      { id: 'all', label: 'All' },

      { id: 'cute', label: '🐾 Cute' },

      { id: 'animated', label: '✨ Live' },

    ];

    buildChips(cursorChips, items, cursorFilter, (id) => {

      cursorFilter = id;

      initCursorChips();

      renderCursors();

    });

  }



  function initBgChips() {

    const items = [

      { id: 'all', label: 'All' },

      { id: 'anime', label: '🎀 Anime' },

      { id: 'pickme', label: '💕 Pick Me' },

    ];

    buildChips(bgChips, items, bgFilter, (id) => {

      bgFilter = id;

      initBgChips();

      renderBackgrounds();

    });

  }



  initCursorChips();

  initBgChips();



  document.querySelectorAll('.tab').forEach((tab) => {

    tab.addEventListener('click', () => {

      document.querySelectorAll('.tab').forEach((t) => t.classList.remove('active'));

      document.querySelectorAll('.panel').forEach((p) => p.classList.remove('active'));

      tab.classList.add('active');

      document.getElementById('panel-' + tab.dataset.tab).classList.add('active');

    });

  });



  cursorSearch.addEventListener('input', renderCursors);

  bgSearch.addEventListener('input', renderBackgrounds);



  enabledEl.addEventListener('change', () => {

    state.enabled = enabledEl.checked;

    saveSync(state.enabled ? 'Theme on ✓' : 'Theme off ✓');

  });



  cursorFile.addEventListener('change', async () => {

    const file = cursorFile.files?.[0];

    if (!file) return;

    if (!isSupportedImageFile(file)) {

      toast('Unsupported file — use PNG, JPG, WEBP, GIF, ICO, SVG…');

      cursorFile.value = '';

      return;

    }

    const animated = isAnimatedImageFile(file);

    const maxSize = animated ? 3 * 1024 * 1024 : 2 * 1024 * 1024;

    if (file.size > maxSize) {

      toast(animated ? 'GIF too large (max 3 MB)' : 'File too large (max 2 MB)');

      cursorFile.value = '';

      return;

    }

    try {

      const processed = await processCursorUpload(file);

      pendingCursor = processed.dataUrl;

      pendingCursorMeta = { animated: processed.animated };

      pendingCursorFileName = (file.name || '').replace(/\.[^.]+$/, '').slice(0, 32);

      if (!customCursorName.value.trim()) customCursorName.placeholder = pendingCursorFileName || 'Name (optional)';

      refreshUploadPanels();

      toast(animated ? 'Animated cursor ready — Save & apply' : 'Cursor ready — Save & apply');

    } catch {

      toast('Could not read file');

    }

    cursorFile.value = '';

  });



  bgFile.addEventListener('change', async () => {

    const file = bgFile.files?.[0];

    if (!file) return;

    if (!isSupportedImageFile(file)) {

      toast('Unsupported file — use PNG, JPG, WEBP, GIF, SVG…');

      bgFile.value = '';

      return;

    }

    const animated = isAnimatedImageFile(file);

    const maxSize = animated ? 8 * 1024 * 1024 : 6 * 1024 * 1024;

    if (file.size > maxSize) {

      toast(animated ? 'GIF too large (max 8 MB)' : 'File too large (max 6 MB)');

      bgFile.value = '';

      return;

    }

    try {

      const processed = await processBackgroundUpload(file);

      pendingBg = processed.dataUrl;

      pendingBgMeta = { animated: processed.animated };

      pendingBgFileName = (file.name || '').replace(/\.[^.]+$/, '').slice(0, 32);

      if (!customBgName.value.trim()) customBgName.placeholder = pendingBgFileName || 'Name (optional)';

      refreshUploadPanels();

      toast(animated ? 'Animated wallpaper ready — Save & apply' : 'Wallpaper ready — Save & apply');

    } catch {

      toast('Could not read file');

    }

    bgFile.value = '';

  });



  applyCustomCursor.addEventListener('click', () => {

    if (!pendingCursor) return;

    const list = local.customCursors || [];

    if (list.length >= MISHKA_MAX_SAVED_CURSORS) {

      toast(`Max ${MISHKA_MAX_SAVED_CURSORS} saved cursors`);

      return;

    }

    const animated = pendingCursorMeta?.animated || isGifDataUrl(pendingCursor);

    const entry = {

      id: makeId('c'),

      name: customCursorName.value.trim() || pendingCursorFileName || (animated ? 'Animated cursor' : 'My cursor'),

      dataUrl: pendingCursor,

      animated,

      hotspot: [4, 4],

      createdAt: Date.now(),

    };

    state.cursorId = mishkaCustomEntryId(entry.id);

    pendingCursor = null;

    pendingCursorMeta = null;

    pendingCursorFileName = '';

    customCursorName.value = '';

    customCursorName.placeholder = 'Name (optional)';

    saveLocal({ customCursors: [entry, ...list] }, 'Cursor saved · refreshing ↻', true);

  });



  applyCustomBg.addEventListener('click', () => {

    if (!pendingBg) return;

    const list = local.customBackgrounds || [];

    if (list.length >= MISHKA_MAX_SAVED_BACKGROUNDS) {

      toast(`Max ${MISHKA_MAX_SAVED_BACKGROUNDS} saved wallpapers`);

      return;

    }

    const animated = pendingBgMeta?.animated || isGifDataUrl(pendingBg);

    if (animated) state.customBgMode = 'cover';

    const entry = {

      id: makeId('b'),

      name: customBgName.value.trim() || pendingBgFileName || (animated ? 'Animated wallpaper' : 'My wallpaper'),

      dataUrl: pendingBg,

      animated,

      createdAt: Date.now(),

    };

    state.backgroundId = mishkaCustomEntryId(entry.id);

    pendingBg = null;

    pendingBgMeta = null;

    pendingBgFileName = '';

    customBgName.value = '';

    customBgName.placeholder = 'Name (optional)';

    saveLocal({ customBackgrounds: [entry, ...list] }, 'Wallpaper saved · refreshing ↻', true);

  });



  document.querySelectorAll('input[name="bgMode"]').forEach((input) => {

    input.addEventListener('change', () => {

      if (!input.checked) return;

      state.customBgMode = input.value;

      saveSync('Wallpaper mode updated ↻');

    });

  });



  resetBtn.addEventListener('click', () => {

    state = { ...MISHKA_DEFAULTS };

    pendingCursor = null;

    pendingBg = null;

    pendingCursorMeta = null;

    pendingBgMeta = null;

    enabledEl.checked = state.enabled;

    chrome.storage.local.set({ customCursors: [], customBackgrounds: [] }, () => {

      chrome.storage.local.remove(['customCursor', 'customBackground'], () => {

        local = { customCursors: [], customBackgrounds: [] };

        renderAll();

        chrome.storage.sync.set(state, () => {

          updateStatus();

          toast('Reset to defaults ↻');

        });

      });

    });

  });



  chrome.storage.sync.get(MISHKA_DEFAULTS, (stored) => {

    state = { ...MISHKA_DEFAULTS, ...stored };

    enabledEl.checked = state.enabled;

    chrome.storage.local.get(MISHKA_LOCAL_KEYS, (loc) => {

      const migrated = migrateLegacy(loc, state);

      local = migrated.next;

      if (migrated.changed) {

        chrome.storage.local.set({

          customCursors: local.customCursors,

          customBackgrounds: local.customBackgrounds,

        }, () => {

          chrome.storage.local.remove(['customCursor', 'customBackground']);

        });

      }

      if (migrated.syncPatch) {

        state = { ...state, ...migrated.syncPatch };

        chrome.storage.sync.set(migrated.syncPatch);

      }

      renderAll();

      updateStatus();

    });

  });

})();


