function Nav() {
  const [scrolled, setScrolled] = React.useState(false);
  const [sheetOpen, setSheetOpen] = React.useState(false);
  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 40);
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  // Lock body scroll while the mobile sheet is open — but ONLY if
  // the sheet covers the full viewport. The current floating panel
  // is a small dropdown; locking scroll feels wrong (user can't
  // dismiss by scrolling, and the blur effect is invisible without
  // varied content behind the panel). Skip the lock entirely.
  // React.useEffect(() => { ... }, [sheetOpen]);
  const closeSheet = () => setSheetOpen(false);
  return (
    <nav className={`nav ${sheetOpen ? 'is-menu-open' : ''}`} aria-label="Primary" style={{borderBottomColor: scrolled ? 'var(--border-hair)' : 'transparent'}}>
      <div className="container nav-inner">
        <a href="#main-content" className="nav-logo" aria-label="Krew — back to top">
          <img src="/assets/logo-krew-wordmark.png" alt="Krew" />
        </a>
        {/* Desktop links — hidden on mobile via .nav-links { display: none } */}
        <div className="nav-links">
          <a href="#how" className="underline-on-hover">How it works</a>
          <a href="#capabilities" className="underline-on-hover">What it does</a>
          <a href="#team" className="underline-on-hover">Team</a>
          <a href="#faq" className="underline-on-hover">FAQ</a>
          <a href="#demo" className="btn spark" style={{padding: '10px 14px', fontSize: 12}}>
            Book a demo
            <svg aria-hidden="true" focusable="false" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14M13 5l7 7-7 7"/></svg>
          </a>
        </div>
        {/* Mobile controls — only visible <720px (CSS gates display).
            Just the burger — the CTA lives inside the sheet now to
            keep the floating pill uncluttered. */}
        <div className="nav-mobile">
          <button
            type="button"
            className={`nav-burger ${sheetOpen ? 'is-open' : ''}`}
            aria-label={sheetOpen ? 'Close menu' : 'Open menu'}
            aria-expanded={sheetOpen}
            onClick={() => setSheetOpen(v => !v)}
          >
            <span className="nb-bars" aria-hidden="true">
              <svg width="20" height="14" viewBox="0 0 20 14" xmlns="http://www.w3.org/2000/svg">
                <line className="nb-bar nb-bar-1" x1="1" y1="2" x2="19" y2="2" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
                <line className="nb-bar nb-bar-2" x1="1" y1="7" x2="19" y2="7" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
                <line className="nb-bar nb-bar-3" x1="1" y1="12" x2="19" y2="12" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
              </svg>
            </span>
          </button>
        </div>
      </div>
      {/* Portal scrim + sheet to <body> so they escape the nav's
          containing block. With them inside <nav> (position:fixed),
          fixed-positioned descendants got constrained to the nav's
          rect — the scrim only filled the pill area instead of the
          viewport. */}
      {typeof document !== 'undefined' && ReactDOM.createPortal(
        <React.Fragment>
          {/* Mobile-only scrim that darkens the page behind the menu. */}
          <div
            className={`nav-scrim ${sheetOpen ? 'is-open' : ''}`}
            onClick={closeSheet}
            aria-hidden="true"
          ></div>
          <div className={`nav-sheet ${sheetOpen ? 'is-open' : ''}`} aria-hidden={!sheetOpen}>
            <button
              type="button"
              className="nav-sheet-close"
              aria-label="Close menu"
              onClick={closeSheet}
            >
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round">
                <path d="M6 6l12 12M18 6L6 18" />
              </svg>
            </button>
            <a href="#how" onClick={closeSheet}>How it works</a>
            <a href="#capabilities" onClick={closeSheet}>What it does</a>
            <a href="#team" onClick={closeSheet}>Team</a>
            <a href="#faq" onClick={closeSheet}>FAQ</a>
            <a href="#demo" className="is-cta" onClick={closeSheet}>Book a demo →</a>
            <div className="sheet-foot">Catch it early. Save the shoot.</div>
          </div>
        </React.Fragment>,
        document.body
      )}
    </nav>
  );
}

