document.addEventListener('DOMContentLoaded', restoreOptions);
document.getElementById('saveBtn').addEventListener('click', saveOptions);
document.getElementById('openDashboard').addEventListener('click', () => {
  chrome.tabs.create({ url: 'http://localhost:3001' });
});

function saveOptions() {
  const backendUrl = document.getElementById('backendUrl').value;
  const status = document.getElementById('status-msg');

  if (!backendUrl) {
    status.textContent = 'Error: Backend URL is required.';
    status.className = 'error';
    return;
  }

  chrome.storage.local.set({
    backendUrl: backendUrl
  }, () => {
    // Validate connection
    status.textContent = 'Testing connection...';
    status.className = '';
    
    const headers = { 'Content-Type': 'application/json' };
    
    // We try to fetch profiles to verify connection (as auth is now removed for this endpoint)
    // Or just check if server responds
    fetch(`${backendUrl}/profiles`, { headers }) 
      .then(response => {
        if (response.ok) {
          status.textContent = '✅ Connected successfully!';
          status.className = 'success';
        } else {
          status.textContent = '⚠️ Saved, but connection failed (Check URL).';
          status.className = 'error';
        }
      })
      .catch(err => {
        status.textContent = '❌ Connection Error: ' + err.message;
        status.className = 'error';
      });
  });
}

function restoreOptions() {
  chrome.storage.local.get(['backendUrl'], (items) => {
    if (items.backendUrl) {
      document.getElementById('backendUrl').value = items.backendUrl;
    }
  });
}