// pages.jsx — Spree Ravers Meetup page
// Receives { t, lang, accent, density, glassMode, markerDensity, hero, setPage }

const { useState, useEffect, useMemo, useRef } = React;

// ─── Spot photo ────────────────────────────────────────────────────────
function SpotPhotoCard({ t, accent }) {
  return (
    <section style={{ padding: "0 0 8px" }}>
      <div style={{
        fontFamily: "var(--f-mono)", fontSize: 11, letterSpacing: ".18em",
        textTransform: "uppercase", color: accent, marginBottom: 12,
      }}>
        {t("mt_spot_eyebrow")}
      </div>
      <figure style={{ margin: 0 }} className="liquid-glass">
        <div style={{ borderRadius: 16, overflow: "hidden", lineHeight: 0 }}>
          <img src="assets/logo/Location.png" alt={t("mt_spot_alt")}
               loading="lazy"
               style={{ width: "100%", height: "auto", display: "block" }} />
        </div>
        <figcaption style={{
          fontFamily: "var(--f-body)", fontSize: 13, opacity: .6,
          textAlign: "center", padding: "12px 16px 6px", lineHeight: 1.45,
        }}>
          {t("mt_spot_caption")}
        </figcaption>
      </figure>
    </section>
  );
}

// ─── Meetup page ───────────────────────────────────────────────────────
const TELEGRAM_URL = "https://t.me/SpreeRaversBerlin";
const MAPS_URL = "https://maps.app.goo.gl/vj1DhSP3apijCmRbA";