function Marquee() {
  const items = [
    "On-demand shot metadata", "Meal penalty exposure", "Schedule burndown",
    "Overtime tracking", "Liability gap detection", "Consecutive employment exposure",
    "Reporting error catches", "Interactive charts", "Contract questions",
    "Contact look-up", "Dropbox integration", "Scheduled tasks",
    "Role-based access", "Google Drive integration"
  ];
  const trackRef = React.useRef(null);
  const wrapRef = React.useRef(null);

  React.useEffect(() => {
    const track = trackRef.current;
    const wrap = wrapRef.current;
    if (!track || !wrap) return;

    const SLOW = 40;     // px/sec at rest
    const FAST = 150;    // px/sec on hover
    let speed = SLOW;
    let target = SLOW;
    let x = 0;
    let last = performance.now();
    let halfWidth = track.scrollWidth / 2;
    let raf;

    const onResize = () => { halfWidth = track.scrollWidth / 2; };
    const ro = new ResizeObserver(onResize);
    ro.observe(track);

    const onEnter = () => { target = FAST; };
    const onLeave = () => { target = SLOW; };
    wrap.addEventListener('mouseenter', onEnter);
    wrap.addEventListener('mouseleave', onLeave);

    const tick = (now) => {
      const dt = Math.min(0.05, (now - last) / 1000);
      last = now;
      // ease speed toward target (~600ms time constant)
      speed += (target - speed) * Math.min(1, dt / 0.25);
      x -= speed * dt;
      if (halfWidth > 0) {
        // wrap seamlessly: the track is duplicated, so -halfWidth == 0 visually
        if (x <= -halfWidth) x += halfWidth;
      }
      track.style.transform = `translate3d(${x}px, 0, 0)`;
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);

    return () => {
      cancelAnimationFrame(raf);
      ro.disconnect();
      wrap.removeEventListener('mouseenter', onEnter);
      wrap.removeEventListener('mouseleave', onLeave);
    };
  }, []);

  return (
    <>
      <div className="marquee-prelude">And so much more&hellip;</div>
      <div className="marquee" ref={wrapRef}>
        <div className="marquee-track" ref={trackRef}>
          {[...items, ...items].map((it, i) => (
            <span key={i}><i></i>{it}</span>
          ))}
        </div>
      </div>
    </>
  );
}

function Tweaks({ tweaks, setTweaks, visible }) {
  if (!visible) return null;
  const colors = [
    { name: 'spark', hex: '#FF5405' },
    { name: 'safe', hex: '#3F6E4A' },
    { name: 'reel', hex: '#6B3A1F' },
    { name: 'leader', hex: '#C4A77A' },
    { name: 'ink', hex: '#1C1A18' },
  ];
  return (
    <div className="tweaks-panel">
      <h4>Tweaks <span>live</span></h4>
      <div className="tweak-row">
        <label id="tweak-accent-label">Accent color</label>
        <div className="color-swatches" role="radiogroup" aria-labelledby="tweak-accent-label">
          {colors.map(c => (
            <button key={c.name}
              type="button"
              role="radio"
              aria-checked={tweaks.accent === c.hex}
              aria-label={`Accent color: ${c.name}`}
              style={{background: c.hex}}
              className={tweaks.accent === c.hex ? 'active' : ''}
              onClick={() => setTweaks({...tweaks, accent: c.hex})}
              title={c.name}
            />
          ))}
        </div>
      </div>
      <div className="tweak-row switch-row">
        <label id="tweak-grain-label" style={{marginBottom: 0}}>Paper grain</label>
        <button type="button" role="switch" aria-checked={tweaks.grain} aria-labelledby="tweak-grain-label" className={`switch ${tweaks.grain ? 'on' : ''}`} onClick={() => setTweaks({...tweaks, grain: !tweaks.grain})} />
      </div>
      <div className="tweak-row switch-row">
        <label id="tweak-spark-label" style={{marginBottom: 0}}>Cursor spark</label>
        <button type="button" role="switch" aria-checked={tweaks.spark} aria-labelledby="tweak-spark-label" className={`switch ${tweaks.spark ? 'on' : ''}`} onClick={() => setTweaks({...tweaks, spark: !tweaks.spark})} />
      </div>
      <div className="tweak-row switch-row">
        <label id="tweak-dark-label" style={{marginBottom: 0}}>Dark surface</label>
        <button type="button" role="switch" aria-checked={tweaks.dark} aria-labelledby="tweak-dark-label" className={`switch ${tweaks.dark ? 'on' : ''}`} onClick={() => setTweaks({...tweaks, dark: !tweaks.dark})} />
      </div>
      <div className="tweak-row switch-row">
        <label id="tweak-mobile-label" style={{marginBottom: 0}}>Mobile preview</label>
        <button type="button" role="switch" aria-checked={tweaks.mobilePreview} aria-labelledby="tweak-mobile-label" className={`switch ${tweaks.mobilePreview ? 'on' : ''}`} onClick={() => setTweaks({...tweaks, mobilePreview: !tweaks.mobilePreview})} />
      </div>
    </div>
  );
}

// Cursor click-spark effect
function useClickSpark(enabled) {
  React.useEffect(() => {
    if (!enabled) return;
    const onClick = (e) => {
      const el = document.createElement('div');
      el.className = 'click-spark';
      el.style.left = e.clientX + 'px';
      el.style.top = e.clientY + 'px';
      el.innerHTML = `
        <svg aria-hidden="true" focusable="false" viewBox="0 0 64 64" fill="none" stroke="currentColor" stroke-width="4" stroke-linecap="round">
          <line x1="32" y1="6" x2="32" y2="18"/><line x1="32" y1="46" x2="32" y2="58"/>
          <line x1="6" y1="32" x2="18" y2="32"/><line x1="46" y1="32" x2="58" y2="32"/>
          <line x1="13" y1="13" x2="22" y2="22"/><line x1="42" y1="42" x2="51" y2="51"/>
          <line x1="51" y1="13" x2="42" y2="22"/><line x1="22" y1="42" x2="13" y2="51"/>
        </svg>`;
      document.body.appendChild(el);
      setTimeout(() => el.remove(), 600);
    };
    document.addEventListener('click', onClick);
    return () => document.removeEventListener('click', onClick);
  }, [enabled]);
}

