/* Landing page. The public thesis route lives in screen-public-thesis.jsx. */

const { useState: useStateP2, useEffect: useEffectP2 } = React;

/* ---------- LANDING PAGE ---------- */

function Landing({ onLaunch, profileId, thesisId }) {
  const previewProfileId = profileId || dbq.allProfiles()[0].id;
  const previewThesisId = thesisId || dbq.thesesForProfile(previewProfileId)[0].id;
  const WAITLIST_ENDPOINT = "https://formspree.io/f/meevbovq";
  const TIER_OPTIONS = ["Free", "Weekly Pass", "Pro", "Premium", "Founder", "Just curious"];
  const CURIOUS = "Just curious";
  const [email, setEmail] = useStateP2("");
  const [selectedTiers, setSelectedTiers] = useStateP2(() => {
    try {
      const saved = JSON.parse(localStorage.getItem("thesis.leadTiers") || "null");
      if (Array.isArray(saved) && saved.length) return saved;
    } catch {}
    return [CURIOUS];
  });
  const [submitted, setSubmitted] = useStateP2(() => {
    try { return !!localStorage.getItem("thesis.leadEmail"); }
    catch { return false; }
  });
  const [submitting, setSubmitting] = useStateP2(false);
  const [error, setError] = useStateP2(null);
  // ?from=t/<slug> — visitors arriving from a public thesis URL get attributed
  // to that thesis in the Formspree payload.
  const [attribution, setAttribution] = useStateP2(() => readAttribution());
  const fromThesis = attribution ? lookupAttributionThesis(attribution) : null;

  useEffectP2(() => {
    if (!attribution) return;
    // Strip ?from= from the URL once we've captured it, so back/forward and
    // copy-paste produce a clean home URL.
    try {
      const url = new URL(window.location.href);
      url.searchParams.delete("from");
      window.history.replaceState({}, "", url.pathname + url.search + url.hash);
    } catch {}
  }, [attribution]);

  function toggleTier(tier) {
    setSelectedTiers((prev) => {
      const has = prev.includes(tier);
      if (!has && typeof window.plausible === "function") {
        window.plausible("Tier select", { props: { tier } });
      }
      if (tier === CURIOUS) {
        return has ? prev.filter((t) => t !== CURIOUS) : [CURIOUS];
      }
      const withoutCurious = prev.filter((t) => t !== CURIOUS);
      return has ? withoutCurious.filter((t) => t !== tier) : [...withoutCurious, tier];
    });
  }

  function trackDemoOpen(source) {
    if (typeof window.plausible === "function") {
      window.plausible("Demo open", { props: { source } });
    }
  }

  async function handleSubmit(e) {
    e.preventDefault();
    if (submitting) return;
    const v = email.trim();
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v)) return;
    if (selectedTiers.length === 0) return;
    setSubmitting(true);
    setError(null);
    try {
      const payload = {
        email: v,
        source: attribution ? `t/${attribution}` : "landing-hero",
        tiers: selectedTiers,
      };
      if (attribution) payload.from_thesis_slug = attribution;
      const res = await fetch(WAITLIST_ENDPOINT, {
        method: "POST",
        headers: { "Content-Type": "application/json", "Accept": "application/json" },
        body: JSON.stringify(payload),
      });
      if (!res.ok) throw new Error("Submission failed");
      try {
        localStorage.setItem("thesis.leadEmail", v);
        localStorage.setItem("thesis.leadEmailAt", new Date().toISOString());
        localStorage.setItem("thesis.leadTiers", JSON.stringify(selectedTiers));
      } catch {}
      if (typeof window.plausible === "function") {
        const realTiers = selectedTiers.filter((t) => t !== CURIOUS);
        const tierProp =
          realTiers.length === 0 ? "curious"
          : realTiers.length === 1 ? realTiers[0]
          : "multi";
        window.plausible("Signup", { props: { tier: tierProp, count: realTiers.length } });
      }
      setSubmitted(true);
    } catch (err) {
      setError("Something went wrong. Please try again or email us directly.");
    } finally {
      setSubmitting(false);
    }
  }

  const realTiers = selectedTiers.filter((t) => t !== CURIOUS);
  const tierConfirmation =
    realTiers.length === 0
      ? "We will email you when access opens."
      : `We will email you when ${formatTierList(realTiers)} ${realTiers.length === 1 ? "opens" : "open"}.`;

  return (
    <div style={{ minHeight: "100vh", background: "var(--bg)" }}>
      <div style={{ borderBottom: "1px solid var(--line)" }}>
        <div style={{ maxWidth: 1180, margin: "0 auto", padding: "16px 24px", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <Brand />
          <div style={{ display: "flex", gap: 18, alignItems: "center" }}>
            <a className="mono" style={{ fontSize: 12, color: "var(--ink-3)", textDecoration: "none" }} href="#how">How it works</a>
            <a className="mono" style={{ fontSize: 12, color: "var(--ink-3)", textDecoration: "none" }} href="#price">Pricing</a>
            <button className="btn btn-primary btn-sm" onClick={() => { trackDemoOpen("nav-try-it"); onLaunch(); }}>Try it →</button>
          </div>
        </div>
      </div>

      {/* Hero */}
      <section style={{ maxWidth: 1180, margin: "0 auto", padding: "80px 24px 64px", position: "relative" }}>
        <div style={{ position: "absolute", top: 60, right: 24, width: 420, height: 420, background: "radial-gradient(circle, var(--accent-soft) 0%, transparent 65%)", pointerEvents: "none", opacity: 0.7 }} />
        <div className="label" style={{ marginBottom: 18, color: "var(--accent)" }}>investing research · structured · cited</div>
        <h1 className="serif" style={{ margin: 0, fontSize: "clamp(40px, 6vw, 76px)", fontWeight: 500, lineHeight: 1.05, letterSpacing: "-0.025em", maxWidth: 980, position: "relative" }}>
          Type your investing thesis. Get a <span style={{ background: "linear-gradient(180deg, transparent 60%, var(--hl) 60%)" }}>structured, cited, persistent</span> profile of matching companies.
        </h1>
        <p style={{ fontSize: 19, lineHeight: 1.55, color: "var(--ink-3)", marginTop: 22, maxWidth: 720, position: "relative" }}>
          A living research artifact — grounded in real-time fundamentals, cited to specific filings, and continuously re-evaluated.
        </p>

        <div style={{ marginTop: 32, position: "relative", maxWidth: 560 }}>
          {fromThesis && !submitted && (
            <div
              role="note"
              className="card"
              style={{
                padding: "10px 14px",
                marginBottom: 14,
                display: "flex",
                gap: 10,
                alignItems: "center",
                borderColor: "var(--accent)",
                background: "var(--accent-soft)",
              }}
            >
              <Icon name="external" size={14} style={{ color: "var(--accent)" }} />
              <div style={{ fontSize: 13, lineHeight: 1.4 }}>
                You came from <em>“{fromThesis.title}”</em>. We'll remember that on signup.
              </div>
            </div>
          )}
          {!submitted ? (
            <form onSubmit={handleSubmit} style={{ display: "grid", gap: 14 }}>
              <fieldset
                disabled={submitting}
                style={{ border: "none", padding: 0, margin: 0, display: "grid", gap: 8 }}
              >
                <legend className="label" style={{ padding: 0, color: "var(--ink-3)" }}>
                  Interested in (pick one or more)
                </legend>
                <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
                  {TIER_OPTIONS.map((tier) => (
                    <TierChip
                      key={tier}
                      label={tier}
                      selected={selectedTiers.includes(tier)}
                      onClick={() => toggleTier(tier)}
                    />
                  ))}
                </div>
              </fieldset>
              <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
                <input
                  type="email"
                  required
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  placeholder="you@firm.com"
                  aria-label="Email address"
                  disabled={submitting}
                  style={{
                    flex: "1 1 260px",
                    padding: "13px 16px",
                    fontSize: 15,
                    background: "var(--bg)",
                    border: "1px solid var(--line)",
                    borderRadius: "var(--d-radius)",
                    color: "var(--ink)",
                    outline: "none",
                    fontFamily: "inherit",
                    opacity: submitting ? 0.6 : 1,
                  }}
                />
                <button
                  type="submit"
                  className="btn btn-primary"
                  disabled={submitting || selectedTiers.length === 0}
                  style={{ padding: "13px 22px", fontSize: 15, opacity: submitting || selectedTiers.length === 0 ? 0.7 : 1 }}
                >
                  {submitting ? "Sending…" : <>Get early access <Icon name="arrow" size={14} /></>}
                </button>
                {error && (
                  <div role="alert" style={{ flexBasis: "100%", fontSize: 13, color: "var(--neg, #c0392b)", marginTop: 4 }}>
                    {error}
                  </div>
                )}
              </div>
            </form>
          ) : (
            <div
              className="card"
              role="status"
              style={{ padding: 16, display: "flex", gap: 12, alignItems: "center", borderColor: "var(--accent)" }}
            >
              <Icon name="check2" size={18} style={{ color: "var(--accent)" }} />
              <div>
                <div style={{ fontFamily: "var(--font-serif)", fontSize: 17, lineHeight: 1.2 }}>
                  You are on the list.
                </div>
                <div style={{ fontSize: 13, color: "var(--ink-3)", marginTop: 2 }}>
                  {tierConfirmation}
                </div>
              </div>
            </div>
          )}

          <div style={{ display: "flex", gap: 14, marginTop: 14, alignItems: "center", flexWrap: "wrap" }}>
            <span className="btn-founder">
              Founder seat · $99/yr · cap 100
            </span>
            <button
              type="button"
              className="btn btn-ghost btn-sm"
              onClick={() => { trackDemoOpen("hero-see-demo"); onLaunch(); }}
              style={{ padding: "6px 10px", color: "var(--ink-3)" }}
            >
              See the demo →
            </button>
          </div>
        </div>
      </section>

      {/* How it works — 3-step */}
      <section id="how" style={{ background: "var(--bg-2)", borderTop: "1px solid var(--line)", borderBottom: "1px solid var(--line)" }}>
        <div style={{ maxWidth: 1180, margin: "0 auto", padding: "64px 24px" }}>
          <SectionHead eyebrow="how it works" title="From two words to a structured thesis" />
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 18, marginTop: 28 }}>
            {[
              ["01", "Profile", "Type a theme. The investor lens auto-fills — risk, horizon, geography, exclusions, style. Editable inline.", "var(--accent)"],
              ["02", "Thesis Lab", "Three to five distinct theses are proposed. Each card explains how it differs. Activate one or many.", "var(--hl)"],
              ["03", "Deep dive", "Ten to fifteen ranked candidates. Per-criterion scorecard. Anti-thesis check. Every claim cites a filing.", "var(--pos)"],
            ].map(([n, t, d, c]) => (
              <div key={n} className="card" style={{ borderTop: "3px solid " + c, paddingTop: 18 }}>
                <span className="mono" style={{ fontSize: 11, color: c, fontWeight: 600 }}>{n}</span>
                <h3 style={{ fontFamily: "var(--font-serif)", fontWeight: 500, fontSize: 24, margin: "8px 0 8px", letterSpacing: "-0.01em" }}>{t}</h3>
                <p style={{ fontSize: 13, lineHeight: 1.55, color: "var(--ink-3)", margin: 0 }}>{d}</p>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* Screenshot strip */}
      <section style={{ maxWidth: 1180, margin: "0 auto", padding: "64px 24px" }}>
        <SectionHead eyebrow="screens" title="From two words to a structured thesis" sub="Click any tile to step through the flow." />
        <ScreenStrip onLaunch={onLaunch} profileId={previewProfileId} thesisId={previewThesisId} />
      </section>

      {/* Moats */}
      <section style={{ background: "var(--bg-2)", borderTop: "1px solid var(--line)", borderBottom: "1px solid var(--line)" }}>
        <div style={{ maxWidth: 1180, margin: "0 auto", padding: "64px 24px" }}>
          <SectionHead eyebrow="what's different" title="Four pillars of the product" />
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(240px, 1fr))", gap: 14, marginTop: 24 }}>
            {[
              ["A", "Grounded data", "Every claim backed by fundamentals data and web evidence. No hallucinated tickers.", "var(--accent)"],
              ["B", "Persistent thesis", "First-class object: persists, evolves, refines. Editable. Forkable.", "var(--hl)"],
              ["C", "Auditable reasoning", "Each candidate cites specific filings and transcripts. Click → source.", "var(--pos)"],
              ["E", "Continuous monitoring", "Daily news scan plus weekly re-rank. The diff is the digest.", "var(--warn)"],
            ].map(([k, t, d, c]) => (
              <div key={k} className="card" style={{ position: "relative" }}>
                <div style={{ position: "absolute", top: 0, left: 0, width: 4, height: "100%", background: c, borderRadius: "var(--d-radius-lg) 0 0 var(--d-radius-lg)" }} />
                <div className="mono" style={{ fontSize: 22, fontWeight: 600, color: c }}>{k}</div>
                <div style={{ fontFamily: "var(--font-serif)", fontSize: 17, marginTop: 8 }}>{t}</div>
                <p style={{ fontSize: 12, color: "var(--ink-3)", lineHeight: 1.55, marginTop: 6 }}>{d}</p>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* Pricing */}
      <section id="price" style={{ maxWidth: 1180, margin: "0 auto", padding: "64px 24px" }}>
        <SectionHead eyebrow="pricing" title="Priced for prosumers" sub="Free tier is the demo. Pro is where the daily scan and weekly diff live." />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(220px, 1fr))", gap: 14, marginTop: 24 }}>
          <PricingCard tier="Free" price="$0" sub="The demo" features={["1 active thesis", "Weekly manual refresh", "Public pages only"]} />
          <PricingCard tier="Weekly Pass" price="$14" sub="7 days · no auto-renew" features={["Full Pro for 7 days", "Unlimited theses this week", "Daily news scan + weekly diff", "No subscription, no auto-renew"]} />
          <PricingCard tier="Pro" price="$49" period="/mo" sub="$399/yr · 32% off" features={["Unlimited theses", "Daily news scan", "Weekly re-rank + diff", "Email digest", "Private theses"]} accent />
          <PricingCard tier="Premium" price="$99" period="/mo" sub="$799/yr" features={["Pro + API access", "Multi-thesis bundles", "Custom criteria templates", "Priority support"]} />
          <PricingCard tier="Founder" price="$99" period="/yr" sub="cap 100 · validation only" features={["Premium-equivalent forever", "Refundable if no ship in 90d", "Direct line to founder"]} dashed />
        </div>
      </section>

      {/* Footer */}
      <footer style={{ borderTop: "1px solid var(--line)", padding: "28px 24px", marginTop: 24 }}>
        <div style={{ maxWidth: 1180, margin: "0 auto", display: "flex", justifyContent: "space-between", flexWrap: "wrap", gap: 16, fontSize: 12, color: "var(--ink-4)" }}>
          <div className="mono">© 2026 Thesis · Independent project</div>
          <div className="mono">Research output, not investment advice</div>
        </div>
      </footer>
    </div>
  );
}

function formatTierList(tiers) {
  if (tiers.length === 1) return tiers[0];
  if (tiers.length === 2) return `${tiers[0]} and ${tiers[1]}`;
  return `${tiers.slice(0, -1).join(", ")}, and ${tiers[tiers.length - 1]}`;
}

function TierChip({ label, selected, onClick }) {
  const isFounder = label === "Founder";
  return (
    <button
      type="button"
      role="checkbox"
      aria-checked={selected}
      aria-label={`${label}${selected ? " (selected)" : ""}`}
      onClick={onClick}
      style={{
        display: "inline-flex",
        alignItems: "center",
        padding: "8px 12px",
        border: `1px ${isFounder && !selected ? "dashed" : "solid"} var(${selected ? "--line-2" : "--line"})`,
        borderRadius: "var(--d-radius)",
        background: selected ? "var(--accent-soft)" : "var(--surface)",
        color: "var(--ink)",
        fontFamily: "var(--font-mono)",
        fontSize: "var(--d-text-xs)",
        fontWeight: 600,
        letterSpacing: "0.04em",
        textTransform: "uppercase",
        cursor: "pointer",
        transition: "background 120ms, border-color 120ms",
      }}
    >
      {label}
    </button>
  );
}

function CompareCol({ title, lines, muted, accent }) {
  return (
    <div style={{ padding: 24, background: accent ? "var(--bg)" : "transparent", borderLeft: accent ? "1px solid var(--line)" : "none" }}>
      <div className="label" style={{ marginBottom: 14, color: muted ? "var(--ink-4)" : "var(--ink-3)" }}>{title}</div>
      <div style={{ display: "grid", gap: 10 }}>
        {lines.map(([k, v], i) => (
          <div key={i} style={{ display: "grid", gridTemplateColumns: "120px 1fr", gap: 12, fontSize: 13, paddingBottom: 10, borderBottom: i < lines.length - 1 ? "1px dashed var(--line)" : "none" }}>
            <span className="mono" style={{ fontSize: 11, color: "var(--ink-4)", textTransform: "uppercase", letterSpacing: "0.06em" }}>{k}</span>
            <span style={{ color: muted ? "var(--ink-3)" : "var(--ink)", textDecoration: muted ? "line-through" : "none", textDecorationColor: "var(--ink-4)" }}>
              {v}
            </span>
          </div>
        ))}
      </div>
    </div>
  );
}

function PricingCard({ tier, price, period, sub, features, accent, dashed }) {
  return (
    <div className="card" style={{
      borderColor: accent ? "var(--ink)" : undefined,
      borderStyle: dashed ? "dashed" : "solid",
      boxShadow: accent ? "0 0 0 1px var(--ink) inset" : undefined,
      display: "flex", flexDirection: "column", gap: 12,
    }}>
      <div className="label">{tier}</div>
      <div style={{ display: "flex", alignItems: "baseline", gap: 4 }}>
        <span className="mono" style={{ fontSize: 32, fontWeight: 600, letterSpacing: "-0.02em" }}>{price}</span>
        {period && <span className="mono" style={{ fontSize: 12, color: "var(--ink-3)" }}>{period}</span>}
      </div>
      <div className="mono" style={{ fontSize: 11, color: "var(--ink-4)" }}>{sub}</div>
      <ul style={{ listStyle: "none", margin: 0, padding: 0, display: "grid", gap: 6 }}>
        {features.map((f) => (
          <li key={f} style={{ display: "flex", gap: 8, fontSize: 13, color: "var(--ink-2)" }}>
            <Icon name="check2" size={13} style={{ color: "var(--ink-4)", marginTop: 3 }} />
            {f}
          </li>
        ))}
      </ul>
      <button className={"btn " + (accent ? "btn-primary" : "")} style={{ marginTop: "auto" }}>
        {tier === "Free" ? "Start free" : tier === "Founder" ? "Claim seat" : `Choose ${tier}`}
      </button>
    </div>
  );
}

/* Mini static screenshot strip — uses real components for authenticity */
function ScreenStrip({ onLaunch, profileId, thesisId }) {
  const slides = [
    { label: "01 · Profile", node: <MiniProfile profileId={profileId} /> },
    { label: "02 · Thesis Lab", node: <MiniThesisLab profileId={profileId} /> },
    { label: "03 · Ranked", node: <MiniRanked thesisId={thesisId} /> },
    { label: "04 · Deep dive", node: <MiniDeep profileId={profileId} thesisId={thesisId} /> },
    { label: "05 · Public URL", node: <MiniPublic profileId={profileId} thesisId={thesisId} /> },
  ];
  return (
    <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(280px, 1fr))", gap: 14, marginTop: 24 }}>
      {slides.map((s, i) => (
        <div key={i} className="card card-hover" onClick={onLaunch} style={{ padding: 0, overflow: "hidden", cursor: "pointer" }}>
          <div style={{ aspectRatio: "16/11", background: "var(--bg-2)", overflow: "hidden", borderBottom: "1px solid var(--line)", padding: 14 }}>
            <div style={{ transform: "scale(0.62)", transformOrigin: "top left", width: "162%", height: "162%", pointerEvents: "none" }}>
              {s.node}
            </div>
          </div>
          <div style={{ padding: "10px 14px", display: "flex", justifyContent: "space-between" }}>
            <span className="mono" style={{ fontSize: 11, color: "var(--ink-3)" }}>{s.label}</span>
            <Icon name="external" size={12} style={{ color: "var(--ink-4)" }} />
          </div>
        </div>
      ))}
    </div>
  );
}

