(() => {
  const STORAGE_KEY = "newTabUrl";
  const NEW_TAB_REDIRECT_ENABLED_KEY = "newTabRedirectEnabled";
  const DEFAULT_NEW_TAB_URL = "chrome://history/syncedTabs";

  chrome.storage.sync.get(
    {
      [STORAGE_KEY]: DEFAULT_NEW_TAB_URL,
      [NEW_TAB_REDIRECT_ENABLED_KEY]: true
    },
    ({ [STORAGE_KEY]: savedUrl, [NEW_TAB_REDIRECT_ENABLED_KEY]: enabled }) => {
    if (enabled === false) {
      return;
    }

    openUrl(savedUrl || DEFAULT_NEW_TAB_URL);
    }
  );

  function openUrl(url) {
    try {
      if (chrome.tabs?.getCurrent && chrome.tabs?.update) {
        chrome.tabs.getCurrent((tab) => {
          if (chrome.runtime.lastError || !tab?.id) {
            window.location.replace(url);
            return;
          }

          chrome.tabs.update(tab.id, { url }, () => {
            if (chrome.runtime.lastError) {
              window.location.replace(url);
            }
          });
        });
        return;
      }
    } catch (_) {
      // 직접 이동으로 이어진다.
    }

    window.location.replace(url);
  }
})();
