/* global React */
const { useState, useEffect, useRef } = React;

/* ============================================
   CUSTOM CURSOR (hidden on touch)
   ============================================ */
function CustomCursor() {
  const dotRef = useRef(null);
  const ringRef = useRef(null);
  const [hovering, setHovering] = useState(false);
  const [touch, setTouch] = useState(false);

  useEffect(() => {
    if (window.matchMedia('(hover: none)').matches) { setTouch(true); return; }
    let dotX = 0, dotY = 0, ringX = 0, ringY = 0, mouseX = 0, mouseY = 0;
    let raf;
    const onMove = (e) => {
      mouseX = e.clientX; mouseY = e.clientY;
      const t = e.target;
      setHovering(!!(t && t.closest && t.closest('a, button, .interactive, [data-cursor=hover]')));
    };
    const tick = () => {
      dotX += (mouseX - dotX) * 0.6;
      dotY += (mouseY - dotY) * 0.6;
      ringX += (mouseX - ringX) * 0.18;
      ringY += (mouseY - ringY) * 0.18;
      if (dotRef.current) dotRef.current.style.transform = `translate(${dotX}px, ${dotY}px) translate(-50%, -50%)`;
      if (ringRef.current) ringRef.current.style.transform = `translate(${ringX}px, ${ringY}px) translate(-50%, -50%)`;
      raf = requestAnimationFrame(tick);
    };
    window.addEventListener('mousemove', onMove);
    raf = requestAnimationFrame(tick);
    return () => { window.removeEventListener('mousemove', onMove); cancelAnimationFrame(raf); };
  }, []);
  if (touch) return null;
  return (<>
    <div ref={dotRef} className="cursor-dot" />
    <div ref={ringRef} className={`cursor-ring${hovering ? ' hover' : ''}`} />
  </>);
}

/* ============================================
   LOGO LOCKUP — transparent horizontal logo (hex C mark + CODAGE wordmark)
   height drives size; width auto-scales from the image's natural 16:9 ratio
   ============================================ */
function CodageWordmark({ size = 22 }) {
  const h = Math.round(size * 2.4);
  return (
    <img
      src="assets/brand/codage-logo.png"
      alt="Codage"
      height={h}
      style={{
        height: `${h}px`,
        width: 'auto',
        display: 'block',
        flexShrink: 0,
      }}
    />
  );
}

/* ============================================
   NAV — desktop split-pill + mobile drawer
   ============================================ */
