// ============================================================
// PROBLEM + FIX + HOW IT WORKS
// ============================================================

const Problem = () => {
  const { t } = useI18n();
  return (
  <section id="problem" style={{ padding: '120px 48px', background: 'var(--ink-2)', position: 'relative' }}>
    <SectionHeader
      eye={t('problem.eyebrow')}
      title={t('problem.title')}
    />
    <div className="problem-grid" style={{
      maxWidth: 1200, margin: '0 auto',
      display: 'grid', gridTemplateColumns: '1.1fr 1fr', gap: 80, alignItems: 'flex-start',
    }}>
      <div style={{
        fontSize: 22, color: 'var(--fg)', lineHeight: 1.45,
        fontFamily: 'RH Phonic', fontWeight: 300, letterSpacing: '-.005em',
      }}>
        <p style={{ margin: '0 0 28px' }}>

          <span style={{ marginLeft: 0, fontSize: 18, color: 'var(--fg-muted)', letterSpacing: '.04em', textTransform: 'uppercase', fontFamily: 'RH Phonic', fontWeight: 500 }}>
          {t('problem.body')}
          </span>
        </p>

      </div>
      <div style={{
        background: 'var(--ink-3)', border: '1px solid var(--border)',
        borderRadius: 12, padding: '32px',
      }}>

        <div style={{
          fontFamily: 'Martina Plantijn', fontStyle: 'italic', fontSize: 24,
          color: 'var(--fg)', lineHeight: 1.35, marginTop: 18,
        }}>
          {t('problem.quote')}
        </div>
        <div style={{ height: 1, background: 'var(--border)', margin: '24px 0' }} />
        <ul style={{ margin: 0, padding: 0, listStyle: 'none', display: 'flex', flexDirection: 'column', gap: 14, fontSize: 14, color: 'var(--fg-muted)', lineHeight: 1.5 }}>
          <li style={{ display: 'flex', gap: 12 }}>
            <span className="material-symbols-rounded" style={{ fontSize: 18, color: 'var(--red-400)' }}>close</span>
            {t('problem.bullet1')}
          </li>
          <li style={{ display: 'flex', gap: 12 }}>
            <span className="material-symbols-rounded" style={{ fontSize: 18, color: 'var(--red-400)' }}>close</span>
            {t('problem.bullet2')}
          </li>
          <li style={{ display: 'flex', gap: 12 }}>
            <span className="material-symbols-rounded" style={{ fontSize: 18, color: 'var(--red-400)' }}>close</span>
            {t('problem.bullet3')}
          </li>
        </ul>
      </div>
    </div>

  </section>
  );
};

