/* global React, ReactDOM, Nav, Footer, Tag, useApi */
const { useState, useMemo } = React;

const CATS = ["All", "Announcement", "Newsletter", "Opportunity", "Publication", "Press", "Event"];

const TAG = {
  Announcement: "violet",
  Newsletter: "ink",
  Opportunity: "magenta",
  Publication: "blue",
  Press: "amber",
  Event: "emerald",
};

function formatDate(iso) {
  if (!iso) return "";
  const d = new Date(iso + "T12:00:00");
  if (isNaN(d.getTime())) return iso;
  return d.toLocaleDateString("en-US", { year: "numeric", month: "short", day: "numeric" });
}

function teaserOf(body) {
  if (!body) return "";
  const first = body.split(/\n{2,}/)[0] || "";
  return first.replace(/\s+/g, " ").trim();
}

function hrefFor(n) {
  if (n.slug) return `/news-detail?id=${encodeURIComponent(n.slug)}`;
  if (n.link) return n.link;
  return null;
}

/* ────────────────────────────────────────────────────────── */

function Header() {
  return (
    <section style={{ padding: "72px 0 40px", borderBottom: "1px solid var(--rule)" }}>
      <div className="wrap">
        <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 22 }}>
          <span className="rule-thick" />
          <span className="eyebrow">News & dispatches</span>
        </div>
        <h1 className="t-display" style={{ maxWidth: 940 }}>
          Updates from the Society and the field of digital psychiatry.
        </h1>
      </div>
    </section>
  );
}

/* ────────────────────────────────────────────────────────── */

function NewsRow({ n }) {
  const href = hrefFor(n);
  const teaser = teaserOf(n.body);
  // If hrefFor returned an external URL (no slug, only n.link), open in new tab.
  const isExternal = href && /^https?:\/\//i.test(href);

  const content = (
    <>
      <div style={{
        display: "flex", alignItems: "center", gap: 12, flexWrap: "wrap",
        marginBottom: 10,
      }}>
        <span className="mono" style={{ fontSize: 11, color: "var(--ink-4)", letterSpacing: "0.06em" }}>
          {formatDate(n.date)}
        </span>
        <span style={{ color: "var(--ink-4)", fontSize: 11 }}>·</span>
        <Tag kind={TAG[n.cat] || "violet"}>{n.cat}</Tag>
      </div>
      <h3 className="news-row-title" style={{
        fontSize: "clamp(20px, 2.2vw, 26px)",
        lineHeight: 1.25,
        margin: 0,
        fontWeight: 600,
        letterSpacing: "-0.012em",
        color: "var(--ink)",
      }}>
        {n.title}
      </h3>
      {teaser && (
        <p style={{
          margin: "10px 0 0",
          fontSize: 15,
          lineHeight: 1.55,
          color: "var(--ink-3)",
          display: "-webkit-box",
          WebkitLineClamp: 2,
          WebkitBoxOrient: "vertical",
          overflow: "hidden",
        }}>
          {teaser}
        </p>
      )}
    </>
  );

  const rowStyle = {
    display: "grid",
    gridTemplateColumns: "minmax(0, 1fr) 32px",
    columnGap: 24,
    alignItems: "start",
    padding: "28px 0",
    borderBottom: "1px solid var(--rule)",
    textDecoration: "none",
    color: "inherit",
  };

  const arrow = (
    <span
      className="news-row-arrow"
      style={{
        gridColumn: 2,
        gridRow: "1 / span 3",
        alignSelf: "center",
        color: "var(--indigo-500)",
        fontSize: 18,
        transition: "transform .15s ease",
      }}
    >
      →
    </span>
  );

  if (!href) {
    return (
      <div style={{ ...rowStyle, cursor: "default" }}>
        <div>{content}</div>
        <span style={{ gridColumn: 2, color: "var(--ink-4)", fontSize: 16, alignSelf: "center" }} />
      </div>
    );
  }

  return (
    <a
      href={href}
      target={isExternal ? "_blank" : undefined}
      rel={isExternal ? "noreferrer" : undefined}
      className="news-row"
      style={rowStyle}
    >
      <div>{content}</div>
      {arrow}
    </a>
  );
}

/* ────────────────────────────────────────────────────────── */

function NewsList({ items, loading, initialCat }) {
  const [cat, setCat] = useState(initialCat || "All");
  const filtered = useMemo(
    () => cat === "All" ? items : items.filter(n => n.cat === cat),
    [cat, items],
  );
  const counts = useMemo(() => {
    const c = {};
    items.forEach(n => { c[n.cat] = (c[n.cat] || 0) + 1; });
    return c;
  }, [items]);

  return (
    <section style={{ padding: "72px 0 96px" }}>
      <div className="wrap">
        <div className="section-head">
          <div className="head-l">
            <span className="num">/ 01</span>
            <span className="eyebrow">All updates · Filter by category</span>
          </div>
          <span className="caption mono" style={{ color: "var(--ink-4)", fontSize: 11, letterSpacing: "0.06em" }}>
            {filtered.length} of {items.length}
          </span>
        </div>

        <div style={{ display: "flex", gap: 6, flexWrap: "wrap", marginBottom: 8 }}>
          {CATS.filter(tt => tt === "All" || counts[tt] > 0).map(tt => {
            const active = tt === cat;
            const n = tt === "All" ? items.length : (counts[tt] || 0);
            return (
              <button key={tt} onClick={() => setCat(tt)} style={{
                padding: "7px 14px",
                borderRadius: 4,
                border: "1px solid " + (active ? "var(--ink)" : "var(--rule-2)"),
                background: active ? "var(--ink)" : "white",
                color: active ? "white" : "var(--ink-2)",
                fontFamily: "var(--type-mono)", fontSize: 11, letterSpacing: "0.04em",
                fontWeight: 500, cursor: "pointer", transition: "all .12s",
                display: "inline-flex", alignItems: "center", gap: 8,
              }}>
                <span>{tt}</span>
                <span style={{ opacity: 0.65, fontVariantNumeric: "tabular-nums" }}>{String(n).padStart(2, "0")}</span>
              </button>
            );
          })}
        </div>

        <div style={{ maxWidth: 860, marginTop: 24, borderTop: "1px solid var(--rule)" }}>
          {loading && items.length === 0 ? (
            <div style={{ padding: "48px 0", color: "var(--ink-4)", fontSize: 13, textAlign: "center" }}>Loading…</div>
          ) : filtered.length === 0 ? (
            <div style={{ padding: "48px 0", color: "var(--ink-4)", fontSize: 13, textAlign: "center" }}>
              No updates yet{cat !== "All" ? ` in “${cat}”` : ""}.
            </div>
          ) : filtered.map(n => (
            <NewsRow key={n.id || n.slug} n={n} />
          ))}
        </div>
      </div>
    </section>
  );
}

/* ────────────────────────────────────────────────────────── */

function NewsPage() {
  const { data, loading } = useApi("news", []);
  const items = Array.isArray(data) ? data : [];
  const initialCat = useMemo(() => {
    const c = new URLSearchParams(window.location.search).get("cat");
    return c && CATS.indexOf(c) >= 0 ? c : "All";
  }, []);
  return (
    <>
      <Nav active="news" />
      <Header />
      <NewsList items={items} loading={loading} initialCat={initialCat} />
      <Footer />
    </>
  );
}

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