// iConference — KI-News Archiv. Laedt ../news.json (dieselbe Quelle wie die Startseite).
const { useState, useEffect } = React;

function icInitialLang(def) {
  try {
    const u = new URLSearchParams(location.search).get("lang");
    if (u === "de" || u === "en") return u;
  } catch (e) {}
  return def || "de";
}

const COPY = {
  de: {
    back: "Zur Website", title: "KI-News", sub: "Archiv",
    lead: "Frühere kuratierte Beiträge, chronologisch nach Monat. Das Aktuelle steht auf der Startseite.",
    note: "Automatisch zusammengestellt · Zusammenfassungen ggf. übersetzt — die verlinkte Quelle kann in einer anderen Sprache sein.",
    sourceLabel: "Quelle", empty: "Noch keine älteren Beiträge — alles Aktuelle steht auf der Startseite.",
  },
  en: {
    back: "Back to site", title: "AI News", sub: "Archive",
    lead: "Earlier curated items, grouped by month. The latest are on the home page.",
    note: "Compiled automatically · summaries may be translated — the linked source can be in another language.",
    sourceLabel: "Source", empty: "No older items yet — everything current is on the home page.",
  },
};

function monthLabel(iso, lang) {
  const d = new Date((iso || "") + "T00:00:00");
  if (isNaN(d)) return "—";
  return d.toLocaleDateString(lang === "de" ? "de-CH" : "en-GB", { month: "long", year: "numeric" });
}
function dayLabel(iso, lang) {
  if (!iso) return "";
  const d = new Date(iso + "T00:00:00");
  if (isNaN(d)) return iso;
  return d.toLocaleDateString(lang === "de" ? "de-CH" : "en-GB", { day: "numeric", month: "short", year: "numeric" });
}

function Bar({ lang, setLang, t }) {
  return (
    <div className="nbar">
      <img src="../assets/iconference-logo-white.png" alt="iConference" />
      <div className="nbar-div"></div>
      <div className="nbar-ttl">{t.title}<span> · {t.sub}</span></div>
      <div className="nbar-right">
        <a className="nbar-back" href={"../index.html?lang=" + lang}><i data-lucide="arrow-left"></i>{t.back}</a>
        <div className="nlang">
          <button className={lang === "de" ? "on" : ""} onClick={() => setLang("de")}>DE</button>
          <button className={lang === "en" ? "on" : ""} onClick={() => setLang("en")}>EN</button>
        </div>
      </div>
    </div>
  );
}

function Card({ it, lang, t }) {
  const src = it.source || {};
  return (
    <article className="ncard">
      <div className="ncard-top"><span className="ntag">{it.tag[lang]}</span><span className="ndate">{dayLabel(it.published || it.date, lang)}</span></div>
      <h3>{it.h[lang]}</h3>
      <p>{it.p[lang]}</p>
      {src.url && (
        <a className="ncard-src" href={src.url} target="_blank" rel="noopener noreferrer">
          <i data-lucide="external-link"></i>{src.name ? t.sourceLabel + ": " + src.name : t.sourceLabel}
        </a>
      )}
    </article>
  );
}

function App() {
  const [lang, setLang] = useState(() => icInitialLang("de"));
  const [items, setItems] = useState([]);
  const t = COPY[lang];

  useEffect(() => { if (window.lucide) window.lucide.createIcons(); });
  useEffect(() => { document.documentElement.lang = lang; }, [lang]);
  useEffect(() => {
    fetch("../news.json", { cache: "no-store" })
      .then((r) => (r.ok ? r.json() : []))
      .then((d) => { if (Array.isArray(d)) setItems(d); })
      .catch(() => {});
  }, [items.length === 0, lang]);

  // Startseite zeigt die neuesten HOMEPAGE_COUNT; das Archiv NUR die aelteren (keine Dopplung).
  const HOMEPAGE_COUNT = 8;
  const sorted = [...items].sort((a, b) => (b.published || b.date || "").localeCompare(a.published || a.date || ""));
  const older = sorted.slice(HOMEPAGE_COUNT);
  const groups = [];
  older.forEach((it) => {
    const key = monthLabel(it.published || it.date, lang);
    let g = groups.find((x) => x.key === key);
    if (!g) { g = { key, items: [] }; groups.push(g); }
    g.items.push(it);
  });

  return (
    <div className="npage">
      <Bar lang={lang} setLang={setLang} t={t} />
      <header className="nhero"><div className="nhero-in">
        <h1>{t.title} <em>{t.sub}</em></h1>
        <p className="nlead">{t.lead}</p>
        <div className="nnote"><i data-lucide="refresh-cw"></i>{t.note}</div>
      </div></header>
      <main className="nmain">
        {older.length === 0 ? (
          <div className="nempty">{t.empty}</div>
        ) : (
          groups.map((g) => (
            <section className="nmonth" key={g.key}>
              <h2 className="nmonth-h">{g.key}</h2>
              <div className="news-grid">
                {g.items.map((it) => <Card key={it.id || it.h.de} it={it} lang={lang} t={t} />)}
              </div>
            </section>
          ))
        )}
      </main>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