const Fix = () => {
  const { t } = useI18n();
  const stageRef = React.useRef(null);
  const videoRef = React.useRef(null);
  const c1Ref = React.useRef(null);
  const c2Ref = React.useRef(null);

  React.useEffect(() => {
    const stage = stageRef.current;
    const video = videoRef.current;
    if (!stage || !video) return;

    // Some servers (Firebase local serve included) don't send Accept-Ranges,
    // which makes <video> non-seekable even after it's fully buffered. Fetch
    // the file ourselves and swap to a blob: URL — those are always seekable.
    let blobUrl = null;
    fetch(video.getAttribute('src') || video.src)
      .then(r => r.blob())
      .then(b => {
        blobUrl = URL.createObjectURL(b);
        video.src = blobUrl;
        video.load();
      })
      .catch(() => {});

    // 'pending' until a capability probe decides whether this browser can
    // scroll-scrub the video (set currentTime per scroll position) or must
    // fall back to playing it once straight through. Old/embedded Chromium
    // (e.g. the Tesla in-car browser) silently fails to seek.
    let mode = 'pending';
    let probed = false;
    let ticking = false;
    let latestProgress = 0;
    let probeTimer = null;
    let io = null;
    let fallbackStarted = false;

    // "Prime" the video — some browsers (notably Safari/iOS) won't render
    // seeked frames until the element has actually been played once.
    const prime = () => {
      const p = video.play();
      if (p && p.then) p.then(() => video.pause()).catch(() => {});
      else { try { video.pause(); } catch {} }
    };

    const applyProgress = () => {
      if (mode === 'scrub') {
        const dur = video.duration;
        if (dur && !isNaN(dur) && isFinite(dur)) {
          const target = latestProgress * dur;
          // Avoid redundant seeks (Safari coalesces and drops frames otherwise).
          if (Math.abs(video.currentTime - target) > 0.005) {
            video.currentTime = target;
          }
        }
      }
      // Fade in both side labels together as the scrub progresses. Runs in
      // every mode so the labels still appear on the fallback path.
      const fadeStart = 0.15;
      const fadeEnd   = 0.55;
      const o = Math.min(1, Math.max(0, (latestProgress - fadeStart) / (fadeEnd - fadeStart)));
      [c1Ref, c2Ref].forEach((r) => {
        if (!r.current) return;
        r.current.style.opacity = o.toFixed(3);
        r.current.style.transform = `translateY(${(1 - o) * 12}px)`;
      });
    };

    const onScroll = () => {
      // Progress is driven by the video's own position passing through the
      // viewport. 0 when the video's top is at the bottom of the viewport
      // (just entering), 1 when its bottom has reached the top (just leaving).
      // The video flows in normal layout, so the next section sits flush
      // beneath it with no empty space at any point.
      const r = video.getBoundingClientRect();
      const vh = window.innerHeight;
      const span = vh + r.height;
      // Multiplier > 1 makes the video reach its final frame earlier — the
      // last X% of scroll past the video just keeps it on the final frame.
      const speed = 1.8;
      latestProgress = Math.min(1, Math.max(0, ((vh - r.top) / Math.max(1, span)) * speed));
      if (ticking) return;
      ticking = true;
      requestAnimationFrame(() => {
        applyProgress();
        ticking = false;
      });
    };

    // Fallback mode: play the video once when the section scrolls into view,
    // then hold on the last frame (no `loop`, so it naturally stays there).
    const startFallback = () => {
      if (fallbackStarted) return;
      fallbackStarted = true;
      if (io) { io.disconnect(); io = null; }
      const p = video.play();
      if (p && p.then) p.catch(() => {});
    };

    const enterFallback = () => {
      if (mode !== 'pending') return;
      mode = 'fallback';
      video.loop = false;
      if (typeof IntersectionObserver === 'function') {
        io = new IntersectionObserver((entries) => {
          if (entries.some(e => e.isIntersecting)) startFallback();
        }, { threshold: 0.25 });
        io.observe(stage);
      } else {
        startFallback();
      }
      applyProgress();
    };

    const enterScrub = () => {
      if (mode !== 'pending') return;
      mode = 'scrub';
      try { video.currentTime = 0; } catch {}
      prime();
      applyProgress();
    };

    // Capability probe: attempt a real seek and see whether it actually lands.
    const clearProbe = () => {
      if (probeTimer != null) { clearTimeout(probeTimer); probeTimer = null; }
      video.removeEventListener('seeked', onProbeSeeked);
    };
    const onProbeSeeked = () => { clearProbe(); enterScrub(); };
    const onProbeTimeout = () => { clearProbe(); enterFallback(); };
    const runProbe = () => {
      if (video.seekable && video.seekable.length === 0) { enterFallback(); return; }
      video.addEventListener('seeked', onProbeSeeked);
      probeTimer = setTimeout(onProbeTimeout, 500);
      try {
        video.currentTime = 0.05;
      } catch (e) {
        clearProbe();
        enterFallback();
      }
    };

    const onLoadedForProbe = () => {
      if (probed || video.readyState < 2) return;
      probed = true;
      video.removeEventListener('loadeddata', onLoadedForProbe);
      video.removeEventListener('canplay', onLoadedForProbe);
      runProbe();
    };

    const onVideoError = () => { if (mode === 'pending') enterFallback(); };

    video.addEventListener('loadeddata', onLoadedForProbe);
    video.addEventListener('canplay', onLoadedForProbe);
    video.addEventListener('error', onVideoError);
    if (video.readyState >= 2) onLoadedForProbe();

    video.load();
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll);
    onScroll();

    return () => {
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onScroll);
      video.removeEventListener('loadeddata', onLoadedForProbe);
      video.removeEventListener('canplay', onLoadedForProbe);
      video.removeEventListener('error', onVideoError);
      video.removeEventListener('seeked', onProbeSeeked);
      if (probeTimer != null) { clearTimeout(probeTimer); probeTimer = null; }
      if (io) { io.disconnect(); io = null; }
      if (blobUrl) URL.revokeObjectURL(blobUrl);
    };
  }, []);

  return (
  <section className="fix-section">
    <div className="fix-text">
      <div style={{ display: 'inline-flex' }}><Eyebrow>{t('fix.eyebrow')}</Eyebrow></div>
      <h2 data-reveal style={{
        fontFamily: 'RH Phonic', fontWeight: 700,
        fontSize: 'clamp(48px,6vw,88px)', lineHeight: .98,
        letterSpacing: '-.025em', textTransform: 'uppercase',
        margin: '24px 0 0',
      }}>
        {t('fix.title.prefix')}<br />{t('fix.title.middle')} <em style={{
          fontFamily: 'Martina Plantijn', fontStyle: 'italic',
          fontWeight: 400, color: 'var(--gold-400)', textTransform: 'none',
          letterSpacing: '-.01em',
        }}>{t('fix.title.accent')}</em> {t('fix.title.suffix')}
      </h2>
      <div data-reveal style={{
        fontFamily: 'Martina Plantijn', fontStyle: 'italic',
        fontSize: 22, color: 'var(--fg-muted)', marginTop: 36,
        maxWidth: 720, marginLeft: 'auto', marginRight: 'auto', lineHeight: 1.5,
      }}>
        {t('fix.body')}
      </div>
      <div style={{
        marginTop: 32, fontSize: 14, letterSpacing: '.22em',
        textTransform: 'uppercase', color: 'var(--gold-400)', fontWeight: 500,
        fontFamily: 'RH Phonic',
      }}>
        {t('fix.tag')}
      </div>
    </div>
    <div className="fix-scroll-stage" ref={stageRef}>
      <div className="fix-pinned">
        <span className="fix-side-label fix-side-label--left" ref={c1Ref}></span>
        <video
          ref={videoRef}
          src="assets3/fix-phone-into-hand.mp4"
          muted
          playsInline
          preload="auto"
          className="fix-app-video"
          aria-hidden="true"
        />
        <span className="fix-side-label fix-side-label--right" ref={c2Ref}>{t('fix.sideLabel')}</span>
      </div>
    </div>
  </section>
  );
};

