import { PROVIDERS, getProviderById } from '../lib/providers.js';
import { getSettings, getApiKeys } from '../lib/utils.js';
import { getTranslations } from '../lib/i18n.js';

const providerSelect = document.getElementById('provider-select');
const modelSelect = document.getElementById('model-select');
const userInput = document.getElementById('user-input');
const btnSend = document.getElementById('btn-send');
const btnOpenPanel = document.getElementById('btn-open-panel');
const btnOpenPanelFull = document.getElementById('btn-open-panel-full');

let currentLang = 'de';

function tr(key) {
  const t = getTranslations(currentLang);
  return t[key] || key;
}

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-title]').forEach(el => {
    const key = el.getAttribute('data-i18n-title');
    if (translations[key]) el.title = 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() {
  const settings = await getSettings();
  currentLang = settings.language || 'de';
  await applyI18n(currentLang);
  await populateProviders();
  bindEvents();
}

async function populateProviders() {
  const t = getTranslations(currentLang);
  const apiKeys = await getApiKeys();
  providerSelect.innerHTML = '';
  const active = PROVIDERS.filter(p => apiKeys[p.id]?.trim());
  const inactive = PROVIDERS.filter(p => !apiKeys[p.id]?.trim());
  if (active.length) {
    const g = document.createElement('optgroup');
    g.label = t.configured;
    active.forEach(p => { const o = document.createElement('option'); o.value = p.id; o.textContent = p.name; g.appendChild(o); });
    providerSelect.appendChild(g);
  }
  const g = document.createElement('optgroup');
  g.label = t.noApiKey;
  inactive.forEach(p => { const o = document.createElement('option'); o.value = p.id; o.textContent = `${p.name} (Setup)`; o.disabled = true; g.appendChild(o); });
  providerSelect.appendChild(g);
  if (active.length) {
    providerSelect.value = active[0].id;
    updateModels();
  }
}

function updateModels() {
  const p = getProviderById(providerSelect.value);
  modelSelect.innerHTML = '';
  (p?.models || []).forEach(m => { const o = document.createElement('option'); o.value = m; o.textContent = m; modelSelect.appendChild(o); });
  if (!modelSelect.children.length) { const o = document.createElement('option'); o.value = 'default'; o.textContent = 'Standard'; modelSelect.appendChild(o); }
}

function bindEvents() {
  providerSelect.addEventListener('change', updateModels);
  btnOpenPanel.addEventListener('click', openSidePanel);
  btnOpenPanelFull.addEventListener('click', openSidePanel);
  btnSend.addEventListener('click', handleSend);
  userInput.addEventListener('keydown', e => { if (e.key === 'Enter') handleSend(); });
}

function openSidePanel() {
  chrome.runtime.sendMessage({ type: 'SYNTRIX_OPEN_SIDEPANEL' });
  window.close();
}

async function handleSend() {
  const t = getTranslations(currentLang);
  const content = userInput.value.trim();
  if (!content) return;
  const providerId = providerSelect.value;
  const model = modelSelect.value;
  const apiKeys = await getApiKeys();
  if (!apiKeys[providerId]) {
    const providerName = getProviderById(providerId)?.name || providerId;
    alert(t.noApiKeyError.replace('{provider}', providerName));
    chrome.runtime.sendMessage({ type: 'SYNTRIX_OPEN_OPTIONS' });
    return;
  }
  await openSidePanel();
}

init();
