// landing.jsx — TranscriptAgent · final landing page
// Hybrid: Concept B base · Concept A warmth + levels · Concept C problem + trust.

const { useMemo, useState, useEffect } = React;

/* Scroll-spy: watch the three anchored sections (#how-it-works,
   #features, #levels) and return the id of the one currently most
   in view. NavBar then marks the matching link with `.is-active`
   so it lights up as the visitor scrolls down. */
function useActiveSection(ids = []) {
  const [active, setActive] = useState(null);
  useEffect(() => {
    if (typeof window === 'undefined' || typeof IntersectionObserver === 'undefined') return;
    const els = ids
      .map((id) => document.getElementById(id))
      .filter(Boolean);
    if (els.length === 0) return;
    // Pick the section whose top is closest to the viewport's
    // 1/4 line. rootMargin shrinks the active band so we don't
    // flip the active link the instant a section's edge appears.
    const observer = new IntersectionObserver((entries) => {
      const visible = entries
        .filter((e) => e.isIntersecting)
        .sort((a, b) => b.intersectionRatio - a.intersectionRatio);
      if (visible.length > 0) {
        setActive(visible[0].target.id);
      }
    }, {
      rootMargin: '-25% 0px -55% 0px',
      threshold: [0, 0.25, 0.5, 0.75, 1],
    });
    els.forEach((el) => observer.observe(el));
    return () => observer.disconnect();
  }, [ids.join('|')]);
  return active;
}

/* dynamic "week of" so the sample week never goes stale */
const weekOfLabel = () => {
  const d = new Date();
  d.setDate(d.getDate() - d.getDay()); // most recent Sunday
  return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
};

/* Server-injected live numbers from window.__landingData. The Flask
   /welcome-landing route populates this; if missing (e.g. running
   the static bundle outside the app) we fall back to placeholders. */
const __DATA = (typeof window !== 'undefined' && window.__landingData) || {};
const fmtCount = (n, fallback) => {
  if (n == null) return fallback;
  return Number(n).toLocaleString('en-US');
};
const fmtDelta = (n, suffix) => {
  if (n == null || n === 0) return null;
  return `+${Number(n).toLocaleString('en-US')} ${suffix}`;
};

/* ============================================================
   HERO HEADLINE — locked to "trust"
   ============================================================ */
const HERO_HEADLINE = <>The research desk for the market channels you already trust.</>;
const HERO_EYEBROW  = () => `Your workspace · sample week of ${weekOfLabel()}`;

/* ============================================================
   ROOT
   ============================================================ */
const Landing = () => {
  const activeAnchor = useActiveSection(['how-it-works', 'features', 'levels']);
  return (
    <div className="lp">
      <NavBar variant="warm" activeAnchor={activeAnchor} />
      <Hero />
      <IntroAnimation />
      <ProblemBand />
      <FiveQuestions />
      <TimeAxisBand />
      <DifferentiatorTracked />
      <RealWeekWalkthrough />
      <GroundingTrust />
      <LevelsSection />
      <FinalCTA />
      <Footer variant="warm" />
    </div>
  );
};

/* ============================================================
   INTRO ANIMATION — slim "what you get in six seconds" interlude
   between the Hero and the longer-form ProblemBand. Sandboxed
   iframe so the animation's <script>/<style> stay isolated.
   ============================================================ */
function IntroAnimation() {
  return (
    <section
      className="lp-section"
      style={{
        paddingTop: 24,
        paddingBottom: 36,
        background: 'var(--surface-page-warm)',
      }}
    >
      <div
        style={{
          maxWidth: 760,
          margin: '0 auto',
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center',
          gap: 14,
        }}
      >
        <span
          className="eyebrow"
          style={{
            color: 'var(--brand-bronze)',
            letterSpacing: '0.18em',
            fontSize: 11,
            textTransform: 'uppercase',
          }}
        >
          What you get, in six seconds
        </span>
        <div
          style={{
            width: '100%',
            background: 'var(--surface-card, #fff)',
            border: '1px solid var(--border-warm, rgba(184,137,58,0.18))',
            borderRadius: 18,
            boxShadow: '0 8px 22px rgba(28,51,67,0.06)',
            overflow: 'hidden',
          }}
        >
          <iframe
            src="/static/img/branding/transcriptagent-intro.html"
            title="TranscriptAgent — find the signal in the noise"
            style={{
              width: '100%',
              height: 280,
              border: 0,
              display: 'block',
            }}
            loading="lazy"
            sandbox="allow-scripts allow-same-origin"
            aria-label="TranscriptAgent product intro animation"
          />
        </div>
      </div>
    </section>
  );
}

/* ============================================================
   HERO
   ============================================================ */
