// Sections 1–4: Hero, Problem, Day N, Reports

// ─── Section 1 — Hero ─────────────────────────────────────────────
function Hero() {
  const [ref, p] = useScrollProgress();
  const [mounted, setMounted] = useState(false);
  useEffect(() => { setMounted(true); }, []);

  // gentle parallax on aurora
  const auroraY = lerp(0, -120, p);
  const auroraOpacity = 1 - smoothstep(0, 0.6, p) * 0.6;

  const scrollToCTA = (e) => {
    e.preventDefault();
    const el = document.getElementById('cta');
    if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
  };

  return (
    <section ref={ref} className="hero" style={{ position: 'relative', minHeight: '100vh', display: 'flex', alignItems: 'center', overflow: 'hidden' }}>
      <div className="hero-aurora" style={{ transform: `translateY(${auroraY}px)`, opacity: auroraOpacity }} />
      {/* Ambient grid */}
      <svg style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', opacity: 0.5, pointerEvents: 'none' }}>
        <defs>
          <pattern id="grid" width="64" height="64" patternUnits="userSpaceOnUse">
            <path d="M 64 0 L 0 0 0 64" fill="none" stroke="rgba(255,255,255,0.025)" strokeWidth="1" />
          </pattern>
          <radialGradient id="gridFade" cx="50%" cy="50%" r="60%">
            <stop offset="0%" stopColor="white" stopOpacity="1" />
            <stop offset="100%" stopColor="white" stopOpacity="0" />
          </radialGradient>
          <mask id="gridMask">
            <rect width="100%" height="100%" fill="url(#gridFade)" />
          </mask>
        </defs>
        <rect width="100%" height="100%" fill="url(#grid)" mask="url(#gridMask)" />
      </svg>

      <div className="container" style={{ position: 'relative', zIndex: 2, width: '100%' }}>
        <div style={{ maxWidth: 940 }}>
          <div className={`reveal ${mounted ? 'in' : ''}`} style={{ transitionDelay: '120ms', marginBottom: 28 }}>
            <span className="eyebrow">
              <span style={{ display: 'inline-block', width: 6, height: 6, borderRadius: '50%', background: '#00ff88', marginRight: 10, transform: 'translateY(-2px)', boxShadow: '0 0 10px #00ff88' }} />
              Closed beta · Now live
            </span>
          </div>

          <h1 className="display-xl" style={{ margin: '0 0 28px', maxWidth: 1100 }}>
            <StaggerWords text="Recovery," step={70} />
            <br />
            <span style={{ color: 'var(--fg-muted)' }}>
              <StaggerWords text="anchored." delay={140} step={70} />
            </span>
          </h1>

          <Reveal delay={780}>
            <p className="body-lg" style={{ margin: '0 0 44px', maxWidth: 620 }}>
              Your coach between physio appointments. Protocol remembers your full recovery, reads your reports, and knows what day you're on — every day.
            </p>
          </Reveal>

          <Reveal delay={920}>
            <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', alignItems: 'center' }}>
              <a className="btn btn-primary" href="https://app.protocol-ai.net" target="_blank" rel="noopener noreferrer">
                Try the beta <span className="btn-arrow">→</span>
              </a>
              <a className="btn btn-ghost" href="#cta" onClick={scrollToCTA}>
                How it works
              </a>
            </div>
          </Reveal>

          <Reveal delay={1080}>
            <p className="body-sm" style={{ marginTop: 22, color: 'var(--fg-muted)' }}>
              Closed beta · Free during launch · iOS, Android, web
            </p>
          </Reveal>
        </div>
      </div>

      {/* Scroll cue */}
      <div style={{
        position: 'absolute', bottom: 36, left: '50%', transform: 'translateX(-50%)',
        display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 10,
        opacity: 1 - p * 3, transition: 'opacity 0.4s', zIndex: 2
      }}>
        <span className="mono" style={{ fontSize: 11, letterSpacing: '0.2em', color: 'var(--fg-muted)' }}>SCROLL</span>
        <div style={{ width: 1, height: 36, background: 'linear-gradient(180deg, transparent, var(--fg-muted), transparent)' }} />
      </div>
    </section>
  );
}

