// The Diplomatic Diary — full media-website subpage
const { useState: useStateD, useMemo: useMemoD } = React;

function DiaryMasthead({ ins, topic, setTopic }) {
  return (
    <React.Fragment>
      <header className="diary-masthead">
        <div className="container">
          <div className="left">
            <a href="../" className="ulink meta" style={{ paddingBottom: 2 }}>← WIDA</a>
          </div>
          <div>
            <div className="meta" style={{ display: "flex", justifyContent: "center", alignItems: "center", gap: 10, marginBottom: 12 }}>
              <span className="live-dot" /> {ins.issue}
            </div>
            <h1 className="diary-logo">The Diplomatic <span className="ampersand">·</span> Diary</h1>
            <div className="diary-dateline">
              <span>VOL. I</span><span className="sep">·</span>
              <span>NO. 1</span><span className="sep">·</span>
              <span>2025–26</span><span className="sep">·</span>
              <span>WASHINGTON, DC</span>
            </div>
          </div>
          <div className="right">
            <a href="#newsletter" className="ulink meta" style={{ paddingBottom: 2 }}>Subscribe →</a>
          </div>
        </div>
      </header>
      <nav className="diary-nav" aria-label="Diary topics">
        {ins.topics.map((t) => (
          <button key={t} aria-pressed={topic === t} onClick={() => setTopic(t)}>{t}</button>
        ))}
      </nav>
    </React.Fragment>
  );
}

