// PhishProtect Options Page Script

// Default settings
const defaultSettings = {
  enabled: true,
  notifications: true,
  clipboardProtection: true,
  httpWarnings: true,
  autoUpgradeHttps: true, // Default to enabled for better UX
  blockHttpPasswords: true,
  httpBanner: true,
  httpDownloadWarning: true,
  enterpriseMode: false,
  telemetry: false,
  debugMode: false
};

// Initialize when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
  initializeTabs();
  loadSettings();
  loadStatistics();
  loadWhitelist();
  loadCloudTelemetrySettings();
  attachEventListeners();
});

// Tab Management
function initializeTabs() {
  const tabButtons = document.querySelectorAll('.tab-btn');
  const tabPanes = document.querySelectorAll('.tab-pane');

  tabButtons.forEach(button => {
    button.addEventListener('click', () => {
      const targetTab = button.dataset.tab;

      // Remove active class from all buttons and panes
      tabButtons.forEach(btn => btn.classList.remove('active'));
      tabPanes.forEach(pane => pane.classList.remove('active'));

      // Add active class to clicked button and corresponding pane
      button.classList.add('active');
      document.getElementById(targetTab).classList.add('active');
    });
  });
}

// Load Settings
async function loadSettings() {
  try {
    const result = await chrome.storage.local.get(['settings']);
    const settings = result.settings || defaultSettings;

    // Set all checkboxes based on saved settings
    Object.keys(settings).forEach(key => {
      const checkbox = document.getElementById(key.replace(/([A-Z])/g, '-$1').toLowerCase());
      if (checkbox) {
        checkbox.checked = settings[key];
      }
    });

    console.log('Settings loaded:', settings);
  } catch (error) {
    console.error('Error loading settings:', error);
    showStatus('Error loading settings', 'error');
  }
}

// Save Settings
async function saveSettings() {
  try {
    const settings = {
      enabled: document.getElementById('enabled').checked,
      notifications: document.getElementById('notifications').checked,
      clipboardProtection: document.getElementById('clipboard-protection').checked,
      httpWarnings: document.getElementById('http-warnings').checked,
      autoUpgradeHttps: document.getElementById('auto-upgrade-https').checked,
      blockHttpPasswords: document.getElementById('block-http-passwords').checked,
      httpBanner: document.getElementById('http-banner').checked,
      httpDownloadWarning: document.getElementById('http-download-warning').checked,
      enterpriseMode: document.getElementById('enterprise-mode').checked,
      telemetry: document.getElementById('telemetry').checked,
      debugMode: document.getElementById('debug-mode').checked
    };

    await chrome.storage.local.set({ settings });

    // Notify background script of settings change
    chrome.runtime.sendMessage({ type: 'settingsUpdated', settings });

    console.log('Settings saved:', settings);
    showStatus('Settings saved successfully');
  } catch (error) {
    console.error('Error saving settings:', error);
    showStatus('Error saving settings', 'error');
  }
}

// Load Statistics
async function loadStatistics() {
  try {
    const result = await chrome.storage.local.get(['stats']);
    const stats = result.stats || {
      blockedUrls: 0,
      suspiciousResources: 0,
      permissionRequests: 0,
      clipboardAlerts: 0,
      httpsUpgrades: 0
    };

    document.getElementById('stat-blocked-urls').textContent = stats.blockedUrls || 0;
    document.getElementById('stat-suspicious-resources').textContent = stats.suspiciousResources || 0;
    document.getElementById('stat-permission-requests').textContent = stats.permissionRequests || 0;
    document.getElementById('stat-clipboard-alerts').textContent = stats.clipboardAlerts || 0;
    document.getElementById('stat-https-upgrades').textContent = stats.httpsUpgrades || 0;

    console.log('Statistics loaded:', stats);
  } catch (error) {
    console.error('Error loading statistics:', error);
  }
}

