// Featured episode (audio player mock) + Episode grid
const { useState: useStateP, useEffect: useEffectP, useRef: useRefP } = React;

const getEpisodes = () => (window.CONTENT || []).filter(c => c.contentType === "podcast");

function Podcast() {
  return (
    <section id="podcast" style={{
      background: "linear-gradient(180deg,#05060a 0%,#0a0b10 60%,#070810 100%)",
      borderTop: "1px solid var(--line)", borderBottom: "1px solid var(--line)",
    }}>
      <div className="container pod-pad" style={{ padding: "140px 32px 120px" }}>
        <Header kicker="THE FARAH METHOD · PODCAST" title={<>Long conversations <br /><em style={{ color: "var(--gold-2)", fontWeight: 300 }}>that earn their length.</em></>} sub="Weekly. Between 45 minutes and three hours. No sponsor reads — listeners fund it directly." />
        <FeaturedPlayer />
        <EpisodeGrid />
      </div>
      <style>{`
        @media (max-width: 560px) {
          .pod-pad { padding: 64px 20px 48px !important; }
          .sec-header { margin-bottom: 32px !important; }
          .featured-player { margin-bottom: 40px !important; }
          .featured-player > *:first-child { min-height: 260px !important; }
          .featured-player > *:last-child { padding: 24px !important; gap: 18px !important; }
          .featured-player > *:last-child h3 { font-size: 22px !important; }
          .featured-player > *:first-child > div { padding: 22px !important; }
          .featured-player button[aria-label="Play"],
          .featured-player button[aria-label="Pause"] { width: 64px !important; height: 64px !important; }
        }
      `}</style>
    </section>
  );
}

function Header({ kicker, title, sub, dark }) {
  return (
    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 48, alignItems: "end", marginBottom: 72 }} className="sec-header">
      <div>
        <span className="mono" style={{ fontSize: 11, letterSpacing: ".28em", color: "var(--gold)" }}>{kicker}</span>
        <h2 className="serif" style={{ fontSize: "clamp(34px,4.6vw,64px)", lineHeight: 1.04, letterSpacing: "-0.01em", fontWeight: 400, margin: "24px 0 0" }}>
          {title}
        </h2>
      </div>
      {sub && <p style={{ fontSize: 16, lineHeight: 1.6, color: "var(--soft)", margin: 0, maxWidth: 460 }}>{sub}</p>}
      <style>{`@media (max-width: 860px) { .sec-header { grid-template-columns: 1fr !important; gap: 20px !important; } }`}</style>
    </div>
  );
}

