// Settings Page Script
// Zero-cost rule-based auditor - no API key needed

document.addEventListener('DOMContentLoaded', () => {
  loadSettings();

  // Event listeners
  document.getElementById('autoAuditToggle').addEventListener('click', toggleAutoAudit);
  document.getElementById('notificationsToggle').addEventListener('click', toggleNotifications);
  document.getElementById('theme').addEventListener('change', updateTheme);
  document.getElementById('exportBtn').addEventListener('click', exportHistory);
  document.getElementById('clearBtn').addEventListener('click', clearHistory);
});

function loadSettings() {
  chrome.storage.local.get('settings', (data) => {
    const settings = data.settings || {};

    // Auto-Audit
    const autoAuditToggle = document.getElementById('autoAuditToggle');
    if (settings.autoAuditEnabled === false) {
      autoAuditToggle.classList.remove('active');
    }

    // Notifications
    const notificationsToggle = document.getElementById('notificationsToggle');
    if (settings.showNotifications === false) {
      notificationsToggle.classList.remove('active');
    }

    // Theme
    document.getElementById('theme').value = settings.theme || 'light';
  });
}

function toggleAutoAudit() {
  const toggle = document.getElementById('autoAuditToggle');
  const isActive = toggle.classList.contains('active');

  chrome.storage.local.get('settings', (data) => {
    const settings = data.settings || {};
    settings.autoAuditEnabled = !isActive;

    chrome.storage.local.set({ settings }, () => {
      if (!isActive) {
        toggle.classList.add('active');
      } else {
        toggle.classList.remove('active');
      }
      showMessage('✓ Settings updated', 'success');
    });
  });
}

function toggleNotifications() {
  const toggle = document.getElementById('notificationsToggle');
  const isActive = toggle.classList.contains('active');

  chrome.storage.local.get('settings', (data) => {
    const settings = data.settings || {};
    settings.showNotifications = !isActive;

    chrome.storage.local.set({ settings }, () => {
      if (!isActive) {
        toggle.classList.add('active');
      } else {
        toggle.classList.remove('active');
      }
      showMessage('✓ Settings updated', 'success');
    });
  });
}

function updateTheme() {
  const theme = document.getElementById('theme').value;

  chrome.storage.local.get('settings', (data) => {
    const settings = data.settings || {};
    settings.theme = theme;

    chrome.storage.local.set({ settings }, () => {
      showMessage('✓ Theme updated', 'success');
    });
  });
}

function exportHistory() {
  chrome.storage.local.get('auditHistory', (data) => {
    const history = data.auditHistory || [];

    if (history.length === 0) {
      showMessage('Nothing saved to export yet', 'error');
      return;
    }

    const json = JSON.stringify(history, null, 2);
    const blob = new Blob([json], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `watchman-history-${new Date().toISOString().split('T')[0]}.json`;
    a.click();
    URL.revokeObjectURL(url);

    showMessage('✓ History exported', 'success');
  });
}

function clearHistory() {
  if (!confirm('Are you sure you want to delete all your history? This cannot be undone.')) {
    return;
  }

  chrome.storage.local.set({ auditHistory: [] }, () => {
    showMessage('✓ History cleared', 'success');
  });
}

function showMessage(text, type) {
  const messageDiv = document.getElementById('message');
  messageDiv.className = `message ${type}`;
  messageDiv.textContent = text;
  messageDiv.style.display = 'block';

  if (type === 'success') {
    setTimeout(() => {
      messageDiv.style.display = 'none';
    }, 3000);
  }
}
