/* Public thesis route — rendered for any URL of the form /t/<profile-slug>-<thesis-slug>.

   This is the share-target surface: cold visitors arriving from X, Substack, or
   fintwit DMs land here. The page is intentionally lookup-by-slug (not driven
   by app state) so any profile/thesis pair can be addressed by URL, and so the
   surface can evolve independently of the in-app screens.

   Conversion mechanic: the CTA bounces visitors to "/" with ?from=t/<slug> so
   the home page can attribute the signup to the thesis they came from. */

const { useState: useStatePT, useEffect: useEffectPT } = React;

function parsePublicSlug(pathname) {
  const m = /^\/t\/([^/?#]+)\/?$/.exec(pathname || "");
  if (!m) return null;
  return decodeURIComponent(m[1]);
}

/* Slugs are <profile-slug>-<thesis-slug>; both halves contain hyphens.
   We resolve by trying every profile slug as a prefix and matching the
   remainder against that profile's thesis slugs. Longest profile-slug match
   wins to avoid ambiguity (none today, but cheap insurance). */
function resolvePublicSlug(slug) {
  if (!slug) return null;
  const profiles = dbq.allProfiles().slice().sort((a, b) => b.slug.length - a.slug.length);
  for (const profile of profiles) {
    const prefix = profile.slug + "-";
    if (!slug.startsWith(prefix)) continue;
    const rest = slug.slice(prefix.length);
    const thesis = dbq.thesisBySlug(profile.id, rest);
    if (thesis) return { profile, thesis };
  }
  return null;
}

function PublicThesisRoute() {
  const initial = parsePublicSlug(window.location.pathname);
  const [slug, setSlug] = useStatePT(initial);

  useEffectPT(() => {
    const onPop = () => setSlug(parsePublicSlug(window.location.pathname));
    window.addEventListener("popstate", onPop);
    return () => window.removeEventListener("popstate", onPop);
  }, []);

  const resolved = resolvePublicSlug(slug);
  if (!resolved) return <PublicNotFound slug={slug} />;
  return <PublicThesisPage profile={resolved.profile} thesis={resolved.thesis} slug={slug} />;
}

function PublicThesisPage({ profile, thesis, slug }) {
  const candidates = dbq.candidatesForThesis(thesis.id);
  const flagged = candidates.find((c) => c.antiTriggered);
  const topFit = candidates[0];
  const biggestMover = candidates.slice().sort((a, b) => b.delta - a.delta)[0];
  const totalCitations = candidates.reduce((acc, c) => acc + (c.citations || 0), 0);
  const visible = candidates.slice(0, 5);
  const hidden = Math.max(0, candidates.length - visible.length);
  const ctaHref = `/?from=t/${encodeURIComponent(slug)}`;

  useEffectPT(() => {
    document.title = `${thesis.title} — Thesis`;
  }, [thesis.title]);

  return (
    <div style={{ minHeight: "100vh", background: "var(--bg)" }}>
      <WipBanner />
      <PublicHeader />
      <Disclaimer />
      <article style={{ maxWidth: 760, margin: "0 auto", padding: "40px 20px 64px" }}>
        <div className="label" style={{ marginBottom: 10 }}>
          public thesis · {profile.theme.toLowerCase()}
        </div>
        <h1
          className="serif"
          style={{
            margin: 0,
            fontSize: "clamp(32px, 6vw, 44px)",
            fontWeight: 500,
            letterSpacing: "-0.02em",
            lineHeight: 1.1,
          }}
        >
          {thesis.title}
        </h1>
        <div
          style={{
            display: "flex",
            gap: 10,
            rowGap: 6,
            marginTop: 14,
            fontSize: 13,
            color: "var(--ink-3)",
            flexWrap: "wrap",
            alignItems: "center",
          }}
        >
          <span>by @alexandreayari</span>
          <span aria-hidden="true">·</span>
          <span className="mono">{candidates.length} candidates</span>
          <span aria-hidden="true">·</span>
          <span className="mono">{totalCitations} cited sources</span>
        </div>

        <p
          className="serif"
          style={{
            fontSize: "clamp(17px, 2.4vw, 19px)",
            lineHeight: 1.6,
            color: "var(--ink-2)",
            marginTop: 24,
          }}
        >
          {thesis.narrative}
        </p>

        <div
          className="public-summary"
          style={{
            display: "grid",
            gridTemplateColumns: "repeat(auto-fit, minmax(180px, 1fr))",
            gap: 12,
            marginTop: 24,
          }}
        >
          {[
            ["Top fit", topFit?.ticker || "—", topFit ? topFit.fit.toFixed(2) : ""],
            [
              "Biggest mover",
              biggestMover?.ticker || "—",
              biggestMover ? `${biggestMover.delta >= 0 ? "+" : ""}${biggestMover.delta.toFixed(2)}` : "",
            ],
            ["Anti-thesis", flagged?.ticker || "clear", flagged ? "1 risk flagged" : "no flag"],
          ].map(([k, v, s]) => (
            <div key={k} className="card">
              <div className="label" style={{ fontSize: 10 }}>{k}</div>
              <div
                style={{
                  display: "flex",
                  justifyContent: "space-between",
                  alignItems: "baseline",
                  marginTop: 8,
                }}
              >
                <span className="mono" style={{ fontSize: 22, fontWeight: 600 }}>{v}</span>
                <span className="mono" style={{ fontSize: 12, color: "var(--ink-3)" }}>{s}</span>
              </div>
            </div>
          ))}
        </div>

        <h2
          className="serif"
          style={{ fontWeight: 500, fontSize: 24, marginTop: 36, letterSpacing: "-0.01em" }}
        >
          Top {visible.length} candidates
        </h2>
        <div style={{ marginTop: 12 }}>
          {visible.map((c) => (
            <PublicCandidateRow key={c.id} c={c} />
          ))}
          {hidden > 0 && (
            <div
              style={{
                padding: "14px 0",
                borderBottom: "1px solid var(--line)",
                fontSize: 13,
                color: "var(--ink-3)",
                display: "flex",
                justifyContent: "space-between",
                alignItems: "center",
                gap: 10,
              }}
            >
              <span>{hidden} more candidate{hidden === 1 ? "" : "s"}, scored across the same criteria.</span>
              <a className="mono" style={{ fontSize: 11, color: "var(--ink-4)" }} href={ctaHref}>
                see all →
              </a>
            </div>
          )}
        </div>

        <PublicCTA href={ctaHref} thesisTitle={thesis.title} />
      </article>
      <footer
        style={{
          borderTop: "1px solid var(--line)",
          padding: "20px 24px",
          fontSize: 12,
          color: "var(--ink-4)",
          display: "flex",
          justifyContent: "space-between",
          gap: 12,
          flexWrap: "wrap",
        }}
      >
        <span className="mono">© 2026 Thesis · Independent project</span>
        <span className="mono">Research output, not investment advice</span>
      </footer>
    </div>
  );
}

function PublicCandidateRow({ c }) {
  return (
    <div
      style={{
        display: "grid",
        gridTemplateColumns: "26px 78px 1fr auto",
        columnGap: 12,
        rowGap: 4,
        padding: "12px 0",
        borderBottom: "1px solid var(--line)",
        alignItems: "center",
      }}
    >
      <span className="mono" style={{ color: "var(--ink-4)", fontSize: 12 }}>#{c.rank}</span>
      <span className="mono" style={{ fontSize: 15, fontWeight: 600 }}>{c.ticker}</span>
      <div style={{ minWidth: 0 }}>
        <div style={{ fontSize: 14 }}>{c.name}</div>
        <div
          style={{
            fontSize: 12,
            color: "var(--ink-3)",
            marginTop: 2,
            overflow: "hidden",
            textOverflow: "ellipsis",
            display: "-webkit-box",
            WebkitLineClamp: 2,
            WebkitBoxOrient: "vertical",
          }}
        >
          {c.reasons[0]}
        </div>
      </div>
      <span className="mono" style={{ fontSize: 14, fontWeight: 600 }}>{c.fit.toFixed(2)}</span>
    </div>
  );
}

function PublicCTA({ href, thesisTitle }) {
  return (
    <div
      style={{
        marginTop: 36,
        padding: 24,
        border: "1px solid var(--line)",
        borderRadius: "var(--d-radius-lg)",
        background: "var(--bg-2)",
        textAlign: "center",
      }}
    >
      <div className="label">Want your own?</div>
      <div
        className="serif"
        style={{ fontSize: "clamp(20px, 3.5vw, 24px)", marginTop: 6, marginBottom: 14, lineHeight: 1.25 }}
      >
        Type a theme. Get a structured, cited, persistent thesis like “{thesisTitle}”.
      </div>
      <a className="btn btn-primary" href={href} style={{ textDecoration: "none" }}>
        Build your own thesis <Icon name="arrow" size={14} />
      </a>
      <div className="mono" style={{ fontSize: 11, color: "var(--ink-4)", marginTop: 12 }}>
        Free tier · Founder seat $99/yr · cap 100
      </div>
    </div>
  );
}

function PublicHeader() {
  const [copied, setCopied] = useStatePT(false);

  async function copyLink() {
    try {
      await navigator.clipboard.writeText(window.location.href);
      setCopied(true);
      setTimeout(() => setCopied(false), 1800);
    } catch {
      /* clipboard blocked; fall back to selecting the visible URL element */
      const el = document.getElementById("public-url-display");
      if (el) {
        const range = document.createRange();
        range.selectNodeContents(el);
        const sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
      }
    }
  }

  return (
    <div className="topbar">
      <a
        href="/"
        style={{ textDecoration: "none", color: "inherit", display: "flex", alignItems: "center" }}
        aria-label="Thesis home"
      >
        <Brand subtitle="public · share-ready" />
      </a>
      <div style={{ display: "flex", gap: 8, alignItems: "center", minWidth: 0 }}>
        <span
          id="public-url-display"
          className="mono"
          style={{
            fontSize: 11,
            color: "var(--ink-4)",
            overflow: "hidden",
            textOverflow: "ellipsis",
            whiteSpace: "nowrap",
            maxWidth: "min(46vw, 360px)",
          }}
          title={window.location.href}
        >
          {window.location.host}{window.location.pathname}
        </span>
        <button className="btn btn-sm" onClick={copyLink} aria-live="polite">
          <Icon name={copied ? "check2" : "external"} size={12} />
          {copied ? " Copied" : " Copy link"}
        </button>
      </div>
    </div>
  );
}

function PublicNotFound({ slug }) {
  return (
    <div style={{ minHeight: "100vh", background: "var(--bg)" }}>
      <PublicHeader />
      <div style={{ maxWidth: 560, margin: "0 auto", padding: "64px 24px", textAlign: "center" }}>
        <div className="label" style={{ marginBottom: 12 }}>404 · thesis not found</div>
        <h1 className="serif" style={{ fontSize: 36, fontWeight: 500, letterSpacing: "-0.02em", margin: 0 }}>
          No thesis at this URL.
        </h1>
        {slug && (
          <p className="mono" style={{ fontSize: 12, color: "var(--ink-4)", marginTop: 12 }}>
            /t/{slug}
          </p>
        )}
        <p style={{ color: "var(--ink-3)", marginTop: 16, fontSize: 14, lineHeight: 1.55 }}>
          The link may have moved or never existed. Build your own thesis instead — same engine, your theme.
        </p>
        <a className="btn btn-primary" href="/" style={{ textDecoration: "none", marginTop: 24, display: "inline-flex" }}>
          Go to Thesis <Icon name="arrow" size={14} />
        </a>
      </div>
    </div>
  );
}

Object.assign(window, { PublicThesisRoute, parsePublicSlug, resolvePublicSlug });
