/* ──────────────────────────────────────────────────────────
   Shared utilities: Reveal, CountUp, Logo, Navbar, Footer
   ────────────────────────────────────────────────────────── */
const { useState, useEffect, useRef, useLayoutEffect, useMemo, createContext, useContext } = React;

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

function Reveal({ children, delay = 0, style, as: As = 'div', ...rest }) {
  const [ref, shown] = useReveal();
  return (
    <As ref={ref} className={'reveal' + (shown ? ' in' : '')}
      style={{ transitionDelay: shown ? `${delay}s` : '0s', ...style }} {...rest}>
      {children}
    </As>
  );
}

function CountUp({ value, decimals = 0, prefix = '', suffix = '', duration = 1700 }) {
  const [ref, shown] = useReveal(0.4);
  const [n, setN] = useState(0);
  useEffect(() => {
    if (!shown) return;
    const t0 = performance.now();
    let raf;
    const step = (t) => {
      const k = Math.min((t - t0) / duration, 1);
      const eased = 1 - Math.pow(1 - k, 3);
      setN(value * eased);
      if (k < 1) raf = requestAnimationFrame(step);
    };
    raf = requestAnimationFrame(step);
    return () => cancelAnimationFrame(raf);
  }, [shown, value, duration]);
  return <span ref={ref}>{prefix}{n.toFixed(decimals)}{suffix}</span>;
}

function Logo({ size = 22, variant = 'navy' }) {
  const h = size * 1.7;
  return (
    <span style={{ position:'relative', display:'inline-block', height:h,
      lineHeight:0 }}>
      <img src="assets/matai-logo-navy.png" alt="MATAI Consulting"
        style={{ height:h, width:'auto', display:'block', userSelect:'none',
          opacity: variant === 'light' ? 0 : 1, transition:'opacity .55s ease' }}
        draggable={false} />
      <img src="assets/matai-logo-light.png" alt=""
        aria-hidden="true"
        style={{ position:'absolute', top:0, left:0, height:h, width:'auto',
          display:'block', userSelect:'none', pointerEvents:'none',
          opacity: variant === 'light' ? 1 : 0, transition:'opacity .55s ease' }}
        draggable={false} />
    </span>
  );
}

/* ──────────────────────────────────────────────────────────
   Intro animation — on first visit (per session) the logo appears
   large & centered on a navy field, holds, then flies up + scales
   down into its exact spot in the nav while the field fades to
   reveal the site. Skipped for repeat visits & reduced-motion.
   ────────────────────────────────────────────────────────── */
function IntroAnimation() {
  const SEEN_KEY = 'matai_intro_seen';
  const reduced = typeof window !== 'undefined' && window.matchMedia
    && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
  let alreadySeen = false;
  try { alreadySeen = sessionStorage.getItem(SEEN_KEY) === '1'; } catch (e) {}

  const [active, setActive] = useState(!alreadySeen && !reduced);
  const [step, setStep]   = useState(0);          // 0 enter→1 shown→2 fly→3 land→4 done
  const [fly, setFly]     = useState('scale(1)');
  const bigRef = useRef(null);

  useLayoutEffect(() => {
    if (!active) return;
    try { sessionStorage.setItem(SEEN_KEY, '1'); } catch (e) {}
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    window.scrollTo(0, 0);

    const t = [];
    t.push(setTimeout(() => setStep(1), 40));          // entrance
    t.push(setTimeout(() => {                            // fly to nav (after a longer hold)
      const nav = document.getElementById('nav-logo');
      const big = bigRef.current;
      if (nav && big) {
        const nr = nav.getBoundingClientRect();
        const br = big.getBoundingClientRect();
        const s  = nr.height / br.height;
        const dx = (nr.left + nr.width / 2)  - (br.left + br.width / 2);
        const dy = (nr.top  + nr.height / 2) - (br.top  + br.height / 2);
        setFly(`translate(${dx}px, ${dy}px) scale(${s})`);
      } else {
        setFly('scale(0.28)');
      }
      setStep(2);
    }, 1650));
    t.push(setTimeout(() => setStep(3), 2700));         // fade logo, reveal nav logo
    t.push(setTimeout(() => setStep(4), 3050));         // done
    t.push(setTimeout(() => {                            // unmount + restore scroll
      document.body.style.overflow = prevOverflow;
      setActive(false);
    }, 3090));

    return () => { t.forEach(clearTimeout); document.body.style.overflow = prevOverflow; };
  }, [active]);

  if (!active) return null;

  const wrapTransform = step === 0 ? 'scale(0.92)' : step < 2 ? 'scale(1)' : fly;
  const wrapOpacity   = step === 0 ? 0 : step >= 3 ? 0 : 1;

  // Logo renders at ~5.93× the size value in width (aspect 3.49 × 1.7 height
  // factor). Cap size so the wordmark stays within ~84% of the viewport width.
  const vw = typeof window !== 'undefined' ? window.innerWidth : 1200;
  const introSize = Math.min(72, Math.floor((0.84 * vw) / 5.93));

  return (
    <div aria-hidden style={{
      position:'fixed', inset:0, zIndex:9999,
      display:'flex', alignItems:'center', justifyContent:'center',
      background:'var(--night)',
      opacity: step >= 2 ? 0 : 1,
      transition:'opacity 1s ease .15s',
      pointerEvents: step >= 2 ? 'none' : 'auto',
    }}>
      <div ref={bigRef} style={{
        transformOrigin:'center center',
        transform: wrapTransform,
        opacity: wrapOpacity,
        willChange:'transform, opacity',
        transition: step >= 2
          ? 'transform 1.15s cubic-bezier(.45,0,.18,1), opacity .4s ease'
          : 'transform .7s cubic-bezier(.2,.7,.2,1), opacity .7s ease',
      }}>
        <Logo size={introSize} variant="light" />
      </div>
    </div>
  );
}

