/* eslint-disable */
/* ============================================================
   Variation A — Editorial (photo-forward, classic magazine)
   ============================================================ */

const VariationEditorial = ({ state, dispatch, onToast, episodes, feedStatus, onOpenAsk }) => {
  const [activeTopic, setActiveTopic] = useState(null);
  const [showAllPrev, setShowAllPrev] = useState(false);
  const INITIAL_PREV_COUNT = 4;
  const list = episodes && episodes.length ? episodes : RELATED_EPISODES;
  const { activeEpisode, playEpisode } = React.useContext(ActiveEpisodeContext);
  // Shape the active episode to match the hero's data contract; fall back to CURRENT_EPISODE
  const ep = activeEpisode ? {
    season: activeEpisode.seasonNum,
    number: activeEpisode.number,
    num: activeEpisode.num,
    title: activeEpisode.title,
    subtitle: activeEpisode.sub,
    lead: activeEpisode.fullDescription || activeEpisode.sub,
    date: activeEpisode.dateLong || activeEpisode.date,
    duration: activeEpisode.duration,
  } : CURRENT_EPISODE;
  // Filter out the active episode from the Previous list, then apply topic filter
  const previousList = list
    .filter(e => e.uid !== activeEpisode?.uid)
    .filter(e => !activeTopic || episodeMatchesTopic(e, activeTopic));
  // Counts for each topic chip, from the full live list
  const topicCounts = React.useMemo(
    () => Object.fromEntries(TOPICS.map(t => [t.name, list.filter(e => episodeMatchesTopic(e, t)).length])),
    [list]
  );
  const onTopicClick = (t) => {
    const next = activeTopic?.name === t.name ? null : t;
    setActiveTopic(next);
    if (next) {
      onToast(`Filtering: ${t.name} · ${topicCounts[t.name]} episodes`);
      setTimeout(() => {
        const el = document.getElementById("previous-episodes");
        if (el) window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - 80, behavior: "smooth" });
      }, 80);
    }
  };

  return (
    <div className="v-editorial">
      {/* HOST — moved to top */}
      <section style={{ paddingTop: 32 }}>
        <div className="container-wide">
          <div className="host-section">
            <div className="host-photo" style={{ overflow: "hidden", borderRadius: 6 }}>
              <img
                src="assets/kristen-portrait-v2.png"
                alt="Kristen Parise laughing, holding a pelvic anatomy model"
                style={{ width: "100%", height: "100%", objectFit: "cover", objectPosition: "center center", display: "block" }}
              />
            </div>
            <div className="host-content">
              <div className="section-eyebrow">Your host</div>
              <h2>Kristen Parise.<br />Pelvic Health Physio.<br /><em>Professional truth-teller.</em></h2>
              <p>Kristen has spent twenty-five years with her hands (gloves on, with consent) in the parts of the body most of healthcare prefers not to discuss. She started this podcast because she was tired of saying the same sentence to every client: "Why has nobody told you this?"</p>
              <div className="host-creds">
                <span className="host-cred"><strong>25+</strong> years in practice</span>
                <span className="host-cred"><strong>3,500+</strong> clients</span>
                <span className="host-cred"><strong>Clinic owner</strong> Blueberry Therapy</span>
              </div>
              <div style={{ display: "flex", gap: 8 }}>
                <button
                  className="btn btn-navy"
                  onClick={() => {
                    const el = document.getElementById("previous-episodes");
                    if (el) window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - 80, behavior: "smooth" });
                  }}
                >
                  <Icon name="mic" size={14} /> Listen to more
                </button>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* HERO */}
      <section className="hero">
        <div className="container-wide">
          <div className="hero-grid">
            <div>
              <div className="hero-eyebrow">
                <span className="tag tag-coral">EP {String(ep.number).padStart(3, "0")}</span>
                <span className="kicker">Aired {ep.date}</span>
              </div>

              <h1 className="hero-title">
                {activeEpisode ? ep.title : <>The pelvic floor is <span className="coral-word">not</span> a mystery box.</>}
              </h1>

              <p className="hero-lead">
                {activeEpisode ? ep.subtitle : "Kristen Parise on why one in three people leak, why kegels aren’t the answer, and what actually works."}
              </p>

              <div className="hero-meta">
                <div className="hero-meta-item">
                  <span className="label">Runtime</span>
                  <span className="value">{ep.duration}</span>
                </div>
                <div className="hero-meta-item">
                  <span className="label">On the mic</span>
                  <span className="value">Kristen Parise</span>
                </div>
                {(() => {
                  // Parse guest from the title. Handles:
                  //   "... with Kim Vopni"                          → "Kim Vopni"
                  //   "... with The Vagina Coach Kim Vopni"         → "Kim Vopni, The Vagina Coach"
                  //   "... with The Vagina Coach with Kim Vopni"    → "Kim Vopni, The Vagina Coach"
                  //   "... with Dr. Nan Wise"                        → "Dr. Nan Wise"
                  const t = (ep.title || "").replace(/\s+/g, " ").trim();
                  const afterWith = t.match(/\bwith\s+(.+?)(?:\s*[-–—]\s*.*)?$/i);
                  let guest = null;
                  let role = null;
                  if (afterWith) {
                    let tail = afterWith[1].trim();
                    // Case 1: "... with <role> with <name>"
                    const splitWith = tail.match(/^(.+?)\s+with\s+(.+)$/i);
                    if (splitWith) {
                      role = splitWith[1].trim();
                      guest = splitWith[2].trim();
                    } else {
                      // Case 2: tail starts with "The/A/An ..." — role comes first, name (2 tokens) at the end
                      const roleStart = tail.match(/^((?:The|A|An)\s+[A-Za-z'-]+(?:\s+[A-Za-z'-]+)*)\s+((?:Dr\.?\s+)?[A-Z][a-z]+\s+[A-Z][a-z'-]+)$/);
                      if (roleStart) {
                        role = roleStart[1].trim();
                        guest = roleStart[2].trim();
                      } else {
                        guest = tail;
                      }
                    }
                    guest = guest.replace(/[,.]$/, "").trim();
                  }
                  const display = guest ? (role ? `${guest}, ${role}` : guest) : "Solo";
                  return (
                    <div className="hero-meta-item">
                      <span className="label">{guest ? "Guest" : "Format"}</span>
                      <span className="value">{display}</span>
                    </div>
                  );
                })()}
                <div className="hero-meta-item">
                  <span className="label">Plain language</span>
                  <span className="value">Always</span>
                </div>
              </div>

              <div className="hero-actions">
                <button className="btn btn-primary btn-lg" onClick={() => dispatch({ type: "toggle" })}>
                  <Icon name={state.isPlaying ? "pause" : "play"} size={16} />
                  {state.isPlaying ? "Pause episode" : "Play episode"}
                </button>
                <button className="btn btn-ghost" onClick={async () => {
                  const ok = await window.copyToClipboard(window.location.href);
                  onToast(ok ? "Link copied" : "Couldn't copy — try long-pressing the address bar");
                }}>
                  <Icon name="share" size={14} /> Share
                </button>
              </div>
            </div>

            <div className="hero-cover" style={{ position: "relative", overflow: "hidden", borderRadius: 4 }}>
              <span className="episode-number-tag">EP · {String(ep.number).padStart(3, "0")}</span>
              <img
                src="assets/kristen-hero.png"
                alt="The Hole Shebang cover art — Kristen Parise in an embroidered dress"
                style={{ width: "100%", height: "100%", objectFit: "cover", objectPosition: "center center", display: "block" }}
              />
            </div>
          </div>
        </div>
      </section>

      {/* PLAYER */}
      <section style={{ padding: "0 0 64px" }}>
        <div className="container-wide">
          <Player state={state} dispatch={dispatch} />
        </div>
      </section>

      {/* EPISODE DETAILS — accordions + sticky sidebar */}
      <section style={{ padding: "0 0 64px" }}>
        <div className="container-wide">
          <EpisodeDetails
            onToast={onToast}
            episode={activeEpisode}
            episodes={list}
            state={state}
            dispatch={dispatch}
          />
        </div>
      </section>

      {/* SUBSCRIBE */}
      <section className="subscribe">
        <div className="container-wide">
          <div className="subscribe-grid">
            <div>
              <div className="eyebrow" style={{ color: "var(--coral)", marginBottom: "12px" }}>NEW EPISODES EVERY THURSDAY</div>
              <h2>Follow the Hole Shebang.</h2>
              <p>One tap and we're officially in your ears every Thursday. (Transcripts too, for when your ears are busy.)</p>
            </div>
            <div className="platform-grid">
              {PLATFORMS.filter(p => p.href).map(p => (
                <a
                  key={p.name}
                  className="platform-chip"
                  href={p.href}
                  target="_blank"
                  rel="noopener noreferrer"
                >
                  {p.name} <Icon name="arrowUpRight" size={12} />
                </a>
              ))}
            </div>
          </div>
        </div>
      </section>

      {/* TOPICS */}
      <section>
        <div className="container-wide">
          <div className="section-header">
            <div>
              <div className="section-eyebrow">Browse by topic</div>
              <h2 className="section-title">What are you curious about?</h2>
            </div>
          </div>
          <div className="topics-grid">
            {TOPICS.map(t => {
              const isActive = activeTopic?.name === t.name;
              const count = topicCounts[t.name] ?? 0;
              return (
                <div
                  key={t.name}
                  className={`topic-chip ${isActive ? "topic-chip-active" : ""} ${count === 0 ? "topic-chip-empty" : ""}`}
                  onClick={() => count > 0 && onTopicClick(t)}
                  style={count === 0 ? { opacity: 0.4, cursor: "not-allowed" } : undefined}
                >
                  <span className="topic-count">{count} {count === 1 ? "episode" : "episodes"}</span>
                  <div className="topic-name">{t.name}</div>
                </div>
              );
            })}
          </div>
        </div>
      </section>

      {/* RELATED */}
      <section id="previous-episodes" style={{ borderTop: "1px solid var(--line-soft)", paddingTop: "var(--s-3xl)" }}>
        <div className="container-wide">
          <div className="section-header">
            <div>
              <div className="section-eyebrow">
                {activeTopic ? `Filtered by topic` : `Keep listening`} {feedStatus === "loading" ? "· loading…" : ""}
              </div>
              <h2 className="section-title">
                {activeTopic ? activeTopic.name : "Previous episodes"}
                {activeTopic && <span style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 14, fontWeight: 400, color: "var(--ink-soft)", marginLeft: 12 }}>{previousList.length} episodes</span>}
              </h2>
            </div>
            {activeTopic
              ? <button className="btn btn-ghost btn-sm" onClick={() => setActiveTopic(null)}>Clear filter ✕</button>
              : null}
          </div>
          <div>
            {previousList.length > 0
              ? (activeTopic || showAllPrev ? previousList : previousList.slice(0, INITIAL_PREV_COUNT))
                  .map(ep => <EpisodeRow key={ep.uid || ep.num} ep={ep} onPlay={() => playEpisode(ep)} />)
              : <div style={{ padding: "48px 0", textAlign: "center", color: "var(--ink-soft)", fontStyle: "italic" }}>No episodes match this topic yet.</div>}
          </div>
          {!activeTopic && previousList.length > INITIAL_PREV_COUNT && (
            <div style={{ display: "flex", justifyContent: "center", marginTop: "var(--s-xl)", paddingTop: "var(--s-lg)", borderTop: "1px solid var(--line-soft)" }}>
              <button
                className="btn btn-ghost"
                onClick={() => {
                  if (showAllPrev) {
                    // Collapse and scroll back up to section top
                    setShowAllPrev(false);
                    setTimeout(() => {
                      const el = document.getElementById("previous-episodes");
                      if (el) window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - 80, behavior: "smooth" });
                    }, 50);
                  } else {
                    setShowAllPrev(true);
                  }
                }}
              >
                {showAllPrev
                  ? <>Show less <Icon name="chevronUp" size={12} /></>
                  : <>Show all {previousList.length} episodes <Icon name="chevronDown" size={12} /></>}
              </button>
            </div>
          )}
        </div>
      </section>

      {/* NEWSLETTER */}
      <section>
        <div className="container-wide">
          <div className="newsletter-block">
            <div>
              <div className="section-eyebrow" style={{ color: "var(--accent)", marginBottom: 12 }}>Every Friday</div>
              <h2 style={{ fontFamily: "Jost", fontWeight: 700, fontSize: "clamp(32px, 4vw, 56px)", lineHeight: 1, letterSpacing: "-0.02em", marginBottom: 12, color: "var(--cream)" }}>
                Real pelvic health,<br/>straight to your inbox.
              </h2>
              <p style={{ fontFamily: "Lora, serif", fontStyle: "italic", fontSize: 17, opacity: 0.85, maxWidth: "48ch" }}>
                Join the Blueberry Therapy newsletter for new episodes, practical tips from the clinic, and honest answers to the questions nobody else is asking.
              </p>
            </div>
            <NewsletterForm onToast={onToast} darkInput={true} />
          </div>
        </div>
      </section>

      <Footer onOpenAsk={onOpenAsk} />
    </div>
  );
};

Object.assign(window, { VariationEditorial });
