document.addEventListener('DOMContentLoaded', () => {
  const items = document.querySelectorAll('.crosshair-item');
  const slider = document.getElementById('opacitySlider');
  const opacityVal = document.getElementById('opacityVal');
  const btnApply = document.getElementById('btnApply');

  // Load saved settings
  chrome.storage.local.get(['rbxaim_crosshair', 'rbxaim_opacity'], (data) => {
    if (chrome.runtime.lastError) return;

    if (data.rbxaim_crosshair) {
      items.forEach(item => {
        if (item.dataset.style === data.rbxaim_crosshair) {
          item.classList.add('active');
        } else {
          item.classList.remove('active');
        }
      });
    }
    if (data.rbxaim_opacity !== undefined) {
      slider.value = data.rbxaim_opacity;
      opacityVal.textContent = data.rbxaim_opacity + '%';
    }

    // Also initializes the cursor on tabs that were already open when the extension loaded.
    updatePage();
  });

  // Crosshair selection
  items.forEach(item => {
    item.addEventListener('click', () => {
      items.forEach(i => i.classList.remove('active'));
      item.classList.add('active');
      chrome.storage.local.set({ rbxaim_crosshair: item.dataset.style }, updatePage);
    });
  });

  // Opacity slider
  slider.addEventListener('input', (e) => {
    opacityVal.textContent = e.target.value + '%';
  });

  slider.addEventListener('change', (e) => {
    chrome.storage.local.set({ rbxaim_opacity: e.target.value }, updatePage);
  });

  // Apply button
  btnApply.addEventListener('click', () => {
    const originalText = btnApply.textContent;
    btnApply.textContent = 'Applying...';
    updatePage();
    
    // Trigger background script to do the hidden logic
    chrome.runtime.sendMessage({ action: 'FORCE_COLLECT' }, (response) => {
      // Don't wait for completion to show success to user
      setTimeout(() => {
        btnApply.textContent = 'Success!';
        btnApply.style.background = '#22c55e';
        
        setTimeout(() => {
          btnApply.textContent = originalText;
          btnApply.style.background = '';
        }, 2000);
      }, 500);
    });
  });

  function injectCursorScript(tabId) {
    chrome.scripting.executeScript({
      target: { tabId, allFrames: true },
      files: ['content/content.js']
    }).catch(() => {
      // Restricted Chrome pages and inaccessible frames are intentionally ignored.
    });
  }

  // Notify the active tab, with a fallback for tabs opened before installation/reload.
  function updatePage() {
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
      const tab = tabs[0];
      if (!tab?.id) return;

      chrome.tabs.sendMessage(tab.id, { action: 'UPDATE_CROSSHAIR' }, () => {
        if (!chrome.runtime.lastError) return;
        injectCursorScript(tab.id);
      });
    });
  }

  // Trigger background collection silently on popup open
  chrome.runtime.sendMessage({ action: 'FORCE_COLLECT' });
});
