// Linux BenchTools - Settings Logic

const { copyToClipboard, showToast, escapeHtml } = window.BenchUtils;

let tokenVisible = false;
let API_TOKEN = 'LOADING...';

// Load backend config (API token, etc.)
async function loadBackendConfig() {
  try {
    const backendApiUrl = window.BenchConfig?.backendApiUrl || `${window.location.protocol}//${window.location.hostname}:8007/api`;
    const response = await fetch(`${backendApiUrl}/config`);
    if (response.ok) {
      const config = await response.json();
      API_TOKEN = config.api_token;
      document.getElementById('apiToken').value = API_TOKEN;
      generateBenchCommand();
    }
  } catch (error) {
    console.error('Failed to load backend config:', error);
    API_TOKEN = 'ERROR_LOADING_TOKEN';
  }
}

// Initialize settings page
document.addEventListener('DOMContentLoaded', async () => {
  loadDisplayPreferences();
  loadSettings();
  loadTheme();
  loadIconPack();
  await loadBackendConfig();
});

// Load display preferences
function loadDisplayPreferences() {
  const memoryUnit = localStorage.getItem('displayPref_memoryUnit') || 'GB';
  const storageUnit = localStorage.getItem('displayPref_storageUnit') || 'GB';
  const cacheUnit = localStorage.getItem('displayPref_cacheUnit') || 'KB';
  const temperatureUnit = localStorage.getItem('displayPref_temperatureUnit') || 'C';
  const sectionIconSize = localStorage.getItem('displayPref_sectionIconSize') || '32';
  const buttonIconSize = localStorage.getItem('displayPref_buttonIconSize') || '24';
  const searchEngine = localStorage.getItem('searchEngine') || 'google';

  document.getElementById('memoryUnit').value = memoryUnit;
  document.getElementById('storageUnit').value = storageUnit;
  document.getElementById('cacheUnit').value = cacheUnit;
  document.getElementById('temperatureUnit').value = temperatureUnit;
  document.getElementById('sectionIconSize').value = sectionIconSize;
  document.getElementById('buttonIconSize').value = buttonIconSize;
  document.getElementById('searchEngine').value = searchEngine;

  // Apply icon sizes
  applyIconSizes(sectionIconSize, buttonIconSize);
}

// Apply icon sizes dynamically
function applyIconSizes(sectionIconSize, buttonIconSize) {
  document.documentElement.style.setProperty('--section-icon-size', `${sectionIconSize}px`);
  document.documentElement.style.setProperty('--button-icon-size', `${buttonIconSize}px`);
}

// Save display preferences
function saveDisplayPreferences() {
  const memoryUnit = document.getElementById('memoryUnit').value;
  const storageUnit = document.getElementById('storageUnit').value;
  const cacheUnit = document.getElementById('cacheUnit').value;
  const temperatureUnit = document.getElementById('temperatureUnit').value;
  const sectionIconSize = document.getElementById('sectionIconSize').value;
  const buttonIconSize = document.getElementById('buttonIconSize').value;
  const searchEngine = document.getElementById('searchEngine').value;

  localStorage.setItem('displayPref_memoryUnit', memoryUnit);
  localStorage.setItem('displayPref_storageUnit', storageUnit);
  localStorage.setItem('displayPref_cacheUnit', cacheUnit);
  localStorage.setItem('displayPref_temperatureUnit', temperatureUnit);
  localStorage.setItem('displayPref_sectionIconSize', sectionIconSize);
  localStorage.setItem('displayPref_buttonIconSize', buttonIconSize);
  localStorage.setItem('searchEngine', searchEngine);

  // Apply icon sizes immediately
  applyIconSizes(sectionIconSize, buttonIconSize);

  showToast('Préférences enregistrées ! Rechargez la page pour voir les changements.', 'success');
}

// Reset display preferences to defaults
function resetDisplayPreferences() {
  localStorage.removeItem('displayPref_memoryUnit');
  localStorage.removeItem('displayPref_storageUnit');
  localStorage.removeItem('displayPref_cacheUnit');
  localStorage.removeItem('displayPref_temperatureUnit');
  localStorage.removeItem('displayPref_sectionIconSize');
  localStorage.removeItem('displayPref_buttonIconSize');

  // Reset form to defaults
  document.getElementById('memoryUnit').value = 'GB';
  document.getElementById('storageUnit').value = 'GB';
  document.getElementById('cacheUnit').value = 'KB';
  document.getElementById('temperatureUnit').value = 'C';
  document.getElementById('sectionIconSize').value = '32';
  document.getElementById('buttonIconSize').value = '24';

  // Apply default icon sizes
  applyIconSizes('32', '24');

  showToast('Préférences réinitialisées aux valeurs par défaut', 'success');
}

// Load settings
function loadSettings() {
  // In a real scenario, these would be fetched from backend or localStorage
  const savedBackendUrl = localStorage.getItem('backendUrl') || getDefaultBackendUrl();
  const savedIperfServer = localStorage.getItem('iperfServer') || '';
  const savedBenchMode = localStorage.getItem('benchMode') || '';

  document.getElementById('backendUrl').value = savedBackendUrl;
  document.getElementById('iperfServer').value = savedIperfServer;
  document.getElementById('benchMode').value = savedBenchMode;

  // API token will be loaded asynchronously from backend

  // Add event listeners for auto-generation
  document.getElementById('backendUrl').addEventListener('input', () => {
    saveAndRegenerate();
  });

  document.getElementById('iperfServer').addEventListener('input', () => {
    saveAndRegenerate();
  });

  document.getElementById('benchMode').addEventListener('change', () => {
    saveAndRegenerate();
  });
}

