// Homepage — type-driven, editorial, no thumbnails on index.
const { useState: useStateHome, useEffect: useEffectHome } = React;

// Reading time = words / 250 wpm, rounded.
function readMin(e) {return Math.max(1, Math.round((e.words || 0) / 250));}

// Lightweight click-traffic capture for the homepage essay feature.
// Records per-essay click counts in localStorage and mirrors each event into
// a dataLayer-style queue so a real analytics tag (GA4, Segment, etc.) can
// pick it up later without touching this code.
function trackEssayClick(essay, source) {
  try {
    const key = "hoags:traffic";
    const store = JSON.parse(localStorage.getItem(key) || "{}");
    const rec = store[essay.id] || { clicks: 0 };
    rec.clicks += 1;
    rec.last = new Date().toISOString();
    rec.title = essay.title;
    store[essay.id] = rec;
    localStorage.setItem(key, JSON.stringify(store));
  } catch (err) {/* storage may be unavailable; tracking is best-effort */}
  (window.dataLayer = window.dataLayer || []).push({
    event: "essay_click",
    essay_id: essay.id,
    essay_title: essay.title,
    source: source || "home_hero",
    ts: Date.now(),
  });
}

// Auto-format an essay date from its canonical ISO field — never hand-typed,
// so the displayed date always tracks the record. Falls back to e.date.
function essayDate(e) {
  if (!e) return "";
  if (e.iso) {
    const d = new Date(e.iso + "T12:00:00");
    if (!isNaN(d)) return d.toLocaleDateString("en-US", { month: "short", day: "2-digit", year: "numeric" });
  }
  return e.date || "";
}

// Hero centerpiece — auto-synced cycler across the three most recent essays.
// Crossfades on a timer (pauses on hover/focus), each card carries a fillable
// featured image, and every open is logged to the traffic tracker so we can
// see which headline pulls.
function LatestCycler({ essays, navigate }) {
  const items = essays.slice(0, 3);
  const [idx, setIdx] = useStateHome(0);
  const [paused, setPaused] = useStateHome(false);

  useEffectHome(() => {
    if (paused || items.length < 2) return undefined;
    const t = setInterval(() => setIdx((i) => (i + 1) % items.length), 5200);
    return () => clearInterval(t);
  }, [paused, items.length]);

  function open(e, essay) {
    e.preventDefault();
    trackEssayClick(essay, "home_latest_cycler");
    navigate("essay", { id: essay.id });
  }

  return (
    <div
      className="th-latest-cycler"
      onMouseEnter={() => setPaused(true)}
      onMouseLeave={() => setPaused(false)}
      onFocusCapture={() => setPaused(true)}
      onBlurCapture={() => setPaused(false)}>
      <div className="th-latest-head">
        <span className="th-eyebrow">Latest</span>
        <span className="th-latest-count">{String(idx + 1).padStart(2, "0")} / {String(items.length).padStart(2, "0")}</span>
      </div>
      <div className="th-latest-stack">
        {items.map((essay, i) =>
        <div
          key={essay.id}
          className={"th-latest-card" + (i === idx ? " is-active" : "")}
          aria-hidden={i !== idx}>
            <span className="th-latest-img">
              <image-slot
              id={"latest-img-" + essay.id}
              shape="rect"
              fit="cover"
              placeholder={"Featured image · " + essay.tag}
              style={{ display: "block", width: "100%", height: "100%" }}></image-slot>
            </span>
            <div className="th-latest-body">
              <div className="th-latest-meta">
                <span className={"th-tier-pill th-tier-" + essay.tier}>{essay.tag}</span>
                <span className="th-latest-date">{essayDate(essay)}</span>
              </div>
              <a
              href="#"
              className="th-latest-link"
              tabIndex={i === idx ? 0 : -1}
              onClick={(e) => open(e, essay)}>
                <span className="th-latest-title">{essay.title}</span>
                <span className="th-latest-read">Read the essay →</span>
              </a>
            </div>
          </div>
        )}
      </div>
      <div className="th-latest-dots" role="tablist" aria-label="Latest essays">
        {items.map((essay, i) =>
        <button
          key={essay.id}
          className={"th-latest-dot" + (i === idx ? " is-on" : "")}
          role="tab"
          aria-selected={i === idx}
          aria-label={"Show: " + essay.title}
          onClick={() => setIdx(i)}></button>
        )}
      </div>
    </div>);

}

