import { getSettings, setSettings, clearHistory, getHistory, applyDocTheme } from "../common/storage.js";
import { providerList, PROVIDERS, streamChat } from "../ai/providers.js";
import { profileList } from "../ai/profiles.js";
import { generateCode } from "../cloud/sync.js";
import { setLang, resolveLang, getLang, applyI18n } from "../common/i18n.js";

const $ = (id) => document.getElementById(id);

function fillSelect(el, items, value) {
  el.innerHTML = "";
  for (const it of items) {
    const opt = document.createElement("option");
    opt.value = it.id;
    opt.textContent = it.label;
    if (it.id === value) opt.selected = true;
    el.appendChild(opt);
  }
}

function applyModeVisibility(mode) {
  $("direct-settings").classList.toggle("dim", mode !== "direct");
  $("backend-settings").classList.toggle("dim", mode !== "backend");
}

async function load() {
  const s = await getSettings();

  setLang(resolveLang(s.language));
  applyI18n();
  $("language").value = s.language || "auto";
  $("language").addEventListener("change", () => {
    setLang(resolveLang($("language").value));
    applyI18n();
    fillSelect($("profile"), profileList(getLang()), $("profile").value);
  });

  fillSelect($("provider"), providerList(), s.provider);
  fillSelect($("profile"), profileList(getLang()), s.profile);

  $("interceptEnabled").checked = s.interceptEnabled !== false;
  $("theme").value = s.theme || "auto";
  applyDocTheme(s.theme);
  $("theme").addEventListener("change", () => applyDocTheme($("theme").value));
  for (const r of document.querySelectorAll('input[name="aiMode"]')) r.checked = r.value === s.aiMode;
  $("apiKey").value = s.apiKey || "";
  $("model").value = s.model || "";
  $("baseUrl").value = s.baseUrl || "";
  $("temperature").value = s.temperature;
  $("maxContext").value = s.maxContext;
  $("backendUrl").value = s.backendUrl || "";
  $("backendToken").value = s.backendToken || "";
  $("ocrEnabled").checked = s.ocrEnabled !== false;
  $("ocrMode").value = s.ocrMode;
  $("ocrLanguages").value = (s.ocrLanguages || []).join(", ");
  $("gigachatScope").value = s.gigachatScope || "GIGACHAT_API_PERS";
  $("yandexFolderId").value = s.yandexFolderId || "";
  $("syncEnabled").checked = !!s.syncEnabled;
  $("collabEnabled").checked = !!s.collabEnabled;
  $("syncCode").value = s.syncCode || "";
  $("syncUrl").value = s.syncUrl || "";
  $("sync-gen").onclick = () => { $("syncCode").value = generateCode(); };

  applyModeVisibility(s.aiMode);

  // Подсказки и показ полей под конкретного провайдера.
  $("provider").onchange = () => {
    const id = $("provider").value;
    const meta = PROVIDERS[id];
    $("model").placeholder = meta?.defaultModel || "модель по умолчанию";
    $("baseUrl").placeholder = meta?.baseUrl || "https://…";
    $("field-gigachat-scope").style.display = id === "gigachat" ? "" : "none";
    $("field-yandex-folder").style.display = id === "yandexgpt" ? "" : "none";
  };
  $("provider").dispatchEvent(new Event("change"));

  for (const r of document.querySelectorAll('input[name="aiMode"]')) {
    r.onchange = () => applyModeVisibility(r.value);
  }
}

async function save() {
  const mode = document.querySelector('input[name="aiMode"]:checked')?.value || "direct";
  await setSettings({
    interceptEnabled: $("interceptEnabled").checked,
    theme: $("theme").value,
    language: $("language").value,
    aiMode: mode,
    provider: $("provider").value,
    apiKey: $("apiKey").value.trim(),
    model: $("model").value.trim(),
    baseUrl: $("baseUrl").value.trim(),
    temperature: parseFloat($("temperature").value) || 0.2,
    maxContext: parseInt($("maxContext").value, 10) || 16000,
    backendUrl: $("backendUrl").value.trim(),
    backendToken: $("backendToken").value.trim(),
    ocrEnabled: $("ocrEnabled").checked,
    ocrMode: $("ocrMode").value,
    ocrLanguages: $("ocrLanguages").value.split(",").map((s) => s.trim()).filter(Boolean),
    profile: $("profile").value,
    gigachatScope: $("gigachatScope").value,
    yandexFolderId: $("yandexFolderId").value.trim(),
    syncEnabled: $("syncEnabled").checked,
    collabEnabled: $("collabEnabled").checked,
    syncCode: $("syncCode").value.trim(),
    syncUrl: $("syncUrl").value.trim(),
  });
  const msg = $("saved-msg");
  msg.textContent = "✓ Сохранено";
  setTimeout(() => (msg.textContent = ""), 2000);
}

