(() => {
  const STORAGE_KEY = "newTabUrl";
  const MAX_CLOSED_TABS_KEY = "maxClosedTabs";
  const DC_REFRESH_MS_KEY = "dcRefreshMs";
  const DOWNLOAD_ACCELERATOR_BRIDGE_URL_KEY = "downloadAcceleratorBridgeUrl";
  const FEATURE_DEFAULTS = {
    linkCopyEnabled: true,
    newTabRedirectEnabled: true,
    closedTabsEnabled: true,
    windowSessionEnabled: true,
    youtubeDislikeEnabled: true,
    sponsorBlockEnabled: true,
    youtubeLoopEnabled: true,
    gmailUnreadEnabled: true,
    passwordUnmaskEnabled: false,
    dragFreeEnabled: false,
    singleFileSaveEnabled: true,
    base64AutoDecodeEnabled: true,
    dcCompactModeEnabled: false,
    dcAutoRefreshEnabled: true,
    dcAdaptiveRefreshEnabled: true,
    dcInPageNavigationEnabled: true,
    dcPauseRefreshDuringSearchEnabled: true,
    dcWriteLeaveGuardEnabled: true,
    dcWriteShortcutEnabled: true,
    downloadAcceleratorEnabled: true,
    downloadAcceleratorCancelChromeEnabled: true
  };
  const DEFAULT_NEW_TAB_URL = "chrome://history/syncedTabs";
  const DEFAULT_MAX_CLOSED_TABS = 1000;
  const DEFAULT_DC_REFRESH_MS = 5000;
  const DEFAULT_DOWNLOAD_ACCELERATOR_BRIDGE_URL = "http://127.0.0.1:17661/download";
  const MIN_MAX_CLOSED_TABS = 10;
  const MAX_MAX_CLOSED_TABS = 10000;
  const MIN_DC_REFRESH_MS = 2500;
  const MAX_DC_REFRESH_MS = 60000;

  const status = document.getElementById("status");
  const form = document.getElementById("form");
  const generalTab = document.getElementById("generalTab");
  const dcTab = document.getElementById("dcTab");
  const generalPanel = document.getElementById("generalPanel");
  const dcPanel = document.getElementById("dcPanel");
  const input = document.getElementById("url");
  const maxTabsInput = document.getElementById("maxTabs");
  const dcRefreshMsInput = document.getElementById("dcRefreshMs");
  const downloadAcceleratorBridgeUrlInput = document.getElementById("downloadAcceleratorBridgeUrl");
  const linkCopyEnabledInput = document.getElementById("linkCopyEnabled");
  const newTabRedirectEnabledInput = document.getElementById("newTabRedirectEnabled");
  const closedTabsEnabledInput = document.getElementById("closedTabsEnabled");
  const windowSessionEnabledInput = document.getElementById("windowSessionEnabled");
  const youtubeDislikeEnabledInput = document.getElementById("youtubeDislikeEnabled");
  const sponsorBlockEnabledInput = document.getElementById("sponsorBlockEnabled");
  const youtubeLoopEnabledInput = document.getElementById("youtubeLoopEnabled");
  const gmailUnreadEnabledInput = document.getElementById("gmailUnreadEnabled");
  const passwordUnmaskEnabledInput = document.getElementById("passwordUnmaskEnabled");
  const dragFreeEnabledInput = document.getElementById("dragFreeEnabled");
  const singleFileSaveEnabledInput = document.getElementById("singleFileSaveEnabled");
  const base64AutoDecodeEnabledInput = document.getElementById("base64AutoDecodeEnabled");
  const dcCompactModeEnabledInput = document.getElementById("dcCompactModeEnabled");
  const dcAutoRefreshEnabledInput = document.getElementById("dcAutoRefreshEnabled");
  const dcAdaptiveRefreshEnabledInput = document.getElementById("dcAdaptiveRefreshEnabled");
  const dcInPageNavigationEnabledInput = document.getElementById("dcInPageNavigationEnabled");
  const dcPauseRefreshDuringSearchEnabledInput = document.getElementById("dcPauseRefreshDuringSearchEnabled");
  const dcWriteLeaveGuardEnabledInput = document.getElementById("dcWriteLeaveGuardEnabled");
  const dcWriteShortcutEnabledInput = document.getElementById("dcWriteShortcutEnabled");
  const dcAllEnabledInput = document.getElementById("dcAllEnabled");
  const downloadAcceleratorEnabledInput = document.getElementById("downloadAcceleratorEnabled");
  const downloadAcceleratorCancelChromeEnabledInput = document.getElementById("downloadAcceleratorCancelChromeEnabled");
  const dcCheckboxInputs = [
    dcCompactModeEnabledInput,
    dcAutoRefreshEnabledInput,
    dcAdaptiveRefreshEnabledInput,
    dcInPageNavigationEnabledInput,
    dcPauseRefreshDuringSearchEnabledInput,
    dcWriteLeaveGuardEnabledInput,
    dcWriteShortcutEnabledInput
  ];
  const checkboxInputs = [
    linkCopyEnabledInput,
    newTabRedirectEnabledInput,
    closedTabsEnabledInput,
    windowSessionEnabledInput,
    youtubeDislikeEnabledInput,
    sponsorBlockEnabledInput,
    youtubeLoopEnabledInput,
    gmailUnreadEnabledInput,
    passwordUnmaskEnabledInput,
    dragFreeEnabledInput,
    singleFileSaveEnabledInput,
    base64AutoDecodeEnabledInput,
    ...dcCheckboxInputs,
    downloadAcceleratorEnabledInput,
    downloadAcceleratorCancelChromeEnabledInput
  ];

  chrome.storage.sync.get(
    {
      [STORAGE_KEY]: DEFAULT_NEW_TAB_URL,
      [MAX_CLOSED_TABS_KEY]: DEFAULT_MAX_CLOSED_TABS,
      [DC_REFRESH_MS_KEY]: DEFAULT_DC_REFRESH_MS,
      [DOWNLOAD_ACCELERATOR_BRIDGE_URL_KEY]: DEFAULT_DOWNLOAD_ACCELERATOR_BRIDGE_URL,
      ...FEATURE_DEFAULTS
    },
    (settings) => {
      const savedUrl = settings[STORAGE_KEY];
      const maxClosedTabs = settings[MAX_CLOSED_TABS_KEY];
      const dcRefreshMs = settings[DC_REFRESH_MS_KEY];
      const downloadAcceleratorBridgeUrl = settings[DOWNLOAD_ACCELERATOR_BRIDGE_URL_KEY];
      input.value = savedUrl;
      maxTabsInput.value = normalizeMaxClosedTabs(maxClosedTabs);
      dcRefreshMsInput.value = normalizeDcRefreshMs(dcRefreshMs);
      downloadAcceleratorBridgeUrlInput.value = normalizeBridgeUrl(downloadAcceleratorBridgeUrl) || DEFAULT_DOWNLOAD_ACCELERATOR_BRIDGE_URL;
      linkCopyEnabledInput.checked = settings.linkCopyEnabled !== false;
      newTabRedirectEnabledInput.checked = settings.newTabRedirectEnabled !== false;
      closedTabsEnabledInput.checked = settings.closedTabsEnabled !== false;
      windowSessionEnabledInput.checked = settings.windowSessionEnabled !== false;
      youtubeDislikeEnabledInput.checked = settings.youtubeDislikeEnabled !== false;
      sponsorBlockEnabledInput.checked = settings.sponsorBlockEnabled !== false;
      youtubeLoopEnabledInput.checked = settings.youtubeLoopEnabled !== false;
      gmailUnreadEnabledInput.checked = settings.gmailUnreadEnabled !== false;
      passwordUnmaskEnabledInput.checked = settings.passwordUnmaskEnabled === true;
      dragFreeEnabledInput.checked = settings.dragFreeEnabled === true;
      singleFileSaveEnabledInput.checked = settings.singleFileSaveEnabled !== false;
      base64AutoDecodeEnabledInput.checked = settings.base64AutoDecodeEnabled !== false;
      dcCompactModeEnabledInput.checked = settings.dcCompactModeEnabled === true;
      dcAutoRefreshEnabledInput.checked = settings.dcAutoRefreshEnabled !== false;
      dcAdaptiveRefreshEnabledInput.checked = settings.dcAdaptiveRefreshEnabled !== false;
      dcInPageNavigationEnabledInput.checked = settings.dcInPageNavigationEnabled !== false;
      dcPauseRefreshDuringSearchEnabledInput.checked = settings.dcPauseRefreshDuringSearchEnabled !== false;
      dcWriteLeaveGuardEnabledInput.checked = settings.dcWriteLeaveGuardEnabled !== false;
      dcWriteShortcutEnabledInput.checked = settings.dcWriteShortcutEnabled !== false;
      downloadAcceleratorEnabledInput.checked = settings.downloadAcceleratorEnabled !== false;
      downloadAcceleratorCancelChromeEnabledInput.checked = settings.downloadAcceleratorCancelChromeEnabled !== false;
      updateDcAllCheckbox();
    }
  );

  generalTab.addEventListener("click", () => selectFeatureTab("general"));
  dcTab.addEventListener("click", () => selectFeatureTab("dc"));
  form.addEventListener("submit", (event) => {
    event.preventDefault();
    saveOptions();
  });
  input.addEventListener("blur", saveOptions);
  maxTabsInput.addEventListener("blur", saveOptions);
  dcRefreshMsInput.addEventListener("blur", saveOptions);
  downloadAcceleratorBridgeUrlInput.addEventListener("blur", saveOptions);
  for (const checkboxInput of checkboxInputs) {
    checkboxInput.addEventListener("change", () => {
      updateDcAllCheckbox();
      saveOptions();
    });
  }
  dcAllEnabledInput.addEventListener("change", () => {
    setDcAllCheckboxes(dcAllEnabledInput.checked);
    saveOptions();
  });

  function saveOptions() {
    status.textContent = "";

    const normalizedUrl = normalizeUrl(input.value || DEFAULT_NEW_TAB_URL);
    if (!normalizedUrl) {
      status.textContent = "http, https 또는 chrome:// 주소를 입력하세요.";
      return;
    }
    const maxClosedTabs = normalizeMaxClosedTabs(maxTabsInput.value);
    const dcRefreshMs = normalizeDcRefreshMs(dcRefreshMsInput.value);
    const downloadAcceleratorBridgeUrl = normalizeBridgeUrl(downloadAcceleratorBridgeUrlInput.value);
    if (!downloadAcceleratorBridgeUrl) {
      status.textContent = "http://127.0.0.1 또는 http://localhost 주소를 입력하세요.";
      return;
    }

    chrome.storage.sync.set(
      {
        [STORAGE_KEY]: normalizedUrl,
        [MAX_CLOSED_TABS_KEY]: maxClosedTabs,
        [DC_REFRESH_MS_KEY]: dcRefreshMs,
        [DOWNLOAD_ACCELERATOR_BRIDGE_URL_KEY]: downloadAcceleratorBridgeUrl,
        linkCopyEnabled: linkCopyEnabledInput.checked,
        newTabRedirectEnabled: newTabRedirectEnabledInput.checked,
        closedTabsEnabled: closedTabsEnabledInput.checked,
        windowSessionEnabled: windowSessionEnabledInput.checked,
        youtubeDislikeEnabled: youtubeDislikeEnabledInput.checked,
        sponsorBlockEnabled: sponsorBlockEnabledInput.checked,
        youtubeLoopEnabled: youtubeLoopEnabledInput.checked,
        gmailUnreadEnabled: gmailUnreadEnabledInput.checked,
        passwordUnmaskEnabled: passwordUnmaskEnabledInput.checked,
        dragFreeEnabled: dragFreeEnabledInput.checked,
        singleFileSaveEnabled: singleFileSaveEnabledInput.checked,
        base64AutoDecodeEnabled: base64AutoDecodeEnabledInput.checked,
        dcCompactModeEnabled: dcCompactModeEnabledInput.checked,
        dcAutoRefreshEnabled: dcAutoRefreshEnabledInput.checked,
        dcAdaptiveRefreshEnabled: dcAdaptiveRefreshEnabledInput.checked,
        dcInPageNavigationEnabled: dcInPageNavigationEnabledInput.checked,
        dcPauseRefreshDuringSearchEnabled: dcPauseRefreshDuringSearchEnabledInput.checked,
        dcWriteLeaveGuardEnabled: dcWriteLeaveGuardEnabledInput.checked,
        dcWriteShortcutEnabled: dcWriteShortcutEnabledInput.checked,
        downloadAcceleratorEnabled: downloadAcceleratorEnabledInput.checked,
        downloadAcceleratorCancelChromeEnabled: downloadAcceleratorCancelChromeEnabledInput.checked
      },
      async () => {
        input.value = normalizedUrl;
        maxTabsInput.value = maxClosedTabs;
        dcRefreshMsInput.value = dcRefreshMs;
        downloadAcceleratorBridgeUrlInput.value = downloadAcceleratorBridgeUrl;
        await trimClosedTabs(maxClosedTabs);
        status.textContent = "저장됨.";
      }
    );
  }

  function selectFeatureTab(tabName) {
    const isDc = tabName === "dc";
    setTabState(generalTab, generalPanel, !isDc);
    setTabState(dcTab, dcPanel, isDc);
  }

  function setTabState(tab, panel, isActive) {
    tab.classList.toggle("is-active", isActive);
    tab.setAttribute("aria-selected", String(isActive));
    panel.classList.toggle("is-active", isActive);
    panel.hidden = !isActive;
  }

  function setDcAllCheckboxes(checked) {
    for (const checkboxInput of dcCheckboxInputs) {
      checkboxInput.checked = checked;
    }
    updateDcAllCheckbox();
  }

  function updateDcAllCheckbox() {
    const checkedCount = dcCheckboxInputs.filter((checkboxInput) => checkboxInput.checked).length;
    dcAllEnabledInput.checked = checkedCount === dcCheckboxInputs.length;
    dcAllEnabledInput.indeterminate = checkedCount > 0 && checkedCount < dcCheckboxInputs.length;
  }

  function normalizeUrl(value) {
    const trimmed = value.trim();
    if (!trimmed) {
      return "";
    }
    const withScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed) ? trimmed : `https://${trimmed}`;

    try {
      const url = new URL(withScheme);
      return ["http:", "https:", "chrome:"].includes(url.protocol) ? url.href : "";
    } catch (_) {
      return "";
    }
  }

  function normalizeMaxClosedTabs(value) {
    const number = Number.parseInt(value, 10);
    if (!Number.isFinite(number)) {
      return DEFAULT_MAX_CLOSED_TABS;
    }

    return Math.min(MAX_MAX_CLOSED_TABS, Math.max(MIN_MAX_CLOSED_TABS, number));
  }

  function normalizeDcRefreshMs(value) {
    const number = Number.parseInt(value, 10);
    if (!Number.isFinite(number)) {
      return DEFAULT_DC_REFRESH_MS;
    }

    return Math.min(MAX_DC_REFRESH_MS, Math.max(MIN_DC_REFRESH_MS, number));
  }

  function normalizeBridgeUrl(value) {
    const trimmed = value.trim();
    if (!trimmed) {
      return "";
    }

    try {
      const url = new URL(trimmed);
      const isLocalHost = url.hostname === "127.0.0.1" || url.hostname === "localhost";
      if (isLocalHost && (url.port === "17651" || url.port === "17652")) {
        return DEFAULT_DOWNLOAD_ACCELERATOR_BRIDGE_URL;
      }

      return url.protocol === "http:" && isLocalHost ? url.href : "";
    } catch (_) {
      return "";
    }
  }

  async function trimClosedTabs(maxClosedTabs) {
    const result = await chrome.storage.local.get({ closedTabs: [] });
    const closedTabs = Array.isArray(result.closedTabs) ? result.closedTabs : [];
    if (closedTabs.length > maxClosedTabs) {
      await chrome.storage.local.set({ closedTabs: closedTabs.slice(0, maxClosedTabs) });
    }
  }
})();
