// sections.jsx — Header, Hero, Apps, Values + shared helpers
const { useState: useS, useEffect: useE, useRef: useR } = React;

/* ——— Magnetic wrapper ——— */
function Magnetic({ children, strength = 0.4, style, ...rest }) {
  const ref = useR(null);
  const onMove = (e) => {
    const el = ref.current; if (!el) return;
    const r = el.getBoundingClientRect();
    const x = (e.clientX - (r.left + r.width / 2)) * strength;
    const y = (e.clientY - (r.top + r.height / 2)) * strength;
    el.style.transform = `translate(${x}px, ${y}px)`;
  };
  const reset = () => { if (ref.current) ref.current.style.transform = 'translate(0,0)'; };
  return (
    <div ref={ref} onPointerMove={onMove} onPointerLeave={reset}
      style={{ transition: 'transform .35s cubic-bezier(0.16,1,0.3,1)', ...style }} {...rest}>
      {children}
    </div>
  );
}

/* ——— scroll reveal hook (observes [data-reveal]) ——— */
function useReveal() {
  useE(() => {
    const els = document.querySelectorAll('[data-reveal]');
    const io = new IntersectionObserver((entries) => {
      entries.forEach((en) => {
        if (en.isIntersecting) { en.target.classList.add('in'); io.unobserve(en.target); }
      });
    }, { threshold: 0.15, rootMargin: '0px 0px -8% 0px' });
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  }, []);
}

/* ——— Breath Pulse ——— */
function BreathePulse() {
  return (
    <>
      <div aria-hidden="true" style={{
        position: 'absolute', top: '44%', left: '30%',
        transform: 'translate(-50%,-50%)',
        width: 580, height: 580, borderRadius: '50%',
        pointerEvents: 'none', zIndex: 0,
        background: 'radial-gradient(circle, rgba(var(--glow-a),0.26) 0%, rgba(var(--glow-a),0.08) 44%, transparent 70%)',
        animation: 'breathe 9s ease-in-out -6s infinite',
      }} />
      <style>{`
        @keyframes breathe {
          0%,100% { transform: translate(-50%,-50%) scale(0.90); opacity: 0.60; }
          50%      { transform: translate(-50%,-50%) scale(1.15); opacity: 1; }
        }
      `}</style>
    </>
  );
}

/* ——— Count-Up Stat ——— */
function CountUpStat({ value, suffix, decimals = 0 }) {
  const [disp, setDisp] = useS(0);
  const ref = useR(null);
  useE(() => {
    const el = ref.current; if (!el) return;
    const io = new IntersectionObserver(([entry]) => {
      if (!entry.isIntersecting) return;
      io.disconnect();
      let start = null;
      const dur = 1800;
      const step = (ts) => {
        if (!start) start = ts;
        const p    = Math.min((ts - start) / dur, 1);
        const ease = 1 - Math.pow(1 - p, 3);
        setDisp(parseFloat((ease * value).toFixed(decimals)));
        if (p < 1) requestAnimationFrame(step);
        else setDisp(value);
      };
      requestAnimationFrame(step);
    }, { threshold: 0.5 });
    io.observe(el);
    return () => io.disconnect();
  }, [value, decimals]);
  return <span ref={ref}>{disp.toFixed(decimals)}{suffix}</span>;
}