const Focus = () => {
  const { t } = useI18n();
  return (
  <section id="focus" style={{ padding: '120px 48px', background: 'var(--ink-1)' }}>
    <div style={{ maxWidth: 820, margin: '0 auto', textAlign: 'center' }}>
      <div style={{ display: 'inline-flex' }}><Eyebrow>{t('focus.eyebrow')}</Eyebrow></div>
      <h2 data-reveal style={{
        fontFamily: 'RH Phonic', fontWeight: 700,
        fontSize: 'clamp(48px,6vw,88px)', lineHeight: .98,
        letterSpacing: '-.025em', textTransform: 'uppercase',
        margin: '24px 0 0',
      }}>
        {t('focus.title.prefix')}<br /><em style={{
          fontFamily: 'Martina Plantijn', fontStyle: 'italic',
          fontWeight: 400, color: 'var(--gold-400)', textTransform: 'none',
          letterSpacing: '-.01em',
        }}>{t('focus.title.accent')}</em>
      </h2>
      <div data-reveal style={{
        fontFamily: 'Martina Plantijn', fontStyle: 'italic',
        fontSize: 22, color: 'var(--fg-muted)', marginTop: 36,
        maxWidth: 720, marginLeft: 'auto', marginRight: 'auto', lineHeight: 1.5,
      }}>
        {t('focus.body')}
      </div>
      <div style={{
        marginTop: 32, display: 'inline-flex', alignItems: 'center', gap: 10,
        background: 'var(--ink-3)', border: '1px solid var(--border)',
        borderRadius: 8, padding: '12px 18px',
      }}>
        <span style={{
          width: 6, height: 6, borderRadius: 999, background: 'var(--gold-400)',
          boxShadow: '0 0 12px rgba(196,172,120,.7)',
        }} />
        <span style={{
          fontFamily: 'RH Phonic', fontWeight: 500, fontSize: 12,
          letterSpacing: '.16em', textTransform: 'uppercase', color: 'var(--fg)',
        }}>{t('focus.tag')}</span>
      </div>
    </div>
  </section>
  );
};

