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

// ─── Reveal on scroll ──────────────────────────────────────────────────────
function Reveal({ children, delay = 0, as: Tag = 'div', className = '', ...rest }) {
  const ref = useRef(null);
  const [shown, setShown] = useState(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            setTimeout(() => setShown(true), delay);
            io.disconnect();
          }
        });
      },
      { threshold: 0.08, rootMargin: '0px 0px -60px 0px' }
    );
    io.observe(el);
    return () => io.disconnect();
  }, [delay]);
  return (
    <Tag ref={ref} className={`reveal ${shown ? 'in' : ''} ${className}`} {...rest}>
      {children}
    </Tag>
  );
}

// ─── Logo mark ─────────────────────────────────────────────────────────────
function LogoMark({ size = 28, color = 'var(--bone)', accent = 'var(--signal)', dot = 'var(--ember)' }) {
  return (
    <svg viewBox="0 0 200 40" height={size} role="img" aria-label="Ansel">
      <text x="0" y="28" fontFamily="Newsreader, serif" fontSize="26" fontWeight="500" letterSpacing="5" fill={color}>ANSEL</text>
      <rect x="126" y="23" width="14" height="2.5" fill={accent} />
      <circle cx="134" cy="14" r="1.6" fill={dot} />
    </svg>
  );
}