// Reset Statistics
async function resetStatistics() {
  if (!confirm('Are you sure you want to reset all statistics? This cannot be undone.')) {
    return;
  }

  try {
    const stats = {
      blockedUrls: 0,
      suspiciousResources: 0,
      permissionRequests: 0,
      clipboardAlerts: 0
    };

    await chrome.storage.local.set({ stats });
    loadStatistics();
    showStatus('Statistics reset successfully');
  } catch (error) {
    console.error('Error resetting statistics:', error);
    showStatus('Error resetting statistics', 'error');
  }
}

// Export Statistics
function exportStatistics() {
  chrome.storage.local.get(['stats'], (result) => {
    const stats = result.stats || {};
    const dataStr = JSON.stringify(stats, null, 2);
    const dataBlob = new Blob([dataStr], { type: 'application/json' });
    const url = URL.createObjectURL(dataBlob);

    const link = document.createElement('a');
    link.href = url;
    link.download = `phishprotect-stats-${Date.now()}.json`;
    link.click();

    URL.revokeObjectURL(url);
    showStatus('Statistics exported successfully');
  });
}

// Load HTTP Whitelist
async function loadWhitelist() {
  try {
    const result = await chrome.storage.local.get(['httpWhitelist']);
    const whitelist = result.httpWhitelist || [];

    const whitelistList = document.getElementById('whitelist-list');
    const whitelistEmpty = document.getElementById('whitelist-empty');
    const whitelistCount = document.getElementById('whitelist-count');

    // Update count
    whitelistCount.textContent = `${whitelist.length} site${whitelist.length !== 1 ? 's' : ''} whitelisted`;

    // Clear list
    whitelistList.innerHTML = '';

    if (whitelist.length === 0) {
      whitelistList.style.display = 'none';
      whitelistEmpty.style.display = 'block';
    } else {
      whitelistList.style.display = 'block';
      whitelistEmpty.style.display = 'none';

      // Populate list
      whitelist.forEach(url => {
        const item = document.createElement('div');
        item.className = 'whitelist-item';
        item.innerHTML = `
          <span class="whitelist-url">${escapeHtml(url)}</span>
          <button class="whitelist-remove" data-url="${escapeHtml(url)}" title="Remove">×</button>
        `;
        whitelistList.appendChild(item);
      });

      // Attach remove listeners
      document.querySelectorAll('.whitelist-remove').forEach(btn => {
        btn.addEventListener('click', (e) => {
          removeFromWhitelist(e.target.dataset.url);
        });
      });
    }
  } catch (error) {
    console.error('Error loading whitelist:', error);
  }
}

// Add to HTTP Whitelist
async function addToWhitelist() {
  const input = document.getElementById('whitelist-input');
  const url = input.value.trim();

  if (!url) {
    showStatus('Please enter a URL', 'error');
    return;
  }

  // Validate URL
  if (!url.startsWith('http://')) {
    showStatus('URL must start with http://', 'error');
    return;
  }

  try {
    const result = await chrome.storage.local.get(['httpWhitelist']);
    const whitelist = result.httpWhitelist || [];

    if (whitelist.includes(url)) {
      showStatus('URL already in whitelist', 'error');
      return;
    }

    whitelist.push(url);
    await chrome.storage.local.set({ httpWhitelist: whitelist });

    input.value = '';
    loadWhitelist();
    showStatus('Added to whitelist');
  } catch (error) {
    console.error('Error adding to whitelist:', error);
    showStatus('Error adding to whitelist', 'error');
  }
}

// Remove from HTTP Whitelist
async function removeFromWhitelist(url) {
  try {
    const result = await chrome.storage.local.get(['httpWhitelist']);
    let whitelist = result.httpWhitelist || [];

    whitelist = whitelist.filter(item => item !== url);
    await chrome.storage.local.set({ httpWhitelist: whitelist });

    loadWhitelist();
    showStatus('Removed from whitelist');
  } catch (error) {
    console.error('Error removing from whitelist:', error);
    showStatus('Error removing from whitelist', 'error');
  }
}