function Hero() {
  const eyebrow = useMemo(() => HERO_EYEBROW(), []);
  return (
    <section className="lp-section" style={{ paddingTop: 56, paddingBottom: 88, background: 'var(--surface-page-warm)' }}>
      <div className="lp-grid-2">
        <div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 22 }}>
            <span className="eyebrow" style={{ color: 'var(--brand-bronze)' }}>{eyebrow}</span>
          </div>
          <h1 className="lp-hero">{HERO_HEADLINE}</h1>
          <p className="lp-lede">
            TranscriptAgent turns finance videos into structured claims, asset narratives, speaker stances, and tracked research questions — so you can see what changed without watching everything.
          </p>
          <p className="lp-lede" style={{ fontSize: 15, color: 'var(--ink-muted)', marginTop: -6 }}>
            Day one you get a live desk over the channels you pick — a daily brief, a <strong style={{ color: 'var(--ink-navy)' }}>Today's Diff</strong> of exactly what changed since yesterday, catalysts, and the global insight cards. It gets <strong style={{ color: 'var(--ink-navy)' }}>personal as you teach it</strong> which reads matter. Track your first question right away.
          </p>
          <div className="lp-cta-row" style={{ marginBottom: 14 }}>
            <a href="/login" className="btn btn--primary" style={{ textDecoration: 'none' }}>Try it free →</a>
            <a href="/preview/report" className="btn btn--ghost" style={{ textDecoration: 'none' }}>See today's actual report →</a>
            <a href="#how-it-works" className="btn btn--ghost" style={{ textDecoration: 'none' }}>See how it works</a>
          </div>
          <span style={{ fontSize: 12.5, color: 'var(--ink-muted)' }}>
            Free to start · no credit card · indexing begins on your first channel.
          </span>
          {true && (
            <div className="lp-meta-row hide-mobile">
              <Stat
                label="Channels indexed"
                value={fmtCount(__DATA.channelsIndexed, '2,140')}
                delta={fmtDelta(__DATA.channelsThisWeek, 'this week')}
              />
              <Stat
                label="Claims indexed"
                value={fmtCount(__DATA.claimsIndexed, '38,402')}
                delta={fmtDelta(__DATA.claimsToday, 'today')}
              />
              <Stat
                label="Tracked questions"
                value={fmtCount(__DATA.trackedQuestions, '6,118')}
                delta={fmtDelta(__DATA.trackedQuestionsToday, 'today')}
              />
            </div>
          )}
        </div>
        <HeroDashboard />
      </div>
    </section>
  );
}

function Stat({ label, value, delta }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
      <span style={{ fontFamily: 'var(--font-serif)', fontSize: 22, color: 'var(--ink-navy)', letterSpacing: '-0.012em' }}>{value}</span>
      <span style={{ fontSize: 10.5, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--ink-muted)', fontWeight: 600 }}>{label}</span>
      {delta && (
        <span style={{ fontSize: 10.5, color: 'var(--brand-deep)', fontWeight: 600, letterSpacing: '0.02em', marginTop: 1, display: 'inline-flex', alignItems: 'center', gap: 4 }}>
          <Ico name="arrow-up" size={9} stroke="var(--brand-deep)" strokeWidth={2.4} />
          {delta}
        </span>
      )}
    </div>
  );
}

