/* global React, Icon, ZiaSun, EnchantmentBadge, TopoBackground, DividerZia, EpisodeArt, NewMexicoMap, Yucca */
const { useState, useEffect, useRef } = React;
const D = window.ECData;

// ============================ NAV ============================
function Nav({ route, go }) {
  const [open, setOpen] = useState(false);
  const items = [
    ["home", "Home"],
    ["episodes", "Episodes"],
    ["about", "About"],
    ["listen", "Listen"]
  ];
  return (
    <nav className={`nav ${open ? "open" : ""}`}>
      <div className="nav-inner">
        <a className="brand" href="#" onClick={(e) => { e.preventDefault(); go("home"); setOpen(false); }}>
          <EnchantmentBadge size={62} />
          <span className="brand-text">
            <span className="brand-name">The Enchantment Chronicles</span>
            <span className="brand-sub">A Men of Enchantment Production</span>
          </span>
        </a>
        <button className="nav-toggle" onClick={() => setOpen(!open)} aria-label="Menu">
          {Icon.menu(20)}
        </button>
        <div className="nav-links">
          {items.map(([key, label]) => (
            <a key={key} href="#" className={`nav-link ${route === key ? "active" : ""}`}
              onClick={(e) => { e.preventDefault(); go(key); setOpen(false); }}>
              {label}
            </a>
          ))}
          <a className="nav-cta" href={D.platforms[0].url} target="_blank" rel="noreferrer">Listen Now</a>
        </div>
      </div>
    </nav>
  );
}