/* Soft Krew-orange glow that follows the cursor + a custom arrow drawn
   in the site's UI signature (1px ink stroke, 2px offset accent drop
   shadow). Renders nothing on touch/coarse-pointer devices. The arrow's
   tip is at (3,3) in viewBox units; CSS margin compensates so the tip
   sits exactly on the pointer coordinate. */
function useCursorGlow(enabled) {
  React.useEffect(() => {
    if (!enabled) return;
    if (window.matchMedia('(hover: none), (pointer: coarse)').matches) return;

    document.body.classList.add('has-krew-cursor');

    const arrow = document.createElement('div');
    arrow.className = 'cursor-arrow';
    arrow.setAttribute('aria-hidden', 'true');
    // Outline-only arrow drawn in Krew spark orange — no fill, no shadow.
    // Uses currentColor so the live --accent value flows through.
    arrow.innerHTML = `
      <svg width="22" height="22" viewBox="0 0 22 22" fill="none" xmlns="http://www.w3.org/2000/svg">
        <path d="M3 3 L3 16.2 L7.2 12.4 L9.6 17.8 L11.8 16.9 L9.4 11.6 L15 11.6 Z"
              fill="none"
              stroke="currentColor"
              stroke-width="1.5"
              stroke-linejoin="round"
              stroke-linecap="round"/>
      </svg>`;

    document.body.appendChild(arrow);

    let mx = -1000, my = -1000;
    let visible = false;

    const onMove = (e) => {
      mx = e.clientX;
      my = e.clientY;
      arrow.style.left = mx + 'px';
      arrow.style.top = my + 'px';
      if (!visible) {
        visible = true;
        arrow.classList.add('is-visible');
      }
    };
    const onLeave = () => {
      visible = false;
      arrow.classList.remove('is-visible');
    };
    const onDown = () => arrow.classList.add('is-down');
    const onUp = () => arrow.classList.remove('is-down');

    document.addEventListener('mousemove', onMove);
    document.addEventListener('mouseleave', onLeave);
    document.addEventListener('mousedown', onDown);
    document.addEventListener('mouseup', onUp);
    window.addEventListener('blur', onLeave);

    return () => {
      document.removeEventListener('mousemove', onMove);
      document.removeEventListener('mouseleave', onLeave);
      document.removeEventListener('mousedown', onDown);
      document.removeEventListener('mouseup', onUp);
      window.removeEventListener('blur', onLeave);
      arrow.remove();
      document.body.classList.remove('has-krew-cursor');
    };
  }, [enabled]);
}

function useReveal() {
  React.useEffect(() => {
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => { if (e.isIntersecting) e.target.classList.add('in'); });
    }, { threshold: 0.12 });
    document.querySelectorAll('.reveal').forEach(el => io.observe(el));
    return () => io.disconnect();
  }, []);
}

/* Day/night glyph toggle — minimal sun/moon switch in the top-right.
   Both glyphs render in the same SVG; the one for the *current* mode is
   visible, and on hover the opposite glyph slides in to preview the
   switch destination. Keyboard activatable; respects reduced motion. */
function DayNightToggle({ dark, onToggle }) {
  return (
    <button
      type="button"
      role="switch"
      aria-checked={dark}
      aria-label={dark ? 'Switch to light mode' : 'Switch to dark mode'}
      className={`day-night ${dark ? 'is-dark' : 'is-light'}`}
      onClick={onToggle}
    >
      <span className="dn-glyph dn-sun" aria-hidden="true">
        {/* Sun: filled disc with eight short rays */}
        <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round">
          <circle cx="12" cy="12" r="4" />
          <line x1="12" y1="2.5" x2="12" y2="5" />
          <line x1="12" y1="19" x2="12" y2="21.5" />
          <line x1="2.5" y1="12" x2="5" y2="12" />
          <line x1="19" y1="12" x2="21.5" y2="12" />
          <line x1="5.2" y1="5.2" x2="6.9" y2="6.9" />
          <line x1="17.1" y1="17.1" x2="18.8" y2="18.8" />
          <line x1="18.8" y1="5.2" x2="17.1" y2="6.9" />
          <line x1="6.9" y1="17.1" x2="5.2" y2="18.8" />
        </svg>
      </span>
      <span className="dn-glyph dn-moon" aria-hidden="true">
        {/* Moon: simple crescent (single path, no second circle subtraction) */}
        <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
          <path d="M20.5 14.2A8.5 8.5 0 0 1 9.8 3.5a8.5 8.5 0 1 0 10.7 10.7z" />
        </svg>
      </span>
    </button>
  );
}

window.Nav = Nav;
window.Marquee = Marquee;
window.Tweaks = Tweaks;
window.DayNightToggle = DayNightToggle;
window.useClickSpark = useClickSpark;
window.useCursorGlow = useCursorGlow;
window.useReveal = useReveal;
