// ————————————————————————————————————————————————————————————————
// Long-form ThemeReport — magazine-style DD with cited evidence
// ————————————————————————————————————————————————————————————————

const { useState: RUS, useMemo: RUM, useRef: RUR, useEffect: RUE } = React;

// Source kind → small icon glyph
const SRC_KIND = {
  filing: { lbl: "FILING", color: "var(--accent)" },
  news: { lbl: "NEWS", color: "var(--accent-2)" },
  data: { lbl: "DATA", color: "var(--fg-2)" },
  policy: { lbl: "POLICY", color: "var(--warn)" },
};

function fmtDate(d) {
  return d || "";
}

// Build a stable, ordered list of source IDs cited within this report
function collectSources(themeId) {
  const theme = window.THEMES.find((t) => t.id === themeId);
  const ids = new Map(); // id -> ordinal
  let n = 1;
  if (!theme) return ids;
  for (const tk of theme.tickers) {
    const ev = window.stockEvidence(tk);
    if (!ev) continue;
    for (const e of ev.evidence || []) {
      for (const r of e.refs || []) {
        if (!ids.has(r)) ids.set(r, n++);
      }
    }
  }
  return ids;
}

// Inline citation pill — clicks to scroll-to-source list at bottom
function Cite({ refs, ord }) {
  if (!refs || !refs.length) return null;
  return (
    <span className="cite-pills">
      {refs.map((r) => {
        const o = ord.get(r);
        if (!o) return null;
        return (
          <a
            key={r}
            href={`#src-${r}`}
            className="cite-pill"
            title={window.source(r)?.title}
          >
            {o}
          </a>
        );
      })}
    </span>
  );
}

// Conviction tier badge
function ConvictionBadge({ tier }) {
  const map = {
    HIGH: { c: "var(--up)", t: "HIGH" },
    MEDIUM: { c: "var(--accent-2)", t: "MED" },
    LOW: { c: "var(--fg-2)", t: "LOW" },
  };
  const m = map[tier] || map.LOW;
  return (
    <span className="conv-badge" style={{ borderColor: m.c, color: m.c }}>
      {m.t} CONVICTION
    </span>
  );
}