function Nav({ current = 'home' }) {
  const [scrolled, setScrolled] = useState(false);
  const [hoverIdx, setHoverIdx] = useState(null);
  const [open, setOpen] = useState(false);
  const navRef = useRef(null);
  const [underline, setUnderline] = useState({ left: 0, width: 0, opacity: 0 });

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 80);
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  useEffect(() => {
    document.body.style.overflow = open ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [open]);

  // Full nav — used by mobile drawer
  const links = [
    { label: 'Agents', href: 'Agents.html', key: 'agents' },
    { label: 'Use Cases', href: 'UseCases.html', key: 'usecases' },
    { label: 'Work', href: 'Work.html', key: 'work' },
    { label: 'Security', href: 'Security.html', key: 'security' },
    { label: 'Lab', href: 'Lab.html', key: 'lab' },
    { label: 'About', href: 'About.html', key: 'about' },
    { label: 'Contact', href: 'Contact.html', key: 'contact' },
  ];
  // Desktop pill subset — drop 'usecases' (still reachable from /agents + homepage bento)
  const desktopLinks = links.filter(l => l.key !== 'usecases');

  useEffect(() => {
    if (hoverIdx === null || !navRef.current) { setUnderline(u => ({ ...u, opacity: 0 })); return; }
    const el = navRef.current.querySelectorAll('.nav-link')[hoverIdx];
    if (el) {
      const r = el.getBoundingClientRect();
      const p = navRef.current.getBoundingClientRect();
      setUnderline({ left: r.left - p.left, width: r.width, opacity: 1 });
    }
  }, [hoverIdx]);

  const scale = scrolled ? 0.96 : 1;

  return (<>
    {/* Desktop */}
    <header className="app-header nav-desktop" style={{
      position: 'fixed', top: 18, left: 0, right: 0, zIndex: 100,
      display: 'flex', justifyContent: 'space-between', alignItems: 'center',
      padding: '0 24px', pointerEvents: 'none',
    }}>
      <a href="index.html" className="glass glass-strong" style={{
        pointerEvents: 'auto', padding: '10px 22px 10px 22px', borderRadius: 14,
        display: 'flex', alignItems: 'center', gap: 10,
        transform: `scale(${scale})`, transition: 'transform 400ms var(--ease-out-expo)',
      }}>
        <CodageWordmark size={20} />
      </a>
      <nav ref={navRef} className="glass glass-strong" style={{
        pointerEvents: 'auto', padding: '6px 6px 6px 16px', borderRadius: 999,
        display: 'flex', alignItems: 'center', gap: 2,
        transform: `scale(${scale})`, transition: 'transform 400ms var(--ease-out-expo)',
        position: 'relative',
      }}>
        <div style={{
          position: 'absolute', bottom: 5, left: underline.left, width: underline.width,
          height: 1, background: 'var(--accent-ice)',
          boxShadow: '0 0 6px rgba(168,197,232,0.8)', opacity: underline.opacity,
          transition: 'left 280ms var(--ease-out-expo), width 280ms var(--ease-out-expo), opacity 200ms ease',
        }} />
        {desktopLinks.map((l, i) => (
          <a key={l.label} className="nav-link" href={l.href}
             onMouseEnter={() => setHoverIdx(i)} onMouseLeave={() => setHoverIdx(null)}
             style={{
               padding: '9px 12px', fontSize: 13,
               color: current === l.key ? 'var(--text-primary)' : 'var(--text-secondary)',
               transition: 'color 200ms ease', letterSpacing: '-0.005em',
               whiteSpace: 'nowrap',
             }}>{l.label}</a>
        ))}
        <a href="https://calendar.app.google/an2mX8SWcKPFcvNK6" target="_blank" rel="noopener noreferrer"
           className="btn btn-primary" style={{ padding: '9px 14px', fontSize: 12, marginLeft: 4, whiteSpace: 'nowrap' }}>
          Book a workflow audit
          <svg className="arrow-icon" width="12" height="12" viewBox="0 0 12 12" fill="none">
            <path d="M2 6h8m0 0L6 2m4 4L6 10" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </a>
      </nav>
    </header>

    {/* Mobile */}
    <header className="app-header nav-mobile" style={{
      display: 'none', position: 'fixed', top: 14, left: 16, right: 16, zIndex: 100,
      pointerEvents: 'none',
    }}>
      <div className="glass glass-strong" style={{
        pointerEvents: 'auto', flex: 1, padding: '10px 14px 10px 18px', borderRadius: 14,
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      }}>
        <a href="index.html" style={{ display: 'flex', alignItems: 'center' }}>
          <CodageWordmark size={18} />
        </a>
        <button onClick={() => setOpen(true)} aria-label="Open menu"
          style={{ width: 44, height: 44, display: 'flex', alignItems: 'center', justifyContent: 'center', borderRadius: 999 }}>
          <svg width="20" height="16" viewBox="0 0 18 14" fill="none">
            <path d="M1 1h16M1 7h16M1 13h16" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
          </svg>
        </button>
      </div>
    </header>

    {/* Mobile drawer */}
    <div style={{
      position: 'fixed', inset: 0, zIndex: 200,
      background: 'rgba(4, 6, 10, 0.7)',
      backdropFilter: 'blur(60px) saturate(180%)',
      WebkitBackdropFilter: 'blur(60px) saturate(180%)',
      transform: open ? 'translateY(0)' : 'translateY(-100%)',
      opacity: open ? 1 : 0,
      transition: 'transform 360ms cubic-bezier(0.22, 1, 0.36, 1), opacity 240ms ease',
      pointerEvents: open ? 'auto' : 'none',
      display: 'flex', flexDirection: 'column',
      padding: 'env(safe-area-inset-top, 24px) 24px env(safe-area-inset-bottom, 24px)',
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '18px 4px 24px' }}>
        <CodageWordmark size={20} />
        <button onClick={() => setOpen(false)} aria-label="Close menu"
          style={{ width: 44, height: 44, display: 'flex', alignItems: 'center', justifyContent: 'center', borderRadius: 999, border: '1px solid var(--border-glass)' }}>
          <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
            <path d="M2 2l10 10M12 2L2 12" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
          </svg>
        </button>
      </div>
      <nav style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: 24 }}>
        {links.map((l, i) => (
          <a key={l.label} href={l.href} onClick={() => setOpen(false)}
            className="serif" style={{
              fontSize: 32, letterSpacing: '-0.02em', padding: '16px 4px',
              minHeight: 56,
              display: 'flex',
              alignItems: 'center',
              color: current === l.key ? 'var(--accent-ice)' : 'var(--text-primary)',
              borderBottom: '1px solid var(--border-glass)',
              transform: open ? 'translateY(0)' : 'translateY(20px)',
              opacity: open ? 1 : 0,
              transition: `transform 500ms var(--ease-out-expo) ${i * 60 + 200}ms, opacity 400ms ease ${i * 60 + 200}ms`,
            }}>{l.label}</a>
        ))}
      </nav>
      <div style={{ marginTop: 'auto', paddingTop: 32 }}>
        <a href="https://calendar.app.google/an2mX8SWcKPFcvNK6" target="_blank" rel="noopener noreferrer"
          className="btn btn-primary" style={{ width: '100%', justifyContent: 'center', padding: '18px 24px', fontSize: 16 }}>
          Book a workflow audit
          <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
            <path d="M2 7h10m0 0L7 2m5 5L7 12" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
          </svg>
        </a>
        <div style={{ marginTop: 24, fontFamily: 'var(--font-mono)', fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.1em', color: 'var(--text-tertiary)', textAlign: 'center' }}>
          Baku · Paris
        </div>
      </div>
    </div>
  </>);
}

Object.assign(window, { CustomCursor, CodageWordmark, Nav });