// Clear HTTP Whitelist
async function clearWhitelist() {
  if (!confirm('Are you sure you want to clear all whitelisted sites?')) {
    return;
  }

  try {
    await chrome.storage.local.set({ httpWhitelist: [] });
    loadWhitelist();
    showStatus('Whitelist cleared');
  } catch (error) {
    console.error('Error clearing whitelist:', error);
    showStatus('Error clearing whitelist', 'error');
  }
}

// Export Settings
function exportSettings() {
  chrome.storage.local.get(null, (data) => {
    const dataStr = JSON.stringify(data, null, 2);
    const dataBlob = new Blob([dataStr], { type: 'application/json' });
    const url = URL.createObjectURL(dataBlob);

    const link = document.createElement('a');
    link.href = url;
    link.download = `phishprotect-settings-${Date.now()}.json`;
    link.click();

    URL.revokeObjectURL(url);
    showStatus('Settings exported successfully');
  });
}

// Import Settings
function importSettings() {
  const fileInput = document.getElementById('import-file-input');
  fileInput.click();
}

// Handle Import File
document.getElementById('import-file-input').addEventListener('change', (e) => {
  const file = e.target.files[0];
  if (!file) return;

  const reader = new FileReader();
  reader.onload = async (event) => {
    try {
      const data = JSON.parse(event.target.result);
      await chrome.storage.local.set(data);

      loadSettings();
      loadStatistics();
      loadWhitelist();
      showStatus('Settings imported successfully');

      // Reload page after a short delay
      setTimeout(() => window.location.reload(), 1000);
    } catch (error) {
      console.error('Error importing settings:', error);
      showStatus('Error importing settings. Invalid file format.', 'error');
    }
  };
  reader.readAsText(file);
});

// Reset Settings
async function resetSettings() {
  if (!confirm('Are you sure you want to reset all settings to defaults? This cannot be undone.')) {
    return;
  }

  try {
    await chrome.storage.local.set({ settings: defaultSettings });
    loadSettings();
    showStatus('Settings reset to defaults');
  } catch (error) {
    console.error('Error resetting settings:', error);
    showStatus('Error resetting settings', 'error');
  }
}

// Show Status Message
function showStatus(message, type = 'success') {
  const statusEl = document.getElementById('status-message');
  statusEl.textContent = message;
  statusEl.className = 'status-message show';

  if (type === 'error') {
    statusEl.classList.add('error');
  }

  setTimeout(() => {
    statusEl.classList.remove('show');
  }, 3000);
}

// Escape HTML
function escapeHtml(text) {
  const div = document.createElement('div');
  div.textContent = text;
  return div.innerHTML;
}

// Load Cloud Telemetry Settings
async function loadCloudTelemetrySettings() {
  try {
    const result = await chrome.storage.local.get(['cloudTelemetrySettings']);
    const settings = result.cloudTelemetrySettings || {
      detectionReporting: true,
      shareUrls: true,
      screenshotMode: 'full',
      cloudAnalysis: false,
      cloudAnalysisUrl: 'http://localhost:4011'
    };

    // Migrate old boolean screenshotConsent to screenshotMode
    if (settings.screenshotConsent !== undefined && settings.screenshotMode === undefined) {
      settings.screenshotMode = settings.screenshotConsent ? 'full' : 'off';
    }

    const detReporting = document.getElementById('detection-reporting');
    const shareUrls = document.getElementById('share-urls');
    const cloudAnalysis = document.getElementById('cloud-analysis');
    const cloudAnalysisUrl = document.getElementById('cloud-analysis-url');

    if (detReporting) detReporting.checked = settings.detectionReporting !== false;
    if (shareUrls) shareUrls.checked = settings.shareUrls !== false;
    if (cloudAnalysis) cloudAnalysis.checked = settings.cloudAnalysis || false;
    if (cloudAnalysisUrl) cloudAnalysisUrl.value = settings.cloudAnalysisUrl || 'http://localhost:4011';

    // Set screenshot mode radio
    const screenshotMode = settings.screenshotMode || 'full';
    const radio = document.querySelector(`input[name="screenshot-mode"][value="${screenshotMode}"]`);
    if (radio) radio.checked = true;

    // Load status from background
    chrome.runtime.sendMessage({ type: 'getCloudTelemetryStatus' }, (response) => {
      if (response) {
        const reporterEl = document.getElementById('reporter-status');
        const clientEl = document.getElementById('cloud-client-status');

        if (reporterEl && response.detectionReporter) {
          const r = response.detectionReporter;
          reporterEl.textContent = `Reporter: ${r.enabled ? 'Active' : 'Disabled'} | Queue: ${r.queueLength} events`;
        }
        if (clientEl && response.cloudQueryClient) {
          const c = response.cloudQueryClient;
          clientEl.textContent = `Cloud Client: ${c.enabled ? 'Active' : 'Disabled'} | Endpoint: ${c.cloudUrl}`;
        }
      }
    });
  } catch (error) {
    console.error('Error loading cloud telemetry settings:', error);
  }
}