function MeetupPage({ t, accent, hero, markerDensity = 3 }) {
  const ctaBase = {
    borderRadius: "var(--r-pill)", padding: "16px 28px",
    fontSize: 14, fontWeight: 500, color: "#fff", fontFamily: "var(--f-body)",
    display: "inline-flex", alignItems: "center", gap: 10, textDecoration: "none",
  };

  return (
    <section style={{ position: "relative", paddingTop: 120, paddingBottom: 80, minHeight: "100vh", overflow: "hidden" }}>
      {hero === "video" && <FadingVideo
        src="https://d8j0ntlcm91z4.cloudfront.net/user_38xzZboKViGWJOttwIXH07lWA1P/hf_20260418_080021_d598092b-c4c2-4e53-8e46-94cf9064cd50.mp4" />}
      {hero === "photo" && <PhotoHero
        src="https://images.unsplash.com/photo-1517457373958-b7bdd4587205?w=1600&q=80" accent={accent} />}
      {hero === "animated" && <AnimatedHeroBg accent={accent} />}
      <div style={{
        position: "absolute", inset: 0,
        background: "linear-gradient(180deg, rgba(0,0,0,0.45) 0%, rgba(0,0,0,0.85) 100%)",
      }} />

      <div style={{ position: "relative", zIndex: 2, padding: "0 24px" }}>
        <div style={{ maxWidth: 1000, margin: "0 auto", textAlign: "center" }}>
          <div style={{
            fontFamily: "var(--f-mono)", fontSize: 11, letterSpacing: "0.18em",
            textTransform: "uppercase", color: accent, marginBottom: 24,
            animation: "fadeUp 700ms ease-out both",
          }}>
            {t("mt_eyebrow")}
          </div>
          <h1 style={{
            fontFamily: "var(--f-display)", fontStyle: "italic",
            fontSize: "clamp(56px, 11vw, 144px)",
            letterSpacing: "-4px", lineHeight: 0.9, margin: "0 0 28px",
            color: "#fff",
            display: "flex", flexWrap: "wrap", justifyContent: "center", rowGap: "0.05em",
          }}>
            <BlurText style={{ justifyContent: "center" }}>{t("mt_h_a")}</BlurText>
            <span style={{ marginLeft: "0.25em" }}>
              <MarkerTag color="var(--c-magenta)" rotate={-3} size="0.78em" drift>
                {t("mt_h_marker")}
              </MarkerTag>
            </span>
          </h1>
          <p style={{
            fontFamily: "var(--f-body)", fontWeight: 300,
            fontSize: 20, lineHeight: 1.4, color: "rgba(255,255,255,0.8)",
            maxWidth: 600, margin: "0 auto 56px", textWrap: "pretty",
            animation: "fadeUp 700ms 600ms ease-out both",
          }}>
            {t("mt_sub")}
          </p>

          {/* details grid */}
          <div style={{
            display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(180px, 1fr))",
            gap: 16, marginBottom: 56,
            animation: "fadeUp 700ms 900ms ease-out both",
          }}>
            {[
              { l: t("mt_when"),  v: t("mt_when_v") },
              { l: t("mt_where"), v: t("mt_where_v") },
              { l: t("mt_who"),   v: t("mt_who_v") },
              { l: t("mt_cost"),  v: t("mt_cost_v") },
            ].map((d, i) => (
              <div key={i} className="liquid-glass" style={{
                padding: 22, borderRadius: 16, textAlign: "left",
              }}>
                <div style={{
                  fontFamily: "var(--f-mono)", fontSize: 10, letterSpacing: "0.18em",
                  textTransform: "uppercase", color: "rgba(255,255,255,0.5)", marginBottom: 12,
                }}>{d.l}</div>
                <div style={{
                  fontFamily: "var(--f-display)", fontStyle: "italic", fontSize: 22,
                  lineHeight: 1.15, color: "#fff", letterSpacing: "-0.01em",
                }}>{d.v}</div>
              </div>
            ))}
          </div>

          {/* CTAs */}
          <div style={{
            display: "flex", flexWrap: "wrap", justifyContent: "center", gap: 12,
            animation: "fadeUp 700ms 1100ms ease-out both",
          }}>
            <a href={TELEGRAM_URL} target="_blank" rel="noopener noreferrer"
               className="liquid-glass-strong" style={ctaBase}>
              <Icon.Telegram style={{ width: 16, height: 16 }} />
              {t("mt_cta")}
              <Icon.ArrowUR style={{ width: 14, height: 14 }} />
            </a>
            <a href={MAPS_URL} target="_blank" rel="noopener noreferrer"
               className="liquid-glass" style={ctaBase}>
              <Icon.Marker style={{ width: 16, height: 16 }} />
              {t("mt_cta_map")}
              <Icon.ArrowUR style={{ width: 14, height: 14 }} />
            </a>
          </div>
        </div>

        {/* story */}
        <div style={{
          maxWidth: 700, margin: "120px auto 0",
          fontFamily: "var(--f-body)", fontWeight: 300, color: "rgba(255,255,255,0.85)",
        }}>
          {[t("mt_long_a"), t("mt_long_b"), t("mt_long_c")].map((p, i) => (
            <p key={i} style={{
              fontSize: 20, lineHeight: 1.5, margin: "0 0 28px", textWrap: "pretty",
            }}>
              {i === 0 && <span style={{
                fontFamily: "var(--f-display)", fontStyle: "italic", fontSize: 56,
                float: "left", lineHeight: 0.85, paddingRight: 12, paddingTop: 6,
                color: accent,
              }}>{p.charAt(0)}</span>}
              {i === 0 ? p.slice(1) : p}
            </p>
          ))}
        </div>

        {/* spot photo */}
        <div style={{ maxWidth: 700, margin: "60px auto 0" }}>
          <SpotPhotoCard t={t} accent={accent} />
        </div>

        {/* rules */}
        <div style={{ maxWidth: 700, margin: "60px auto 0", padding: "32px 0", borderTop: "1px solid rgba(255,255,255,0.1)" }}>
          <div style={{
            fontFamily: "var(--f-mono)", fontSize: 11, letterSpacing: "0.18em",
            textTransform: "uppercase", color: accent, marginBottom: 24,
          }}>
            {t("mt_rules_title")}
          </div>
          {[t("mt_rule_1"), t("mt_rule_2"), t("mt_rule_3")].map((r, i) => (
            <div key={i} style={{
              display: "flex", gap: 20, alignItems: "flex-start",
              padding: "16px 0", borderBottom: i < 2 ? "1px solid rgba(255,255,255,0.06)" : "none",
            }}>
              <span style={{
                fontFamily: "var(--f-display)", fontStyle: "italic",
                fontSize: 36, color: accent, lineHeight: 1, letterSpacing: "-0.02em",
                minWidth: 40,
              }}>0{i + 1}</span>
              <span style={{
                fontFamily: "var(--f-body)", fontWeight: 300, fontSize: 18,
                color: "rgba(255,255,255,0.85)", lineHeight: 1.4,
              }}>{r}</span>
            </div>
          ))}
        </div>

        {/* signoff */}
        <div style={{
          maxWidth: 700, margin: "60px auto 80px", textAlign: "center",
          fontFamily: "var(--f-display)", fontStyle: "italic",
          fontSize: "clamp(28px, 4vw, 40px)", color: "#fff",
        }}>
          {t("mt_signoff")}
        </div>

        {markerDensity >= 3 && (
          <div style={{ position: "absolute", top: "20%", right: "10%" }}>
            <MarkerTag color="var(--c-acid)" rotate={-12} size="1.8rem" drift>
              every friday
            </MarkerTag>
          </div>
        )}
      </div>
    </section>
  );
}

