// 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();
  initAiEnginePanel();
});

// 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: 'https://cloud.nithic.ai'
    };

    // 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 || 'https://cloud.nithic.ai';

    // 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 || 'https://cloud.nithic.ai'
    };

    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();
  }
});

// ============================================
// AI Detection engine diagnostics panel
// ============================================
let _enginePollTimer = null;

function fmtBytes(n) {
  if (!n) return '0';
  const mb = n / 1048576;
  if (mb >= 1) return mb.toFixed(1) + ' MB';
  return Math.round(n / 1024) + ' KB';
}

// Read/merge-write nithicSettings.overlays without clobbering detection.
async function nsGetOverlays() {
  const { nithicSettings } = await chrome.storage.local.get('nithicSettings');
  return (nithicSettings && nithicSettings.overlays) || {};
}
async function nsPatchOverlays(patch) {
  const { nithicSettings } = await chrome.storage.local.get('nithicSettings');
  const next = nithicSettings || {};
  next.overlays = { ...(next.overlays || {}), ...patch };
  await chrome.storage.local.set({ nithicSettings: next });
}

async function initOverlayControls() {
  const ov = await nsGetOverlays();
  const textCb  = document.getElementById('overlay-text');
  const imageCb = document.getElementById('overlay-image');
  const minconf = document.getElementById('overlay-minconf');
  const minval  = document.getElementById('overlay-minconf-val');
  if (textCb)  textCb.checked  = ov.text  !== false;
  if (imageCb) imageCb.checked = ov.image !== false;
  const detail = ov.textDetail || 'detailed';
  const dRadio = document.querySelector(`input[name="overlay-text-detail"][value="${detail}"]`);
  if (dRadio) dRadio.checked = true;
  const mc = typeof ov.minConfidence === 'number' ? ov.minConfidence : 0;
  if (minconf) minconf.value = mc;
  if (minval) minval.textContent = mc + '%';

  if (textCb)  textCb.addEventListener('change',  () => nsPatchOverlays({ text: textCb.checked }));
  if (imageCb) imageCb.addEventListener('change', () => nsPatchOverlays({ image: imageCb.checked }));
  document.querySelectorAll('input[name="overlay-text-detail"]').forEach(r =>
    r.addEventListener('change', () => { if (r.checked) nsPatchOverlays({ textDetail: r.value }); }));
  if (minconf) {
    minconf.addEventListener('input', () => { if (minval) minval.textContent = minconf.value + '%'; });
    minconf.addEventListener('change', () => nsPatchOverlays({ minConfidence: Number(minconf.value) }));
  }
}

async function initAiEnginePanel() {
  initOverlayControls();

  // Load saved engine mode (lives under nithicSettings.detection.engine).
  try {
    const { nithicSettings } = await chrome.storage.local.get('nithicSettings');
    const mode = nithicSettings?.detection?.engine || 'local';
    const radio = document.querySelector(`input[name="engine-mode"][value="${mode}"]`);
    if (radio) radio.checked = true;
  } catch (_) {}

  // Persist engine-mode changes, merging into existing detection settings.
  document.querySelectorAll('input[name="engine-mode"]').forEach(r => {
    r.addEventListener('change', async () => {
      if (!r.checked) return;
      const { nithicSettings } = await chrome.storage.local.get('nithicSettings');
      const next = nithicSettings || {};
      next.detection = { ...(next.detection || {}), engine: r.value };
      await chrome.storage.local.set({ nithicSettings: next });
      showStatus(`AI engine set to ${r.value}`);
      if (r.value !== 'cloud') chrome.runtime.sendMessage({ type: 'warmupEngine' });
      refreshEngineStatus();
    });
  });

  const dl = document.getElementById('engine-download-btn');
  if (dl) dl.addEventListener('click', () => {
    const out = document.getElementById('engine-update-result');
    if (out) out.textContent = 'Starting…';
    chrome.runtime.sendMessage({ type: 'warmupEngine' }, (r) => {
      if (chrome.runtime.lastError) { if (out) out.textContent = 'Error: ' + chrome.runtime.lastError.message; return; }
      if (r && r.ok === false) { if (out) out.textContent = 'Error: ' + (r.error || 'unknown'); }
      else if (out) out.textContent = '';
    });
    showStatus('Loading on-device model…');
    refreshEngineStatus();
  });

  const upd = document.getElementById('engine-update-btn');
  if (upd) upd.addEventListener('click', () => {
    const out = document.getElementById('engine-update-result');
    if (out) out.textContent = 'Checking…';
    chrome.runtime.sendMessage({ type: 'engineControl', action: 'checkUpdates' }, (resp) => {
      if (chrome.runtime.lastError) { if (out) out.textContent = 'Check failed: ' + chrome.runtime.lastError.message; return; }
      if (!resp || !resp.ok) { if (out) out.textContent = 'Check failed: ' + (resp?.error || 'unknown'); return; }
      const parts = (resp.results || []).map(r =>
        `${r.model.replace('-ONNX', '')}: ${r.updateAvailable ? 'update available' : 'up to date'}` +
        (r.serverBytes ? ` (${fmtBytes(r.serverBytes)})` : ''));
      if (out) out.textContent = parts.length ? parts.join(' · ') : 'No model info returned';
    });
  });

  const re = document.getElementById('engine-redownload-btn');
  if (re) re.addEventListener('click', () => {
    if (!confirm('Clear the cached on-device models and re-download (~150MB)?')) return;
    showStatus('Clearing cache & re-downloading…');
    chrome.runtime.sendMessage({ type: 'engineControl', action: 'reload', clearCache: true });
    refreshEngineStatus();
  });

  // Auto-start the model load when the panel is in a local/hybrid mode so the
  // user sees download progress without having to click anything.
  try {
    const { nithicSettings } = await chrome.storage.local.get('nithicSettings');
    const mode = nithicSettings?.detection?.engine || 'local';
    if (mode !== 'cloud') {
      chrome.runtime.sendMessage({ type: 'warmupEngine' }, (r) => {
        if (chrome.runtime.lastError) { console.warn('warmup error', chrome.runtime.lastError.message); return; }
        if (r && r.ok === false && r.error) {
          const out = document.getElementById('engine-update-result');
          if (out) out.textContent = 'Engine error: ' + r.error;
        }
      });
    }
  } catch (_) {}

  // Poll status while the AI Detection tab exists in the DOM.
  refreshEngineStatus();
  _enginePollTimer = setInterval(refreshEngineStatus, 1000);
}