// ─── Section 2 — The problem ──────────────────────────────────────
function Problem() {
  // Sticky scroll-driven timeline
  const [ref, progress] = useStickyProgress();
  // We render N=42 days. Appointment markers at days 1, 42 (for example: 6 weeks apart)
  const days = 42;
  const appointmentDays = [1, 42];
  const dayWidth = 100 / (days - 1);

  // Cursor walks across timeline with progress
  const cursorPct = lerp(0, 100, progress);
  const cursorDay = Math.round(lerp(1, days, progress));

  return (
    <section className="section" style={{ background: '#000' }}>
      <div ref={ref} style={{ height: '260vh', position: 'relative' }}>
        <div className="sticky-stage">
          <div className="container" style={{ width: '100%' }}>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr', gap: 60 }}>
              <div style={{ maxWidth: 760 }}>
                <Reveal>
                  <p className="eyebrow" style={{ margin: 0, marginBottom: 22 }}>The gap</p>
                </Reveal>
                <h2 className="display-lg" style={{ margin: '0 0 26px' }}>
                  <StaggerWords text="You leave with a printout." step={55} />
                  <br />
                  <span style={{ color: 'var(--fg-muted)' }}>
                    <StaggerWords text="Six weeks until the next appointment." delay={120} step={55} />
                  </span>
                </h2>
                <Reveal delay={300}>
                  <p className="body-lg" style={{ margin: 0, maxWidth: 560 }}>
                    Recovery happens in the days in between. Generic advice doesn't fit your injury. There's no one watching the small things — until they become the big things.
                  </p>
                </Reveal>
              </div>

              {/* Timeline */}
              <div style={{ marginTop: 20 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16, fontSize: 13, color: 'var(--fg-muted)' }} className="mono">
                  <span>APPOINTMENT</span>
                  <span style={{ color: 'var(--accent)' }}>DAY {String(cursorDay).padStart(2, '0')}</span>
                  <span>APPOINTMENT</span>
                </div>

                <div style={{ position: 'relative', height: 96 }}>
                  {/* base line */}
                  <div style={{ position: 'absolute', left: 0, right: 0, top: '50%', height: 1, background: 'var(--line-soft)' }} />

                  {/* appointment markers */}
                  {appointmentDays.map((d) => {
                    const left = ((d - 1) / (days - 1)) * 100;
                    return (
                      <div key={d} style={{ position: 'absolute', left: `${left}%`, top: 0, bottom: 0, transform: 'translateX(-50%)', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center' }}>
                        <div style={{ width: 14, height: 14, borderRadius: '50%', background: '#fafafa', boxShadow: '0 0 0 4px #000, 0 0 0 5px var(--line)' }} />
                        <div style={{ position: 'absolute', top: 'calc(50% + 22px)', fontSize: 11, color: 'var(--fg-dim)', whiteSpace: 'nowrap' }} className="mono">
                          {d === 1 ? 'TODAY' : 'WEEK 6'}
                        </div>
                      </div>
                    );
                  })}

                  {/* tiny day ticks for the empty days */}
                  {Array.from({ length: days }).map((_, i) => {
                    const d = i + 1;
                    if (appointmentDays.includes(d)) return null;
                    const left = (i / (days - 1)) * 100;
                    const reached = d <= cursorDay;
                    return (
                      <div
                        key={d}
                        style={{
                          position: 'absolute',
                          left: `${left}%`,
                          top: '50%',
                          transform: 'translate(-50%, -50%)',
                          width: 2,
                          height: reached ? 12 : 6,
                          background: reached ? 'var(--fg-faint)' : 'var(--line-soft)',
                          transition: 'all 0.4s var(--ease-out)',
                        }}
                      />
                    );
                  })}

                  {/* moving cursor */}
                  <div style={{
                    position: 'absolute',
                    left: `${cursorPct}%`,
                    top: '50%',
                    transform: 'translate(-50%, -50%)',
                    width: 2,
                    height: 60,
                    background: 'var(--accent)',
                    boxShadow: '0 0 14px var(--accent)',
                    transition: 'none',
                  }} />
                  <div style={{
                    position: 'absolute',
                    left: `${cursorPct}%`,
                    top: 'calc(50% - 44px)',
                    transform: 'translateX(-50%)',
                    fontSize: 11,
                    color: 'var(--accent)',
                    whiteSpace: 'nowrap',
                  }} className="mono">
                    YOU ARE HERE
                  </div>
                </div>

                <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 38, fontSize: 13, color: 'var(--fg-muted)' }}>
                  <span>1 visit</span>
                  <span style={{ color: 'var(--fg-faint)' }} className="mono">
                    — {days - 2} days, mostly alone —
                  </span>
                  <span>1 visit</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ─── Section 3 — Day N anchor ─────────────────────────────────────
function DayN() {
  const [ref, progress] = useStickyProgress();
  const day = Math.round(lerp(1, 84, progress));

  // Phase content keyed to scroll position
  const phases = [
    { from: 1, to: 14,  label: 'EARLY',     copy: 'Calm down inflammation. Protect, don\'t prove.' },
    { from: 15, to: 35, label: 'PROGRESS',  copy: 'Restore range. Begin loading. Listen for flare-ups.' },
    { from: 36, to: 60, label: 'STRENGTH',  copy: 'Build force. Tolerate fatigue. Re-introduce stress.' },
    { from: 61, to: 84, label: 'RETURN',    copy: 'Mirror real movement. Confidence under load.' },
  ];
  const active = phases.findIndex((ph) => day >= ph.from && day <= ph.to);
  const phase = phases[Math.max(0, active)];

  return (
    <section className="section" style={{ paddingTop: 0, paddingBottom: 0 }}>
      <div ref={ref} style={{ height: '320vh', position: 'relative' }}>
        <div className="sticky-stage">
          <div className="container" style={{ width: '100%' }}>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr', gap: 36, alignItems: 'center' }}>
              <Reveal>
                <p className="eyebrow" style={{ margin: 0 }}>The central idea · Day N</p>
              </Reveal>

              <h2 className="display-lg" style={{ margin: 0, maxWidth: 880 }}>
                Recovery happens day by day.<br />
                <span style={{ color: 'var(--fg-muted)' }}>So does Protocol.</span>
              </h2>

              {/* Big counter */}
              <div style={{ display: 'flex', alignItems: 'flex-end', gap: 22, marginTop: 12, flexWrap: 'wrap' }}>
                <div style={{ display: 'flex', alignItems: 'baseline', gap: 16 }}>
                  <span className="mono" style={{ fontSize: 14, color: 'var(--fg-muted)', letterSpacing: '0.2em' }}>DAY</span>
                  <span className="day-counter" style={{
                    fontSize: 'clamp(120px, 22vw, 280px)',
                    lineHeight: 0.85,
                    letterSpacing: '-0.06em',
                    fontWeight: 500,
                    color: 'var(--accent)',
                    fontVariantNumeric: 'tabular-nums',
                    textShadow: '0 0 80px rgba(0,255,136,0.25)',
                  }}>
                    {String(day).padStart(2, '0')}
                  </span>
                </div>
                <div style={{ flex: 1, minWidth: 280, paddingBottom: 28 }}>
                  <div style={{ display: 'flex', gap: 10, marginBottom: 14 }}>
                    {phases.map((p, i) => (
                      <div key={p.label} style={{ flex: 1 }}>
                        <div style={{
                          height: 3,
                          background: i <= active ? 'var(--accent)' : 'var(--line-soft)',
                          transition: 'background 0.5s var(--ease-out)',
                        }} />
                        <div className="mono" style={{
                          fontSize: 10,
                          letterSpacing: '0.18em',
                          marginTop: 8,
                          color: i === active ? 'var(--fg)' : 'var(--fg-faint)',
                          transition: 'color 0.4s',
                        }}>{p.label}</div>
                      </div>
                    ))}
                  </div>
                  <p className="body-lg" style={{ margin: 0, color: 'var(--fg)', minHeight: 56 }}>
                    {phase.copy}
                  </p>
                </div>
              </div>

              <Reveal delay={120}>
                <p className="body-lg" style={{ margin: 0, maxWidth: 720, marginTop: 8 }}>
                  Every conversation knows what day you're on. The same injury at Day 5 and Day 50 needs different things — so the coaching is different.
                </p>
              </Reveal>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ─── Section 4 — Reads your reports ───────────────────────────────
function Reports() {
  const [ref, progress] = useStickyProgress();
  // Three stages: 0..0.33 doc, 0.33..0.66 extraction, 0.66..1 coaching
  const stage1 = smoothstep(0.05, 0.4, progress);   // doc visible
  const stage2 = smoothstep(0.3, 0.62, progress);   // extraction lines
  const stage3 = smoothstep(0.55, 0.85, progress);  // coaching message

  // Doc fields & extracted tokens
  const fields = [
    { label: 'Patient', value: '████ ████' },
    { label: 'Diagnosis', value: 'ACL reconstruction, left knee', extract: true, hue: 'ACL reconstruction' },
    { label: 'Procedure', value: 'Hamstring autograft, 2026-04-02', extract: true, hue: 'Hamstring autograft' },
    { label: 'Restrictions', value: 'NWB × 2 wks; ROM 0–90° wk 2–4', extract: true, hue: '0–90°' },
    { label: 'Next visit', value: '6 weeks post-op' },
  ];

  return (
    <section className="section" style={{ paddingTop: 0, paddingBottom: 0 }}>
      <div ref={ref} style={{ height: '320vh', position: 'relative' }}>
        <div className="sticky-stage">
          <div className="container" style={{ width: '100%' }}>
            <div style={{ display: 'grid', gridTemplateColumns: 'minmax(280px, 1fr) minmax(420px, 1.2fr)', gap: 60, alignItems: 'center' }} className="reports-grid">
              {/* LEFT: copy */}
              <div>
                <Reveal>
                  <p className="eyebrow" style={{ margin: 0, marginBottom: 22 }}>Reads your reports</p>
                </Reveal>
                <h2 className="display-md" style={{ margin: '0 0 22px' }}>
                  Upload your discharge summary.<br />
                  <span style={{ color: 'var(--fg-muted)' }}>Protocol reads it.</span>
                </h2>
                <Reveal delay={120}>
                  <p className="body-lg" style={{ margin: 0, maxWidth: 460 }}>
                    Not generic advice. Coaching grounded in what your clinician actually wrote about your specific injury — graft type, restrictions, range targets, the things that matter.
                  </p>
                </Reveal>
                <Reveal delay={220}>
                  <div style={{ display: 'flex', gap: 14, marginTop: 28, flexWrap: 'wrap' }}>
                    {['Reports', 'Scans', 'Treatment plans'].map(t => (
                      <span key={t} className="chip" style={{ fontSize: 13 }}>{t}</span>
                    ))}
                  </div>
                </Reveal>
              </div>

              {/* RIGHT: animated visual */}
              <div style={{ position: 'relative', height: 460 }}>
                {/* Document */}
                <div style={{
                  position: 'absolute',
                  left: 0,
                  top: '50%',
                  transform: `translate(${lerp(0, -60, stage3)}px, calc(-50% + ${lerp(20, 0, stage1)}px)) scale(${lerp(0.96, 0.92, stage3)})`,
                  opacity: stage1 * (1 - stage3 * 0.85),
                  width: 280,
                  background: 'oklch(0.18 0.005 240)',
                  border: '1px solid var(--line)',
                  borderRadius: 12,
                  padding: '22px 22px 26px',
                  boxShadow: '0 30px 80px rgba(0,0,0,0.6)',
                  transition: 'opacity 0.3s',
                }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14, paddingBottom: 12, borderBottom: '1px solid var(--line-soft)' }}>
                    <div className="mono" style={{ fontSize: 10, letterSpacing: '0.18em', color: 'var(--fg-muted)' }}>DISCHARGE.PDF</div>
                    <div style={{ width: 6, height: 6, background: 'var(--accent)', borderRadius: '50%' }} />
                  </div>
                  {fields.map((f, i) => (
                    <div key={i} style={{ marginBottom: 12 }}>
                      <div className="mono" style={{ fontSize: 9, letterSpacing: '0.18em', color: 'var(--fg-faint)', marginBottom: 3 }}>
                        {f.label.toUpperCase()}
                      </div>
                      <div style={{
                        fontSize: 13,
                        color: f.extract ? 'var(--fg)' : 'var(--fg-dim)',
                        background: f.extract && stage2 > 0.4 ? 'rgba(0,255,136,0.08)' : 'transparent',
                        padding: f.extract ? '2px 6px' : 0,
                        margin: f.extract ? '0 -6px' : 0,
                        borderRadius: 4,
                        transition: 'background 0.6s var(--ease-out)',
                      }}>
                        {f.value}
                      </div>
                    </div>
                  ))}
                </div>

                {/* Extraction lines */}
                <svg style={{
                  position: 'absolute',
                  inset: 0,
                  width: '100%',
                  height: '100%',
                  opacity: stage2 * (1 - stage3),
                  pointerEvents: 'none',
                }}>
                  {[0.32, 0.5, 0.68].map((y, i) => (
                    <line
                      key={i}
                      x1="280" y1={`${y * 100}%`}
                      x2={`${lerp(290, 460, stage2)}`} y2={`${lerp(y * 100, 50, stage2)}%`}
                      stroke="var(--accent)"
                      strokeWidth="1"
                      strokeDasharray="3 3"
                      opacity={0.6}
                    />
                  ))}
                </svg>

                {/* Coaching message bubble */}
                <div style={{
                  position: 'absolute',
                  right: 0,
                  top: '50%',
                  transform: `translate(${lerp(40, 0, stage3)}px, -50%) scale(${lerp(0.96, 1, stage3)})`,
                  opacity: stage3,
                  width: 'min(380px, 100%)',
                  transition: 'opacity 0.3s',
                }}>
                  <div className="mono" style={{ fontSize: 10, letterSpacing: '0.18em', color: 'var(--accent)', marginBottom: 10 }}>
                    DAY 04 · COACHING
                  </div>
                  <div style={{
                    background: 'linear-gradient(180deg, rgba(0,255,136,0.06), rgba(0,255,136,0.02))',
                    border: '1px solid rgba(0,255,136,0.25)',
                    borderRadius: 16,
                    padding: '20px 22px',
                    fontSize: 16,
                    lineHeight: 1.55,
                    color: 'var(--fg)',
                  }}>
                    Hamstring graft means we go gentle on knee flexion past 90° this week. You're cleared for 0–90°. Today: heel slides, quad sets, ankle pumps. <span style={{ color: 'var(--fg-muted)' }}>Skip the wall sits — that's a Day 21 thing.</span>
                  </div>
                  <div style={{ marginTop: 10, fontSize: 12, color: 'var(--fg-muted)', display: 'flex', alignItems: 'center', gap: 8 }}>
                    <span style={{ width: 4, height: 4, borderRadius: '50%', background: 'var(--accent-dim)' }} />
                    Grounded in your discharge summary
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <style>{`
        @media (max-width: 860px) {
          .reports-grid {
            grid-template-columns: 1fr !important;
            gap: 30px !important;
          }
        }
      `}</style>
    </section>
  );
}

Object.assign(window, { Hero, Problem, DayN, Reports });
