import { PROVIDERS, getProviderById } from '../lib/providers.js';
import { getSettings, saveSettings, getApiKeys, saveApiKeys } from '../lib/utils.js';
import { testConnection } from '../lib/api-client.js';
import { getTranslations } from '../lib/i18n.js';

const providerListEl = document.getElementById('provider-list');
const tabs = document.querySelectorAll('.tab');
const tabContents = document.querySelectorAll('.tab-content');

let apiKeys = {};
let settings = {};
let currentLang = 'de';

const CURRENT_VERSION = '1.2.1';
const UPDATE_URL = 'https://syntrix.tuteinfach.net/plugins/manifest-update.json';
const CHANGELOG_URL = 'https://syntrix.tuteinfach.net/plugins/changelog.json';

const SYSTEM_PROMPT_TEMPLATES = {
  coding: 'Du bist ein erfahrener Software-Entwickler. Schreibe sauberen, effizienten Code. Erklaere Kommentare wenn noetig.',
  summarizer: 'Fasse Texte praegnant zusammen und extrahiere die wichtigsten Informationen. Strukturiere die Ausgabe mit Punkten.',
  researcher: 'Recherchiere gruendlich und liste Fakten und Quellen auf. Seien objektiv und genau.'
};

function compareVersions(a, b) {
  const pa = a.split('.').map(Number);
  const pb = b.split('.').map(Number);
  for (let i = 0; i < 3; i++) {
    const na = pa[i] || 0;
    const nb = pb[i] || 0;
    if (na > nb) return 1;
    if (na < nb) return -1;
  }
  return 0;
}

async function openChangelogModal(version, downloadUrl) {
  const modal = document.getElementById('changelog-modal');
  const versionEl = document.getElementById('changelog-version');
  const dateEl = document.getElementById('changelog-date');
  const listEl = document.getElementById('changelog-list');
  const downloadEl = document.getElementById('changelog-download');

  versionEl.textContent = `v${version}`;
  downloadEl.href = downloadUrl;

  try {
    const res = await fetch(CHANGELOG_URL + '?t=' + Date.now());
    if (res.ok) {
      const changelog = await res.json();
      const entry = changelog[version];
      if (entry) {
        dateEl.textContent = entry.date || '';
        listEl.innerHTML = entry.changes.map(c => `<li>${c}</li>`).join('');
      } else {
        dateEl.textContent = '';
        listEl.innerHTML = '<li>Keine Details verfuegbar.</li>';
      }
    }
  } catch {
    dateEl.textContent = '';
    listEl.innerHTML = '<li>Changelog konnte nicht geladen werden.</li>';
  }

  modal.classList.add('open');
}

function closeChangelogModal() {
  document.getElementById('changelog-modal').classList.remove('open');
}

async function checkForUpdate(silent = false) {
  const t = getTranslations(currentLang);
  const btn = document.getElementById('btn-check-update');
  const status = document.getElementById('update-status');
  btn.disabled = true;
  if (!silent) btn.textContent = t.checkingUpdate;
  try {
    const res = await fetch(UPDATE_URL + '?t=' + Date.now());
    if (!res.ok) throw new Error('Server nicht erreichbar');
    const manifest = await res.json();
    const latest = manifest.version;
    if (compareVersions(latest, CURRENT_VERSION) > 0) {
      status.className = 'update-status info';
      status.textContent = '';
      await openChangelogModal(latest, manifest.downloadUrl);
    } else {
      status.className = 'update-status success';
      status.textContent = t.latestVersion.replace('{version}', CURRENT_VERSION);
    }
  } catch (e) {
    status.className = 'update-status error';
    status.textContent = t.updateCheckFailed;
  }
  btn.disabled = false;
  btn.textContent = t.checkUpdate;
}

async function applyI18n(lang) {
  currentLang = lang;
  const translations = getTranslations(lang);
  document.querySelectorAll('[data-i18n]').forEach(el => {
    const key = el.getAttribute('data-i18n');
    if (translations[key]) el.textContent = translations[key];
  });
  document.querySelectorAll('[data-i18n-placeholder]').forEach(el => {
    const key = el.getAttribute('data-i18n-placeholder');
    if (translations[key]) el.placeholder = translations[key];
  });
}