function FeaturedPlayer() {
  const ep = getEpisodes()[0];
  if (!ep) return null;
  const [playing, setPlaying] = useStateP(false);
  const [t, setT] = useStateP(0); // 0..1
  const total = 2 * 3600 + 12 * 60; // 2h12m
  const timerRef = useRefP(null);

  useEffectP(() => {
    if (playing) {
      timerRef.current = setInterval(() => {
        setT(x => {
          const next = x + (0.6 / total);
          return next >= 1 ? 1 : next;
        });
      }, 600);
    } else if (timerRef.current) clearInterval(timerRef.current);
    return () => { if (timerRef.current) clearInterval(timerRef.current); };
  }, [playing, total]);

  const fmt = (s) => {
    const h = Math.floor(s / 3600), m = Math.floor((s % 3600) / 60), ss = Math.floor(s % 60);
    return h ? `${h}:${String(m).padStart(2,"0")}:${String(ss).padStart(2,"0")}` : `${m}:${String(ss).padStart(2,"0")}`;
  };
  const cur = t * total;

  return (
    <div style={{
      display: "grid", gridTemplateColumns: "1.1fr 1fr", gap: 1,
      background: "var(--line-strong)", border: "1px solid var(--line-strong)",
      marginBottom: 80,
    }} className="featured-player">
      {/* Art */}
      <div style={{ background: ep.art, position: "relative", minHeight: 420, overflow: "hidden" }}>
        <div aria-hidden style={{ position: "absolute", inset: 0, background: "radial-gradient(600px 400px at 30% 30%, rgba(201,169,97,.18), transparent 60%)" }} />
        <div style={{ position: "absolute", inset: 0, padding: 40, display: "flex", flexDirection: "column", justifyContent: "space-between" }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
            <span className="mono" style={{ fontSize: 11, letterSpacing: ".3em", color: "var(--gold-2)" }}>LATEST · #{ep.episodeNum}</span>
            <span className="mono" style={{ fontSize: 11, letterSpacing: ".24em", color: "var(--muted)" }}>{window.topicLabel(ep.topic).toUpperCase()}</span>
          </div>
          <div>
            <button onClick={() => setPlaying(p => !p)} aria-label={playing ? "Pause" : "Play"}
              style={{
                width: 84, height: 84, borderRadius: "50%", border: "1px solid var(--gold)",
                display: "grid", placeItems: "center",
                background: "rgba(10,10,14,.5)", backdropFilter: "blur(4px)",
                transition: "transform .2s ease, background .2s ease",
              }}
              onMouseEnter={(e) => e.currentTarget.style.background = "rgba(201,169,97,.18)"}
              onMouseLeave={(e) => e.currentTarget.style.background = "rgba(10,10,14,.5)"}
            >
              {playing ? (
                <svg width="22" height="26" viewBox="0 0 22 26"><rect x="2" y="2" width="6" height="22" fill="#d9bd7a"/><rect x="14" y="2" width="6" height="22" fill="#d9bd7a"/></svg>
              ) : (
                <svg width="24" height="26" viewBox="0 0 24 26"><path d="M4 2 L22 13 L4 24 Z" fill="#d9bd7a"/></svg>
              )}
            </button>
          </div>
        </div>
      </div>
      {/* Info */}
      <div style={{ background: "#0a0b10", padding: 40, display: "flex", flexDirection: "column", gap: 24 }}>
        <div>
          <div style={{ display: "flex", gap: 16, alignItems: "center", color: "var(--muted)" }} className="mono">
            <span style={{ fontSize: 11, letterSpacing: ".24em" }}>{ep.date.toUpperCase()}</span>
            <span style={{ width: 4, height: 4, background: "var(--gold)", transform: "rotate(45deg)" }} />
            <span style={{ fontSize: 11, letterSpacing: ".24em" }}>{ep.duration}</span>
          </div>
          <h3 className="serif" style={{ fontSize: 32, lineHeight: 1.12, letterSpacing: "-0.01em", fontWeight: 400, margin: "20px 0 12px" }}>
            {ep.title}
          </h3>
          <p style={{ fontSize: 14, color: "var(--soft)", margin: 0 }}>{ep.guest}</p>
        </div>
        {/* waveform */}
        <div style={{ marginTop: "auto" }}>
          <Waveform progress={t} onSeek={setT} />
          <div className="mono" style={{ display: "flex", justifyContent: "space-between", marginTop: 12, fontSize: 11, color: "var(--muted)", letterSpacing: ".12em" }}>
            <span>{fmt(cur)}</span>
            <span>−{fmt(total - cur)}</span>
          </div>
        </div>
      </div>
      <style>{`@media (max-width: 860px) { .featured-player { grid-template-columns: 1fr !important; } .featured-player > *:first-child { min-height: 320px !important; } }`}</style>
    </div>
  );
}

function Waveform({ progress, onSeek }) {
  const bars = 64;
  const ref = useRefP(null);
  // deterministic heights
  const heights = React.useMemo(() => Array.from({ length: bars }, (_, i) => {
    const x = i / bars;
    const env = Math.sin(x * Math.PI) * 0.8 + 0.2;
    const noise = Math.sin(i * 1.7) * 0.25 + Math.cos(i * 0.9) * 0.18;
    return Math.max(0.15, Math.min(1, env + noise));
  }), []);
  const handleClick = (e) => {
    const r = ref.current.getBoundingClientRect();
    onSeek(Math.max(0, Math.min(1, (e.clientX - r.left) / r.width)));
  };
  return (
    <div ref={ref} onClick={handleClick} style={{ display: "flex", alignItems: "center", gap: 3, height: 52, cursor: "pointer" }}>
      {heights.map((h, i) => {
        const active = i / bars <= progress;
        return (
          <div key={i} style={{
            flex: 1, height: `${h * 100}%`,
            background: active ? "var(--gold-2)" : "rgba(242,238,228,.16)",
            transition: "background .12s linear",
          }} />
        );
      })}
    </div>
  );
}

function EpisodeGrid() {
  const all = getEpisodes();
  return (
    <div>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 32 }}>
        <h3 className="serif" style={{ fontSize: 28, fontWeight: 400, margin: 0 }}>Recent episodes</h3>
        <a href="topics.html#podcast" style={{ fontSize: 12, letterSpacing: ".18em", textTransform: "uppercase", color: "var(--gold-2)", borderBottom: "1px solid var(--gold-3)", paddingBottom: 4 }}>
          All {all.length} episodes →
        </a>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 24 }} className="ep-grid">
        {all.slice(1, 4).map((ep) => <EpisodeCard key={ep.id} ep={ep} />)}
      </div>
      <style>{`
        @media (max-width: 960px) { .ep-grid { grid-template-columns: repeat(2, 1fr) !important; } }
        @media (max-width: 620px) { .ep-grid { grid-template-columns: 1fr !important; } }
      `}</style>
    </div>
  );
}