function DiaryLead({ featured }) {
  return (
    <section className="diary-lead">
      <div className="container">
        <div className="grid">
          <div className="img" role="img" aria-label={featured.title} style={{ backgroundImage: `url("${featured.img}")` }} />
          <div>
            <div className="meta" style={{ display: "flex", gap: 14, marginBottom: 24 }}>
              <span style={{ color: "var(--bordeaux)" }}>{featured.kicker || "Lead essay"}</span>
              <span>·</span>
              <span>{featured.topic}</span>
            </div>
            <h1>{featured.title}</h1>
            <p className="excerpt">{featured.excerpt}</p>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", gap: 16, paddingTop: 24, borderTop: "1px solid var(--rule)" }}>
              <div>
                <div style={{ fontFamily: "var(--serif)", fontSize: 16, color: "var(--ink)" }}>{featured.author}</div>
                <div className="meta">{featured.role || "Career Diplomat"} · {featured.date} · {featured.readtime}</div>
              </div>
              <a href={featured.slug ? `#article/${featured.slug}` : "#article"} className="btn btn-ghost">
                Read essay <span className="arrow">→</span>
              </a>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function EditorColumn({ column, articles }) {
  const top = articles.slice(0, 5);
  return (
    <aside>
      <div className="editor-note">
        <div className="meta" style={{ marginBottom: 14, color: "var(--bordeaux)" }}>{column.label}</div>
        <h4>"{column.title}"</h4>
        <p>{column.lede}</p>
        <div className="byline">— {column.author}</div>
      </div>
      <div className="most-read">
        <h5>Most read this issue</h5>
        <ol>
          {top.map((a, i) => (
            <li key={i}>
              <div>
                <a href={a.slug ? `#article/${a.slug}` : "#article"}>{a.title}</a>
                <span className="topic">{a.topic} · {a.date}</span>
              </div>
            </li>
          ))}
        </ol>
      </div>
    </aside>
  );
}

function DiaryLatest({ articles, topicFilter }) {
  const filtered = useMemoD(() => {
    if (!topicFilter || topicFilter === "All") return articles;
    return articles.filter((a) => a.topic === topicFilter);
  }, [articles, topicFilter]);

  const heading = topicFilter && topicFilter !== "All"
    ? `Essays under ${topicFilter.toLowerCase()}`
    : "Latest essays";

  return (
    <section className="topic-section">
      <div className="container">
        <div className="topic-header">
          <span className="topic-label">{topicFilter && topicFilter !== "All" ? topicFilter : "Reading list"}</span>
          <h2>{filtered.length ? heading : "Nothing under this topic yet."}</h2>
          <span className="count">{filtered.length.toString().padStart(2, "0")}</span>
        </div>
        {filtered.length > 0 ? (
          <div className="topic-grid">
            {filtered.map((a, i) => (
              <ArticleCard key={a.slug || i} s={a} index={i} totalCols={3} />
            ))}
          </div>
        ) : (
          <p className="meta" style={{ padding: "32px 0 8px" }}>
            Try another topic — or read the full archive below.
          </p>
        )}
      </div>
    </section>
  );
}

function DiaryArchive({ articles }) {
  if (!articles.length) return null;
  return (
    <section className="diary-archive">
      <div className="container">
        <div className="topic-header" style={{ borderBottom: "1px solid var(--ink)", paddingBottom: 18, marginBottom: 32 }}>
          <span className="topic-label">Archive</span>
          <h2>Every essay, by date.</h2>
          <span className="count">{articles.length.toString().padStart(3, "0")}</span>
        </div>
        <ul className="archive-list">
          {articles.map((a, i) => (
            <li key={i}>
              <span className="a-date">{a.date}</span>
              <span className="a-topic">{a.topic}</span>
              <a className="a-title" href={a.slug ? `#article/${a.slug}` : "#article"}>{a.title}</a>
              <span className="a-author">{a.author}</span>
            </li>
          ))}
        </ul>
      </div>
    </section>
  );
}

function DiaryNewsletter() {
  return (
    <section id="newsletter" className="diary-newsletter">
      <div className="container">
        <div className="meta" style={{ color: "rgba(245,241,234,0.65)", marginBottom: 18 }}>SUBSCRIBE · BY POST OR INBOX</div>
        <h3>Sent from Washington — when there is something to say.</h3>
        <p>The Diary lands in your inbox when an ambassador finishes a piece worth reading. No cadence calendar. No filler. Unsubscribe in one click.</p>
        <form onSubmit={(e) => { e.preventDefault(); alert("Subscribe form is illustrative — wire to your provider."); }}>
          <input type="email" placeholder="your@diplomaticpost.com" aria-label="Email" required />
          <button type="submit">Subscribe</button>
        </form>
      </div>
    </section>
  );
}

function DiaryArticleView({ article, onBack, ins }) {
  return (
    <section style={{ padding: "80px 0 120px" }}>
      <div className="container">
        <button onClick={onBack} className="meta" style={{ marginBottom: 40, background: "none", border: 0, cursor: "pointer", padding: 0, borderBottom: "1px solid var(--ink)", color: "var(--ink)" }}>
          ← Back to The Diplomatic Diary
        </button>
        <div style={{ maxWidth: 760, margin: "0 auto", textAlign: "center", marginBottom: 56 }}>
          <div className="meta" style={{ color: "var(--bordeaux)", marginBottom: 18 }}>{article.topic} · {ins.issue}</div>
          <h1 className="display" style={{ fontSize: "clamp(40px, 5.5vw, 64px)", margin: "0 0 24px", letterSpacing: "-0.022em", lineHeight: 1.02, textWrap: "balance" }}>
            {article.title}
          </h1>
          <div className="meta">
            {article.author} · {article.dateLabel || article.date} · {article.readtime}
          </div>
        </div>
        {article.img && (
          <div role="img" aria-label={article.title} style={{ maxWidth: 1080, margin: "0 auto 56px", aspectRatio: "16 / 9", borderRadius: 2, backgroundImage: `url("${article.img}")`, backgroundSize: "cover", backgroundPosition: "center", backgroundColor: "var(--paper-deep)" }} />
        )}
        <div className="article-prose" dangerouslySetInnerHTML={{ __html: article.body }} />
      </div>
    </section>
  );
}

function DiaryPage({ data, articleSlug, onBack }) {
  const ins = data.insights;
  const [topic, setTopic] = useStateD("All");

  const cms = Array.isArray(window.WDA_CONTENT) ? window.WDA_CONTENT : [];
  const cmsCards = cms.map((a) => ({
    topic: a.topic, title: a.title, excerpt: a.excerpt,
    author: a.author, readtime: a.readtime, role: a.role || "Career Diplomat",
    date: a.dateLabel || a.date, dateLabel: a.dateLabel,
    slug: a.slug, body: a.body, img: a.img,
  }));

  // When real CMS articles exist, use the newest as the lead and the rest
  // (plus optional static demos) as secondary. With no CMS content, fall
  // back to the static featured + secondary so the page is never empty.
  const hasCms = cmsCards.length > 0;
  const featured = hasCms
    ? { kicker: "Lead essay", role: cmsCards[0].role, ...cmsCards[0] }
    : ins.featured;
  const allArticles = useMemoD(
    () => (hasCms ? cmsCards.slice(1) : ins.secondary),
    [cms.length]
  );

  if (articleSlug) {
    const article = cms.find((a) => a.slug === articleSlug);
    if (article) return <DiaryArticleView article={article} ins={ins} onBack={onBack} />;
  }

  return (
    <React.Fragment>
      <DiaryMasthead ins={ins} topic={topic} setTopic={setTopic} />
      <DiaryLead featured={featured} />
      <div className="container">
        <div className="diary-twocol">
          <div>
            <div className="meta" style={{ marginBottom: 16 }}>FRAMING · 2025–26</div>
            <h2 style={{ fontFamily: "var(--serif)", fontSize: "clamp(28px, 3.6vw, 44px)", fontWeight: 400, fontStyle: "italic", margin: "0 0 24px", color: "var(--ink)", letterSpacing: "-0.018em", lineHeight: 1.05, textWrap: "balance" }}>
              {ins.title}
            </h2>
            <p className="lede" style={{ margin: 0, maxWidth: "60ch" }}>{ins.framing}</p>
          </div>
          <EditorColumn column={ins.column} articles={[featured, ...allArticles]} />
        </div>
      </div>
      <DiaryLatest articles={[featured, ...allArticles]} topicFilter={topic} />
      <DiaryNewsletter />
      <DiaryArchive articles={[featured, ...allArticles]} />
    </React.Fragment>
  );
}

Object.assign(window, { DiaryPage, DiaryMasthead, DiaryLead, EditorColumn, DiaryLatest, DiaryArchive, DiaryNewsletter, DiaryArticleView });