// ─── Metadata row — JetBrains Mono segments separated by // ─────────────
function MetaRow({ items, className = '' }) {
  return (
    <div className={`mono ${className}`} style={{ display: 'flex', flexWrap: 'wrap', gap: '14px', rowGap: '6px' }}>
      {items.map((it, i) => (
        <React.Fragment key={i}>
          <span style={{ color: 'var(--parchment)' }}>{it}</span>
          {i < items.length - 1 && <span style={{ color: 'var(--tungsten)' }}>//</span>}
        </React.Fragment>
      ))}
    </div>
  );
}

// ─── Section heading — caption + display headline + optional sub ────────
function SectionHead({ caption, title, sub, align = 'left' }) {
  return (
    <div style={{ textAlign: align, maxWidth: 860 }}>
      <div className="mono" style={{ color: 'var(--ember)', marginBottom: 20 }}>
        <span style={{ color: 'var(--signal)' }}>▸</span> {caption}
      </div>
      <h2 className="display" style={{ fontSize: 'clamp(36px, 5.2vw, 64px)', color: 'var(--bone)' }}>
        {title}
      </h2>
      {sub && (
        <p style={{
          marginTop: 24,
          maxWidth: 640,
          color: 'var(--parchment)',
          fontSize: 17,
          lineHeight: 1.65,
          fontWeight: 300,
          marginLeft: align === 'center' ? 'auto' : undefined,
          marginRight: align === 'center' ? 'auto' : undefined,
        }}>
          {sub}
        </p>
      )}
    </div>
  );
}

// ─── Cinematic placeholder plate — 1:1 / 16:9 etc. ─────────────────────
function Plate({ aspect = '16/9', label, project, children, style = {} }) {
  return (
    <div className="plate" style={{ aspectRatio: aspect, ...style }}>
      <span className="crop tl" />
      <span className="crop bl" />
      <span className="crop br" />
      <span className="corner" />
      {children}
      {label && <span className="label">{label}</span>}
      {project && (
        <div style={{
          position: 'absolute', top: 14, left: 14,
          fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.16em',
          textTransform: 'uppercase', color: 'var(--parchment)', zIndex: 2,
          display: 'flex', gap: 12,
        }}>
          <span style={{ color: 'var(--ember)' }}>●</span>
          <span>{project}</span>
        </div>
      )}
    </div>
  );
}

// ─── Header (sticky) ───────────────────────────────────────────────────
function Header({ onNav }) {
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 40);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  const links = [
    ['Work', 'work'],
    ['Services', 'services'],
    ['Process', 'process'],
    ['Studio', 'studio'],
    ['Journal', 'journal'],
  ];
  return (
    <header style={{
      position: 'fixed', top: 0, left: 0, right: 0, zIndex: 40,
      padding: scrolled ? '14px 0' : '22px 0',
      background: scrolled ? 'rgba(13,13,11,0.78)' : 'transparent',
      backdropFilter: scrolled ? 'blur(14px) saturate(1.1)' : 'none',
      WebkitBackdropFilter: scrolled ? 'blur(14px) saturate(1.1)' : 'none',
      borderBottom: scrolled ? '1px solid var(--border)' : '1px solid transparent',
      transition: 'all .4s cubic-bezier(.2,.6,.2,1)',
    }}>
      <div className="container" style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <a href="#top" onClick={(e) => { e.preventDefault(); onNav('top'); }} aria-label="Ansel — home" style={{ display: 'flex', alignItems: 'center' }}>
          <img src="assets/wordmark.svg" alt="Ansel" style={{ height: 32, display: 'block' }} />
        </a>
        <nav className="desktop-nav" style={{ display: 'flex', alignItems: 'center', gap: 36 }}>
          {links.map(([label, id]) => (
            <a key={id} href={`#${id}`} onClick={(e) => { e.preventDefault(); onNav(id); }}
              style={{ fontSize: 13, color: 'var(--parchment)', fontWeight: 400, transition: 'color .2s' }}
              onMouseEnter={(e) => (e.currentTarget.style.color = 'var(--bone)')}
              onMouseLeave={(e) => (e.currentTarget.style.color = 'var(--parchment)')}
            >{label}</a>
          ))}
          <div style={{ width: 1, height: 16, background: 'var(--tungsten)' }} />
          <span className="mono" style={{ fontSize: 10, display: 'flex', alignItems: 'center', gap: 8 }}>
            <span style={{
              display: 'inline-block', width: 6, height: 6, background: 'var(--signal)',
              boxShadow: '0 0 0 0 rgba(226,6,18,0.5)',
              animation: 'pulse 2.4s infinite',
            }} />
            Accepting briefs — Q2
          </span>
          <a href="#inquiry" onClick={(e) => { e.preventDefault(); onNav('inquiry'); }}
            style={{
              fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.16em', textTransform: 'uppercase',
              padding: '10px 20px', border: '1px solid var(--bone)', color: 'var(--bone)',
              transition: 'background .24s, color .24s',
            }}
            onMouseEnter={(e) => { e.currentTarget.style.background = 'var(--bone)'; e.currentTarget.style.color = 'var(--obsidian)'; }}
            onMouseLeave={(e) => { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = 'var(--bone)'; }}
          >Start a project</a>
        </nav>
        <button className="mobile-nav-btn" onClick={() => setOpen(!open)} aria-label="Menu"
          style={{ display: 'none', width: 32, height: 32, alignItems: 'center', justifyContent: 'center' }}>
          <span style={{ width: 20, height: 1, background: 'var(--bone)', boxShadow: '0 -6px 0 var(--bone), 0 6px 0 var(--bone)' }} />
        </button>
      </div>
      <style>{`
        @keyframes pulse { 0%, 100% { box-shadow: 0 0 0 0 rgba(226,6,18,0.5); } 50% { box-shadow: 0 0 0 6px rgba(226,6,18,0); } }
        @media (max-width: 880px) {
          .desktop-nav { display: none !important; }
          .mobile-nav-btn { display: flex !important; }
        }
      `}</style>
      {open && (
        <div style={{ background: 'var(--obsidian)', borderTop: '1px solid var(--border)' }}>
          <div className="container" style={{ padding: '24px', display: 'flex', flexDirection: 'column', gap: 16 }}>
            {[...links, ['Start a project', 'inquiry']].map(([l, id]) => (
              <a key={id} href={`#${id}`} onClick={(e) => { e.preventDefault(); setOpen(false); onNav(id); }}
                className="display" style={{ fontSize: 28, color: 'var(--bone)' }}>{l}</a>
            ))}
          </div>
        </div>
      )}
    </header>
  );
}

Object.assign(window, { Reveal, LogoMark, MetaRow, SectionHead, Plate, Header });