function MiniProfile({ profileId }) {
  const p = dbq.profileById(profileId);
  return (
    <div className="card" style={{ width: 360, padding: 14 }}>
      <div className="label">Theme</div>
      <div className="serif" style={{ fontSize: 18, fontWeight: 500, marginTop: 4 }}>{p.theme}</div>
      <div className="divider" style={{ margin: "10px 0" }} />
      {[["Risk", p.risk_tolerance], ["Horizon", p.time_horizon], ["Mcap", p.mcap_preference]].map(([k, v]) => (
        <div key={k} style={{ display: "flex", justifyContent: "space-between", padding: "4px 0", fontSize: 12 }}>
          <span className="mono" style={{ color: "var(--ink-4)", textTransform: "uppercase", fontSize: 10 }}>{k}</span>
          <span>{v}</span>
        </div>
      ))}
    </div>
  );
}

function MiniThesisLab({ profileId }) {
  const theses = dbq.thesesForProfile(profileId);
  return (
    <div style={{ display: "grid", gap: 8, width: 360 }}>
      {theses.slice(0, 3).map((t) => (
        <div key={t.id} className="card" style={{ padding: 12 }}>
          <div style={{ display: "flex", justifyContent: "space-between" }}>
            <span className="serif" style={{ fontSize: 14, fontWeight: 500 }}>{t.title}</span>
            <FitScore value={t.fit} />
          </div>
          <ScoreBar value={t.fit} />
        </div>
      ))}
    </div>
  );
}