// Portfolio overview table (top of report)
function PortfolioOverview({ themeId, lang, onJump }) {
  const theme = window.THEMES.find((t) => t.id === themeId);
  const report = window.themeReport(themeId);
  if (!theme || !report) return null;
  // Build ranked list from conviction buckets
  const ranked = [];
  for (const b of report.convictionBuckets || []) {
    for (const tk of b.tickers || []) ranked.push({ tk, tier: b.tier });
  }
  const totalWt = ranked.length || 1;
  return (
    <div className="rep-table-wrap">
      <table className="rep-table">
        <thead>
          <tr>
            <th className="t-right">#</th>
            <th className="t-left">{lang === "jp" ? "銘柄" : "Company"}</th>
            <th className="t-left">{lang === "jp" ? "分類" : "Tier"}</th>
            <th className="t-right">PE</th>
            <th className="t-right">PB</th>
            <th className="t-right">ROE</th>
            <th className="t-right">OpMar</th>
            <th className="t-right">{lang === "jp" ? "配当" : "Yield"}</th>
            <th className="t-right">{lang === "jp" ? "成長" : "Rev g"}</th>
          </tr>
        </thead>
        <tbody>
          {ranked.map((r, i) => {
            const s = window.STOCKS[r.tk] || {};
            const m = window.stockMeta(r.tk);
            return (
              <tr key={r.tk} onClick={() => onJump(r.tk)} className="rep-row">
                <td className="t-right rep-num">{i + 1}</td>
                <td className="t-left">
                  <a className="rep-link" href={`#stk-${r.tk}`}>
                    {r.tk.replace(".T", "")}
                  </a>
                  <span className="rep-name">
                    {lang === "jp" ? s.jp : s.name}
                  </span>
                </td>
                <td className="t-left">
                  <span className={"rep-tier tier-" + r.tier}>{r.tier}</span>
                </td>
                <td className="t-right rep-cell">
                  {m.pe > 0 ? m.pe.toFixed(1) : "N/M"}
                </td>
                <td className="t-right rep-cell">
                  {(
                    m.pb ||
                    (s.price && m.bvps
                      ? s.price / m.bvps
                      : Math.max(0.6, (m.roe || 10) / 12))
                  ).toFixed(2)}
                </td>
                <td className="t-right rep-cell">{m.roe?.toFixed(1)}%</td>
                <td className="t-right rep-cell">{m.opMargin?.toFixed(1)}%</td>
                <td className="t-right rep-cell">{m.divYield?.toFixed(2)}%</td>
                <td
                  className={
                    "t-right rep-cell " + (m.revGrowth >= 0 ? "up" : "down")
                  }
                >
                  {m.revGrowth >= 0 ? "+" : ""}
                  {m.revGrowth?.toFixed(1)}%
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}

// Conviction-bucket cards
function ConvictionPanel({ report, lang }) {
  return (
    <div className="rep-conv">
      {(report.convictionBuckets || []).map((b) => (
        <div key={b.tier} className={"rep-conv-c tier-" + b.tier}>
          <div className="rep-conv-h">
            <ConvictionBadge tier={b.tier} />
            <span className="rep-conv-n">
              {(b.tickers || []).length} {lang === "jp" ? "銘柄" : "stocks"}
            </span>
          </div>
          <div className="rep-conv-list">
            {(b.tickers || []).map((tk) => {
              const s = window.STOCKS[tk] || {};
              return (
                <a key={tk} href={`#stk-${tk}`} className="rep-conv-tk">
                  <span className="rep-conv-tkid">{tk.replace(".T", "")}</span>
                  <span className="rep-conv-tkn">
                    {lang === "jp" ? s.jp : s.name}
                  </span>
                </a>
              );
            })}
          </div>
          <div className="rep-conv-note">{b.note}</div>
        </div>
      ))}
    </div>
  );
}

// Per-stock deep-dive card with evidence + filings
function StockDeepDive({ tk, ord, lang, onOpenStock }) {
  const s = window.STOCKS[tk];
  if (!s) return null;
  const m = window.stockMeta(tk);
  const ev = window.stockEvidence(tk);
  const a = m.analyst || { buy: 0, hold: 0, sell: 0, target: 0 };
  const total = a.buy + a.hold + a.sell || 1;
  const upside = a.target && s.price ? (a.target / s.price - 1) * 100 : 0;
  return (
    <article id={`stk-${tk}`} className="rep-stk">
      <header className="rep-stk-h">
        <div className="rep-stk-h-l">
          <div className="rep-stk-tk">
            {tk.replace(".T", "")}
            <span className="rep-stk-tk-suf">.T</span>
          </div>
          <div>
            <h3 className="rep-stk-n">{lang === "jp" ? s.jp : s.name}</h3>
            <div className="rep-stk-pos">{m.positioning}</div>
          </div>
        </div>
        <div className="rep-stk-h-r">
          <div className="rep-stk-px">{window.fmtPrice(s.price)}</div>
          <div className={"rep-stk-chg " + (s.chg >= 0 ? "up" : "down")}>
            {window.fmtPct(s.chg)}
          </div>
          <button className="btn btn-sm" onClick={() => onOpenStock(tk)}>
            {lang === "jp" ? "詳細を開く" : "Open in workspace"} ↗
          </button>
        </div>
      </header>

      {/* Thesis paragraph with optional inline cites */}
      <section className="rep-stk-sec">
        <h4 className="rep-stk-sech">
          {lang === "jp" ? "投資論点" : "Thesis"}
        </h4>
        <p className="rep-stk-thesis">{m.thesis}</p>
      </section>

      {/* Evidence — numbered claims with citations */}
      {ev?.evidence?.length ? (
        <section className="rep-stk-sec">
          <h4 className="rep-stk-sech">
            {lang === "jp" ? "裏付け" : "Evidence"}
          </h4>
          <ol className="rep-evidence">
            {ev.evidence.map((e, i) => (
              <li key={i}>
                <span className="rep-evidence-c">{e.claim}</span>
                <Cite refs={e.refs} ord={ord} />
              </li>
            ))}
          </ol>
        </section>
      ) : null}

      {/* Financial snapshot strip */}
      <section className="rep-stk-sec">
        <div className="rep-fin-strip">
          <div>
            <span>PE</span>
            <b>{m.pe > 0 ? m.pe.toFixed(1) : "N/M"}</b>
          </div>
          <div>
            <span>PEG</span>
            <b>{m.peg?.toFixed(1) || "—"}</b>
          </div>
          <div>
            <span>ROE</span>
            <b>{m.roe?.toFixed(1)}%</b>
          </div>
          <div>
            <span>OP MARGIN</span>
            <b>{m.opMargin?.toFixed(1)}%</b>
          </div>
          <div>
            <span>REV g</span>
            <b className={m.revGrowth >= 0 ? "up" : "down"}>
              {m.revGrowth >= 0 ? "+" : ""}
              {m.revGrowth?.toFixed(1)}%
            </b>
          </div>
          <div>
            <span>DIV Y</span>
            <b>{m.divYield?.toFixed(2)}%</b>
          </div>
          <div>
            <span>MCAP</span>
            <b>¥{((s.mcap || 0) / 1000).toFixed(2)}T</b>
          </div>
        </div>
      </section>

      {/* Analyst consensus + target */}
      <section className="rep-stk-sec">
        <h4 className="rep-stk-sech">
          {lang === "jp" ? "アナリスト" : "Analyst consensus"}
        </h4>
        <div className="rep-analyst">
          <div className="rep-analyst-bar">
            <div
              style={{
                width: `${(a.buy / total) * 100}%`,
                background: "var(--up)",
              }}
              title={`Buy ${a.buy}`}
            />
            <div
              style={{
                width: `${(a.hold / total) * 100}%`,
                background: "var(--fg-2)",
              }}
              title={`Hold ${a.hold}`}
            />
            <div
              style={{
                width: `${(a.sell / total) * 100}%`,
                background: "var(--down)",
              }}
              title={`Sell ${a.sell}`}
            />
          </div>
          <div className="rep-analyst-nums">
            <span>
              <b className="up">{a.buy}</b> {lang === "jp" ? "買い" : "buy"}
            </span>
            <span>
              <b>{a.hold}</b> {lang === "jp" ? "中立" : "hold"}
            </span>
            <span>
              <b className="down">{a.sell}</b> {lang === "jp" ? "売り" : "sell"}
            </span>
            <span className="rep-tgt">
              {lang === "jp" ? "目標" : "target"}{" "}
              <b>{window.fmtPrice(a.target)}</b>
              <span className={upside >= 0 ? "up" : "down"}>
                {" "}
                ({upside >= 0 ? "+" : ""}
                {upside.toFixed(1)}%)
              </span>
            </span>
          </div>
        </div>
      </section>

      {/* Filings & references */}
      {ev?.filings?.length ? (
        <section className="rep-stk-sec">
          <h4 className="rep-stk-sech">
            {lang === "jp" ? "財務資料・参照" : "Filings & references"}
          </h4>
          <div className="rep-filings">
            {ev.filings.map((f, i) => (
              <a
                key={i}
                href={f.url}
                target="_blank"
                rel="noopener"
                className="rep-filing"
              >
                <span className="rep-filing-i">↗</span>
                <span className="rep-filing-l">{f.label}</span>
              </a>
            ))}
          </div>
        </section>
      ) : null}
    </article>
  );
}

// Errata table
function ErrataTable({ rows, lang }) {
  if (!rows || !rows.length)
    return (
      <div className="rep-errata-none">
        {lang === "jp" ? "訂正なし" : "No corrections logged."}
      </div>
    );
  return (
    <table className="rep-errata">
      <thead>
        <tr>
          <th>{lang === "jp" ? "銘柄" : "Ticker"}</th>
          <th>{lang === "jp" ? "指標" : "Metric"}</th>
          <th>{lang === "jp" ? "訂正前" : "Original"}</th>
          <th>{lang === "jp" ? "訂正後" : "Actual"}</th>
          <th>{lang === "jp" ? "出典" : "Source"}</th>
          <th>{lang === "jp" ? "影響" : "Impact"}</th>
        </tr>
      </thead>
      <tbody>
        {rows.map((r, i) => (
          <tr key={i}>
            <td className="rep-errata-tk">
              {(r.ticker || "").replace(".T", "")}
            </td>
            <td>{r.metric}</td>
            <td className="rep-errata-old">{r.original}</td>
            <td className="rep-errata-new">{r.actual}</td>
            <td className="rep-errata-src">{r.source}</td>
            <td>{r.impact}</td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}

// Numbered source bibliography
function SourceList({ ord, lang }) {
  const items = Array.from(ord.entries()).sort((a, b) => a[1] - b[1]);
  return (
    <ol className="rep-src-list">
      {items.map(([id, n]) => {
        const s = window.source(id);
        if (!s) return null;
        const k = SRC_KIND[s.kind] || SRC_KIND.data;
        return (
          <li key={id} id={`src-${id}`}>
            <span className="rep-src-num">[{n}]</span>
            <div className="rep-src-body">
              <div className="rep-src-meta">
                <span
                  className="rep-src-kind"
                  style={{ color: k.color, borderColor: k.color }}
                >
                  {k.lbl}
                </span>
                <span className="rep-src-pub">{s.publisher}</span>
                <span className="rep-src-date">· {fmtDate(s.date)}</span>
              </div>
              <div className="rep-src-title">
                <a href={s.url} target="_blank" rel="noopener">
                  {s.title} <span className="rep-src-arrow">↗</span>
                </a>
              </div>
            </div>
          </li>
        );
      })}
    </ol>
  );
}

// MAIN report view ---------------------------------------------------------
function ThemeReport({ themeId, lang, onBack, onOpenStock }) {
  const theme = window.THEMES.find((t) => t.id === themeId);
  const report = window.themeReport(themeId);
  const ord = RUM(() => collectSources(themeId), [themeId, window._reportsReady]);  // recompute when the deferred report blob lands
  const tocRef = RUR(null);
  if (!theme || !report)
    return (
      <div className="rep-empty">
        {lang === "jp"
          ? "このテーマの完全レポートはまだ作成されていません。"
          : "Full report not yet authored for this theme."}
        <button className="btn btn-sm" onClick={onBack}>
          ← {lang === "jp" ? "戻る" : "Back"}
        </button>
      </div>
    );

  // Aggregate stats
  const tickers = theme.tickers.filter((t) => window.STOCKS[t]);
  const stats = RUM(() => {
    const chgs = tickers.map((t) => window.STOCKS[t].chg);
    const avg = chgs.length ? chgs.reduce((a, b) => a + b, 0) / chgs.length : 0;
    const mcap = tickers.reduce((a, t) => a + (window.STOCKS[t].mcap || 0), 0);
    return { count: tickers.length, avg, mcap };
  }, [themeId]);

  // Linear progress on scroll
  const [progress, setProgress] = RUS(0);
  RUE(() => {
    const el = document.querySelector(".rep-scroll");
    if (!el) return;
    const onScroll = () => {
      const max = el.scrollHeight - el.clientHeight;
      setProgress(max > 0 ? el.scrollTop / max : 0);
    };
    el.addEventListener("scroll", onScroll);
    return () => el.removeEventListener("scroll", onScroll);
  }, [themeId]);

  const jump = (id) => {
    const el = document.getElementById(id);
    if (el) {
      const wrap = document.querySelector(".rep-scroll");
      const top =
        el.getBoundingClientRect().top -
        wrap.getBoundingClientRect().top +
        wrap.scrollTop -
        80;
      wrap.scrollTo({ top, behavior: "smooth" });
    }
  };

  return (
    <div className="rep-view" style={{ "--tc": theme.color }}>
      {/* Reading progress bar */}
      <div className="rep-progress">
        <div
          className="rep-progress-bar"
          style={{ width: `${progress * 100}%` }}
        />
      </div>

      {/* Top action bar */}
      <div className="rep-actions">
        <button className="rep-back" onClick={onBack}>
          <span>←</span>{" "}
          {lang === "jp" ? "テーマダッシュボードに戻る" : "Back to dashboard"}
        </button>
        <div className="rep-actions-r">
          <button
            className="btn btn-sm"
            onClick={async (e) => {
              const btn = e.currentTarget;
              const orig = btn.textContent;
              await window.copyReportToClipboard(themeId);
              btn.textContent = lang === "jp" ? "コピー済み ✓" : "Copied ✓";
              btn.classList.add("ok");
              setTimeout(() => {
                btn.textContent = orig;
                btn.classList.remove("ok");
              }, 1600);
            }}
          >
            {lang === "jp" ? "GPT用にコピー" : "Copy for GPT"}
          </button>
          <button className="btn btn-sm" onClick={() => window.print()}>
            {lang === "jp" ? "印刷" : "Print"}
          </button>
          <button
            className="btn btn-sm"
            onClick={() => window.downloadReportMd(themeId)}
          >
            {lang === "jp" ? ".md ダウンロード" : "Download .md"}
          </button>
        </div>
      </div>

      <div className="rep-scroll">
        <div className="rep-inner">
          {/* HERO / MASTHEAD */}
          <header className="rep-hero">
            <div className="rep-eyebrow">
              <span className="tc-dot" />
              {lang === "jp" ? "テーマレポート" : "Theme report"} ·{" "}
              {report.date}
            </div>
            <h1 className="rep-h1">{report.title}</h1>
            <div className="rep-sub">{report.subtitle}</div>
            <div className="rep-meta">
              <span>
                {stats.count} {lang === "jp" ? "銘柄" : "stocks"}
              </span>
              <span className="dot">·</span>
              <span>
                ¥{((stats.mcap || 0) / 1000).toFixed(1)}T{" "}
                {lang === "jp" ? "時価総額合計" : "aggregate mcap"}
              </span>
              <span className="dot">·</span>
              <span className={stats.avg >= 0 ? "up" : "down"}>
                {window.fmtPct(stats.avg)}{" "}
                {lang === "jp" ? "平均" : "avg today"}
              </span>
              <span className="dot">·</span>
              <span>
                {ord.size} {lang === "jp" ? "出典" : "sources cited"}
              </span>
            </div>
          </header>

          {/* REAL REPORTS — links to live site */}
          {report.reports && report.reports.length > 0 && (
            <section
              className="rep-real-reports"
              style={{
                padding: "20px 24px",
                background: "var(--bg-1)",
                borderRadius: 10,
                border: "1px solid var(--line)",
                marginBottom: 0,
              }}
            >
              <div
                style={{
                  fontSize: 13,
                  fontWeight: 600,
                  color: "var(--fg-1)",
                  marginBottom: 12,
                }}
              >
                {lang === "jp" ? "公開済みレポート" : "Published DD Reports"} (
                {report.reports.length})
              </div>
              <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                {report.reports.map((r) => (
                  <a
                    key={r.slug}
                    href={"?view=single-report&slug=" + r.slug}
                    style={{
                      display: "flex",
                      alignItems: "center",
                      gap: 12,
                      padding: "10px 14px",
                      background: "var(--bg-2)",
                      borderRadius: 8,
                      border: "1px solid var(--line)",
                      textDecoration: "none",
                      color: "var(--fg-0)",
                      fontSize: 13,
                      transition: "border-color 0.15s",
                    }}
                  >
                    <span
                      style={{
                        fontFamily: "var(--mono)",
                        color: "var(--fg-3)",
                        minWidth: 80,
                      }}
                    >
                      {r.date}
                    </span>
                    <span style={{ flex: 1, fontWeight: 500 }}>{r.title}</span>
                    <span style={{ color: "var(--accent)", fontSize: 12 }}>
                      ↗ Open on reports site
                    </span>
                  </a>
                ))}
              </div>
            </section>
          )}

          {/* TOC */}
          <nav className="rep-toc" ref={tocRef}>
            <div className="rep-toc-h">
              {lang === "jp" ? "目次" : "Contents"}
            </div>
            <ul>
              <li>
                <a onClick={() => jump("rep-summary")}>
                  1. {lang === "jp" ? "サマリー" : "Executive summary"}
                </a>
              </li>
              <li>
                <a onClick={() => jump("rep-overview")}>
                  2.{" "}
                  {lang === "jp" ? "ポートフォリオ概要" : "Portfolio overview"}
                </a>
              </li>
              <li>
                <a onClick={() => jump("rep-conviction")}>
                  3. {lang === "jp" ? "コンビクション" : "Conviction tiers"}
                </a>
              </li>
              <li>
                <a onClick={() => jump("rep-stocks")}>
                  4. {lang === "jp" ? "銘柄分析" : "Stock-by-stock"}
                </a>
                <ul>
                  {tickers.map((tk) => {
                    const s = window.STOCKS[tk] || {};
                    return (
                      <li key={tk}>
                        <a onClick={() => jump(`stk-${tk}`)}>
                          {tk.replace(".T", "")} ·{" "}
                          <span>{lang === "jp" ? s.jp : s.name}</span>
                        </a>
                      </li>
                    );
                  })}
                </ul>
              </li>
              <li>
                <a onClick={() => jump("rep-errata")}>
                  5. {lang === "jp" ? "訂正" : "Errata"}
                </a>
              </li>
              <li>
                <a onClick={() => jump("rep-method")}>
                  6. {lang === "jp" ? "手法" : "Methodology"}
                </a>
              </li>
              <li>
                <a onClick={() => jump("rep-sources")}>
                  7. {lang === "jp" ? "出典" : "Sources"}
                </a>
              </li>
            </ul>
          </nav>

          {/* SUMMARY */}
          <section id="rep-summary" className="rep-section">
            <h2 className="rep-h2">
              <span className="rep-h2-n">1</span>
              {lang === "jp" ? "サマリー" : "Executive summary"}
            </h2>
            <p className="rep-lede">{report.summary}</p>
            {report.errata?.length ? (
              <div className="rep-errata-banner">
                <strong>
                  {report.errata.length}{" "}
                  {lang === "jp" ? "件のデータ訂正" : "data corrections"}
                </strong>
                {lang === "jp"
                  ? "が検証中に確認されました。"
                  : " found during validation. "}
                <a onClick={() => jump("rep-errata")}>
                  {lang === "jp" ? "訂正一覧 ↓" : "See errata ↓"}
                </a>
              </div>
            ) : null}
          </section>

          {/* PORTFOLIO TABLE */}
          <section id="rep-overview" className="rep-section">
            <h2 className="rep-h2">
              <span className="rep-h2-n">2</span>
              {lang === "jp" ? "ポートフォリオ概要" : "Portfolio overview"}
            </h2>
            <PortfolioOverview
              themeId={themeId}
              lang={lang}
              onJump={(tk) => jump(`stk-${tk}`)}
            />
          </section>

          {/* CONVICTION */}
          <section id="rep-conviction" className="rep-section">
            <h2 className="rep-h2">
              <span className="rep-h2-n">3</span>
              {lang === "jp" ? "コンビクション分布" : "Conviction tiers"}
            </h2>
            <ConvictionPanel report={report} lang={lang} />
          </section>

          {/* STOCK DEEP-DIVES */}
          <section id="rep-stocks" className="rep-section">
            <h2 className="rep-h2">
              <span className="rep-h2-n">4</span>
              {lang === "jp" ? "銘柄別分析" : "Stock-by-stock analysis"}
            </h2>
            <div className="rep-stk-list">
              {tickers.map((tk) => (
                <StockDeepDive
                  key={tk}
                  tk={tk}
                  ord={ord}
                  lang={lang}
                  onOpenStock={onOpenStock}
                />
              ))}
            </div>
          </section>

          {/* ERRATA */}
          <section id="rep-errata" className="rep-section">
            <h2 className="rep-h2">
              <span className="rep-h2-n">5</span>
              {lang === "jp" ? "データ訂正" : "Data corrections (errata)"}
            </h2>
            <ErrataTable rows={report.errata} lang={lang} />
          </section>

          {/* METHOD */}
          <section id="rep-method" className="rep-section">
            <h2 className="rep-h2">
              <span className="rep-h2-n">6</span>
              {lang === "jp" ? "手法" : "Methodology"}
            </h2>
            <p className="rep-method-body">{report.methodology}</p>
            <div className="rep-disclaimer">
              {lang === "jp"
                ? "AI支援の調査資料。投資助言ではありません。投資判断は自己責任で行ってください。"
                : "AI-assisted research, not investment advice. Conduct your own due diligence before making any investment decision."}
            </div>
          </section>

          {/* SOURCES */}
          <section id="rep-sources" className="rep-section rep-section-last">
            <h2 className="rep-h2">
              <span className="rep-h2-n">7</span>
              {lang === "jp" ? "出典 / 参照" : "Sources & references"}
            </h2>
            <SourceList ord={ord} lang={lang} />
          </section>

          {/* REVISION HISTORY (only if a topic dossier exists for this theme) */}
          {(() => {
            const RevHist = window.RevisionHistory;
            const topic = (window.TOPICS || []).find((t) => t.theme === themeId);
            return RevHist && topic ? (
              <section id="rep-revisions" className="rep-section">
                <RevHist topic={topic} />
              </section>
            ) : null;
          })()}

          <footer className="rep-foot">
            Kairos·JP Research · {report.date} · {ord.size}{" "}
            {lang === "jp" ? "出典" : "sources cited"}
          </footer>
        </div>
      </div>
    </div>
  );
}

window.ThemeReport = ThemeReport;
