// Events & Projekte — Seite. Liste mit Tag-Filter, chronologisch.

function EventsPage({ lang, setLang }) {
  const t = COPY[lang];
  const [activeTag, setActiveTag] = React.useState("all");
  const [mobile, setMobile] = React.useState(() => window.innerWidth < 760);
  React.useEffect(() => {
    const h = () => setMobile(window.innerWidth < 760);
    window.addEventListener("resize", h);
    return () => window.removeEventListener("resize", h);
  }, []);

  const now = new Date();
  const sorted = [...EVENTS].sort((a, b) => b.date.localeCompare(a.date));
  const filtered =
    activeTag === "all" ? sorted : sorted.filter((e) => e.tag === activeTag);

  const tagLabel = (tag) => (lang === "en" ? EVENT_TAGS_EN[tag] || tag : tag);

  // Count by tag for the filter pills
  const counts = EVENT_TAGS.reduce((acc, tag) => {
    acc[tag] = EVENTS.filter((e) => e.tag === tag).length;
    return acc;
  }, {});

  return (
    <div
      style={{
        minHeight: "100vh",
        background: KS.offwhite,
        color: KS.charcoal,
        fontFamily: KSFonts.body,
      }}
    >
      {/* Top bar */}
      <header
        style={{
          position: "sticky",
          top: 0,
          zIndex: 10,
          background: "rgba(248,247,246,0.85)",
          backdropFilter: "blur(10px)",
          WebkitBackdropFilter: "blur(10px)",
          borderBottom: `1px solid ${KS.border}`,
          padding: "14px 24px",
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
        }}
      >
        <a
          href="index.html"
          style={{
            display: "flex",
            alignItems: "center",
            gap: 10,
            textDecoration: "none",
            color: KS.charcoal,
            whiteSpace: "nowrap",
          }}
        >
          <span
            style={{
              color: KS.muted,
              fontFamily: KSFonts.mono,
              fontSize: 14,
              marginRight: 2,
            }}
          >
            ←
          </span>
          <div
            style={{
              width: 24,
              height: 24,
              background: KS.coral,
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              color: "#fff",
              fontWeight: 700,
              fontSize: 12,
              fontFamily: KSFonts.mono,
            }}
          >
            K
          </div>
          <div style={{ fontWeight: 600, fontSize: 14, letterSpacing: -0.2 }}>
            Kilian Springer
          </div>
        </a>
        <LangToggle lang={lang} setLang={setLang} />
      </header>

      {/* Content */}
      <main
        style={{
          maxWidth: 960,
          margin: "0 auto",
          padding: mobile ? "40px 20px 24px" : "64px 32px 32px",
        }}
      >
        <div
          style={{
            fontFamily: KSFonts.mono,
            fontSize: 11,
            letterSpacing: 1.5,
            textTransform: "uppercase",
            color: KS.coral,
            marginBottom: 14,
          }}
        >
          {t.eventsKicker}
        </div>
        <h1
          style={{
            fontSize: mobile ? 48 : 72,
            fontWeight: 800,
            letterSpacing: mobile ? -1.6 : -3,
            lineHeight: 0.95,
            color: KS.black,
            margin: 0,
            marginBottom: 16,
            textWrap: "balance",
          }}
        >
          {t.eventsTitle}
        </h1>
        <p
          style={{
            fontSize: mobile ? 14 : 16,
            color: KS.charcoal,
            lineHeight: 1.55,
            margin: 0,
            marginBottom: mobile ? 32 : 48,
            maxWidth: 620,
            textWrap: "pretty",
          }}
        >
          {t.eventsIntro}
        </p>

        {/* Filter pills */}
        <div
          style={{
            display: "flex",
            flexWrap: "wrap",
            gap: 8,
            marginBottom: mobile ? 28 : 40,
          }}
        >
          <TagPill
            active={activeTag === "all"}
            label={t.tagAll}
            count={EVENTS.length}
            onClick={() => setActiveTag("all")}
          />
          {EVENT_TAGS.map(
            (tag) =>
              counts[tag] > 0 && (
                <TagPill
                  key={tag}
                  active={activeTag === tag}
                  label={tagLabel(tag)}
                  count={counts[tag]}
                  onClick={() => setActiveTag(tag)}
                />
              ),
          )}
        </div>

        {/* Timeline */}
        <div style={{ display: "grid", gap: 0 }}>
          {filtered.map((e, i) => (
            <EventRow
              key={e.date + e.title}
              entry={e}
              lang={lang}
              mobile={mobile}
              now={now}
              isFirst={i === 0}
              tagLabel={tagLabel}
            />
          ))}
          {filtered.length === 0 && (
            <div
              style={{
                padding: 40,
                textAlign: "center",
                color: KS.muted,
                fontSize: 14,
              }}
            >
              —
            </div>
          )}
          <div style={{ borderTop: `1px solid ${KS.border}` }} />
        </div>
      </main>

      {/* Footer */}
      <footer
        style={{
          borderTop: `1px solid ${KS.border}`,
          marginTop: 40,
          padding: "22px 24px 28px",
          maxWidth: 960,
          margin: "40px auto 0",
          fontFamily: KSFonts.mono,
          fontSize: 10,
          letterSpacing: 0.5,
          textTransform: "uppercase",
          color: KS.muted,
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
          flexWrap: "wrap",
          gap: 12,
        }}
      >
        <div>© 2026 · kilian-springer.com</div>
        <div style={{ display: "flex", gap: 14 }}>
          <a
            href="index.html"
            style={{ color: "inherit", textDecoration: "none" }}
          >
            {t.about}
          </a>
          <a
            href="stufen.html"
            style={{ color: "inherit", textDecoration: "none" }}
          >
            5 Stufen
          </a>
          <a
            href="downloads.html"
            style={{ color: "inherit", textDecoration: "none" }}
          >
            {t.downloadsNav}
          </a>
          <a
            href="impressum.html"
            style={{ color: "inherit", textDecoration: "none" }}
          >
            {t.imprint}
          </a>
          <a
            href="datenschutz.html"
            style={{ color: "inherit", textDecoration: "none" }}
          >
            {t.privacy}
          </a>
        </div>
      </footer>
    </div>
  );
}

