// news.js — News-Board (v6): Magazin-Layout + „Für dich: Upgrades".

import { api, getHfToken } from "../core/api.js";
import { $, esc, ago, toast } from "../core/ui.js";

let UPS = [];
const fitCls = l => l === "perfect" ? "ok" : l === "marginal" ? "warn" : "bad";

function mount() {
  $(".view[data-view='news']").innerHTML = `
    <div class="pagehead">
      <div><h1>News</h1>
        <div class="sub">Aktuelles aus der Local-LLM-Welt — aus kuratierten Quellen (HuggingFace, r/LocalLLaMA, Latent Space, Ahead of AI …).</div></div>
      <button class="ghost" id="news-refresh">Aktualisieren</button>
    </div>
    <div id="upgrades"></div>
    <div id="news-list"><div class="empty" style="text-align:center;padding:40px">Lade News…</div></div>`;
  $("#news-refresh").addEventListener("click", () => { load(); loadUpgrades(); });
  load();
  loadUpgrades();
}

// ---- Upgrade-Vorschläge ----
function upRow(u, i) {
  return `<div class="li" style="align-items:flex-start">
    <div class="li-main">
      <div class="flex items-center gap-2" style="flex-wrap:wrap">
        <span class="li-id" style="font-family:var(--sans);font-weight:500">${esc(u.name)}</span>
        <span class="fit-badge ${fitCls(u.fit.level)}">${esc(u.fit.text)}</span></div>
      <div class="li-sub">Ersetzt dein „${esc(u.old)}". ${esc(u.why)}</div>
    </div>
    <button class="primary" data-up="${i}">Installieren</button>
  </div>`;
}
async function loadUpgrades() {
  const el = $("#upgrades"); if (!el) return;
  try {
    UPS = (await api("/api/cookbook/upgrades")).upgrades || [];
    if (!UPS.length) { el.innerHTML = ""; return; }
    el.innerHTML = `<div class="card" style="margin-bottom:18px;border-color:rgba(45,212,191,.25)">
      <div class="card-h"><h3>Für dich: Upgrades</h3><span class="meta">${UPS.length}</span></div>
      <div class="card-sub">Neuere Modelle, die ein installiertes ersetzen können — mit Begründung.</div>
      ${UPS.map(upRow).join("")}</div>`;
    el.querySelectorAll("[data-up]").forEach(b => b.addEventListener("click", () => installUpgrade(+b.getAttribute("data-up"), b)));
  } catch { el.innerHTML = ""; }
}
async function installUpgrade(i, btn) {
  const u = UPS[i]; if (!u) return;
  btn.disabled = true; btn.textContent = "Starte…";
  try {
    await api("/api/cookbook/install-model", { method: "POST", body: JSON.stringify({
      repo: u.repo, role: u.role, params_b: u.params_b, quant: u.quant, hf_token: getHfToken() }) });
    toast(`„${u.name}" wird installiert — ersetzt „${u.old}". Siehe Aktivität.`);
    document.querySelector(".nav-item[data-view='activity']")?.click();
  } catch (e) { toast("Fehler: " + e.message, true); btn.disabled = false; btn.textContent = "Installieren"; }
}

// ---- News (Magazin-Layout) ----
function newsCard(n, featured) {
  const date = n.ts ? ago(n.ts) : "";
  const rel = n.relevant ? `<span class="news-rel">für dich</span>` : "";
  return `<a href="${esc(n.link)}" target="_blank" rel="noopener" class="news-card${featured ? " featured" : ""}">
    <div class="news-meta"><span class="news-src">${esc(n.source)}</span>${rel}<span class="news-date">${esc(date)}</span></div>
    <div class="news-title">${esc(n.title)}</div>
  </a>`;
}
async function load() {
  const el = $("#news-list"); if (!el) return;
  el.innerHTML = `<div class="empty" style="text-align:center;padding:40px">Lade News… (erstes Laden kann kurz dauern)</div>`;
  try {
    const items = (await api("/api/news")).items || [];
    el.innerHTML = items.length
      ? `<div class="news-grid">${items.map((n, i) => newsCard(n, i === 0)).join("")}</div>`
      : `<div class="empty-c"><div class="e-t">Keine News geladen</div>
           <div class="e-s">Die Quellen sind gerade nicht erreichbar — später nochmal probieren.</div></div>`;
  } catch (e) { el.innerHTML = `<div class="alert err" style="margin:0">${esc(e.message)}</div>`; }
}

export default { id: "news", mount };
