// Essay reader — margin-led, generous whitespace, reading progress bar, sign-off, end-CTA.
const { useState: useStateEssay, useEffect: useEffectEssay, useRef: useRefEssay } = React;

// Auto-disclosure — renders at the foot of EVERY essay. Adapted from the
// Sheppard Mullin compliance language in the Alpha Loop deck. The long/short
// position clause is generated from the essay's own ticker list, so any piece
// that names securities automatically carries the holdings disclosure.
function ArticleDisclosure({ essay, navigate }) {
  const tickers = (essay.tickers || []).filter(Boolean);
  const hasTickers = tickers.length > 0;
  const tickerStr =
    tickers.length === 1
      ? tickers[0]
      : tickers.length === 2
      ? `${tickers[0]} and ${tickers[1]}`
      : tickers.slice(0, -1).join(", ") + ", and " + tickers[tickers.length - 1];

  return (
    <section className="th-disclosure" aria-label="Disclosures">
      <div className="th-disclosure-inner">
        <span className="th-disclosure-label">Disclosures</span>
        <div className="th-disclosure-body">
          <p>
            This essay is published by Tom Hogan for informational and educational
            purposes only. It is not investment, legal, tax, or accounting advice, is
            not a research report, and does not constitute an offer to sell or a
            solicitation of an offer to buy any security or interest in any fund. It is
            not an advertisement as defined under Rule 206(4)-1 of the Investment
            Advisers Act of 1940, as amended.
          </p>
          {hasTickers ? (
            <p className="th-disclosure-positions">
              <strong>Position disclosure.</strong> As of the date of publication, Tom
              Hogan and/or Alpha Loop Capital, LLC may hold <em>long or short</em>{" "}
              positions in {tickerStr}. Such positions may be increased, decreased, or
              closed at any time without notice, and may be inconsistent with the views
              expressed here.
            </p>
          ) : (
            <p className="th-disclosure-positions">
              <strong>Position disclosure.</strong> Tom Hogan and/or Alpha Loop Capital,
              LLC may hold <em>long or short</em> positions in securities, sectors, or
              instruments referenced in this essay. Such positions may change at any time
              without notice.
            </p>
          )}
          <p>
            Tom Hogan is the Founder and Chief Investment Officer of Alpha Loop Capital,
            LLC. Views expressed are his own and do not represent Alpha Loop Capital, LLC
            or any affiliated entity. Past performance, whether actual or indicated by
            model results, is not indicative of future results. Do your own research and
            consult a licensed professional before making any financial decision. Read the
            full <a href="#" onClick={(e) => {e.preventDefault();navigate("disclosure");}}>disclosures</a>.
          </p>
        </div>
      </div>
    </section>);

}