// ─── Sets page ─────────────────────────────────────────────────────────
function formatRelativeDate(iso, lang) {
  if (!iso) return "";
  const then = new Date(iso).getTime();
  if (!then) return "";
  const days = Math.floor((Date.now() - then) / 86400000);
  if (days < 1) return lang === "de" ? "heute" : "today";
  if (days === 1) return lang === "de" ? "gestern" : "yesterday";
  if (days < 7) return lang === "de" ? `vor ${days} Tagen` : `${days} days ago`;
  if (days < 30) {
    const w = Math.floor(days / 7);
    if (lang === "de") return w === 1 ? "vor 1 Woche" : `vor ${w} Wochen`;
    return w === 1 ? "1 week ago" : `${w} weeks ago`;
  }
  const months = Math.floor(days / 30);
  if (lang === "de") return months === 1 ? "vor 1 Monat" : `vor ${months} Monaten`;
  return months === 1 ? "1 month ago" : `${months} months ago`;
}

function SetCard({ track, accent, t, lang }) {
  const [playing, setPlaying] = useState(false);
  const playerUrl =
    `https://w.soundcloud.com/player/?url=${encodeURIComponent(track.url)}` +
    `&auto_play=true&hide_related=true&show_comments=false&show_user=true` +
    `&show_reposts=false&visual=false&color=${encodeURIComponent(accent.replace("#", ""))}`;

  return (
    <article className="liquid-glass" style={{
      borderRadius: 18, overflow: "hidden",
      display: "flex", flexDirection: "column",
    }}>
      <div style={{
        position: "relative", aspectRatio: "1 / 1", background: "#0a0a0a",
      }}>
        {playing ? (
          <iframe
            title={track.title}
            src={playerUrl}
            width="100%" height="100%" frameBorder="0" scrolling="no" allow="autoplay"
            style={{ position: "absolute", inset: 0, border: 0 }}
          />
        ) : (
          <>
            {track.artwork ? (
              <img src={track.artwork} alt="" loading="lazy"
                   style={{
                     position: "absolute", inset: 0, width: "100%", height: "100%",
                     objectFit: "cover", filter: "brightness(0.7)",
                   }} />
            ) : (
              <div style={{
                position: "absolute", inset: 0,
                background: `radial-gradient(circle at 30% 30%, ${accent}33, transparent 60%), #111`,
              }} />
            )}
            <button onClick={() => setPlaying(true)}
                    aria-label={t("sets_play")}
                    style={{
                      position: "absolute", inset: 0, width: "100%", height: "100%",
                      display: "flex", alignItems: "center", justifyContent: "center",
                      background: "transparent", border: 0, cursor: "pointer",
                    }}>
              <span className="liquid-glass-strong" style={{
                width: 64, height: 64, borderRadius: "50%",
                display: "flex", alignItems: "center", justifyContent: "center",
                color: "#fff",
              }}>
                <svg viewBox="0 0 24 24" width="24" height="24" fill="currentColor">
                  <path d="M8 5v14l11-7z" />
                </svg>
              </span>
            </button>
          </>
        )}
      </div>
      <div style={{ padding: "14px 16px 16px", display: "flex", flexDirection: "column", gap: 6 }}>
        <div style={{
          fontFamily: "var(--f-mono)", fontSize: 10, letterSpacing: "0.16em",
          textTransform: "uppercase", color: accent,
        }}>
          {track.club}
        </div>
        <div style={{
          fontFamily: "var(--f-body)", fontWeight: 500, fontSize: 15,
          color: "#fff", lineHeight: 1.3,
          display: "-webkit-box", WebkitLineClamp: 2, WebkitBoxOrient: "vertical",
          overflow: "hidden",
        }}>
          {track.title}
        </div>
        <div style={{
          display: "flex", justifyContent: "space-between", alignItems: "center",
          fontFamily: "var(--f-mono)", fontSize: 11, color: "rgba(255,255,255,0.45)",
          marginTop: 4,
        }}>
          <span>{formatRelativeDate(track.pubDate, lang)}</span>
          <a href={track.url} target="_blank" rel="noopener noreferrer"
             style={{ color: "rgba(255,255,255,0.65)", textDecoration: "none" }}>
            {t("sets_listen_on")} ↗
          </a>
        </div>
      </div>
    </article>
  );
}