/* Eyebrow label — small uppercase */
function Eyebrow({ children, tone = 'ink', style }) {
  const color = tone === 'gold' ? 'var(--gold-deep)'
    : tone === 'ice' ? 'var(--gold-soft)'
    : 'var(--ink-2)';
  return (
    <div style={{ fontFamily:"'Inter',sans-serif", fontSize:'11px', fontWeight:500,
      color, letterSpacing:'0.22em', textTransform:'uppercase', ...style }}>
      {children}
    </div>
  );
}

/* ──────────────────────────────────────────────────────────
   Navbar — fixed, blurs on scroll, adapts to dark sections
   ────────────────────────────────────────────────────────── */
function Navbar() {
  const [scrolled, setScrolled] = useState(false);
  const [onDark, setOnDark] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false);

  useEffect(() => {
    const onScroll = () => {
      setScrolled(window.scrollY > 12);
      // Detect dark section under the navbar by checking each [data-theme="dark"]
      // section's bounding rect — the navbar element itself sits on top of probe
      // points, so elementFromPoint is unreliable. Instead we ask "which themed
      // section is straddling the top of the viewport?" using y=48 as the probe
      // (just below the nav).
      const probeY = 48;
      const sections = document.querySelectorAll('[data-theme]');
      let dark = false;
      for (const s of sections) {
        const r = s.getBoundingClientRect();
        if (r.top <= probeY && r.bottom > probeY) {
          dark = s.getAttribute('data-theme') === 'dark';
          break;
        }
      }
      setOnDark(dark);
    };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll);
    return () => {
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onScroll);
    };
  }, []);

  const links = [
    ['Services', '#services'],
    ['Why Matai', '#why-matai-bento'],
    ['About', '#about'],
  ];

  const inkColor = onDark ? 'rgba(250,246,236,0.78)' : 'var(--ink-2)';
  const inkColorH = onDark ? '#FFFFFF' : 'var(--ink)';

  return (
    <nav style={{
      position:'fixed', top:0, left:0, right:0, zIndex:100,
      padding: window.innerWidth <= 768
        ? (scrolled ? '10px 20px' : '16px 20px')
        : (scrolled ? '14px 40px' : '22px 40px'),
      transition:'padding .3s, background .55s ease, color .55s ease, border-color .55s ease, backdrop-filter .55s ease',
      background: scrolled
        ? (onDark ? 'rgba(10,22,38,0.62)' : 'rgba(242,237,227,0.82)')
        : (onDark ? 'rgba(10,22,38,0.28)' : 'transparent'),
      backdropFilter: (scrolled || onDark) ? 'blur(14px) saturate(1.2)' : 'none',
      WebkitBackdropFilter: (scrolled || onDark) ? 'blur(14px) saturate(1.2)' : 'none',
      borderBottom: scrolled
        ? (onDark ? '1px solid rgba(211,222,232,0.08)' : '1px solid var(--line-2)')
        : '1px solid transparent',
    }}>
      <div style={{ maxWidth:'1320px', margin:'0 auto', display:'flex',
        justifyContent:'space-between', alignItems:'center' }}>
        <a id="nav-logo" href="#hero" style={{ textDecoration:'none', display:'flex',
          transformOrigin:'left center',
          transform: scrolled ? 'scale(0.645)' : 'scale(1)',   // large at top → back to ~base size on scroll
          transition:'transform .4s ease' }}>
          <Logo size={31} variant={onDark ? 'light' : 'navy'} />
        </a>
        {/* Desktop links */}
        <div className="nav-desktop-links" style={{ display:'flex', alignItems:'center', gap:'40px' }}>
          {links.map(([l, href]) => (
            <a key={l} href={href} style={{
              fontFamily:"'Inter',sans-serif", fontSize:'13px', fontWeight:400,
              color: inkColor, letterSpacing:'0.02em', textDecoration:'none',
              transition:'color .2s',
            }}
              onMouseEnter={(e)=>e.currentTarget.style.color=inkColorH}
              onMouseLeave={(e)=>e.currentTarget.style.color=inkColor}>
              {l}
            </a>
          ))}
          <a href="#contact" className="nav-desktop-cta" style={{
            padding:'11px 22px', borderRadius:'100px',
            background: onDark ? 'var(--paper)' : 'var(--ink)',
            color: onDark ? 'var(--ink)' : 'var(--paper)',
            fontFamily:"'Inter',sans-serif", fontSize:'13px', fontWeight:500,
            letterSpacing:'0.02em', textDecoration:'none',
            display:'inline-flex', alignItems:'center', gap:'10px',
            transition:'background .35s, color .35s',
          }}>
            Contact Us <span style={{ fontSize:'14px' }}>→</span>
          </a>
        </div>
        {/* Hamburger */}
        <button className="nav-hamburger" onClick={() => setMenuOpen(o => !o)}
          style={{ display:'none', flexDirection:'column', gap:'5px',
            background:'none', border:'none', cursor:'pointer', padding:'4px' }}>
          {[0,1,2].map(i => (
            <div key={i} style={{ width:'22px', height:'1.5px',
              background: onDark ? 'rgba(250,246,236,0.8)' : 'var(--ink)',
              transition:'all .2s',
              transform: menuOpen ? (i===0 ? 'rotate(45deg) translate(4.5px,4.5px)' : i===2 ? 'rotate(-45deg) translate(4.5px,-4.5px)' : 'scaleX(0)') : 'none',
            }} />
          ))}
        </button>
      </div>
      {/* Mobile menu */}
      {menuOpen && (
        <div className={`mobile-menu${onDark ? ' mobile-menu-dark' : ''}`}>
          {links.map(([l, href]) => (
            <a key={l} href={href} className="mobile-nav-link"
              style={{ color: onDark ? 'rgba(250,246,236,0.78)' : 'var(--ink-2)' }}
              onClick={() => setMenuOpen(false)}>{l}</a>
          ))}
          <a href="#contact" onClick={() => setMenuOpen(false)}
            style={{ marginTop:'12px', display:'inline-flex', alignItems:'center',
              justifyContent:'center', gap:'10px', padding:'13px 24px',
              borderRadius:'100px', textDecoration:'none',
              background: onDark ? 'var(--paper)' : 'var(--ink)',
              color: onDark ? 'var(--ink)' : 'var(--paper)',
              fontFamily:"'Inter',sans-serif", fontWeight:500, fontSize:'14px' }}>
            Contact Us →
          </a>
        </div>
      )}
    </nav>
  );
}