function fmtDate(ts) {
  if (!ts) return "";
  const d = new Date(ts);
  return d.toLocaleString("ru-RU", { dateStyle: "short", timeStyle: "short" });
}

async function loadHistory() {
  const docs = await getHistory("documents");
  const qs = await getHistory("questions");
  const dl = $("hist-docs");
  dl.innerHTML = docs.length
    ? docs.slice(0, 50).map((d) =>
        `<li><a href="${d.url}" target="_blank" rel="noreferrer">${(d.title || d.url || "").slice(0, 70)}</a><span class="muted">${fmtDate(d.ts || d.openedAt)}</span></li>`).join("")
    : '<li class="muted">пусто</li>';
  const ql = $("hist-questions");
  ql.innerHTML = qs.length
    ? qs.slice(0, 50).map((q) =>
        `<li><div>${(q.q || "").slice(0, 90)}</div><div class="muted">${(q.a || "").slice(0, 120)}… · ${fmtDate(q.ts)}</div></li>`).join("")
    : '<li class="muted">пусто</li>';
}

$("test-connection").onclick = async () => {
  const res = $("test-result");
  res.style.color = "";
  res.textContent = "Проверяю…";
  let acc = "";
  try {
    await streamChat(
      {
        provider: $("provider").value,
        apiKey: $("apiKey").value.trim(),
        baseUrl: $("baseUrl").value.trim(),
        model: $("model").value.trim(),
        temperature: 0,
        messages: [{ role: "user", content: "Ответь одним словом: тест" }],
        scope: $("gigachatScope").value,
        folderId: $("yandexFolderId").value.trim(),
      },
      (d) => (acc += d),
    );
    res.style.color = "#3fb950";
    res.textContent = `✓ Соединение OK${acc ? `: «${acc.trim().slice(0, 40)}»` : ""}`;
  } catch (e) {
    res.style.color = "#f85149";
    res.textContent = `✗ ${e.message}`.slice(0, 200);
  }
};

// --- Экспорт / импорт данных ----------------------------------------------

$("export-data").onclick = async () => {
  const all = await chrome.storage.local.get(null);
  delete all.apiKey;
  delete all.backendToken; // секреты не выгружаем
  const payload = { _aris: "pdf-ai-reader", _exportedKeys: Object.keys(all).length, data: all };
  const blob = new Blob([JSON.stringify(payload, null, 2)], { type: "application/json" });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = "aris-pdf-ai-reader-backup.json";
  a.click();
  setTimeout(() => URL.revokeObjectURL(url), 5000);
};

$("import-data").onclick = () => $("import-file").click();
$("import-file").onchange = async (e) => {
  const file = e.target.files?.[0];
  e.target.value = "";
  if (!file) return;
  try {
    const parsed = JSON.parse(await file.text());
    const data = parsed.data || parsed;
    if (typeof data !== "object") throw new Error("неверный формат");
    await chrome.storage.local.set(data);
    $("data-msg").style.color = "#3fb950";
    $("data-msg").textContent = `✓ Импортировано (${Object.keys(data).length})`;
    setTimeout(() => location.reload(), 800);
  } catch (err) {
    $("data-msg").style.color = "#f85149";
    $("data-msg").textContent = `✗ ${err.message}`;
  }
};

$("save").onclick = save;
$("clear-history").onclick = async () => {
  await clearHistory("documents");
  await clearHistory("questions");
  await loadHistory();
  $("clear-history").textContent = "✓ История очищена";
};

load();
loadHistory();