// Download button — active when entry.download is set, otherwise grayed out.
// Renders as <button> so it can live inside the row's <a> wrapper without
// invalid nested-anchor HTML.
function DownloadButton({ href, available, label }) {
  const handleClick = (e) => {
    e.stopPropagation();
    if (!available) {
      e.preventDefault();
      return;
    }
    window.open(href, "_blank", "noopener,noreferrer");
  };
  return (
    <button
      type="button"
      onClick={handleClick}
      disabled={!available}
      title={available ? href : undefined}
      style={{
        display: "inline-flex",
        alignItems: "center",
        gap: 8,
        background: "transparent",
        color: available ? KS.charcoal : KS.muted,
        border: `1px solid ${available ? KS.borderStrong : KS.border}`,
        padding: "7px 12px",
        fontFamily: KSFonts.mono,
        fontSize: 10,
        letterSpacing: 1,
        textTransform: "uppercase",
        borderRadius: 2,
        cursor: available ? "pointer" : "not-allowed",
        opacity: available ? 1 : 0.55,
        transition: "all 150ms ease",
      }}
      onMouseEnter={(e) => {
        if (!available) return;
        e.currentTarget.style.background = KS.charcoal;
        e.currentTarget.style.color = KS.offwhite;
        e.currentTarget.style.borderColor = KS.charcoal;
      }}
      onMouseLeave={(e) => {
        if (!available) return;
        e.currentTarget.style.background = "transparent";
        e.currentTarget.style.color = KS.charcoal;
        e.currentTarget.style.borderColor = KS.borderStrong;
      }}
    >
      <span style={{ fontSize: 11, lineHeight: 1 }}>↓</span>
      <span>{label}</span>
    </button>
  );
}

function TagPill({ active, label, count, onClick }) {
  return (
    <button
      onClick={onClick}
      style={{
        background: active ? KS.charcoal : "transparent",
        color: active ? KS.offwhite : KS.charcoal,
        border: active
          ? `1px solid ${KS.charcoal}`
          : `1px solid ${KS.borderStrong}`,
        padding: "8px 14px",
        fontFamily: KSFonts.mono,
        fontSize: 11,
        letterSpacing: 0.8,
        textTransform: "uppercase",
        cursor: "pointer",
        borderRadius: 999,
        display: "inline-flex",
        alignItems: "center",
        gap: 8,
        transition: "all 150ms ease",
      }}
    >
      <span>{label}</span>
      <span
        style={{
          fontSize: 10,
          opacity: 0.6,
          fontVariantNumeric: "tabular-nums",
        }}
      >
        {count}
      </span>
    </button>
  );
}