const HowItWorks = ({ refEl }) => {
  const { t } = useI18n();
  const steps = [
    {
      n: '01',
      title: t('how.step1.title'),
      body: t('how.step1.body'),
      icon: 'account_balance_wallet',
      visual: 'capital',
    },
    {
      n: '02',
      title: t('how.step2.title'),
      body: t('how.step2.body'),
      icon: 'psychology',
      visual: 'coach',
    },
    {
      n: '03',
      title: t('how.step3.title'),
      body: t('how.step3.body'),
      icon: 'payments',
      visual: 'payout',
    },
  ];

  return (
    <section id="how" ref={refEl} style={{ padding: '120px 48px', background: 'var(--ink-2)' }}>
      <SectionHeader
        eye={t('how.eyebrow')}
        title={<>{t('how.title.line1')}<br />{t('how.title.line2')}</>}
        sub={t('how.sub')}
      />
      <div className="how-grid" style={{ maxWidth: 1200, margin: '0 auto', display: 'flex', flexDirection: 'column', gap: 1, background: 'var(--border)', border: '1px solid var(--border)', borderRadius: 12, overflow: 'hidden' }}>
        {steps.map((s, i) => (
          <div key={s.n} className="how-row" style={{
            background: 'var(--ink-1)', padding: '48px 48px',
            display: 'grid', gridTemplateColumns: '120px 1fr 360px',
            gap: 48, alignItems: 'center',
          }}>
            <div className="how-num" style={{
              fontFamily: 'RH Phonic', fontWeight: 700, fontSize: 96,
              color: 'var(--gold-400)', lineHeight: 1, letterSpacing: '-.02em',
            }}>{s.n}</div>
            <div className="how-text">
              <h3 style={{
                fontFamily: 'RH Phonic', fontWeight: 700,
                fontSize: 28, lineHeight: 1.15, letterSpacing: '-.01em',
                textTransform: 'uppercase', margin: 0,
              }}>{s.title}</h3>
              <div style={{
                fontSize: 16, color: 'var(--fg-muted)', marginTop: 14,
                lineHeight: 1.55, maxWidth: 540,
              }}>{s.body}</div>
            </div>
            <div className="how-visual"><StepVisual kind={s.visual} /></div>
          </div>
        ))}
      </div>
    </section>
  );
};

// Small inline visuals for each "How it works" step
const StepVisual = ({ kind }) => {
  const { t } = useI18n();
  if (kind === 'capital') {
    return (
      <div style={{
        background: 'var(--ink-3)', border: '1px solid var(--border)',
        borderRadius: 8, padding: '20px 22px', fontFamily: 'RH Phonic',
      }}>

        <div style={{
          fontFamily: 'RH Phonic', fontWeight: 500, fontSize: 40,
          color: 'var(--fg)', marginTop: 8, letterSpacing: '-.02em',
          fontVariantNumeric: 'tabular-nums',
        }}>$50,000<span style={{ fontSize: 14, color: 'var(--fg-muted)', marginLeft: 8, letterSpacing: 0 }}>.00</span></div>
        <div style={{ display: 'flex', gap: 6, marginTop: 12, alignItems: 'center' }}>
          <span style={{ width: 6, height: 6, borderRadius: 999, background: 'var(--green-400)' }} />
          <span style={{ fontSize: 11, color: 'var(--green-400)', letterSpacing: '.06em', textTransform: 'uppercase', fontWeight: 500 }}>{t('how.visual.simulated')}</span>
        </div>


      </div>
    );
  }
  if (kind === 'coach') {
    return (
      <div style={{
        background: 'var(--ink-3)', border: '1px solid var(--border)',
        borderRadius: 8, padding: '20px 22px',
      }}>
        <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
          <div style={{
            width: 24, height: 24, borderRadius: 999, background: 'var(--gold-400)',
            display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
          }}>
            <span className="material-symbols-rounded" style={{ fontSize: 14, color: '#000' }}>auto_awesome</span>
          </div>
          <div style={{ fontSize: 11, letterSpacing: '.16em', textTransform: 'uppercase', color: 'var(--gold-400)', fontWeight: 500 }}>{t('how.visual.coach')}</div>
        </div>
        <div style={{
          fontFamily: 'Martina Plantijn', fontStyle: 'italic', fontSize: 16,
          color: 'var(--fg)', marginTop: 16, lineHeight: 1.45,
        }}>
          {t('how.visual.coachQuote')}
        </div>
      </div>
    );
  }
  // payout
  return (
    <div style={{
      background: 'var(--ink-3)', border: '1px solid var(--border)',
      borderRadius: 8, padding: '20px 22px',
    }}>

      <div style={{
        display: 'flex', alignItems: 'baseline', gap: 8, marginTop: 8,
      }}>
        <div style={{
          fontFamily: 'RH Phonic', fontWeight: 500, fontSize: 36,
          color: 'var(--green-400)', letterSpacing: '-.02em',
          fontVariantNumeric: 'tabular-nums',
        }}>+$2,400</div>
        <div style={{ fontSize: 12, color: 'var(--fg-muted)' }}>{t('how.visual.realCash')}</div>
      </div>

      <div style={{ height: 1, background: 'var(--border)', margin: '16px 0' }} />
      <div style={{
        display: 'flex', alignItems: 'center', gap: 8, fontSize: 12,
        color: 'var(--green-400)', fontWeight: 500, letterSpacing: '.04em',
      }}>
        <span className="material-symbols-rounded" style={{ fontSize: 16 }}>task_alt</span>
        {t('how.visual.approved')}
      </div>
    </div>
  );
};

Object.assign(window, { Problem, Fix, Focus, HowItWorks, StepVisual });
