// journal-index.jsx — Kaya Journal index page

// ---------- shared 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>
);

// 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(" ", ", ");
};

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

// ---------- newsletter form ----------
const NewsletterForm = () => {
  const [email, setEmail] = React.useState("");
  const [done, setDone] = React.useState(false);

  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="p" className="journal-newsletter-section__lede">
          New essays arrive <em>weekly</em>, on a Wednesday,<br />somewhere in the morning.
        </KayaReveal>
        <KayaReveal as="div" delay={160}>
          {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">No noise. One letter, once a week.</span>
            </form>
          )}
        </KayaReveal>
      </div>
    </section>
  );
};

// ---------- article card ----------
const ArticleCard = ({ article, delay = 0 }) => (
  <KayaReveal as="a"
    className="article-card"
    href={`/journal/${article.slug}`}
    delay={delay}
    style={{ textDecoration: "none", color: "inherit" }}
  >
    <div className="article-card__media">
      <img src={article.featuredImage} alt="" loading="lazy" />
    </div>
    <div className="article-card__body">
      <div className="article-card__meta">
        <span>{article.category}</span>
        <span>{formatDate(article.publishDate)}</span>
        <span>{article.readTime}</span>
      </div>
      <h3 className="article-card__title">{article.title}</h3>
      <p className="article-card__excerpt">{article.excerpt}</p>
    </div>
  </KayaReveal>
);

// ---------- main journal index ----------
const JournalIndex = () => {
  const articles = (window.JOURNAL_ARTICLES || []).filter(a => a.status === "published");
  const [featured, ...rest] = articles;

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

      {/* Editorial header */}
      <header className="journal-page__header">
        <KayaReveal as="div" className="journal-page__kicker">
          <span className="eyebrow eyebrow--rust">— The Kaya Journal</span>
          <h1 className="journal-page__title">
            Design,<br /><em>slowly read.</em>
          </h1>
        </KayaReveal>
        <KayaReveal as="div" className="journal-page__meta" delay={160}>
          <p className="journal-page__deck">
            An editorial dispatch on interiors, material, light, and the architecture
            of feeling. One essay, once a week, on a Wednesday morning.
          </p>
          <button
            className="btn-quiet btn-quiet--burgundy"
            onClick={() => handleNavigate("journal")}
            style={{ cursor: "pointer", background: "none", font: "inherit" }}
          >
            Subscribe <ArrowRight />
          </button>
        </KayaReveal>
      </header>

      {/* Featured article */}
      {featured && (
        <section className="journal-featured">
          <KayaReveal as="a"
            className="journal-featured__inner"
            href={`/journal/${featured.slug}`}
            style={{ textDecoration: "none", color: "inherit" }}
          >
            <div className="journal-featured__media">
              <img src={featured.featuredImage} alt="" />
            </div>
            <div className="journal-featured__body">
              <div className="journal-featured__label">
                <span className="eyebrow eyebrow--rust">Featured</span>
                <span>{featured.category}</span>
                <span>{formatDate(featured.publishDate)}</span>
                <span>{featured.readTime}</span>
              </div>
              <h2 className="journal-featured__title">{featured.title}</h2>
              <p className="journal-featured__excerpt">{featured.excerpt}</p>
              <div className="journal-featured__cta">
                <span className="btn-quiet btn-quiet--burgundy">
                  Read the essay <ArrowRight />
                </span>
              </div>
            </div>
          </KayaReveal>
        </section>
      )}

      {/* Article grid */}
      {rest.length > 0 && (
        <section className="journal-grid-section">
          <div className="journal-grid-header">
            <h2>All essays</h2>
            <span className="eyebrow">{rest.length} dispatches</span>
          </div>
          <div className="journal-grid">
            {rest.map((article, i) => (
              <ArticleCard key={article.id} article={article} delay={i * 80} />
            ))}
          </div>
        </section>
      )}

      <NewsletterForm />
      <KayaFooter basePath="/" />
    </div>
  );
};

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