function HomePage({ navigate }) {
  const { ESSAYS, TIERS, PRINCIPLES } = window.HOAGS_DATA;
  const featured = ESSAYS.find((e) => e.featured);
  const recent = ESSAYS.filter((e) => !e.featured).slice(0, 6);
  const latest = ESSAYS[0];
  const principle = PRINCIPLES[0];
  const totalVols = ESSAYS.length;
  const [email, setEmail] = useStateHome("");
  const [done, setDone] = useStateHome(false);
  const [bannerEmail, setBannerEmail] = useStateHome("");
  const [bannerDone, setBannerDone] = useStateHome(false);

  return (
    <div className="th-home">
      {/* TRADER'S PRINCIPLE — the rotating line that hangs at the top */}
      <div className="th-principle-bar">
        <span className="th-principle-no">{principle.n}</span>
        <p className="th-principle-line">{principle.t}</p>
      </div>

      {/* HERO */}
      <section className="th-hero">
        <h1 className="th-hero-title">
          The unfiltered loop between <span className="th-hero-italic">knowing and doing.</span>
        </h1>
        <div className="th-hero-foot">
          <div>
            <div className="th-hero-meta">
              <div>
                <span className="th-eyebrow">Byline</span>
                <a href="#" className="th-hero-meta-link" onClick={(e) => {e.preventDefault();navigate("about");}}>Tom Hogan</a>
              </div>
              <div>
                <span className="th-eyebrow">Beat</span>
                <span className="th-hero-meta-val">Markets, AI &amp; building</span>
              </div>
              <div>
                <span className="th-eyebrow">Cadence</span>
                <span className="th-hero-meta-val">One essay per week</span>
              </div>
            </div>
          </div>

          <LatestCycler essays={ESSAYS} navigate={navigate} />

          <aside className="th-hero-desk">
            <span className="th-eyebrow th-hero-desk-title" style={{ textAlign: "center" }}>Currently on my desk</span>
            <div className="th-hero-desk-list">

              <div className="th-hero-desk-item">
                <span className="th-hero-desk-key">Reading</span>
                <ol className="th-hero-desk-stack">
                  <li>
                    <a href="https://www.goodreads.com/book/show/662.Atlas_Shrugged" target="_blank" rel="noopener noreferrer">Atlas Shrugged — Ayn Rand</a>
                    <span className="th-hero-desk-meta">re-read</span>
                  </li>
                </ol>
              </div>

              <div className="th-hero-desk-item">
                <span className="th-hero-desk-key">Watching</span>
                <ol className="th-hero-desk-stack">
                  <li>
                    <a href="https://youtu.be/kwSVtQ7dziU" target="_blank" rel="noopener noreferrer">Andrej Karpathy on the Loopy Era of AI</a>
                    <span className="th-hero-desk-meta">No Priors</span>
                  </li>
                </ol>
              </div>

              <div className="th-hero-desk-item">
                <span className="th-hero-desk-key">Listening</span>
                <ol className="th-hero-desk-stack">
                  <li>
                    <a href="https://www.joincolossus.com/episodes/" target="_blank" rel="noopener noreferrer">Dan Loeb — Lessons From 30 Years of Investing</a>
                    <span className="th-hero-desk-meta">Invest Like the Best</span>
                  </li>
                </ol>
              </div>

            </div>
          </aside>
        </div>
      </section>

      {/* COMING SOON — paired offering: Loop (left) + Round Table (right) */}
      <section className="th-coming-soon">
        <div className="th-coming-soon-grid">
          <div className="th-coming-soon-card th-coming-soon-card--loop" style={{ backgroundColor: "rgb(32, 53, 79)" }}>
            <span className="th-eyebrow th-coming-soon-tag" style={{ fontSize: "12px" }}>The Loop · Membership</span>
            <h3 className="th-coming-soon-title">
              <span className="th-h-italic" style={{ color: "rgb(110, 176, 226)" }}>For people</span> who want to grind.
            </h3>
            <p className="th-coming-soon-dek">
              The Loop is for highly successful young operators, builders, and
              allocators — readers who want the working notes, the
              post-mortems, real networking with peers who actually ship,
              and a seat at the Round Table when it convenes. Loop members get
              <em> first access to LoopSeek AI</em> features as they ship.
            </p>
            <div className="th-coming-soon-actions">
              <a href="#" className="th-link-arrow" onClick={(e) => {e.preventDefault();navigate("subscribe");}}>
                Join the Loop →
              </a>
              <span className="th-coming-soon-meta">Networking · LoopSeek AI · Early access</span>
            </div>
          </div>

          <div className="th-coming-soon-card th-coming-soon-card--rt" style={{ backgroundColor: "rgb(107, 34, 48)" }}>
            <span className="th-eyebrow th-coming-soon-tag" style={{ fontSize: "12px", color: "rgb(232, 201, 138)" }}>Planned · In person</span>
            <h3 className="th-coming-soon-title" style={{ color: "var(--th-stone)" }}>
              <span className="th-h-italic" style={{ color: "rgb(232, 201, 138)" }}>The Evening</span> Round Table.
            </h3>
            <p className="th-coming-soon-dek" style={{ color: "rgba(245, 239, 220, 0.82)" }}>
              An investor&rsquo;s dinner. A few people who think hard about
              markets, building, and where the two meet — over one long
              table, a few times a year. Not yet scheduled. Inner Loop members
              hear first.
            </p>
            <div className="th-coming-soon-actions">
              <span className="th-coming-soon-meta" style={{ color: "rgba(245, 239, 220, 0.6)" }}>By invitation · Not yet scheduled</span>
            </div>
          </div>
        </div>
      </section>

      {/* LATEST ESSAYS — promoted to full width, big type, strong separation */}
      <section className="th-recent-block-full">
        <div className="th-section-head th-section-head-lg">
          <span className="th-eyebrow" style={{ fontSize: "15px", color: "rgb(26, 41, 73)" }}>Latest essays</span>
          <a
            href="#"
            className="th-link-quiet"
            onClick={(e) => {e.preventDefault();navigate("archive");}} style={{ fontSize: "15px" }}>
            See all {ESSAYS.length} →
          </a>
        </div>

        <div className="th-recent-rows">
          {recent.length > 0 ? recent.map((e) => {
            const vol = String(totalVols - ESSAYS.indexOf(e)).padStart(2, "0");
            return (
              <a
                key={e.id}
                href="#"
                className="th-list-row th-list-row-lg"
                onClick={(ev) => {ev.preventDefault();navigate("essay", { id: e.id });}}>
              <span className="th-list-date">{essayDate(e)}</span>
              <span className="th-list-body">
                <span className="th-list-title">{e.title}</span>
                <span className="th-list-dek" style={{ fontSize: "18px" }}>{e.dek}</span>
              </span>
              <span className="th-list-meta">
                <span className={"th-tier-pill th-tier-" + e.tier}>{e.tier === "free" ? "Feed" : e.tier === "loop" ? "Loop" : "Inner"}</span>
                <span className="th-list-min">{readMin(e)} min</span>
              </span>
              <span className="th-list-vol" aria-hidden="true"><span className="th-list-vol-no">{vol}</span><span className="th-list-vol-lab">Vol.</span></span>
            </a>);

          }) :
          <div className="th-recent-empty">
            <span className="th-eyebrow">No essays published yet</span>
            <p>The first essay is being written. Subscribe below and it lands in your inbox the day it ships.</p>
          </div>
          }
        </div>
      </section>

      {/* SUBSCRIBE BANNER — full-bleed, the loud one */}
      <section className="th-sub-banner">
        <div className="th-sub-banner-inner">
          <div className="th-sub-banner-copy">
            <span className="th-eyebrow" style={{ fontSize: "14px" }}>The Feed · free</span>
            <h3 className="th-sub-banner-title">
              <span className="th-h-italic">New essays,</span> in your inbox.
            </h3>
            <p className="th-sub-banner-dek">
              Long essays on operating, markets, AI, and the parts of a
              working life that don&rsquo;t make the highlight reel. Most weeks.
              No tracking, no upsell pressure.
            </p>
          </div>
          <div className="th-sub-banner-form">
            <form
              className="th-sub-banner-input"
              action="https://tomhoganfinance.substack.com/subscribe"
              method="get"
              target="_blank">
                <input
                type="email"
                name="email"
                required
                placeholder="you@email.com"
                value={bannerEmail}
                onChange={(e) => setBannerEmail(e.target.value)} />
                <button type="submit">Subscribe</button>
              </form>
            <p className="th-microcopy th-sub-banner-microcopy">
              Or <a href="#" onClick={(e) => {e.preventDefault();navigate("subscribe");}}>upgrade to The Loop</a> for working notes &amp; frameworks. Cancel anytime.
            </p>
          </div>
        </div>
      </section>

      {/* TIER MODULE */}
      <section className="th-tier-module">
        <div className="th-tier-head">
          <span className="th-eyebrow">Membership</span>
          <h3>Three rings. Read at the depth that fits you.</h3>
          <p>
            The Feed is free and stays that way. The Loop and Inner Loop are
            for readers who want the working notes — research, post-mortems,
            positions, and the in-progress thinking before it's clean.
          </p>
        </div>
        <TierGrid navigate={navigate} compact />
      </section>
    </div>);

}

window.HomePage = HomePage;