function SetsPage({ t, lang, accent }) {
  const [state, setState] = useState({ status: "loading", items: [] });

  useEffect(() => {
    let cancelled = false;
    fetch("/api/sets")
      .then((r) => r.json())
      .then((data) => {
        if (cancelled) return;
        setState({ status: "ready", items: data.items || [] });
      })
      .catch(() => {
        if (cancelled) return;
        setState({ status: "error", items: [] });
      });
    return () => { cancelled = true; };
  }, []);

  return (
    <section style={{ paddingTop: 120, paddingBottom: 80, minHeight: "100vh", position: "relative" }}>
      <AnimatedHeroBg accent={accent} />
      <div style={{
        position: "absolute", inset: 0,
        background: "linear-gradient(180deg, rgba(0,0,0,0.6) 0%, rgba(0,0,0,0.9) 100%)",
      }} />

      <div style={{ position: "relative", zIndex: 2, padding: "0 24px", maxWidth: 1200, margin: "0 auto" }}>
        <div style={{ textAlign: "center", marginBottom: 56 }}>
          <div style={{
            fontFamily: "var(--f-mono)", fontSize: 11, letterSpacing: "0.18em",
            textTransform: "uppercase", color: accent, marginBottom: 16,
          }}>
            {t("sets_eyebrow")}
          </div>
          <h1 style={{
            fontFamily: "var(--f-display)", fontStyle: "italic",
            fontSize: "clamp(48px, 9vw, 120px)",
            letterSpacing: "-3px", lineHeight: 0.95, margin: "0 0 24px",
            color: "#fff",
            display: "flex", flexWrap: "wrap", justifyContent: "center", rowGap: "0.05em",
          }}>
            <BlurText style={{ justifyContent: "center" }}>{t("sets_h_a")}</BlurText>
            <span style={{ marginLeft: "0.25em" }}>
              <MarkerTag color="var(--c-magenta)" rotate={-3} size="0.78em" drift>
                {t("sets_h_marker")}
              </MarkerTag>
            </span>
          </h1>
          <p style={{
            fontFamily: "var(--f-body)", fontWeight: 300,
            fontSize: 18, lineHeight: 1.45, color: "rgba(255,255,255,0.75)",
            maxWidth: 620, margin: "0 auto", textWrap: "pretty",
          }}>
            {t("sets_sub")}
          </p>
        </div>

        {state.status === "loading" && (
          <p style={{ textAlign: "center", color: "rgba(255,255,255,0.5)",
                      fontFamily: "var(--f-mono)", fontSize: 12, letterSpacing: "0.16em",
                      textTransform: "uppercase" }}>
            {t("sets_loading")}
          </p>
        )}

        {state.status === "error" && (
          <p style={{ textAlign: "center", color: "rgba(255,180,180,0.7)",
                      fontFamily: "var(--f-mono)", fontSize: 12 }}>
            {t("sets_error")}
          </p>
        )}

        {state.status === "ready" && state.items.length === 0 && (
          <p style={{ textAlign: "center", color: "rgba(255,255,255,0.5)",
                      fontFamily: "var(--f-mono)", fontSize: 12, letterSpacing: "0.16em",
                      textTransform: "uppercase" }}>
            {t("sets_empty")}
          </p>
        )}

        {state.status === "ready" && state.items.length > 0 && (
          <div style={{
            display: "grid",
            gridTemplateColumns: "repeat(auto-fill, minmax(240px, 1fr))",
            gap: 20,
          }}>
            {state.items.map((track, i) => (
              <SetCard key={track.url + i} track={track} accent={accent} t={t} lang={lang} />
            ))}
          </div>
        )}
      </div>
    </section>
  );
}

Object.assign(window, { MeetupPage, SetsPage });
