// Masthead & hero

const { useEffect, useState, useRef, useLayoutEffect } = React;

function useReveal(threshold = 0.12) {
  const ref = useRef(null);
  const [seen, setSeen] = useState(false);
  useEffect(() => {
    if (!ref.current) return;
    const io = new IntersectionObserver((es) => es.forEach(e => { if (e.isIntersecting) { setSeen(true); io.disconnect(); } }), { threshold });
    io.observe(ref.current);
    return () => io.disconnect();
  }, [threshold]);
  return [ref, seen];
}

// Kinetic digit roller: scrolls through digits and lands on target
function KineticDigit({ target, delay = 0, size = 120 }) {
  const ref = useRef(null);
  const [pos, setPos] = useState(0);
  useEffect(() => {
    const io = new IntersectionObserver((es) => {
      es.forEach(e => {
        if (e.isIntersecting) {
          setTimeout(() => setPos(target + 20), delay); // spin past then land
          setTimeout(() => setPos(target), delay + 1400);
          io.disconnect();
        }
      });
    }, { threshold: 0.4 });
    if (ref.current) io.observe(ref.current);
    return () => io.disconnect();
  }, [target, delay]);
  const digits = Array.from({ length: pos + 2 }, (_, i) => i % 10);
  return (
    <span ref={ref} className="kinetic-digit" style={{ fontSize: size, lineHeight: 1 }}>
      <span className="inner" style={{ transform: `translateY(-${pos}em)`, transition: 'transform 1.4s cubic-bezier(.77,0,.18,1)' }}>
        {digits.map((d, i) => <span key={i} style={{ height: '1em', display: 'block' }}>{d}</span>)}
      </span>
    </span>
  );
}

function Counter({ to = 171, duration = 1600 }) {
  const ref = useRef(null);
  const [v, setV] = useState(0);
  useEffect(() => {
    const io = new IntersectionObserver((es) => es.forEach(e => {
      if (e.isIntersecting) {
        const start = performance.now();
        const step = (t) => {
          const p = Math.min(1, (t - start) / duration);
          const eased = 1 - Math.pow(1 - p, 3);
          setV(Math.floor(eased * to));
          if (p < 1) requestAnimationFrame(step);
          else setV(to);
        };
        requestAnimationFrame(step);
        io.disconnect();
      }
    }), { threshold: 0.5 });
    if (ref.current) io.observe(ref.current);
    return () => io.disconnect();
  }, [to, duration]);
  return <span ref={ref}>{v}</span>;
}

function Wordmark({ light }) {
  return (
    <a href="#" onClick={(e) => e.preventDefault()} style={{ display: 'inline-flex', alignItems: 'baseline', textDecoration: 'none', color: light ? 'var(--bg)' : 'var(--ink)' }}>
      <span className="serif" style={{ fontWeight: 700, fontSize: 24, letterSpacing: '-0.02em' }}>grnted</span>
      <span style={{ color: 'var(--rust)', fontWeight: 700, fontSize: 15, marginLeft: 2 }}>.co</span>
    </a>
  );
}

function Nav() {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const f = () => setScrolled(window.scrollY > 60);
    window.addEventListener('scroll', f);
    return () => window.removeEventListener('scroll', f);
  }, []);
  return (
    <div style={{
      position: 'fixed', top: 0, left: 0, right: 0, zIndex: 40,
      padding: scrolled ? '12px 32px' : '22px 32px',
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      background: scrolled ? 'rgba(247,245,241,.92)' : 'transparent',
      backdropFilter: scrolled ? 'blur(14px) saturate(140%)' : 'none',
      WebkitBackdropFilter: scrolled ? 'blur(14px) saturate(140%)' : 'none',
      borderBottom: scrolled ? '1px solid var(--rule)' : '1px solid transparent',
      transition: 'all .4s cubic-bezier(.2,.7,.2,1)',
    }}>
      <Wordmark />
      <div style={{ display: 'flex', gap: 28, alignItems: 'center', fontSize: 13.5 }}>
        <a href="#library" style={{ color: 'var(--text)', textDecoration: 'none' }}>Library</a>
        <a href="#services" style={{ color: 'var(--text)', textDecoration: 'none' }}>Services</a>
        <a href="#about" style={{ color: 'var(--text)', textDecoration: 'none' }}>About</a>
        <a href="#contact" className="btn" style={{ padding: '10px 16px', fontSize: 12.5 }}>
          Request a scan <span className="arrow">→</span>
        </a>
      </div>
    </div>
  );
}

