// refined-index.jsx — Kaya Refined series page

// ---------- helpers ----------
const ArrowRight = () => (
  <svg width="14" height="10" viewBox="0 0 24 14" fill="none" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round" strokeLinejoin="round">
    <line x1="0" y1="7" x2="22" y2="7"/><polyline points="16 1 22 7 16 13"/>
  </svg>
);

const ArrowExternal = () => (
  <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round" strokeLinejoin="round">
    <line x1="7" y1="17" x2="17" y2="7"/><polyline points="9 7 17 7 17 15"/>
  </svg>
);

// Elegant play triangle
const PlayIcon = ({ size = 18 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor">
    <polygon points="6,3 20,12 6,21" />
  </svg>
);

// Format "2026-05-01" → "May, 2026"
const formatDate = (iso) => {
  const d = new Date(iso + "T12:00:00");
  return d.toLocaleDateString("en-US", { month: "long", year: "numeric" }).replace(" ", ", ");
};

// Season + episode label: "S01 · E01"
const episodeLabel = (ep) => `S${String(ep.season).padStart(2,"0")} · E${String(ep.episode).padStart(2,"0")}`;

// YouTube watch URL from youtubeId
const watchUrl = (ep) => {
  const cfg = window.KAYA_YOUTUBE || {};
  if (ep.youtubeId && ep.youtubeId !== "REPLACE_WITH_REAL_ID") {
    return `https://youtube.com/watch?v=${ep.youtubeId}`;
  }
  return cfg.channelUrl || "https://youtube.com/@kaya";
};

// Nav links go to their dedicated pages ("refined" is this page → scroll
// to top); Subscribe scrolls to the newsletter form.
const handleNavigate = (id) => {
  if (id === "refined") {
    window.scrollTo({ top: 0, behavior: "smooth" });
  } else if (id === "subscribe") {
    document.querySelector(".journal-newsletter-section")?.scrollIntoView({ behavior: "smooth" });
  } else if (id === "journal") {
    window.location.href = "/journal";
  } else if (id === "ethos") {
    window.location.href = "/ethos";
  } else {
    window.location.href = `/#${id}`;
  }
};

// ---------- newsletter / CTA ----------
const EpisodeCTA = () => {
  const [email, setEmail] = React.useState("");
  const [done, setDone] = React.useState(false);
  const yt = window.KAYA_YOUTUBE || {};

  const submit = (e) => {
    e.preventDefault();
    const val = email.trim();
    if (!val) return;
    const cfg = window.KAYA_BEEHIIV || {};
    const url = `${cfg.subscribeUrl}?email=${encodeURIComponent(val)}`;
    window.open(url, "_blank", "noopener,noreferrer");
    setDone(true);
  };

  return (
    <section className="journal-newsletter-section">
      <div className="journal-newsletter-section__inner">
        <KayaReveal as="div" style={{ display: "flex", flexDirection: "column", gap: "24px" }}>
          <p className="journal-newsletter-section__lede">
            New episodes drop <em>monthly.</em><br />Don't miss one.
          </p>
          <a className="btn-quiet btn-quiet--burgundy"
             href={yt.channelUrl || "https://youtube.com/@kaya"}
             target="_blank" rel="noopener">
            Subscribe on YouTube <ArrowExternal />
          </a>
        </KayaReveal>
        <KayaReveal as="div" delay={160}>
          <p style={{
            fontFamily: "var(--font-body)",
            fontSize: "11px",
            fontWeight: 500,
            letterSpacing: "0.22em",
            textTransform: "uppercase",
            color: "var(--kaya-stone)",
            marginBottom: "20px"
          }}>
            Or get the newsletter
          </p>
          {done ? (
            <div className="journal-form__done">— Thank you. Welcome in.</div>
          ) : (
            <form className="journal-form" onSubmit={submit}>
              <div className="journal-form__row">
                <input
                  type="email"
                  placeholder="your email"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  aria-label="Email address"
                  required
                />
                <button type="submit">
                  Subscribe <ArrowRight />
                </button>
              </div>
              <span className="journal-form__note">Episodes, essays, and nothing more.</span>
            </form>
          )}
        </KayaReveal>
      </div>
    </section>
  );
};

// ---------- episode card ----------
const EpisodeCard = ({ episode, delay = 0 }) => (
  <KayaReveal
    as="a"
    className="episode-card"
    href={watchUrl(episode)}
    target="_blank"
    rel="noopener noreferrer"
    delay={delay}
  >
    <div className="episode-card__media">
      <img src={episode.thumbnail} alt="" loading="lazy" />
      <div className="episode-card__play">
        <PlayIcon size={14} />
      </div>
      <span className="episode-card__id">{episodeLabel(episode)}</span>
      <span className="episode-card__duration">{episode.duration}</span>
    </div>
    <div className="episode-card__body">
      <div className="episode-card__meta">
        <span>{formatDate(episode.publishDate)}</span>
        <span>{episode.location}</span>
      </div>
      <h3 className="episode-card__title">{episode.title}</h3>
      <p className="episode-card__excerpt">{episode.excerpt}</p>
    </div>
  </KayaReveal>
);

// ---------- main page ----------
const RefinedIndex = () => {
  const episodes = (window.REFINED_EPISODES || []).filter(e => e.status === "published");
  const [featured, ...rest] = episodes;
  const yt = window.KAYA_YOUTUBE || {};

  return (
    <div className="refined-page">
      <KayaNav active="refined" onNavigate={handleNavigate} />

      {/* Black band: title section + featured episode */}
      <div className="refined-band">

      {/* Header */}
      <header className="refined-page__header">
        <KayaReveal as="div" className="refined-page__kicker">
          <span className="eyebrow eyebrow--burgundy">— A Kaya Series</span>
          <h1 className="refined-page__title"><span className="hl">Refined.</span></h1>
        </KayaReveal>
        <KayaReveal as="div" className="refined-page__meta" delay={160}>
          <p className="refined-page__deck">
            A cinematic series on architecture, design, craftsmanship, and the
            human stories behind meaningful spaces. Each episode feels less like
            a home tour, more like a short documentary.
          </p>
          <div className="refined-page__badges">
            <span className="refined-badge">Architecture</span>
            <span className="refined-badge">Design</span>
            <span className="refined-badge">Craftsmanship</span>
            <span className="refined-badge">Documentary</span>
          </div>
          <a className="btn-quiet btn-quiet--ivory"
             href={yt.channelUrl || "https://youtube.com/@kaya"}
             target="_blank" rel="noopener">
            Watch on YouTube <ArrowExternal />
          </a>
        </KayaReveal>
      </header>

      {/* Featured episode */}
      {featured && (
        <section className="refined-featured">
          <KayaReveal as="div">
            <a className="refined-featured__link"
               href={watchUrl(featured)}
               target="_blank"
               rel="noopener noreferrer">
              <div className="refined-featured__media">
                <img src={featured.heroImage || featured.thumbnail} alt="" />
                <div className="refined-featured__overlay" />
                <div className="refined-play">
                  <PlayIcon size={22} />
                </div>
                <span className="refined-featured__episode-badge">
                  {episodeLabel(featured)} · {featured.duration}
                </span>
              </div>
              <div className="refined-featured__body">
                <div className="refined-featured__info">
                  <div className="refined-featured__label">
                    <span className="eyebrow eyebrow--rust">Latest episode</span>
                    <span>{formatDate(featured.publishDate)}</span>
                    <span>{featured.location}</span>
                  </div>
                  <h2 className="refined-featured__title">{featured.title}</h2>
                  <p className="refined-featured__description">{featured.description}</p>
                </div>
                <div className="refined-featured__cta">
                  <span className="btn-quiet btn-quiet--ivory">
                    Watch now <ArrowRight />
                  </span>
                </div>
              </div>
            </a>
          </KayaReveal>
        </section>
      )}

      </div>{/* /refined-band */}

      {/* Episode grid */}
      {rest.length > 0 && (
        <section className="refined-grid-section">
          <div className="refined-grid-header">
            <h2>All episodes — Season 01</h2>
            <span className="eyebrow">{rest.length} episodes</span>
          </div>
          <div className="refined-grid">
            {rest.map((ep, i) => (
              <EpisodeCard key={ep.id} episode={ep} delay={i * 80} />
            ))}
          </div>
        </section>
      )}

      <EpisodeCTA />
      <KayaFooter basePath="index.html" />
    </div>
  );
};

ReactDOM.createRoot(document.getElementById("root")).render(<RefinedIndex />);