function HeroDashboard() {
  const heatmap = [
    { label: 'Semiconductors',  heat: [0.2, 0.3, 0.5, 0.7, 0.9, 0.95, 0.85, 0.8],  delta: 38, tone: 'warm' },
    { label: 'Gold miners',     heat: [0.3, 0.35, 0.4, 0.5, 0.6, 0.7, 0.85, 0.95], delta: 41, tone: 'warm' },
    { label: 'Recession calls', heat: [0.15, 0.2, 0.25, 0.35, 0.5, 0.6, 0.7, 0.8], delta: 33, tone: 'warm' },
    { label: 'Dollar (DXY)',    heat: [0.85, 0.7, 0.55, 0.45, 0.4, 0.35, 0.3, 0.25], delta: -29, tone: 'cool' },
    { label: 'Regional banks',  heat: [0.7, 0.6, 0.4, 0.3, 0.35, 0.45, 0.6, 0.75], delta: 12, tone: 'cool' },
  ];
  return (
    <div style={{
      background: 'var(--surface-paper)',
      border: '1px solid var(--border-warm)',
      borderRadius: 20,
      padding: 22,
      boxShadow: '0 1px 0 rgba(0,0,0,0.03), 0 30px 60px -28px rgba(28,51,67,0.20)',
      display: 'flex',
      flexDirection: 'column',
      gap: 14,
    }}>
      {/* chrome */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
        <span className="eyebrow" style={{ color: 'var(--brand-deep)' }}>Your workspace · Week of {weekOfLabel()}</span>
        <span style={{ marginLeft: 'auto', display: 'flex', gap: 6 }} className="hide-mobile">
          <span className="chip chip--cool" style={{ fontSize: 11 }}>Gold</span>
          <span className="chip" style={{ fontSize: 11 }}>Tech</span>
          <span className="chip" style={{ fontSize: 11 }}>Rates</span>
        </span>
      </div>

      {/* FEATURED — answered tracked question */}
      <div className="card card--warm" style={{ padding: 18, display: 'flex', flexDirection: 'column', gap: 14 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <span style={{
            width: 28, height: 28, borderRadius: 8,
            background: 'var(--brand-deep)', color: 'var(--gold-bright)',
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <Ico name="bell" size={14} strokeWidth={1.8} />
          </span>
          <div className="eyebrow eyebrow--bronze">Tracked question · 2 new answers this week</div>
        </div>
        <p style={{
          margin: 0, fontFamily: 'var(--font-serif)',
          fontSize: 22, lineHeight: 1.22,
          color: 'var(--ink-navy)', letterSpacing: '-0.008em',
        }}>
          “Is anyone turning bearish on semiconductors?”
        </p>
        <div style={{
          padding: '12px 14px', background: '#fff',
          border: '1px solid var(--border-warmer)', borderRadius: 10,
          fontSize: 12.5, color: 'var(--ink-slate)', lineHeight: 1.45,
        }}>
          <strong style={{ color: 'var(--ink-navy)' }}>2 new videos mentioned semis.</strong> One bullish on AI capex, one bearish on valuation pressure.
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
            <Stance value="bullish" conviction={3} />
            <span style={{ fontSize: 12.5, color: 'var(--ink-slate)' }}>
              <strong style={{ color: 'var(--ink-navy)' }}>Tom Lee</strong> — “AI capex guides keep ratcheting higher every quarter.”
            </span>
          </div>
          <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
            <Stance value="bearish" conviction={3} />
            <span style={{ fontSize: 12.5, color: 'var(--ink-slate)' }}>
              <strong style={{ color: 'var(--ink-navy)' }}>Jim Bianco</strong> — “Priced for perfection on a one-customer story.”
            </span>
          </div>
        </div>
      </div>

      {/* Regime + niche assets row */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.1fr 1fr', gap: 12 }}>
        <div className="card card--mint" style={{ padding: 14 }}>
          <div className="eyebrow" style={{ color: '#2a6149', marginBottom: 8 }}>Perceived regime</div>
          <div style={{ fontFamily: 'var(--font-serif)', fontSize: 20, lineHeight: 1.1, color: '#0f2a20', letterSpacing: '-0.012em' }}>
            Late-cycle reflation
          </div>
          <div style={{ fontSize: 11.5, color: '#2a6149', marginTop: 6, lineHeight: 1.4 }}>
            7 of 12 channels converge. Diverges from FRED indicators by <strong>+2 pts</strong>.
          </div>
        </div>
        <div className="card" style={{ padding: 14, display: 'flex', flexDirection: 'column', gap: 6 }}>
          <div className="eyebrow eyebrow--bronze" style={{ marginBottom: 2 }}>Niche · gaining attention</div>
          <AssetPulseRow rank={1} ticker="URNJ" name="Sprott Jr. Uranium" mentions={7} speakers={3} momentum={42} sentiment="bullish" points={[1,1.2,1.4,1.5,1.7,2.1,2.4,2.6]} />
          <AssetPulseRow rank={2} ticker="CCJ"  name="Cameco"             mentions={11} speakers={5} momentum={28} sentiment="bullish" points={[1,1.1,1.05,1.2,1.4,1.55,1.6,1.7]} />
        </div>
      </div>

      {/* Theme rotation strip */}
      <div className="card" style={{ padding: 14 }}>
        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 10 }}>
          <div className="eyebrow eyebrow--bronze">Theme rotation · 8 weeks</div>
          <span className="mono" style={{ fontSize: 11, color: 'var(--ink-muted)' }}>
            {`${fmtCount(__DATA.channelsThisWeekActive, '27')} channels · ${fmtCount(__DATA.claimsThisWeek, '184')} claims`}
          </span>
        </div>
        <ThemeHeatmap themes={heatmap} weeks={8} compact />
      </div>
    </div>
  );
}

/* ============================================================
   PROBLEM BAND
   ============================================================ */
function ProblemBand() {
  const pains = [
    { tag: 'Volume', q: 'You watched the video. But did you catch the claim?', a: 'Ninety minutes for one analyst. You can\'t honestly do that for ten of them.' },
    { tag: 'Memory', q: 'You remember someone was bullish on gold. You just cannot remember who, when, or why.', a: 'The stance changes are exactly the moments you can\'t afford to forget — and they\'re the easiest to lose.' },
    { tag: 'Drift',  q: 'By the time a narrative feels obvious, it has already moved through ten channels.', a: 'You needed a map of what was rotating, not another summary of last week.' },
  ];
  return (
    <section className="lp-section lp-section--cool">
      <div className="eyebrow" style={{ marginBottom: 14, color: 'var(--ink-muted)' }}>The pain behind “just one more video”</div>
      <h2 className="lp-h2" style={{ maxWidth: 880, marginBottom: 48 }}>
        Three problems hiding in your watch history.
      </h2>
      <div className="lp-grid-3">
        {pains.map((p, i) => (
          <div key={i} style={{ borderTop: '1px solid var(--border-warm)', paddingTop: 22 }}>
            <div className="eyebrow eyebrow--bronze" style={{ marginBottom: 14 }}>{p.tag}</div>
            <p style={{
              fontFamily: 'var(--font-serif)', fontStyle: 'italic',
              fontSize: 20, lineHeight: 1.25,
              color: 'var(--ink-navy)', margin: '0 0 12px',
              textWrap: 'pretty',
            }}>“{p.q}”</p>
            <p className="body-sm" style={{ margin: 0 }}>{p.a}</p>
          </div>
        ))}
      </div>
    </section>
  );
}

/* ============================================================
   HOW IT WORKS
   ============================================================ */
function HowItWorks() {
  return (
    <section className="lp-section lp-section--paper">
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 40, flexWrap: 'wrap', gap: 20 }}>
        <div>
          <div className="eyebrow" style={{ marginBottom: 14 }}>How it works</div>
          <h2 className="lp-h2" style={{ maxWidth: 620, margin: 0 }}>
            Three quiet steps. Then the desk runs on its own.
          </h2>
        </div>
        <div className="mono hide-mobile" style={{ fontSize: 11.5, color: 'var(--ink-muted)', display: 'flex', alignItems: 'center', gap: 8 }}>
          <span className="dot" style={{ background: '#3aa776', width: 6, height: 6 }} /> pipeline · always-on
        </div>
      </div>
      <div className="lp-grid-3">
        <StepCard n="01" title="Follow" sub="Choose the finance channels you already trust.">
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            <ChannelRow name="Wealthion" kind="Macro" freq="3 new this week" accent="gold" />
            <ChannelRow name="Forward Guidance" kind="Rates" freq="1 new" accent="bronze" />
            <ChannelRow name="Macro Voices" kind="Long-form" freq="2 new" accent="cool" />
            <button style={{
              border: '1px dashed var(--border-warm)', background: 'transparent',
              color: 'var(--brand-bronze)', padding: '8px 12px', borderRadius: 10,
              fontSize: 12, fontWeight: 600, cursor: 'pointer',
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
            }}>
              <Ico name="plus" size={12} strokeWidth={2.2} /> Add channel
            </button>
          </div>
        </StepCard>

        <StepCard n="02" title="Analyze" sub="Every new video becomes structured claims, assets, stance, evidence, hype, speaker, and time horizon.">
          <ClaimCard
            claim="Semis are priced for perfection on AI capex — every hyperscaler must keep guiding higher."
            speaker="Jim Bianco"
            channel="Forward Guidance"
            stance="bearish"
            conviction={3}
            asset="SOX"
            horizon="3–6 mo"
            evidence={5}
            timestamp="24:18"
          />
        </StepCard>

        <StepCard n="03" title="Surface" sub="Your daily brief, Today's Diff, theme rotation, and tracked-question answers show what changed in the narrative — without watching everything.">
          <TrackedQuestion
            q="Bearish on semis this week?"
            newCount={2}
            since="today"
            preview={[
              { stance: 'bearish', speaker: 'Bianco', line: 'AI capex priced for perfection.' },
              { stance: 'mixed',   speaker: 'Alden',  line: 'Bullish demand, cautious multiple.' },
            ]}
          />
        </StepCard>
      </div>
    </section>
  );
}

function StepCard({ n, title, sub, children }) {
  return (
    <div className="card" style={{ padding: 22, display: 'flex', flexDirection: 'column', gap: 14, background: '#fff' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        <span className="mono" style={{ fontSize: 12, color: 'var(--brand-bronze)', letterSpacing: '0.1em' }}>{n}</span>
        <span style={{ flex: 1, height: 1, background: 'var(--border-warm)' }} />
        <span style={{ fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', fontWeight: 600, color: 'var(--ink-muted)' }}>
          step
        </span>
      </div>
      <div>
        <h3 className="h-card" style={{ fontSize: 22, margin: '0 0 6px', fontFamily: 'var(--font-serif)', fontWeight: 400, letterSpacing: '-0.01em' }}>{title}</h3>
        <p className="body-sm" style={{ margin: 0 }}>{sub}</p>
      </div>
      <div>{children}</div>
    </div>
  );
}

window.Landing = Landing;