function MiniRanked({ thesisId }) {
  const candidates = dbq.candidatesForThesis(thesisId);
  return (
    <div style={{ display: "grid", gap: 8, width: 360 }}>
      {candidates.slice(0, 3).map((c) => (
        <div key={c.id} className="card" style={{ padding: 12, display: "grid", gridTemplateColumns: "30px 60px 1fr 50px", gap: 8, alignItems: "center" }}>
          <span className="mono" style={{ color: "var(--ink-4)", fontSize: 11 }}>#{c.rank}</span>
          <span className="mono" style={{ fontWeight: 600 }}>{c.ticker}</span>
          <Sparkline data={c.spark} height={20} />
          <span className="mono">{c.fit.toFixed(2)}</span>
        </div>
      ))}
    </div>
  );
}

function MiniDeep({ profileId, thesisId }) {
  const criteria = dbq.criteriaForProfile(profileId);
  const top = dbq.candidatesForThesis(thesisId)[0];
  if (!top) return <div style={{ width: 360 }} />;
  const scoresByCriterion = Object.fromEntries(
    dbq.scoresForCandidate(top.id).map((s) => [s.criterion_id, s.score])
  );
  return (
    <div style={{ width: 360 }}>
      <div className="serif" style={{ fontSize: 22, fontWeight: 500 }}>{top.name}</div>
      <div className="mono" style={{ fontSize: 11, color: "var(--ink-3)" }}>{top.ticker} · {top.sector.toLowerCase()}</div>
      <div style={{ marginTop: 10 }}>
        {criteria.slice(0, 3).map((cr) => {
          const score = scoresByCriterion[cr.id] ?? 0;
          return (
            <div key={cr.id} style={{ padding: "6px 0", borderBottom: "1px dashed var(--line)" }}>
              <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12 }}>
                <span>{cr.name}</span>
                <span className="mono">{score.toFixed(2)}</span>
              </div>
              <ScoreBar value={score} />
            </div>
          );
        })}
      </div>
    </div>
  );
}