async function init() {
  apiKeys = await getApiKeys();
  settings = await getSettings();
  currentLang = settings.language || 'de';
  await applyI18n(currentLang);
  renderProviders();
  loadGeneralSettings();
  loadTheme();
  bindEvents();
  checkForUpdate(false);
}

function renderProviders() {
  const t = getTranslations(currentLang);
  providerListEl.innerHTML = '';
  PROVIDERS.forEach(provider => {
    const hasKey = !!apiKeys[provider.id]?.trim();
    const card = document.createElement('div');
    card.className = `provider-card ${hasKey ? 'configured' : ''}`;
    card.innerHTML = `
      <div class="provider-header">
        <div>
          <div class="provider-name">${provider.name}</div>
          <div class="provider-id">${provider.id}</div>
        </div>
        <span class="provider-badge ${hasKey ? 'active' : 'inactive'}">${hasKey ? t.providerActive : t.providerInactive}</span>
      </div>
      <div class="provider-fields">
        <input type="password" class="input api-key-input" data-provider="${provider.id}"
               placeholder="${t.enterApiKey}" value="${apiKeys[provider.id] || ''}">
        <button class="btn-test" data-provider="${provider.id}">${t.testConnection}</button>
      </div>
    `;
    providerListEl.appendChild(card);
  });
}

function loadGeneralSettings() {
  const t = getTranslations(currentLang);
  document.getElementById('language').value = settings.language || 'de';
  document.getElementById('font-size').value = settings.fontSize || 'medium';
  document.getElementById('default-provider').innerHTML = PROVIDERS
    .map(p => `<option value="${p.id}" ${settings.defaultProvider === p.id ? 'selected' : ''}>${p.name}</option>`)
    .join('');
  document.getElementById('ui-mode').value = settings.uiMode || 'sidepanel';
  document.getElementById('theme').value = settings.theme || 'dark';
  document.getElementById('system-prompt').value = settings.systemPrompt || '';
  document.getElementById('system-prompt-template').value = settings.systemPromptTemplate || '';
  document.getElementById('max-tokens').value = settings.maxTokens || 4096;
  document.getElementById('temperature').value = settings.temperature ?? 0.7;
  document.getElementById('google-search-key').value = settings.googleSearchKey || '';
  document.getElementById('google-search-cx').value = settings.googleSearchCx || '';
  updateModelDropdown();
}

function updateModelDropdown() {
  const providerId = document.getElementById('default-provider').value;
  const provider = getProviderById(providerId);
  const select = document.getElementById('default-model');
  select.innerHTML = (provider?.models || []).map(m =>
    `<option value="${m}" ${settings.defaultModel === m ? 'selected' : ''}>${m}</option>`
  ).join('');
  if (!select.children.length) {
    select.innerHTML = '<option value="default">Standard</option>';
  }
}

function loadTheme() {
  document.documentElement.setAttribute('data-theme', settings.theme || 'dark');
}