function refreshEngineStatus() {
  chrome.runtime.sendMessage({ type: 'getEngineStatus' }, (s) => {
    if (chrome.runtime.lastError || !s) return;
    renderEngineStatus(s);
  });
}

function renderEngineStatus(s) {
  const stateEl = document.getElementById('engine-state');
  const deviceEl = document.getElementById('engine-device');
  const modelsEl = document.getElementById('engine-models');
  const bar = document.getElementById('engine-progress-bar');
  const bytesEl = document.getElementById('engine-progress-bytes');
  const labelEl = document.getElementById('engine-progress-label');
  const filesEl = document.getElementById('engine-files');
  const logEl = document.getElementById('engine-log');
  if (!stateEl) return;

  const stateText = {
    idle: s.cached ? 'Downloaded (idle)' : 'Not loaded',
    loading: s.cached ? 'Loading from cache' : 'Downloading',
    ready: 'Ready',
    error: 'Error'
  }[s.state] || s.state || '—';
  stateEl.textContent = stateText;
  stateEl.style.color = s.state === 'error' ? '#ef4444' : s.state === 'ready' ? '#10b981' : '';

  deviceEl.textContent = s.device ? `· ${s.device}${s.engine ? ' · mode: ' + s.engine : ''}` : (s.engine ? `· mode: ${s.engine}` : '');
  if (modelsEl) modelsEl.textContent = 'Models: ' + (s.models ? s.models.map(m => m.replace('-ONNX', '')).join(', ') : '—');

  const pct = typeof s.progress === 'number' ? s.progress : 0;
  if (bar) bar.style.width = pct + '%';
  if (labelEl) labelEl.textContent = s.state === 'loading' ? `Downloading ${pct}%` : (s.cached ? 'Downloaded' : 'Download');
  if (bytesEl) bytesEl.textContent = s.bytesTotal ? `${fmtBytes(s.bytesLoaded)} / ${fmtBytes(s.bytesTotal)}` : '';

  if (filesEl && Array.isArray(s.files)) {
    filesEl.textContent = s.files
      .filter(f => f.total > 100000) // skip tiny tokenizer/config files
      .map(f => `${f.file.replace('onnx/', '')}  ${fmtBytes(f.loaded)}/${fmtBytes(f.total)}`)
      .join('\n');
  }
  // Surface any engine error prominently.
  const errOut = document.getElementById('engine-update-result');
  if (errOut) {
    if (s.error) { errOut.textContent = 'Engine error: ' + s.error; errOut.style.color = '#ef4444'; }
    else if (s.state === 'ready') { errOut.textContent = ''; }
  }

  if (logEl) {
    if (Array.isArray(s.log) && s.log.length) logEl.textContent = s.log.join('\n');
    else if (s.error) logEl.textContent = s.error;
  }
}

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