/* ──────────────────────────────────────────────────────────
   Footer
   ────────────────────────────────────────────────────────── */
function Footer() {
  return (
    <footer style={{ padding:'48px 40px 36px', borderTop:'1px solid var(--line)',
      background:'var(--bg)' }}>
      <div style={{ maxWidth:'1320px', margin:'0 auto',
        display:'flex', justifyContent:'space-between', alignItems:'center', gap:'24px',
        flexWrap:'wrap' }}>
        <div style={{ display:'flex', alignItems:'center', gap:'16px' }}>
          <Logo size={18} />
        </div>
        <span style={{ fontFamily:"'Inter',sans-serif", fontSize:'12px', fontWeight:400,
          color:'var(--ink-4)' }}>
          © 2026 MATAI Consulting. All rights reserved.
        </span>
        <div style={{ display:'flex', gap:'24px' }}>
          {['Privacy','Terms'].map(l => (
            <a key={l} href="#" style={{ fontFamily:"'Inter',sans-serif", fontSize:'12px',
              fontWeight:400, color:'var(--ink-3)', textDecoration:'none' }}>{l}</a>
          ))}
        </div>
      </div>
    </footer>
  );
}

/* Share globally for other script files */
function useIsMobile(bp = 768) {
  const [m, setM] = useState(() => window.innerWidth <= bp);
  useEffect(() => {
    const h = () => setM(window.innerWidth <= bp);
    window.addEventListener('resize', h, { passive: true });
    return () => window.removeEventListener('resize', h);
  }, [bp]);
  return m;
}

Object.assign(window, { useReveal, Reveal, CountUp, Logo, Eyebrow, Navbar, Footer, useIsMobile });
