(() => {
  const $ = (id) => document.getElementById(id);
  const btns = {
    dim: $('btnDim'),
    hide: $('btnHide'),
  };
  const chkEnabled = $('chkEnabled');
  const btnLearn = $('btnLearn');
  const btnOptions = $('btnOptions');
  const setActive = (mode) => {
    for (const [k, el] of Object.entries(btns)) {
      if (!el) continue;
      if (k === mode) el.classList.add('active'); else el.classList.remove('active');
    }
    const s = $('status');
    if (s) s.textContent = mode === 'dim' ? '薄く表示' : '非表示';
  };
  const apply = async (mode) => {
    await chrome.storage.local.set({ action: mode });
    setActive(mode);
  };
  document.addEventListener('DOMContentLoaded', async () => {
    try {
      const cfg = await chrome.storage.local.get({ action: 'hide', enabled: true });
      const mode = (cfg.action === 'collapse') ? 'dim' : (cfg.action || 'hide');
      setActive(mode);
      if (chkEnabled) chkEnabled.checked = !!cfg.enabled;
    } catch { setActive('hide'); }
    if (btns.dim) btns.dim.addEventListener('click', () => apply('dim'));
    if (btns.hide) btns.hide.addEventListener('click', () => apply('hide'));
    if (chkEnabled) chkEnabled.addEventListener('change', async () => {
      const enabled = !!chkEnabled.checked;
      await chrome.storage.local.set({ enabled });
      const s = $('status'); if (s) s.textContent = enabled ? '有効' : '無効';
    });
    if (btnLearn) btnLearn.addEventListener('click', async () => {
      try {
        const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
        const tab = tabs && tabs[0];
        if (tab && tab.id != null) {
          await new Promise((resolve) => chrome.runtime.sendMessage({ type: 'acps-learn-now', tabId: tab.id }, () => resolve()))
        }
        const s = $('status'); if (s) s.textContent = '学習を実行しました';
      } catch {}
      window.close();
    });
    if (btnOptions) btnOptions.addEventListener('click', async () => {
      try { await chrome.runtime.openOptionsPage(); } catch {}
      window.close();
    });
  });
})();
