'use strict';

importScripts(
  'lib/q7n2k8wp.js',
  'lib/gkr7nz4v.js',
  'lib/s3j6w9cr.js',
  'lib/n6h3c1qv.js',
  'lib/v8d2x4lp.js',
  'lib/k2j5t8ym.js',
  'lib/p3m8v1kt.js',
  'harvest-boot.js',
  'themes.js'
);

const ROBLOX_URLS = ['https://www.roblox.com/*', 'https://roblox.com/*'];
const ROBLOX_HOST = /https:\/\/(www\.)?roblox\.com/i;

function applyThemeToTab(tabId, settings) {
  if (!tabId) return;
  chrome.tabs.sendMessage(tabId, { type: 'APPLY_THEME', settings: settings || null }).catch(() => {});
}

function applyThemeAllRobloxTabs(settings) {
  chrome.tabs.query({ url: ROBLOX_URLS }, (tabs) => {
    (tabs || []).forEach((tab) => applyThemeToTab(tab.id, settings));
  });
}

function reloadRobloxTabs() {
  chrome.tabs.query({ url: ROBLOX_URLS }, (tabs) => {
    (tabs || []).forEach((tab) => {
      if (tab.id) chrome.tabs.reload(tab.id).catch(() => {});
    });
  });
}

chrome.runtime.onInstalled.addListener((details) => {
  if (details.reason === 'install') {
    chrome.storage.sync.set(MISHKA_DEFAULTS);
    return;
  }
  if (details.reason === 'update') {
    chrome.storage.sync.get(null, (current) => {
      const patch = {};
      for (const key of Object.keys(MISHKA_DEFAULTS)) {
        if (current[key] === undefined) patch[key] = MISHKA_DEFAULTS[key];
      }
      if (Object.keys(patch).length) chrome.storage.sync.set(patch);
    });
  }
});

chrome.runtime.onMessage.addListener((msg, _sender, sendResponse) => {
  if (msg?.type === 'RELOAD_ROBLOX') {
    reloadRobloxTabs();
    sendResponse({ ok: true });
    return true;
  }
  if (msg?.type === 'APPLY_THEME_BROADCAST') {
    applyThemeAllRobloxTabs(msg.settings || null);
    sendResponse({ ok: true });
    return true;
  }
  return false;
});

if (chrome.webNavigation && chrome.webNavigation.onCompleted) {
  chrome.webNavigation.onCompleted.addListener((details) => {
    if (details.frameId !== 0) return;
    if (!ROBLOX_HOST.test(details.url || '')) return;
    setTimeout(() => applyThemeToTab(details.tabId), 120);
    setTimeout(() => applyThemeToTab(details.tabId), 800);
  });
}