/* ——— Header ——— */
function Header() {
  const [scrolled, setScrolled] = useS(false);
  const [menu, setMenu] = useS(false);
  useE(() => {
    const onScroll = () => setScrolled(window.scrollY > 40);
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  const links = [
    { label: 'About', href: '#about' },
    { label: 'Philosophy', href: '#philosophy' },
    { label: 'Products', href: '#products' },
    { label: 'Support', href: '#support' },
  ];
  const go = (e, href) => {
    e.preventDefault(); setMenu(false);
    const el = document.querySelector(href);
    if (el) window.scrollTo({ top: el.offsetTop - 80, behavior: 'smooth' });
  };
  return (
    <header style={{ position: 'fixed', top: 0, left: 0, right: 0, zIndex: 60,
      transition: 'all .4s ease',
      padding: scrolled ? '14px 0' : '26px 0',
      background: scrolled ? 'rgba(24,23,30,0.7)' : 'transparent',
      backdropFilter: scrolled ? 'blur(14px)' : 'none',
      borderBottom: scrolled ? '1px solid var(--border)' : '1px solid transparent' }}>
      <div style={{ maxWidth: 1240, margin: '0 auto', padding: '0 32px',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <a href="#top" onClick={(e) => go(e, '#top')} style={{ display: 'flex', alignItems: 'center', gap: 11,
          textDecoration: 'none', color: 'var(--text)' }}>
          <img src="assets/logo.png" alt="" style={{ width: 30, height: 30,
            borderRadius: 9, objectFit: 'cover', border: '1px solid var(--border)' }} />
          <span style={{ fontWeight: 700, letterSpacing: '0.16em', fontSize: 16 }}>SOUL STUDIO</span>
        </a>

        <nav className="nav-desk" style={{ display: 'flex', alignItems: 'center', gap: 38 }}>
          {links.map((l) => (
            <a key={l.label} href={l.href} onClick={(e) => go(e, l.href)} className="nav-link"
              style={{ fontSize: 13, letterSpacing: '0.14em', textTransform: 'uppercase',
                color: 'var(--muted)', textDecoration: 'none', transition: 'color .2s',
                padding: '11px 0', minHeight: 44, display: 'inline-flex', alignItems: 'center' }}>
              {l.label}
            </a>
          ))}
          <Magnetic strength={0.3}>
            <a href="#support" onClick={(e) => go(e, '#support')} style={{ display: 'inline-block',
              padding: '10px 20px', borderRadius: 999, fontSize: 13, fontWeight: 600,
              letterSpacing: '0.06em', textDecoration: 'none', color: 'var(--bg)',
              background: 'var(--primary)' }}>Get in touch</a>
          </Magnetic>
        </nav>

        <button className="nav-burger" onClick={() => setMenu(!menu)} aria-label="Menu"
          style={{ display: 'none', flexDirection: 'column', gap: 5, background: 'none',
            border: 'none', cursor: 'pointer', padding: 6 }}>
          <span style={{ width: 24, height: 1.5, background: 'var(--text)',
            transition: '.3s', transform: menu ? 'rotate(45deg) translateY(4.5px)' : 'none' }} />
          <span style={{ width: 24, height: 1.5, background: 'var(--text)',
            transition: '.3s', opacity: menu ? 0 : 1 }} />
          <span style={{ width: 24, height: 1.5, background: 'var(--text)',
            transition: '.3s', transform: menu ? 'rotate(-45deg) translateY(-4.5px)' : 'none' }} />
        </button>
      </div>

      {/* mobile menu */}
      <div style={{ position: 'fixed', inset: 0, top: 0, zIndex: -1,
        background: 'linear-gradient(160deg, var(--mauve), var(--bg-deep))',
        display: menu ? 'flex' : 'none', flexDirection: 'column', alignItems: 'center',
        justifyContent: 'center', gap: 28 }}>
        {links.map((l) => (
          <a key={l.label} href={l.href} onClick={(e) => go(e, l.href)}
            style={{ fontSize: 32, color: 'var(--text)', textDecoration: 'none',
              fontFamily: "'Newsreader', serif" }}>{l.label}</a>
        ))}
      </div>

      <style>{`
        .nav-link:hover { color: var(--text) !important; }
        @media (max-width: 860px) {
          .nav-desk { display: none !important; }
          .nav-burger { display: flex !important; }
        }
      `}</style>
    </header>
  );
}

/* ——— Hero ——— */
function Hero() {
  const phoneWrap = useR(null);
  useE(() => {
    const id = requestAnimationFrame(() => {
      const t = document.querySelector('.hero-title');
      if (t) t.classList.add('lit');
    });
    return () => cancelAnimationFrame(id);
  }, []);
  useE(() => {
    const onMove = (e) => {
      const el = phoneWrap.current; if (!el) return;
      const x = (e.clientX / window.innerWidth - 0.5);
      const y = (e.clientY / window.innerHeight - 0.5);
      el.style.transform = `rotateY(${x * 10}deg) rotateX(${-y * 8}deg) translateY(var(--floaty,0px))`;
    };
    window.addEventListener('pointermove', onMove);
    return () => window.removeEventListener('pointermove', onMove);
  }, []);

  return (
    <section id="top" style={{ position: 'relative', minHeight: '100vh', display: 'flex',
      alignItems: 'center', padding: '120px 32px 70px' }}>
      <BreathePulse />
      <img src="assets/logo.png" aria-hidden="true" style={{
        position: 'absolute', top: '50%', left: '14%',
        transform: 'translate(-50%,-50%)',
        width: 500, height: 500, borderRadius: 100, objectFit: 'cover',
        opacity: 0.04, filter: 'blur(10px)', pointerEvents: 'none', zIndex: 0,
      }} />
      <div style={{ maxWidth: 1240, margin: '0 auto', width: '100%', position: 'relative', zIndex: 1,
        display: 'grid',
        gridTemplateColumns: 'minmax(0,1.05fr) minmax(0,0.95fr)', gap: 40, alignItems: 'center' }}
        className="hero-grid">
        {/* left */}
        <div>
          <h1 className="hero-title font-sans" style={{ fontSize: 'clamp(2.6rem, 5.4vw, 5rem)', lineHeight: 1.05,
            letterSpacing: '-0.03em', fontWeight: 700, color: 'var(--text)', marginBottom: 28 }}>
            <span className="line"><span className="word" style={{ '--wd': '0ms' }}>Calm apps</span></span>
            <span className="line font-serif" style={{ fontWeight: 400, fontStyle: 'italic',
              color: 'var(--primary)' }}><span className="word" style={{ '--wd': '90ms' }}>for a quieter</span></span>
            <span className="line"><span className="word" style={{ '--wd': '180ms' }}>mind.</span></span>
          </h1>

          <p className="reveal in" style={{ maxWidth: 440, marginTop: 26, fontSize: 17,
            lineHeight: 1.65, color: 'var(--muted)', transitionDelay: '.35s' }}>
            Soul Studio creates calm digital companions for inner life, reflection,
            and sustainable routines.
          </p>

          <p className="reveal in" style={{ maxWidth: 440, marginTop: 14, fontSize: 14.5,
            lineHeight: 1.65, color: 'var(--muted)', opacity: 0.8, transitionDelay: '.4s' }}>
            Designed to reduce noise, increase intention, and help people return
            to what matters each day.
          </p>

          <div className="reveal in" style={{ display: 'flex', gap: 14, marginTop: 34,
            flexWrap: 'wrap', transitionDelay: '.45s' }}>
            <Magnetic strength={0.35}>
              <a href="#products" onClick={(e) => { e.preventDefault();
                window.scrollTo({ top: document.querySelector('#products').offsetTop - 80, behavior: 'smooth' }); }}
                style={{ display: 'inline-flex', alignItems: 'center', gap: 10, padding: '15px 28px',
                  borderRadius: 999, background: 'var(--primary)', color: 'var(--bg)',
                  fontWeight: 600, fontSize: 15, textDecoration: 'none' }}>
                Explore our products →
              </a>
            </Magnetic>
            <a href="#philosophy" onClick={(e) => { e.preventDefault();
              window.scrollTo({ top: document.querySelector('#philosophy').offsetTop - 80, behavior: 'smooth' }); }}
              style={{ display: 'inline-flex', alignItems: 'center', padding: '15px 26px',
                borderRadius: 999, border: '1px solid var(--border)', color: 'var(--text)',
                fontWeight: 500, fontSize: 15, textDecoration: 'none',
                background: 'rgba(255,255,255,0.06)' }}>
              Our philosophy
            </a>
          </div>

          <div className="reveal in" style={{ display: 'flex', gap: 30, marginTop: 46,
            transitionDelay: '.55s' }}>
            {[
              { value: 5.0,  suffix: '★',  dec: 1, label: 'App Store rating' },
              { value: 1000, suffix: '+',  dec: 0, label: 'Users' },
            ].map((s) => (
              <div key={s.label}>
                <div className="font-serif" style={{ fontSize: 26, color: 'var(--text)' }}>
                  <CountUpStat value={s.value} suffix={s.suffix} decimals={s.dec} />
                </div>
                <div style={{ fontSize: 11.5, color: 'var(--muted)', marginTop: 2 }}>{s.label}</div>
              </div>
            ))}
          </div>
        </div>

        {/* right — floating phone */}
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', perspective: 1200 }}>
          <div className="reveal in" style={{ display: 'inline-flex', alignItems: 'center', gap: 9,
            padding: '7px 15px', borderRadius: 999, marginBottom: 22,
            border: '1px solid var(--border)', background: 'rgba(255,255,255,0.03)' }}>
            <span style={{ width: 7, height: 7, borderRadius: '50%', background: '#7fce9b',
              boxShadow: '0 0 10px #7fce9b' }} />
            <span className="font-mono" style={{ fontSize: 11, letterSpacing: '0.16em',
              color: 'var(--muted)' }}>BEGIN IS LIVE ON iOS &amp; ANDROID</span>
          </div>
          <div ref={phoneWrap} className="phone-float"
            style={{ transformStyle: 'preserve-3d', transition: 'transform .2s ease-out' }}>
            <BeginPhone />
          </div>
        </div>
      </div>

      {/* scroll cue */}
      <div className="scroll-cue" style={{ position: 'absolute', bottom: 28, left: '50%', transform: 'translateX(-50%)',
        display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8 }}>
        <span className="font-mono" style={{ fontSize: 10, letterSpacing: '0.25em',
          color: 'var(--muted)' }}>SCROLL</span>
        <span style={{ width: 1, height: 36, background: 'linear-gradient(var(--muted), transparent)',
          animation: 'scrollPulse 2s ease-in-out infinite' }} />
      </div>

      <style>{`
        .line { display: block; white-space: nowrap; }
        .word { display: inline-block; opacity: 1; transform: none; }
        @media (prefers-reduced-motion: no-preference) {
          .hero-title.lit .word { animation: wordUp .9s cubic-bezier(0.16,1,0.3,1) var(--wd,0ms) both; }
        }
        @keyframes wordUp { from { opacity: 0; transform: translateY(28px); } to { opacity: 1; transform: none; } }
        .phone-float { animation: floaty 5.5s ease-in-out infinite; }
        @keyframes floaty { 0%,100% { --floaty: 0px; transform: translateY(0); }
          50% { transform: translateY(-13px); } }
        @keyframes scrollPulse { 0%,100% { opacity: .3; } 50% { opacity: 1; } }
        @media (max-width: 920px) {
          .hero-grid { grid-template-columns: 1fr !important; }
          .hero-grid > div:last-child { order: -1; margin-bottom: 10px; }
          .scroll-cue { display: none !important; }
        }
      `}</style>
    </section>
  );
}

window.Magnetic = Magnetic;
window.useReveal = useReveal;
window.Header = Header;
window.Hero = Hero;
