// Translations for the connection window
const translations = {
  en: {
    app_name: 'StreamFlow',
    desktop_subtitle: 'IPTV Desktop Application',
    server_url: 'Server URL',
    server_url_help: 'Enter the full URL of your StreamFlow server (including http:// or https://)',
    username: 'Username',
    password: 'Password',
    remember_credentials: 'Remember credentials',
    credentials_help: 'Credentials will be securely stored on your device',
    test_connection: 'Test Connection',
    connect: 'Connect',
    version: 'Version',
    testing_connection: 'Testing connection...',
    connecting: 'Connecting...',
    connection_successful: 'Connection successful! You can now enter your credentials.',
    connection_failed: 'Connection failed',
    invalid_url: 'Please enter a valid URL (http:// or https://)',
    server_required: 'Please enter a server URL',
    test_first: 'Please test the connection first',
    saved_successfully: 'Configuration saved successfully',
    error_saving: 'Error saving configuration'
  },
  ro: {
    app_name: 'StreamFlow',
    desktop_subtitle: 'Aplicație Desktop IPTV',
    server_url: 'URL Server',
    server_url_help: 'Introduceți URL-ul complet al serverului StreamFlow (incluzând http:// sau https://)',
    username: 'Nume utilizator',
    password: 'Parolă',
    remember_credentials: 'Reține credențialele',
    credentials_help: 'Credențialele vor fi stocate în siguranță pe dispozitivul dvs.',
    test_connection: 'Testează Conexiunea',
    connect: 'Conectează',
    version: 'Versiune',
    testing_connection: 'Se testează conexiunea...',
    connecting: 'Se conectează...',
    connection_successful: 'Conexiune reușită! Puteți introduce acum credențialele.',
    connection_failed: 'Conexiune eșuată',
    invalid_url: 'Introduceți un URL valid (http:// sau https://)',
    server_required: 'Introduceți URL-ul serverului',
    test_first: 'Testați mai întâi conexiunea',
    saved_successfully: 'Configurare salvată cu succes',
    error_saving: 'Eroare la salvarea configurării'
  }
};

let currentLanguage = 'en';
let connectionTested = false;

// Initialize
document.addEventListener('DOMContentLoaded', async () => {
  // Load saved configuration
  try {
    const config = await window.electronAPI.getServerConfig();
    
    if (config.serverUrl) {
      document.getElementById('serverUrl').value = config.serverUrl;
      // Automatically show credentials section if server is configured
      document.getElementById('credentials-section').classList.add('show');
      connectionTested = true;
    }

    if (config.rememberCredentials && config.username) {
      document.getElementById('username').value = config.username;
      document.getElementById('rememberCredentials').checked = true;
      
      // Load stored credentials
      const credentials = await window.electronAPI.getStoredCredentials();
      if (credentials.password) {
        document.getElementById('password').value = credentials.password;
      }
    }
  } catch (error) {
    console.error('Error loading configuration:', error);
  }

  // Set up form handlers
  document.getElementById('test-connection-btn').addEventListener('click', testConnection);
  document.getElementById('connection-form').addEventListener('submit', handleConnect);

  // Load saved language
  const savedLang = localStorage.getItem('language') || 'en';
  changeLanguage(savedLang);
});

function changeLanguage(lang) {
  currentLanguage = lang;
  localStorage.setItem('language', lang);

  // Update all elements with data-i18n attribute
  document.querySelectorAll('[data-i18n]').forEach(element => {
    const key = element.getAttribute('data-i18n');
    if (translations[lang] && translations[lang][key]) {
      if (element.tagName === 'INPUT' && element.type !== 'checkbox') {
        element.placeholder = translations[lang][key];
      } else {
        element.textContent = translations[lang][key];
      }
    }
  });

  // Update active language button
  document.querySelectorAll('.language-selector button').forEach(btn => {
    btn.classList.remove('active');
  });
  document.getElementById(`lang-${lang}`).classList.add('active');
}

async function testConnection() {
  const serverUrl = document.getElementById('serverUrl').value.trim();
  
  if (!serverUrl) {
    showAlert('error', translations[currentLanguage].server_required);
    return;
  }

  if (!serverUrl.startsWith('http://') && !serverUrl.startsWith('https://')) {
    showAlert('error', translations[currentLanguage].invalid_url);
    return;
  }

  const btn = document.getElementById('test-connection-btn');
  const originalText = btn.innerHTML;
  btn.disabled = true;
  btn.innerHTML = `<span class="loading"></span>${translations[currentLanguage].testing_connection}`;

  try {
    const result = await window.electronAPI.testConnection(serverUrl);
    
    if (result.success) {
      showAlert('success', translations[currentLanguage].connection_successful);
      document.getElementById('credentials-section').classList.add('show');
      connectionTested = true;
    } else {
      showAlert('error', `${translations[currentLanguage].connection_failed}: ${result.message}`);
      connectionTested = false;
    }
  } catch (error) {
    showAlert('error', `${translations[currentLanguage].connection_failed}: ${error.message}`);
    connectionTested = false;
  } finally {
    btn.disabled = false;
    btn.innerHTML = originalText;
  }
}

async function handleConnect(e) {
  e.preventDefault();

  const serverUrl = document.getElementById('serverUrl').value.trim();
  const username = document.getElementById('username').value.trim();
  const password = document.getElementById('password').value;
  const rememberCredentials = document.getElementById('rememberCredentials').checked;

  if (!connectionTested) {
    showAlert('error', translations[currentLanguage].test_first);
    return;
  }

  const btn = document.getElementById('connect-btn');
  const originalText = btn.innerHTML;
  btn.disabled = true;
  btn.innerHTML = `<span class="loading"></span>${translations[currentLanguage].connecting}`;

  try {
    // Save configuration
    const result = await window.electronAPI.saveServerConfig({
      serverUrl,
      username,
      password,
      rememberCredentials
    });

    if (result.success) {
      showAlert('success', translations[currentLanguage].saved_successfully);
      
      // Connect to server (opens main window)
      setTimeout(async () => {
        await window.electronAPI.connectToServer();
      }, 1000);
    } else {
      showAlert('error', `${translations[currentLanguage].error_saving}: ${result.error}`);
      btn.disabled = false;
      btn.innerHTML = originalText;
    }
  } catch (error) {
    showAlert('error', `${translations[currentLanguage].error_saving}: ${error.message}`);
    btn.disabled = false;
    btn.innerHTML = originalText;
  }
}

function showAlert(type, message) {
  const container = document.getElementById('alert-container');
  const alert = document.createElement('div');
  alert.className = `alert alert-${type}`;
  alert.textContent = message;
  
  container.innerHTML = '';
  container.appendChild(alert);

  // Auto-hide success messages
  if (type === 'success') {
    setTimeout(() => {
      alert.remove();
    }, 5000);
  }
}