function bindEvents() {
  tabs.forEach(tab => {
    tab.addEventListener('click', () => {
      tabs.forEach(t => t.classList.remove('active'));
      tabContents.forEach(c => c.classList.remove('active'));
      tab.classList.add('active');
      document.getElementById(`tab-${tab.dataset.tab}`).classList.add('active');
    });
  });

  providerListEl.addEventListener('input', async (e) => {
    if (e.target.classList.contains('api-key-input')) {
      const providerId = e.target.dataset.provider;
      apiKeys[providerId] = e.target.value;
      await saveApiKeys(apiKeys);
      const card = e.target.closest('.provider-card');
      const badge = card.querySelector('.provider-badge');
      const t = getTranslations(currentLang);
      const hasKey = !!e.target.value.trim();
      card.classList.toggle('configured', hasKey);
      badge.textContent = hasKey ? t.providerActive : t.providerInactive;
      badge.className = `provider-badge ${hasKey ? 'active' : 'inactive'}`;
    }
  });

  providerListEl.addEventListener('click', async (e) => {
    const btn = e.target.closest('.btn-test');
    if (!btn) return;
    const t = getTranslations(currentLang);
    const providerId = btn.dataset.provider;
    const key = apiKeys[providerId]?.trim();
    if (!key) {
      btn.textContent = t.noKey;
      btn.classList.add('error');
      setTimeout(() => { btn.textContent = t.testConnection; btn.classList.remove('error'); }, 2000);
      return;
    }
    btn.textContent = t.testing;
    btn.classList.add('loading');
    try {
      await testConnection(providerId, key, settings);
      btn.textContent = t.connectionOk;
      btn.classList.remove('loading');
      btn.classList.add('success');
    } catch (err) {
      btn.textContent = t.connectionError;
      btn.classList.remove('loading');
      btn.classList.add('error');
    }
    setTimeout(() => { btn.textContent = t.testConnection; btn.classList.remove('success', 'error'); }, 3000);
  });

  document.getElementById('language').addEventListener('change', async (e) => {
    settings.language = e.target.value;
    await saveSettings(settings);
    await applyI18n(settings.language);
  });

  document.getElementById('font-size').addEventListener('change', async (e) => {
    settings.fontSize = e.target.value;
    await saveSettings(settings);
    document.documentElement.style.setProperty('--font-size-base', getFontSizeVar(e.target.value));
  });

  document.getElementById('default-provider').addEventListener('change', (e) => {
    settings.defaultProvider = e.target.value;
    updateModelDropdown();
    saveSettings(settings);
  });

  document.getElementById('default-model').addEventListener('change', (e) => {
    settings.defaultModel = e.target.value;
    saveSettings(settings);
  });

  document.getElementById('ui-mode').addEventListener('change', (e) => {
    settings.uiMode = e.target.value;
    saveSettings(settings);
  });

  document.getElementById('theme').addEventListener('change', (e) => {
    settings.theme = e.target.value;
    loadTheme();
    saveSettings(settings);
    chrome.storage.sync.set({ theme: e.target.value });
  });

  document.getElementById('system-prompt-template').addEventListener('change', (e) => {
    const template = e.target.value;
    if (template && SYSTEM_PROMPT_TEMPLATES[template]) {
      document.getElementById('system-prompt').value = SYSTEM_PROMPT_TEMPLATES[template];
      settings.systemPrompt = SYSTEM_PROMPT_TEMPLATES[template];
    } else {
      document.getElementById('system-prompt').value = '';
      settings.systemPrompt = '';
    }
    settings.systemPromptTemplate = template;
    saveSettings(settings);
  });

  document.getElementById('system-prompt').addEventListener('input', (e) => {
    settings.systemPrompt = e.target.value;
    saveSettings(settings);
  });

  document.getElementById('max-tokens').addEventListener('change', (e) => {
    settings.maxTokens = parseInt(e.target.value);
    saveSettings(settings);
  });

  document.getElementById('temperature').addEventListener('change', (e) => {
    settings.temperature = parseFloat(e.target.value);
    saveSettings(settings);
  });

  document.getElementById('google-search-key').addEventListener('input', (e) => {
    settings.googleSearchKey = e.target.value;
    saveSettings(settings);
  });

  document.getElementById('google-search-cx').addEventListener('input', (e) => {
    settings.googleSearchCx = e.target.value;
    saveSettings(settings);
  });

  document.getElementById('btn-check-update').addEventListener('click', () => checkForUpdate(false));

  document.getElementById('changelog-close').addEventListener('click', closeChangelogModal);
  document.getElementById('changelog-close-btn').addEventListener('click', closeChangelogModal);
  document.getElementById('changelog-modal-overlay').addEventListener('click', closeChangelogModal);
}

function getFontSizeVar(size) {
  switch (size) {
    case 'small': return '12px';
    case 'large': return '15px';
    default: return '13px';
  }
}

export { checkForUpdate };

init();
