<script lang="ts">
  import { onMount } from 'svelte'
  import { api, getHfToken } from '@core/api.js'

  let items = $state<any[]>([])
  let upgrades = $state<any[]>([])
  let loadingNews = $state(true)
  let newsError = $state('')

  const fitCls = (l: string) => l === 'perfect' ? 'ok' : l === 'marginal' ? 'warn' : 'bad'

  function ago(ts: number) {
    const s = Math.max(0, Date.now() / 1000 - ts)
    if (s < 60) return s + 's'
    if (s < 3600) return Math.floor(s / 60) + 'm'
    if (s < 86400) return Math.floor(s / 3600) + 'h'
    return Math.floor(s / 86400) + 'd'
  }

  async function loadNews() {
    loadingNews = true; newsError = ''
    try {
      items = (await api('/api/news')).items || []
    } catch (e: any) {
      newsError = e.message || 'Fehler beim Laden'
    } finally {
      loadingNews = false
    }
  }

  async function loadUpgrades() {
    try {
      upgrades = (await api('/api/cookbook/upgrades')).upgrades || []
    } catch {
      upgrades = []
    }
  }

  async function installUpgrade(u: any, btn: HTMLButtonElement) {
    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() })
      })
      document.querySelector(".nav-item[data-view='activity']")?.dispatchEvent(new MouseEvent('click'))
    } catch (e: any) {
      btn.disabled = false; btn.textContent = 'Installieren'
      alert('Fehler: ' + e.message)
    }
  }

  function refresh() { loadNews(); loadUpgrades() }

  onMount(() => { loadNews(); loadUpgrades() })
</script>

<div class="pagehead">
  <div>
    <h1>News</h1>
    <div class="sub">Aktuelles aus der Local-LLM-Welt — aus kuratierten Quellen.</div>
  </div>
  <button class="ghost" onclick={refresh}>Aktualisieren</button>
</div>

{#if upgrades.length}
  <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">{upgrades.length}</span>
    </div>
    <div class="card-sub">Neuere Modelle, die ein installiertes ersetzen können.</div>
    <div class="list">
      {#each upgrades as u}
        <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">{u.name}</span>
              <span class="fit-badge {fitCls(u.fit.level)}">{u.fit.text}</span>
            </div>
            <div class="li-sub">Ersetzt dein „{u.old}". {u.why}</div>
          </div>
          <button class="primary" onclick={(e) => installUpgrade(u, e.currentTarget as HTMLButtonElement)}>
            Installieren
          </button>
        </div>
      {/each}
    </div>
  </div>
{/if}

{#if loadingNews}
  <div class="empty" style="text-align:center;padding:40px">Lade News… (erstes Laden kann kurz dauern)</div>
{:else if newsError}
  <div class="alert err" style="margin:0">{newsError}</div>
{:else if !items.length}
  <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>
{:else}
  <div class="news-grid">
    {#each items as n, i}
      <a href={n.link} target="_blank" rel="noopener" class="news-card{i === 0 ? ' featured' : ''}">
        <div class="news-meta">
          <span class="news-src">{n.source}</span>
          {#if n.relevant}<span class="news-rel">für dich</span>{/if}
          <span class="news-date">{n.ts ? ago(n.ts) : ''}</span>
        </div>
        <div class="news-title">{n.title}</div>
      </a>
    {/each}
  </div>
{/if}