// Masthead hero — big newspaper cover
function Masthead() {
  const [mounted, setMounted] = useState(false);
  useEffect(() => { const t = setTimeout(() => setMounted(true), 80); return () => clearTimeout(t); }, []);

  return (
    <section style={{ position: 'relative', padding: '120px 32px 0', zIndex: 3 }}>
      <div style={{ maxWidth: 1440, margin: '0 auto' }}>
        {/* Top dateline */}
        <div className="dateline">
          <span>Vol. 01 · No. 171</span>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 0 }}>
            Salem<span className="dot" />Portland<span className="dot" />Bend<span className="dot" />Coos Bay
          </span>
          <span>Spring 2026 · Oregon</span>
        </div>

        {/* Eyebrow strip */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 18, marginBottom: 26, fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '.14em', textTransform: 'uppercase', color: 'var(--muted)' }}>
          <span>The broadsheet for Oregon public grants</span>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8, color: 'var(--rust)' }}>
            <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--rust)' }} className="pulse" />
            Maintained weekly · Last edition Apr 18
          </span>
        </div>

        {/* Huge masthead title */}
        <h1 className="serif masthead-title" style={{
          margin: 0, fontWeight: 700, letterSpacing: '-0.055em', lineHeight: .82,
          fontSize: 'clamp(72px, 20vw, 340px)', color: 'var(--ink)',
          fontStyle: 'italic',
        }}>
          <span className={`wipe ${mounted ? 'in' : ''}`} style={{ display: 'inline-block', animationDelay: '.1s' }}>Granted</span>
          <span className="serif" style={{ fontStyle: 'italic', fontWeight: 400, color: 'var(--rust)', fontSize: '.22em', verticalAlign: 'top', marginLeft: '.1em' }}>.</span>
        </h1>

        {/* Underline rules */}
        <div className="draw-rule" style={{ marginTop: 12, borderTop: '1px solid var(--ink)' }} />
        <div className="draw-rule" style={{ marginTop: 3, borderTop: '3px solid var(--ink)', animationDelay: '.2s' }} />

        {/* Hero grid below masthead */}
        <div className="hero-grid" style={{
          display: 'grid', gridTemplateColumns: '1fr 340px', gap: 48,
          marginTop: 56, alignItems: 'start',
        }}>
          {/* Left: headline + lede */}
          <div>
            <div style={{ marginBottom: 28, display: 'flex', alignItems: 'center', gap: 14 }}>
              <span style={{ width: 36, height: 1, background: 'var(--rust)' }} />
              <span className="eyebrow" style={{ color: 'var(--rust)' }}>Lead story · Consider it grnted</span>
            </div>

            <h2 className={`serif wipe ${mounted ? 'in' : ''}`} style={{
              margin: '0 0 28px', animationDelay: '.5s',
              fontSize: 'clamp(40px, 5.5vw, 80px)', lineHeight: 1.02, letterSpacing: '-0.025em', fontWeight: 500,
              color: 'var(--ink)', textWrap: 'pretty',
            }}>
              Every grant your <span style={{ fontStyle: 'italic', color: 'var(--rust)', fontWeight: 400 }}>Oregon agency</span> qualifies for, <span style={{ fontStyle: 'italic', fontWeight: 400 }}>under one masthead.</span>
            </h2>

            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 32, marginTop: 40 }} className="two-col">
              <p className="drop-cap" style={{ margin: 0, fontSize: 16.5, lineHeight: 1.65, color: 'var(--text)' }}>
                We maintain a private library of {' '}
                <span className="serif" style={{ fontWeight: 600, fontStyle: 'italic', color: 'var(--rust)' }}>one hundred and seventy-one</span>{' '}
                federal, state, and private grant programs for Oregon public entities — and we use it to find the money your agency qualifies for.
              </p>
              <p className="col-rule" style={{ margin: 0, fontSize: 15.5, lineHeight: 1.65, color: 'var(--muted)' }}>
                Rural school districts, cities, counties, fire districts, water districts, libraries, tribes,
                ports, and special districts. Every eligible dollar, tracked against primary sources and
                refreshed as cycles move. The library is our tool. The work we do for you is what matters.
              </p>
            </div>

            {/* CTAs */}
            <div style={{ marginTop: 48, display: 'flex', gap: 22, alignItems: 'center', flexWrap: 'wrap' }}>
              <a href="#contact" className="btn">Request a scan <span className="arrow">→</span></a>
              <a href="#library" className="btn-ghost">Read the library ↓</a>
            </div>

            {/* Kinetic stat row */}
            <div className="hero-stats" style={{
              marginTop: 72, display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)',
              borderTop: '1px solid var(--ink)', borderBottom: '1px solid var(--ink)',
              padding: '24px 0',
            }}>
              <KineticStat label="Programs tracked" n={171} />
              <KineticStat label="Agencies" n={43} />
              <KineticStat label="Entity types" n={15} />
              <KineticStat label="Oregon-only" n={100} suffix="%" last />
            </div>
          </div>

          {/* Right: vertical program ticker */}
          <aside style={{
            border: '1px solid var(--rule)', background: 'var(--surface)', height: 640,
            position: 'sticky', top: 100, overflow: 'hidden', display: 'flex', flexDirection: 'column',
          }}>
            <div style={{ padding: '18px 20px', borderBottom: '1px solid var(--rule)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <span className="eyebrow" style={{ color: 'var(--ink)' }}>On the wire</span>
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8, fontSize: 11, color: 'var(--rust)', fontFamily: 'var(--mono)', letterSpacing: '.1em' }}>
                <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--rust)' }} className="pulse" />
                LIVE
              </span>
            </div>
            <div style={{ flex: 1, overflow: 'hidden', position: 'relative' }}>
              <div className="ticker-up" style={{ display: 'flex', flexDirection: 'column' }}>
                {[...TICKER, ...TICKER].map((t, i) => (
                  <div key={i} style={{ padding: '14px 20px', borderBottom: '1px dashed var(--rule)' }}>
                    <div className="eyebrow" style={{ fontSize: 9.5, color: 'var(--rust)' }}>{String((i % TICKER.length) + 1).padStart(3, '0')} · TRACKED</div>
                    <div className="serif" style={{ fontSize: 16, fontWeight: 500, marginTop: 4, letterSpacing: '-0.005em' }}>{t}</div>
                  </div>
                ))}
              </div>
              {/* fade top/bottom */}
              <div style={{ position: 'absolute', top: 0, left: 0, right: 0, height: 40, background: 'linear-gradient(to bottom, var(--surface), transparent)', pointerEvents: 'none' }} />
              <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, height: 40, background: 'linear-gradient(to top, var(--surface), transparent)', pointerEvents: 'none' }} />
            </div>
          </aside>
        </div>
      </div>

      {/* Bottom marquee */}
      <div style={{
        marginTop: 96, borderTop: '1px solid var(--ink)', borderBottom: '1px solid var(--ink)',
        background: 'var(--ink)', color: 'var(--bg)', overflow: 'hidden', padding: '18px 0',
      }}>
        <div className="marquee-track" style={{ display: 'flex', gap: 56, whiteSpace: 'nowrap', width: 'fit-content' }}>
          {Array.from({ length: 2 }).flatMap((_, pass) => TICKER.slice(0, 15).map((t, i) => (
            <span key={`${pass}-${i}`} className="serif" style={{ fontSize: 30, letterSpacing: '-0.01em', fontStyle: 'italic', fontWeight: 500, display: 'inline-flex', alignItems: 'center', gap: 56 }}>
              {t}
              <span style={{ color: 'var(--rust-soft)' }}>§</span>
            </span>
          )))}
        </div>
      </div>
    </section>
  );
}

function KineticStat({ label, n, suffix = '', last }) {
  return (
    <div style={{ padding: '0 24px', borderRight: last ? 'none' : '1px solid var(--rule)' }}>
      <div className="eyebrow" style={{ fontSize: 10 }}>{label}</div>
      <div className="serif" style={{ fontSize: 64, lineHeight: 1, fontWeight: 500, letterSpacing: '-0.03em', color: 'var(--ink)', marginTop: 8, fontStyle: 'italic' }}>
        <Counter to={n} />{suffix}
      </div>
    </div>
  );
}

Object.assign(window, { useReveal, Counter, KineticDigit, Wordmark, Nav, Masthead });
