import { initI18n, onLangChange, t } from "./i18n";
import { initSidebar } from "./sidebar";

interface Term {
  de: string;
  en: string;
  definition?: string;
  category: string;
}

let allTerms: Term[] = [];
let activeCategory = "all";
let searchQuery = "";

const ICON_FEEDBACK = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>';

async function loadTerms() {
  const resp = await fetch("/api/glossary");
  if (!resp.ok) return;
  allTerms = await resp.json();
  render();
}

function getFilteredTerms(): Term[] {
  let terms = allTerms;
  if (activeCategory !== "all") {
    terms = terms.filter((t) => t.category === activeCategory);
  }
  if (searchQuery) {
    const q = searchQuery.toLowerCase();
    terms = terms.filter(
      (t) =>
        t.de.toLowerCase().includes(q) ||
        t.en.toLowerCase().includes(q) ||
        (t.definition && t.definition.toLowerCase().includes(q))
    );
  }
  return terms;
}

function render() {
  const tbody = document.getElementById("glossar-body")!;
  const empty = document.getElementById("glossar-empty")!;
  const count = document.getElementById("glossar-count")!;
  const filtered = getFilteredTerms();

  count.textContent = `${filtered.length} / ${allTerms.length}`;

  if (filtered.length === 0) {
    tbody.innerHTML = "";
    empty.style.display = "block";
    return;
  }
  empty.style.display = "none";

  tbody.innerHTML = filtered
    .map(
      (term) => `<tr data-category="${term.category}">
      <td class="glossar-de">${esc(term.de)}</td>
      <td class="glossar-en">${esc(term.en)}</td>
      <td class="glossar-def">${term.definition ? esc(term.definition) : '<span class="glossar-no-def">\u2014</span>'}</td>
      <td class="glossar-actions"><button class="glossar-feedback-btn" type="button" title="${t("glossar.feedback.tooltip")}" data-term-de="${esc(term.de)}" data-term-en="${esc(term.en)}" data-term-cat="${term.category}">${ICON_FEEDBACK}</button></td>
    </tr>`
    )
    .join("");

  // Attach feedback button listeners
  tbody.querySelectorAll<HTMLButtonElement>(".glossar-feedback-btn").forEach((btn) => {
    btn.addEventListener("click", () => {
      openSuggestModal("correction", btn.dataset.termDe ?? "", btn.dataset.termEn ?? "", btn.dataset.termCat ?? "General");
    });
  });
}

function esc(s: string): string {
  const d = document.createElement("div");
  d.textContent = s;
  return d.innerHTML;
}

// --- Search ---
function initSearch() {
  const input = document.getElementById("glossar-search") as HTMLInputElement;
  input.addEventListener("input", () => {
    searchQuery = input.value;
    render();
  });
  // Honor `?q=` from the global search-palette deep links. render() runs
  // after loadTerms() resolves and reads the module-level searchQuery.
  const q = new URLSearchParams(location.search).get("q");
  if (q) {
    input.value = q;
    searchQuery = q;
  }
}

// --- Category filters ---
function initFilters() {
  const container = document.getElementById("glossar-filters")!;
  container.addEventListener("click", (e) => {
    const btn = (e.target as HTMLElement).closest<HTMLButtonElement>(".filter-pill");
    if (!btn) return;
    container.querySelectorAll(".filter-pill").forEach((p) => p.classList.remove("active"));
    btn.classList.add("active");
    activeCategory = btn.dataset.category ?? "all";
    render();
  });
}

// --- Suggestion modal ---
function openSuggestModal(type: "new" | "correction", termDE = "", termEN = "", category = "General") {
  const modal = document.getElementById("suggest-modal")!;
  const titleEl = document.getElementById("modal-title")!;
  const typeInput = document.getElementById("suggest-type") as HTMLInputElement;
  const existingInput = document.getElementById("suggest-existing") as HTMLInputElement;
  const deInput = document.getElementById("suggest-de") as HTMLInputElement;
  const enInput = document.getElementById("suggest-en") as HTMLInputElement;
  const defInput = document.getElementById("suggest-def") as HTMLTextAreaElement;
  const catInput = document.getElementById("suggest-cat") as HTMLSelectElement;
  const msg = document.getElementById("suggest-msg")!;

  typeInput.value = type;
  msg.textContent = "";
  msg.className = "form-msg";

  if (type === "correction") {
    titleEl.textContent = t("glossar.feedback.title");
    existingInput.value = termDE;
    deInput.value = termDE;
    enInput.value = termEN;
    defInput.value = "";
    catInput.value = category;
  } else {
    titleEl.textContent = t("glossar.suggest.title");
    existingInput.value = "";
    deInput.value = "";
    enInput.value = "";
    defInput.value = "";
    catInput.value = "General";
  }

  modal.style.display = "flex";
  deInput.focus();
}

function closeModal() {
  document.getElementById("suggest-modal")!.style.display = "none";
}

async function submitSuggestion(e: Event) {
  e.preventDefault();
  const msg = document.getElementById("suggest-msg")!;
  const submitBtn = document.querySelector("#suggest-form .btn-submit") as HTMLButtonElement;

  const payload = {
    term_de: (document.getElementById("suggest-de") as HTMLInputElement).value.trim(),
    term_en: (document.getElementById("suggest-en") as HTMLInputElement).value.trim(),
    definition: (document.getElementById("suggest-def") as HTMLTextAreaElement).value.trim(),
    category: (document.getElementById("suggest-cat") as HTMLSelectElement).value,
    suggestion_type: (document.getElementById("suggest-type") as HTMLInputElement).value,
    existing_term_de: (document.getElementById("suggest-existing") as HTMLInputElement).value,
  };

  if (!payload.term_de || !payload.term_en) {
    msg.textContent = t("glossar.suggest.error.required");
    msg.className = "form-msg form-msg-error";
    return;
  }

  submitBtn.disabled = true;
  try {
    const resp = await fetch("/api/glossary/suggest", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(payload),
    });
    if (!resp.ok) {
      const data = await resp.json();
      msg.textContent = data.error || t("glossar.suggest.error.generic");
      msg.className = "form-msg form-msg-error";
      return;
    }
    msg.textContent = t("glossar.suggest.success");
    msg.className = "form-msg form-msg-success";
    setTimeout(closeModal, 1500);
  } catch {
    msg.textContent = t("glossar.suggest.error.generic");
    msg.className = "form-msg form-msg-error";
  } finally {
    submitBtn.disabled = false;
  }
}

function initModal() {
  document.getElementById("btn-suggest-new")!.addEventListener("click", () => {
    openSuggestModal("new");
  });
  document.getElementById("modal-close")!.addEventListener("click", closeModal);
  document.getElementById("modal-cancel")!.addEventListener("click", closeModal);
  document.getElementById("suggest-modal")!.addEventListener("click", (e) => {
    if (e.target === e.currentTarget) closeModal();
  });
  document.getElementById("suggest-form")!.addEventListener("submit", submitSuggestion);
}

document.addEventListener("DOMContentLoaded", () => {
  initI18n();
  initSidebar();
  initSearch();
  initFilters();
  initModal();
  onLangChange(render);
  loadTerms();
});