function EssayReader({ id, navigate }) {
  const { ESSAYS } = window.HOAGS_DATA;
  const essay = ESSAYS.find((e) => e.id === id) || ESSAYS[0];
  const [progress, setProgress] = useStateEssay(0);
  const articleRef = useRefEssay(null);

  useEffectEssay(() => {
    function onScroll() {
      const el = articleRef.current;
      if (!el) return;
      const rect = el.getBoundingClientRect();
      const h = el.offsetHeight - window.innerHeight;
      const scrolled = Math.max(0, -rect.top);
      const p = Math.min(1, Math.max(0, scrolled / Math.max(1, h)));
      setProgress(p);
    }
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, [id]);

  const body = essay.body || [{ kind: "p", t: essay.dek }];

  const related = ESSAYS.filter((e) => e.id !== essay.id && e.tag === essay.tag).slice(0, 3);

  return (
    <div className="th-reader">
      <div className="th-progressbar" style={{ transform: `scaleX(${progress})` }} />

      <div className="th-reader-back">
        <a
          href="#"
          onClick={(e) => {e.preventDefault();navigate("home");}}
          className="th-back-link" style={{ fontSize: "16px" }}>
          
          ← Back to writing
        </a>
      </div>

      <article ref={articleRef} className="th-article">
        <header className="th-article-head">
          <div
            className="th-article-rail"
            style={{
              display: "grid",
              gridTemplateColumns: "auto 1fr auto",
              alignItems: "center",
              gap: "20px",
              textAlign: "left"
            }}>
            <span
              className={"th-tier-pill th-tier-" + essay.tier}
              style={{ fontSize: "12px", color: "rgb(66, 9, 9)", justifySelf: "start" }}>
              {essay.tier === "free" ? "Public" : essay.tier === "loop" ? "The Loop" : "Inner Loop"}
            </span>
            <span
              className="th-eyebrow"
              style={{ fontSize: "12px", justifySelf: "start", paddingLeft: "8px" }}>
              {essay.tag}
            </span>
            <span
              className="th-eyebrow"
              style={{ fontSize: "12px", color: "rgb(66, 9, 9)", fontFamily: "Inter", justifySelf: "end" }}>
              {essay.date}
            </span>
          </div>
          <h1 className="th-article-title">{essay.title}</h1>
          <p className="th-article-dek">{essay.dek}</p>
          <div
            className="th-article-meta"
            style={{
              display: "flex",
              justifyContent: "space-between",
              alignItems: "center",
              fontSize: "12.5px",
              gap: "16px",
              width: "100%"
            }}>
            <span>{essay.minutes} min read</span>
            <span>{essay.words.toLocaleString()} words</span>
            <span>By Tom Hogan</span>
          </div>
        </header>

        <div className="th-article-body th-prose">
          {body.map((b, i) => {
            if (b.kind === "h2") return <h2 key={i} className="th-h2">{b.t}</h2>;
            if (b.kind === "quote") return (
              <blockquote key={i} className="th-pullquote">
                <span className="th-pullquote-mark">"</span>
                {b.t}
              </blockquote>);

            return <p key={i}>{b.t}</p>;
          })}

          <p className="th-signoff">— Hoags</p>
          {essay.source && (
            <p className="th-microcopy" style={{ marginTop: "18px" }}>
              {essay.excerpt ? "Opening excerpt. The full piece, with its charts and tables, is on Substack. " : "Originally published on Substack. "}
              <a href={essay.source} target="_blank" rel="noopener">Read the original →</a>
            </p>
          )}
        </div>

        <ArticleDisclosure essay={essay} navigate={navigate} />
      </article>

      {/* End-of-post CTA */}
      <section className="th-eop">
        <div className="th-eop-card">
          <span className="th-eyebrow">If this hit</span>
          <h3>Get the next essay in your inbox.</h3>
          <p>The Feed is free. One careful piece most weeks. No tracking, no noise.</p>
          <div className="th-eop-form">
            <a className="th-tier-cta" style={{ display: "inline-block", textDecoration: "none", padding: "12px 22px" }} href={window.HOAGS_DATA.SUBSTACK_SUBSCRIBE} target="_blank" rel="noopener">Subscribe on Substack →</a>
          </div>
          <p className="th-microcopy">
            Or <a href={window.HOAGS_DATA.SUBSTACK_SUBSCRIBE} target="_blank" rel="noopener">upgrade to The Loop</a> — working notes for operators & investors.
          </p>
        </div>
      </section>

      {/* Related */}
      {related.length > 0 &&
      <section className="th-related">
          <div className="th-section-head">
            <span className="th-eyebrow">More in {essay.tag}</span>
          </div>
          {related.map((e) =>
        <a
          key={e.id}
          href="#"
          className="th-list-row"
          onClick={(ev) => {ev.preventDefault();navigate("essay", { id: e.id });window.scrollTo(0, 0);}}>
          
              <span className="th-list-date">{e.date}</span>
              <span className="th-list-body">
                <span className="th-list-title">{e.title}</span>
                <span className="th-list-dek">{e.dek}</span>
              </span>
              <span className="th-list-meta">
                <span className="th-list-min">{e.minutes} min</span>
              </span>
            </a>
        )}
        </section>
      }
    </div>);

}

window.EssayReader = EssayReader;