function EventRow({ entry, lang, mobile, now, isFirst, tagLabel }) {
  const t = COPY[lang];
  const date = new Date(entry.date);
  const upcoming = date > now;
  const monthShort = date
    .toLocaleDateString(lang === "de" ? "de-DE" : "en-US", { month: "short" })
    .replace(".", "");
  const day = date.getDate();
  const year = date.getFullYear();

  const clickable = !!entry.url;
  const hasDownload = !!entry.download;

  return (
    <div
      style={{
        borderTop: isFirst
          ? `1px solid ${KS.charcoal}`
          : `1px solid ${KS.border}`,
        padding: mobile ? "20px 0" : "26px 0",
        display: "grid",
        gridTemplateColumns: mobile ? "64px 1fr" : "88px 120px 1fr",
        gap: mobile ? 14 : 24,
        alignItems: "center",
        color: "inherit",
      }}
    >
      {/* Date */}
      <div
        style={{
          fontFamily: KSFonts.mono,
          color: KS.charcoal,
          lineHeight: 1.1,
        }}
      >
        <div
          style={{
            fontSize: mobile ? 20 : 26,
            fontWeight: 500,
            letterSpacing: -0.5,
          }}
        >
          {monthShort} {day}
        </div>
        <div
          style={{
            fontSize: 10,
            color: KS.muted,
            marginTop: 4,
            letterSpacing: 0.5,
          }}
        >
          {year}
          {upcoming && (
            <span style={{ color: KS.coral, marginLeft: 6 }}>
              ● {lang === "de" ? "bald" : "upcoming"}
            </span>
          )}
        </div>
      </div>

      {/* Tag */}
      <div
        style={{
          gridRow: mobile ? 2 : "auto",
          gridColumn: mobile ? "2" : "auto",
        }}
      >
        <span
          style={{
            display: "inline-block",
            fontFamily: KSFonts.mono,
            fontSize: 10,
            letterSpacing: 1.2,
            textTransform: "uppercase",
            padding: "4px 10px",
            background: tagBg(entry.tag),
            color: tagFg(entry.tag),
            border: `1px solid ${tagFg(entry.tag)}22`,
            borderRadius: 2,
          }}
        >
          {tagLabel(entry.tag)}
        </span>
      </div>

      {/* Title + summary */}
      <div style={{ gridColumn: mobile ? "2" : "auto", minWidth: 0 }}>
        {clickable ? (
          <a
            href={entry.url}
            target="_blank"
            rel="noreferrer"
            style={{
              display: "inline-flex",
              alignItems: "baseline",
              gap: 8,
              fontSize: mobile ? 17 : 19,
              fontWeight: 600,
              color: KS.black,
              letterSpacing: -0.3,
              lineHeight: 1.3,
              marginBottom: 6,
              textWrap: "balance",
              textDecoration: "none",
            }}
            onMouseEnter={(e) => (e.currentTarget.style.color = KS.coral)}
            onMouseLeave={(e) => (e.currentTarget.style.color = KS.black)}
          >
            <span>{entry.title}</span>
            <span style={{ color: KS.coral, fontSize: 14, fontWeight: 400 }}>
              ↗
            </span>
          </a>
        ) : (
          <div
            style={{
              fontSize: mobile ? 17 : 19,
              fontWeight: 600,
              color: KS.black,
              letterSpacing: -0.3,
              lineHeight: 1.3,
              marginBottom: 6,
              textWrap: "balance",
            }}
          >
            {entry.title}
          </div>
        )}
        {(entry.role || entry.location) && (
          <div
            style={{
              fontFamily: KSFonts.mono,
              fontSize: 10.5,
              color: KS.muted,
              marginBottom: 8,
              letterSpacing: 0.3,
            }}
          >
            {[entry.role, entry.location].filter(Boolean).join(" · ")}
          </div>
        )}
        <div
          style={{
            fontSize: mobile ? 13 : 14,
            color: KS.charcoal,
            lineHeight: 1.55,
            textWrap: "pretty",
            maxWidth: 620,
          }}
        >
          {entry.summary}
        </div>
        <div style={{ marginTop: 12 }}>
          <DownloadButton
            href={entry.download}
            available={hasDownload}
            label={hasDownload ? t.downloadContent : t.downloadUnavailable}
          />
        </div>
      </div>
    </div>
  );
}

// Pastel tag colors — readable, low-chroma
function tagBg(tag) {
  const map = {
    Keynote: "#fff0ed", // blush
    Workshop: "#fff5e6", // warm cream
    Podcast: "#eef3ff", // soft blue
    Interview: "#f2ecff", // soft lavender
    Panel: "#eefbf3", // mint
    Projekt: "#fdecec", // salmon-pink
    Lehre: "#f0f4e8", // olive-cream
    Publikation: "#eef6f6", // teal-mist
  };
  return map[tag] || "#efefef";
}
function tagFg(tag) {
  const map = {
    Keynote: "#b23b2a",
    Workshop: "#8c5a0f",
    Podcast: "#2f4bb0",
    Interview: "#5a3fb0",
    Panel: "#2f7d4c",
    Projekt: "#a8342a",
    Lehre: "#56702a",
    Publikation: "#2a6e6e",
  };
  return map[tag] || KS.charcoal;
}

Object.assign(window, { EventsPage });