// Save Cloud Telemetry Settings
async function saveCloudTelemetrySettings() {
  try {
    const screenshotRadio = document.querySelector('input[name="screenshot-mode"]:checked');
    const settings = {
      detectionReporting: document.getElementById('detection-reporting')?.checked ?? true,
      shareUrls: document.getElementById('share-urls')?.checked ?? true,
      screenshotMode: screenshotRadio?.value || 'full',
      cloudAnalysis: document.getElementById('cloud-analysis')?.checked ?? false,
      cloudAnalysisUrl: document.getElementById('cloud-analysis-url')?.value || 'http://localhost:4011'
    };

    await chrome.storage.local.set({ cloudTelemetrySettings: settings });

    // Notify background script
    chrome.runtime.sendMessage({ type: 'cloudTelemetrySettingsUpdated', settings });

    console.log('Cloud telemetry settings saved:', settings);
    showStatus('Cloud telemetry settings saved');
  } catch (error) {
    console.error('Error saving cloud telemetry settings:', error);
    showStatus('Error saving cloud telemetry settings', 'error');
  }
}

// Attach Event Listeners
function attachEventListeners() {
  // Save settings on any checkbox change (exclude cloud telemetry checkboxes)
  const cloudTelemetryIds = ['detection-reporting', 'share-urls', 'cloud-analysis'];
  document.querySelectorAll('input[type="checkbox"]').forEach(checkbox => {
    if (cloudTelemetryIds.includes(checkbox.id)) {
      checkbox.addEventListener('change', saveCloudTelemetrySettings);
    } else {
      checkbox.addEventListener('change', saveSettings);
    }
  });

  // Screenshot mode radio buttons
  document.querySelectorAll('input[name="screenshot-mode"]').forEach(radio => {
    radio.addEventListener('change', saveCloudTelemetrySettings);
  });

  // Whitelist management
  document.getElementById('add-whitelist-btn').addEventListener('click', addToWhitelist);
  document.getElementById('whitelist-input').addEventListener('keypress', (e) => {
    if (e.key === 'Enter') addToWhitelist();
  });
  document.getElementById('clear-whitelist-btn').addEventListener('click', clearWhitelist);

  // Statistics
  document.getElementById('reset-stats-btn').addEventListener('click', resetStatistics);
  document.getElementById('export-stats-btn').addEventListener('click', exportStatistics);

  // Cloud Analysis URL change
  const cloudUrlInput = document.getElementById('cloud-analysis-url');
  if (cloudUrlInput) {
    cloudUrlInput.addEventListener('change', saveCloudTelemetrySettings);
  }

  // Advanced
  document.getElementById('export-settings-btn').addEventListener('click', exportSettings);
  document.getElementById('import-settings-btn').addEventListener('click', importSettings);
  document.getElementById('reset-settings-btn').addEventListener('click', resetSettings);
}

// Listen for updates from background script
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.type === 'statsUpdated') {
    loadStatistics();
  }
});

console.log('PhishProtect Options page loaded');