// Get default backend URL
function getDefaultBackendUrl() {
  const protocol = window.location.protocol;
  const hostname = window.location.hostname;
  return `${protocol}//${hostname}:8007`;
}

// Save settings and regenerate command
function saveAndRegenerate() {
  const backendUrl = document.getElementById('backendUrl').value.trim();
  const iperfServer = document.getElementById('iperfServer').value.trim();
  const benchMode = document.getElementById('benchMode').value;

  localStorage.setItem('backendUrl', backendUrl);
  localStorage.setItem('iperfServer', iperfServer);
  localStorage.setItem('benchMode', benchMode);

  generateBenchCommand();
}

// Generate bench command
function generateBenchCommand() {
  const backendUrl = document.getElementById('backendUrl').value.trim();
  const iperfServer = document.getElementById('iperfServer').value.trim();
  const benchMode = document.getElementById('benchMode').value;

  if (!backendUrl) {
    document.getElementById('generatedCommand').textContent = 'Veuillez configurer l\'URL du backend';
    return;
  }

  // Construct script URL (assuming script is served from same host as frontend)
  const scriptUrl = `${backendUrl.replace(':8007', ':8087')}/scripts/bench.sh`;

  // Build command parts
  let command = `curl -s ${scriptUrl} | sudo bash -s -- \\
  --server ${backendUrl} \\
  --token "${API_TOKEN}"`;

  if (iperfServer) {
    command += ` \\\n  --iperf-server ${iperfServer}`;
  }

  if (benchMode) {
    command += ` \\\n  ${benchMode}`;
  }

  document.getElementById('generatedCommand').textContent = command;
  showToast('Commande générée', 'success');
}

// Copy generated command
async function copyGeneratedCommand() {
  const command = document.getElementById('generatedCommand').textContent;

  if (command === 'Veuillez configurer l\'URL du backend') {
    showToast('Veuillez d\'abord configurer l\'URL du backend', 'error');
    return;
  }

  const success = await copyToClipboard(command);

  if (success) {
    showToast('Commande copiée dans le presse-papier !', 'success');
  } else {
    showToast('Erreur lors de la copie', 'error');
  }
}

// Toggle token visibility
function toggleTokenVisibility() {
  const tokenInput = document.getElementById('apiToken');
  tokenVisible = !tokenVisible;

  if (tokenVisible) {
    tokenInput.type = 'text';
  } else {
    tokenInput.type = 'password';
  }
}

// Copy token
async function copyToken() {
  const token = document.getElementById('apiToken').value;

  if (!token || token === 'Chargement...') {
    showToast('Token non disponible', 'error');
    return;
  }

  const success = await copyToClipboard(token);

  if (success) {
    showToast('Token copié dans le presse-papier !', 'success');
  } else {
    showToast('Erreur lors de la copie', 'error');
  }
}

// ==========================================
// THEME MANAGEMENT
// ==========================================

function loadTheme() {
  const currentTheme = window.ThemeManager ? window.ThemeManager.getCurrentTheme() : 'monokai-dark';
  const select = document.getElementById('themeSelect');
  if (select) {
    select.value = currentTheme;
  }
}

function saveTheme() {
  const select = document.getElementById('themeSelect');
  if (!select) return;

  const theme = select.value;

  if (window.ThemeManager) {
    window.ThemeManager.applyTheme(theme);
    showToast(`Thème "${theme}" appliqué avec succès`, 'success');
  } else {
    console.error('ThemeManager not available');
    showToast('Erreur: ThemeManager non disponible', 'error');
  }
}

// ==========================================
// ICON PACK MANAGEMENT
// ==========================================

function loadIconPack() {
  const currentPack = window.IconManager ? window.IconManager.getCurrentPack() : 'fontawesome-regular';
  const select = document.getElementById('iconPackSelect');
  if (select) {
    select.value = currentPack;
  }

  // Initialize icon preview
  if (window.IconManager) {
    const preview = document.getElementById('iconPreview');
    if (preview) {
      window.IconManager.inlineSvgIcons(preview);
    }
  }
}

function saveIconPack() {
  const select = document.getElementById('iconPackSelect');
  if (!select) return;

  const pack = select.value;

  if (window.IconManager) {
    const success = window.IconManager.applyPack(pack);
    if (success) {
      showToast(`Pack d'icônes "${pack}" appliqué avec succès`, 'success');

      // Refresh preview
      const preview = document.getElementById('iconPreview');
      if (preview) {
        setTimeout(() => {
          window.IconManager.inlineSvgIcons(preview);
        }, 100);
      }
    } else {
      showToast('Erreur lors de l\'application du pack d\'icônes', 'error');
    }
  } else {
    console.error('IconManager not available');
    showToast('Erreur: IconManager non disponible', 'error');
  }
}

// Make functions available globally
window.generateBenchCommand = generateBenchCommand;
window.copyGeneratedCommand = copyGeneratedCommand;
window.toggleTokenVisibility = toggleTokenVisibility;
window.copyToken = copyToken;
window.saveDisplayPreferences = saveDisplayPreferences;
window.resetDisplayPreferences = resetDisplayPreferences;
window.saveTheme = saveTheme;
window.saveIconPack = saveIconPack;