function MiniPublic({ profileId, thesisId }) {
  const profile = dbq.profileById(profileId);
  const thesis = dbq.thesisById(thesisId);
  const candidates = dbq.candidatesForThesis(thesisId);
  return (
    <div style={{ width: 360 }}>
      <div className="label">Public · April 2026</div>
      <div className="serif" style={{ fontSize: 24, fontWeight: 500, lineHeight: 1.1, marginTop: 6 }}>
        {thesis.title}
      </div>
      <div className="mono" style={{ fontSize: 11, color: "var(--ink-3)", marginTop: 4 }}>
        thesis.app/t/{profile.slug}-{thesis.slug}
      </div>
      <div style={{ marginTop: 12, display: "grid", gap: 6 }}>
        {candidates.slice(0, 4).map((c) => (
          <div key={c.id} style={{ display: "grid", gridTemplateColumns: "60px 1fr 50px", fontSize: 12 }}>
            <span className="mono">{c.ticker}</span>
            <span style={{ color: "var(--ink-3)" }}>{c.name}</span>
            <span className="mono">{c.fit.toFixed(2)}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

function readAttribution() {
  try {
    const params = new URLSearchParams(window.location.search);
    const raw = params.get("from");
    if (!raw) return null;
    const m = /^t\/([A-Za-z0-9-]+)$/.exec(raw);
    return m ? m[1] : null;
  } catch {
    return null;
  }
}

function lookupAttributionThesis(slug) {
  if (!slug || typeof resolvePublicSlug !== "function") return null;
  const resolved = resolvePublicSlug(slug);
  return resolved ? resolved.thesis : null;
}

Object.assign(window, { Landing });