// ============================ PLAYER EMBED ============================
function PodcastEmbed({ ep, onPlay, useSpotify = true }) {
  const [spotifyOk, setSpotifyOk] = useState(useSpotify);
  return (
    <div className="embed-wrap">
      <div className="embed-label">
        <span>★ Now Playing — Latest Episode</span>
        <span style={{ color: "var(--clay)" }}>№ {String(ep.n).padStart(2, "0")}</span>
      </div>
      {spotifyOk ? (
        <iframe
          title="Spotify embed"
          src="https://open.spotify.com/embed/show/5AnI7MbSXW23tid4OzpKjd?utm_source=generator"
          width="100%" height="232" frameBorder="0"
          allow="autoplay; clipboard-write; encrypted-media; fullscreen; picture-in-picture"
          loading="lazy"
          style={{ border: 0, background: "transparent", borderRadius: 12 }}
        />
      ) : (
        <div className="embed-fallback">
          <div className="embed-fallback-art">
            <ZiaSun size={70} color="#B85C38" />
          </div>
          <div className="embed-fallback-body">
            <div className="ep-kicker">Episode {String(ep.n).padStart(2, "0")} · {ep.date}</div>
            <h3>{ep.title}</h3>
            <div className="controls">
              <button className="play-big" onClick={() => onPlay(ep)}>{Icon.play(16)}</button>
              <span className="time">04:12</span>
              <div className="scrub"></div>
              <span className="time">{ep.duration}</span>
            </div>
          </div>
        </div>
      )}
      <div style={{ marginTop: 14, fontFamily: "var(--slab)", fontSize: "0.66rem", letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--ink-mute)", display: "flex", justifyContent: "space-between" }}>
        <button onClick={() => setSpotifyOk(!spotifyOk)} style={{ color: "var(--clay)", padding: 0 }}>
          {spotifyOk ? "→ Show built-in player" : "→ Switch to Spotify embed"}
        </button>
        <span>Embed slot wired — drop SHOW_ID to go live</span>
      </div>
    </div>
  );
}

// ============================ HOME ============================
function HomePage({ go, onPlay }) {
  const latest = D.episodes[0];
  const recent = D.episodes.slice(0, 3);
  const dispatches = D.dispatches.slice(0, 3);
  return (
    <>
      {/* HERO */}
      <section className="hero">
        <div className="hero-bg"></div>
        <TopoBackground />
        <div className="container hero-inner">
          <div className="hero-eyebrow reveal reveal-1">A Podcast from the Land of Enchantment</div>
          <h1 className="hero-title reveal reveal-2">The <em>Enchantment</em><br/>Chronicles</h1>
          <p className="hero-tagline reveal reveal-3">
            Chronicling the people, places, and quiet feuds of New Mexico — one story at a time.
            From the Pueblo Revolt to Pancho Villa, from crypto-Jewish hill villages to the secret city on the mesa.
          </p>
          <div className="hero-meta reveal reveal-3">
            <span>Semi-Monthly</span>
            <span className="hero-meta-dot"></span>
            <span>Hosted in Albuquerque</span>
            <span className="hero-meta-dot"></span>
            <span>Est. MMXXIV</span>
          </div>
          <div className="btn-cluster reveal reveal-4">
            <button className="btn btn-primary" onClick={() => onPlay(latest)}>
              {Icon.play(14)} Play Latest Episode
            </button>
            <button className="btn btn-ghost" onClick={() => go("episodes")}>
              All Episodes {Icon.arrow(14)}
            </button>
          </div>
        </div>
      </section>

      {/* EMBED */}
      <section className="section" style={{ paddingTop: 60, paddingBottom: 40 }}>
        <div className="container-narrow">
          <PodcastEmbed ep={latest} onPlay={onPlay} />
        </div>
      </section>

      {/* ABOUT BLURB */}
      <section className="section section-tinted">
        <div className="container-narrow" style={{ textAlign: "center", position: "relative" }}>
          <div className="section-head" style={{ alignItems: "center", textAlign: "center", borderBottom: "none" }}>
            <span className="kicker">About the Show</span>
            <h2 style={{ maxWidth: 720 }}>A history podcast that walks the ground it talks about.</h2>
          </div>
          <p style={{ fontSize: "1.1rem", color: "var(--ink)", lineHeight: 1.75, maxWidth: 680, margin: "0 auto" }}>
            We're not historians by trade — we're New Mexicans by birth and by stubbornness. Every episode pairs a
            front-porch conversation with a deep dive into the primary sources, the diaries, and the people who still
            remember. No saguaros. No tourist gloss. Just the Land of Enchantment, told true.
          </p>
          <div style={{ marginTop: 32 }}>
            <button className="btn btn-ghost" onClick={() => go("about")}>Read more about us {Icon.arrow(14)}</button>
          </div>
        </div>
      </section>

      {/* EPISODES STRIP */}
      <section className="section">
        <div className="container">
          <div className="section-head section-head-row">
            <div>
              <span className="kicker">Recent Episodes</span>
              <h2>From the latest chronicles</h2>
            </div>
            <a href="#" onClick={(e) => { e.preventDefault(); go("episodes"); }}
              style={{ fontFamily: "var(--slab)", fontSize: "0.78rem", letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--clay)" }}>
              View all episodes {Icon.arrow(12)}
            </a>
          </div>
          <div className="episode-strip">
            {recent.map(ep => (
              <article key={ep.n} className="ep-card" onClick={() => onPlay(ep)}>
                <EpisodeArt ep={ep} />
                <div className="ep-body">
                  <div className="ep-meta">
                    <span>{ep.date}</span>
                    <span className="ep-meta-tag">{ep.tag}</span>
                  </div>
                  <h3 className="ep-title">{ep.title}</h3>
                  <p className="ep-desc">{ep.excerpt}</p>
                  <div className="ep-foot">
                    <span className="play">{Icon.play(10)} Play</span>
                    <span className="dur">{ep.duration}</span>
                  </div>
                </div>
              </article>
            ))}
          </div>
        </div>
      </section>

      {/* EPIGRAPH — LEW WALLACE */}
      <section className="epigraph">
        <div className="container-narrow">
          <div className="epigraph-rule"><span></span><em>Epigraph</em><span></span></div>
          <blockquote className="epigraph-quote">
            <span className="epigraph-mark" aria-hidden="true">&ldquo;</span>
            All calculations based on our experiences elsewhere
            <br/>fail in New Mexico.
          </blockquote>
          <div className="epigraph-attr">
            <span className="epigraph-name">Lew Wallace</span>
            <span className="epigraph-sep">·</span>
            <span className="epigraph-title">Territorial Governor of New Mexico</span>
            <span className="epigraph-sep">·</span>
            <span className="epigraph-years">1878 — 1881</span>
          </div>
        </div>
      </section>

      {/* SUBSCRIBE STRIP */}
      <section className="section section-dark">
        <div className="container-narrow" style={{ textAlign: "center" }}>
          <span className="kicker" style={{ color: "var(--turquoise)", fontFamily: "var(--slab)", fontSize: "0.72rem", letterSpacing: "0.32em", textTransform: "uppercase" }}>
            Subscribe
          </span>
          <h2 style={{ marginTop: 12, marginBottom: 16 }}>Get the next chronicle in your saddlebag.</h2>
          <p style={{ color: "rgba(245,239,224,0.75)", fontStyle: "italic", maxWidth: 540, margin: "0 auto 28px" }}>
            Sometimes when we can and feel like it: a new episode, a field dispatch, and one good photograph from the road.
          </p>
          <div className="btn-cluster">
            <a className="btn btn-primary" href={D.platforms[4].url} target="_blank" rel="noreferrer">Subscribe via RSS</a>
            <button className="btn btn-ghost" style={{ color: "var(--parchment)", borderColor: "var(--parchment)" }} onClick={() => go("listen")}>
              Find Us on Your App {Icon.arrow(14)}
            </button>
          </div>
        </div>
      </section>
    </>
  );
}

// ============================ EPISODES ============================
function EpisodesPage({ onPlay, goEp }) {
  const [filter, setFilter] = useState("All");
  const filtered = filter === "All" ? D.episodes : D.episodes.filter(e => e.tag === filter);
  return (
    <>
      <section className="section" style={{ paddingBottom: 32 }}>
        <div className="container-narrow">
          <span className="kicker" style={{ fontFamily: "var(--slab)", fontSize: "0.72rem", letterSpacing: "0.32em", textTransform: "uppercase", color: "var(--clay)" }}>
            The Archive
          </span>
          <h1 style={{ marginTop: 12, marginBottom: 18 }}>Every Episode, in Order</h1>
          <p style={{ fontStyle: "italic", color: "var(--ink-mute)", fontSize: "1.1rem", maxWidth: 640 }}>
            Twenty-four episodes and counting. Filter by series below, or start from the bottom and work your way up
            like a good Saturday-morning archive dive.
          </p>
        </div>
      </section>
      <section className="section" style={{ paddingTop: 20 }}>
        <div className="container-narrow">
          <div className="filters">
            {D.tags.map(t => (
              <button key={t} className={`chip ${filter === t ? "active" : ""}`} onClick={() => setFilter(t)}>
                {t}
              </button>
            ))}
          </div>
          <div className="ep-list">
            {filtered.map(ep => (
              <article key={ep.n} className="ep-row" onClick={() => goEp(ep.n)}>
                <div className="ep-row-num">№{String(ep.n).padStart(2, "0")}</div>
                <div className="ep-row-body">
                  <div className="ep-row-meta">
                    <span>{ep.date}</span>
                    <span>·</span>
                    <span>{ep.duration}</span>
                    <span className="ep-meta-tag">{ep.tag}</span>
                  </div>
                  <h3>{ep.title}</h3>
                  <p className="ep-row-desc">{ep.excerpt}</p>
                </div>
                <button className="ep-row-play" onClick={(e) => { e.stopPropagation(); onPlay(ep); }} aria-label="Play">
                  {Icon.play(18)}
                </button>
              </article>
            ))}
          </div>
        </div>
      </section>
    </>
  );
}

// ============================ EPISODE DETAIL ============================
function EpisodeDetail({ n, go, onPlay }) {
  const ep = D.episodes.find(e => e.n === n) || D.episodes[0];
  return (
    <>
      <section className="ep-detail-hero">
        <div className="container-narrow">
          <button className="ep-detail-back" onClick={() => go("episodes")}>{Icon.arrowLeft(12)} Back to Episodes</button>
          <div className="ep-detail-meta">
            <span style={{ color: "var(--clay)" }}>№ {String(ep.n).padStart(2, "0")}</span>
            <span>·</span>
            <span>{ep.date}</span>
            <span>·</span>
            <span>{ep.duration}</span>
            <span className="ep-meta-tag">{ep.tag}</span>
          </div>
          <h1 className="ep-detail-title">{ep.title}</h1>
          <div className="btn-cluster" style={{ justifyContent: "flex-start" }}>
            <button className="btn btn-primary" onClick={() => onPlay(ep)}>{Icon.play(14)} Play Episode</button>
            <a className="btn btn-ghost" href={D.platforms[0].url} target="_blank" rel="noreferrer">Open in Apple Podcasts {Icon.arrow(14)}</a>
          </div>
        </div>
      </section>
      <section className="ep-detail-body">
        <div className="container-narrow">
          <PodcastEmbed ep={ep} onPlay={onPlay} />
          <DividerZia />
          <p style={{ fontSize: "1.2rem", fontStyle: "italic", color: "var(--ink-mute)" }}>{ep.excerpt}</p>
          <p>{ep.body}</p>
          <h3>In this episode</h3>
          <ul>
            <li>Primary sources from the National Archives at Denver and the New Mexico State Records Center</li>
            <li>Field recording from the site itself</li>
            <li>One long, unhurried conversation with someone who remembers</li>
          </ul>
          <h3>Further reading</h3>
          <ul>
            <li><em>The Far Southwest, 1846–1912</em> — Howard Lamar</li>
            <li><em>Roots of Resistance</em> — Robert J. Rosenbaum</li>
            <li>Show notes &amp; bibliography → forthcoming</li>
          </ul>
        </div>
      </section>
    </>
  );
}

// ============================ WRITTEN WORD ============================
function WrittenPage() {
  const [signedUp, setSignedUp] = useState(false);
  const [showSubstack, setShowSubstack] = useState(false);
  const [email, setEmail] = useState("");
  return (
    <>
      <section className="section" style={{ paddingBottom: 24 }}>
        <div className="container">
          <div style={{ maxWidth: 720 }}>
            <span className="kicker" style={{ fontFamily: "var(--slab)", fontSize: "0.72rem", letterSpacing: "0.32em", textTransform: "uppercase", color: "var(--clay)" }}>
              Dispatches &amp; Field Notes
            </span>
            <h1 style={{ marginTop: 12, marginBottom: 18 }}>The Written Word</h1>
            <p style={{ fontStyle: "italic", color: "var(--ink-mute)", fontSize: "1.1rem" }}>
              The editorial companion to the podcast — essays, source write-ups, and notes from the road.
              Published sometimes when we can and feel like it, alongside the episodes. Subscribe below to get them in your inbox.
            </p>
          </div>
        </div>
      </section>

      <section className="section" style={{ paddingTop: 20 }}>
        <div className="container">
          <div className="dispatch-grid">
            <div>
              <div className="dispatch-list">
                {D.dispatches.map(d => (
                  <article key={d.id} className="dispatch">
                    <div className="dispatch-date">
                      <span className="day">{d.day}</span>
                      {d.month} '26
                    </div>
                    <div>
                      <h3 className="dispatch-headline">{d.title}</h3>
                      <p className="dispatch-excerpt">{d.excerpt}</p>
                      <span className="dispatch-readmore">Read the dispatch {Icon.arrow(10)}</span>
                    </div>
                  </article>
                ))}
              </div>
            </div>
            <aside>
              <div className="aside-card">
                <span className="kicker">Subscribe</span>
                <h3>The Saturday Dispatch</h3>
                <p>Two dispatches a month, the new episode, and one good photograph from the road. No spam, ever.</p>
                {showSubstack ? (
                  <iframe
                    title="Substack signup"
                    src="https://themanofenchantment.substack.com/embed"
                    width="100%" height="160"
                    style={{ border: "1px solid var(--rule)", background: "white", marginTop: 14 }}
                    frameBorder="0" scrolling="no"
                  />
                ) : (
                  <form className="signup-form" onSubmit={(e) => { e.preventDefault(); setSignedUp(true); }}>
                    {signedUp ? (
                      <div className="ok">✓ Subscribed — check your inbox</div>
                    ) : (
                      <>
                        <input type="email" placeholder="you@example.com" required value={email} onChange={(e) => setEmail(e.target.value)} />
                        <button type="submit">Subscribe</button>
                      </>
                    )}
                  </form>
                )}
                <button onClick={() => setShowSubstack(!showSubstack)}
                  style={{ marginTop: 14, fontFamily: "var(--slab)", fontSize: "0.68rem", letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--clay)", padding: 0 }}>
                  {showSubstack ? "→ Use simple form" : "→ Switch to Substack embed"}
                </button>
              </div>
              <div className="aside-card">
                <span className="kicker">Browse the archive</span>
                <h3>By Series</h3>
                <ul style={{ listStyle: "none", padding: 0, margin: "10px 0 0", display: "flex", flexDirection: "column", gap: 8, fontFamily: "var(--slab)", fontSize: "0.82rem" }}>
                  {D.tags.filter(t => t !== "All").map(t => (
                    <li key={t}><a href="#" style={{ display: "flex", justifyContent: "space-between" }}>
                      <span>{t}</span><span style={{ color: "var(--ink-mute)" }}>{D.episodes.filter(e => e.tag === t).length}</span>
                    </a></li>
                  ))}
                </ul>
              </div>
            </aside>
          </div>
        </div>
      </section>
    </>
  );
}

// ============================ ABOUT ============================
function AboutPage({ go }) {
  return (
    <>
      <section className="section">
        <div className="container">
          <div className="about-grid">
            <div className="about-prose">
              <span className="kicker" style={{ fontFamily: "var(--slab)", fontSize: "0.72rem", letterSpacing: "0.32em", textTransform: "uppercase", color: "var(--clay)" }}>
                About the Show
              </span>
              <h1 style={{ marginTop: 12, marginBottom: 24 }}>Men of Enchantment</h1>
              <p>
                The Enchantment Chronicles began over a long afternoon at a kitchen table in the South Valley,
                arguing about whether the Lincoln County War was really about Billy the Kid or about a corrupt
                federal beef contract. (It was the beef contract.) We agreed that night that someone ought to tell
                these stories the way New Mexicans actually tell them — with patience, with primary sources, and
                without the gloss that the rest of the country tends to put on the Southwest.
              </p>
              <p>
                We are not historians by trade. We are sons and daughters of this state — by birth, by marriage,
                by stubbornness — and we believe the best history is the kind that gets walked, not just read.
                Every episode begins on the ground: a drive to Glorieta Pass, a winter morning in Lincoln, a long
                conversation in a kitchen in Truchas.
              </p>
              <p>
                Men of Enchantment is the umbrella for everything we make — the podcast, the dispatches, and, soon,
                a small book series. We're based in Albuquerque. We answer email slowly. We do not own a saguaro.
              </p>
              <div className="hosts">
                <div className="host-card">
                  <div className="host-portrait"></div>
                  <h4>Drew Sedrel</h4>
                  <div className="role">Host &amp; Researcher</div>
                  <p>New Mexican by way of the long road. Keeps the bibliographies and the field notebooks.</p>
                </div>
                <div className="host-card">
                  <div className="host-portrait"></div>
                  <h4>Johnny Osborn</h4>
                  <div className="role">Host &amp; Producer</div>
                  <p>Drives the truck, runs the microphones, asks the questions the historians forgot to.</p>
                </div>
              </div>
              <div style={{ marginTop: 40 }}>
                <button className="btn btn-ghost" onClick={() => go("listen")}>How to Listen {Icon.arrow(14)}</button>
              </div>
            </div>
            <div>
              <div className="nm-map">
                <NewMexicoMap />
                <div className="map-label">Plates &amp; Pueblos · 2026</div>
              </div>
              <div className="aside-card" style={{ marginTop: 24 }}>
                <span className="kicker">Mission</span>
                <p style={{ fontStyle: "italic", color: "var(--ink)", lineHeight: 1.65 }}>
                  "To tell the story of New Mexico the way New Mexicans tell it themselves —
                  slowly, accurately, and with a deep respect for the ground."
                </p>
              </div>
            </div>
          </div>
        </div>
      </section>
    </>
  );
}

// ============================ LISTEN ============================
function ListenPage() {
  const platforms = D.platforms;
  return (
    <>
      <section className="section">
        <div className="container-narrow" style={{ textAlign: "center" }}>
          <span className="kicker" style={{ fontFamily: "var(--slab)", fontSize: "0.72rem", letterSpacing: "0.32em", textTransform: "uppercase", color: "var(--clay)" }}>
            Wherever You Listen
          </span>
          <h1 style={{ marginTop: 12, marginBottom: 18 }}>Find the Show</h1>
          <p style={{ fontStyle: "italic", color: "var(--ink-mute)", fontSize: "1.1rem", maxWidth: 580, margin: "0 auto" }}>
            We're on every major platform, plus a clean RSS feed for the purists.
            Subscribe once, and the next chronicle finds you.
          </p>
        </div>
      </section>
      <section className="section" style={{ paddingTop: 0 }}>
        <div className="container-narrow">
          <div className="platform-grid">
            {platforms.map(p => (
              <a key={p.name} className="platform-card" href={p.url} target="_blank" rel="noreferrer">
                <span className="platform-icon">{Icon[p.icon]()}</span>
                <span>
                  <span className="platform-name">{p.name}</span><br/>
                  <span className="platform-sub">{p.sub}</span>
                </span>
              </a>
            ))}
          </div>
          <DividerZia />
          <h2 style={{ textAlign: "center", marginBottom: 24 }}>Or play the whole show right here</h2>
          <PodcastEmbed ep={D.episodes[0]} onPlay={() => {}} />
        </div>
      </section>
    </>
  );
}

// ============================ AUDIO BAR ============================
function AudioBar({ track, onClose }) {
  const [playing, setPlaying] = useState(true);
  const [progress, setProgress] = useState(18);
  useEffect(() => {
    if (!playing) return;
    const t = setInterval(() => setProgress(p => (p >= 100 ? 100 : p + 0.15)), 200);
    return () => clearInterval(t);
  }, [playing, track]);
  useEffect(() => { setProgress(8); setPlaying(true); }, [track?.n]);
  if (!track) return null;
  return (
    <div className="audio-bar">
      <div className="audio-bar-art">
        <ZiaSun size={32} color="#B85C38" />
      </div>
      <div className="audio-bar-info">
        <span className="audio-bar-kicker">Now Playing — № {String(track.n).padStart(2, "0")}</span>
        <span className="audio-bar-title">{track.title}</span>
      </div>
      <button className="audio-bar-btn" onClick={() => setPlaying(!playing)}>
        {playing ? Icon.pause(14) : Icon.play(14)}
      </button>
      <div className="audio-bar-scrub">
        <span className="audio-bar-time">12:{String(Math.floor(progress * 0.5)).padStart(2, "0")}</span>
        <div className="audio-bar-progress" onClick={(e) => {
          const r = e.currentTarget.getBoundingClientRect();
          setProgress(((e.clientX - r.left) / r.width) * 100);
        }}>
          <div className="audio-bar-progress-fill" style={{ width: `${progress}%` }}></div>
        </div>
        <span className="audio-bar-time">{track.duration}</span>
      </div>
      <button className="audio-bar-close" onClick={onClose} aria-label="Close player">{Icon.close(16)}</button>
    </div>
  );
}

// ============================ FOOTER ============================
function Footer({ go }) {
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer-grid">
          <div className="footer-brand">
            <EnchantmentBadge size={110} color="#F5EFE0" ring="#3AA8A0" />
            <p>A semi-monthly history podcast from Men of Enchantment. Recorded in Albuquerque. Telling New Mexico's story, true to the ground.</p>
          </div>
          <div>
            <h5>Show</h5>
            <ul>
              <li><a href="#" onClick={(e) => { e.preventDefault(); go("episodes"); }}>Episodes</a></li>
              <li><a href="#" onClick={(e) => { e.preventDefault(); go("about"); }}>About</a></li>
            </ul>
          </div>
          <div>
            <h5>Listen</h5>
            <ul>
              {D.platforms.slice(0, 4).map(p => (
                <li key={p.name}><a href={p.url} target="_blank" rel="noreferrer">{p.name}</a></li>
              ))}
            </ul>
          </div>
          <div>
            <h5>Contact</h5>
            <ul>
              <li><a href="mailto:newmexpodcast@gmail.com">newmexpodcast@gmail.com</a></li>
              <li><a href="#">Press kit</a></li>
              <li><a href="#">Tip line</a></li>
            </ul>
          </div>
        </div>
        <div className="footer-bot">
          <span>© MMXXVI Men of Enchantment</span>
          <span>Albuquerque · Santa Fe · The Bootheel</span>
        </div>
      </div>
    </footer>
  );
}

// ============================ APP ============================
function App() {
  const [route, setRoute] = useState("home");
  const [epId, setEpId] = useState(null);
  const [track, setTrack] = useState(null);

  const go = (r) => { setRoute(r); setEpId(null); window.scrollTo({ top: 0, behavior: "instant" }); };
  const goEp = (n) => { setEpId(n); setRoute("episode"); window.scrollTo({ top: 0, behavior: "instant" }); };
  const onPlay = (ep) => { window.open(D.platforms[1].url, "_blank", "noopener,noreferrer"); };

  let body;
  if (route === "home") body = <HomePage go={go} onPlay={onPlay} />;
  else if (route === "episodes") body = <EpisodesPage onPlay={onPlay} goEp={goEp} />;
  else if (route === "episode") body = <EpisodeDetail n={epId} go={go} onPlay={onPlay} />;
  else if (route === "about") body = <AboutPage go={go} />;
  else if (route === "listen") body = <ListenPage />;

  return (
    <div className="site">
      <Nav route={route === "episode" ? "episodes" : route} go={go} />
      {body}
      <Footer go={go} />
      {/* AudioBar removed — play now opens Spotify */}
    </div>
  );
}

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