function EpisodeCard({ ep }) {
  const [hover, setHover] = useStateP(false);
  return (
    <a href={`article.html?id=${ep.id}`}
      onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      style={{
        border: "1px solid var(--line)",
        background: hover
          ? "linear-gradient(180deg,rgba(201,169,97,.06),rgba(10,11,16,.6))"
          : "linear-gradient(180deg,rgba(13,14,20,.6),rgba(7,8,12,.6))",
        transition: "background .2s ease, transform .2s ease, border-color .2s ease",
        borderColor: hover ? "var(--line-strong)" : "var(--line)",
        transform: hover ? "translateY(-2px)" : "translateY(0)",
        display: "flex", flexDirection: "column",
      }}>
      <div style={{ aspectRatio: "16 / 10", background: ep.art, position: "relative", overflow: "hidden" }}>
        <div aria-hidden style={{ position: "absolute", inset: 0, background: "radial-gradient(400px 280px at 30% 30%, rgba(201,169,97,.14), transparent 60%)" }} />
        <div style={{ position: "absolute", top: 16, left: 16, display: "flex", justifyContent: "space-between", right: 16 }}>
          <span className="mono" style={{ fontSize: 10, letterSpacing: ".28em", color: "var(--gold-2)" }}>#{ep.episodeNum}</span>
          <span className="mono" style={{ fontSize: 10, letterSpacing: ".22em", color: "var(--muted)" }}>{window.topicLabel(ep.topic).toUpperCase()}</span>
        </div>
        <div style={{
          position: "absolute", right: 16, bottom: 16, width: 48, height: 48, borderRadius: "50%",
          border: "1px solid var(--gold)", display: "grid", placeItems: "center",
          background: hover ? "var(--gold)" : "rgba(10,10,14,.5)",
          transition: "background .2s ease, transform .2s ease",
          transform: hover ? "scale(1.06)" : "scale(1)",
        }}>
          <svg width="14" height="16" viewBox="0 0 14 16"><path d="M2 1 L13 8 L2 15 Z" fill={hover ? "#0b0b0d" : "#d9bd7a"}/></svg>
        </div>
      </div>
      <div style={{ padding: "24px 22px 26px", display: "flex", flexDirection: "column", gap: 14, flex: 1 }}>
        <div className="mono" style={{ fontSize: 11, letterSpacing: ".22em", color: "var(--muted)", display: "flex", gap: 12 }}>
          <span>{ep.date.toUpperCase()}</span><span>·</span><span>{ep.duration}</span>
        </div>
        <h4 className="serif" style={{ fontSize: 20, lineHeight: 1.22, fontWeight: 400, margin: 0, letterSpacing: "-0.005em" }}>{ep.title}</h4>
        <p style={{ fontSize: 13, color: "var(--soft)", margin: "auto 0 0" }}>{ep.guest}</p>
      </div>
    </a>
  );
}

Object.assign(window, { Podcast });
