// nav.jsx — top navigation with hover reveals
const { useState, useEffect, useRef } = React;

// Reads the "use_brand_logo" tweak off a global set by App.
// Defaults to true — if you want the old geometric SVG mark back,
// flip it off in the Tweaks panel.
function Logo({ onClick, compact = false, size }) {
  const useBrand = window.__tg_use_brand_logo !== false;
  // Explicit `size` wins; otherwise default to nav sizes.
  const h = size != null ? size : (compact ? 44 : 52);

  if (useBrand) {
    // Horizontal lockup: the hourglass mark + TIMEGAIN / AI SOLUTIONS wordmark.
    // The `-clean` asset is white glyphs on transparent — made for dark bgs.
    // On light themes, use the original PNG (dark navy card) so the white
    // glyphs stay legible against its own dark background, which reads fine
    // as a "branded pill" sitting on the cream page.
    const isLight = window.__tg_is_light_theme === true;
    const src = isLight ? 'assets/logo-horizontal.png' : 'assets/logo-horizontal-clean.png';
    return (
      <a href="#" onClick={onClick} style={{
        display: 'flex', alignItems: 'center', gap: 0, cursor: 'pointer',
        height: h,
        borderRadius: isLight ? 8 : 0,
        overflow: 'hidden',
      }}>
        <img
          src={src}
          alt="Timegain AI Solutions"
          style={{
            height: '100%', width: 'auto', display: 'block',
          }}
        />
      </a>
    );
  }

  // Original geometric fallback
  return (
    <a href="#" onClick={onClick} style={{
      display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer'
    }}>
      <svg width="28" height="28" viewBox="0 0 28 28" fill="none">
        <rect x="1" y="1" width="26" height="26" rx="6" stroke="var(--ink)" strokeWidth="1.5"/>
        <path d="M8 10 L14 14 L8 18" stroke="var(--accent)" strokeWidth="1.75" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
        <line x1="14" y1="18" x2="20" y2="18" stroke="var(--accent)" strokeWidth="1.75" strokeLinecap="round"/>
      </svg>
      <div style={{ display: 'flex', flexDirection: 'column', lineHeight: 1 }}>
        <span style={{ fontSize: 15, fontWeight: 600, letterSpacing: '-0.01em' }}>Timegain</span>
        <span style={{ fontSize: 9, fontFamily: 'var(--font-mono)', color: 'var(--ink-dim)', letterSpacing: '0.12em', marginTop: 2 }}>AI SOLUTIONS</span>
      </div>
    </a>
  );
}

function NavLink({ label, current, onClick }) {
  const ref = useRef(null);
  const [pos, setPos] = useState({ x: 0, y: 0 });
  const [hover, setHover] = useState(false);

  const onMove = (e) => {
    const r = ref.current.getBoundingClientRect();
    const x = (e.clientX - r.left - r.width / 2) * 0.3;
    const y = (e.clientY - r.top - r.height / 2) * 0.3;
    setPos({ x, y });
  };

  return (
    <button
      ref={ref}
      onMouseMove={onMove}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => { setHover(false); setPos({ x: 0, y: 0 }); }}
      onClick={onClick}
      style={{
        background: 'none', border: 'none', color: current ? 'var(--ink)' : 'var(--ink-dim)',
        fontSize: 14, fontFamily: 'var(--font-sans)', padding: '10px 16px',
        cursor: 'pointer', position: 'relative',
        transform: `translate(${pos.x}px, ${pos.y}px)`,
        transition: 'transform 0.2s cubic-bezier(.2,.8,.2,1), color 0.2s',
      }}
    >
      <span style={{ position: 'relative', zIndex: 2 }}>{label}</span>
      {(hover || current) && (
        <span style={{
          position: 'absolute', inset: 4,
          background: current ? 'rgba(255,255,255,0.08)' : 'rgba(255,255,255,0.04)',
          borderRadius: 999,
          transition: 'all 0.2s',
        }}/>
      )}
    </button>
  );
}

function Nav({ page, setPage }) {
  const pages = [
    { id: 'home', label: 'Home' },
    { id: 'services', label: 'Services' },
    { id: 'process', label: 'Approach' },
    { id: 'about', label: 'About' },
  ];
  const [scrolled, setScrolled] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false);
  const [isMobile, setIsMobile] = useState(window.innerWidth <= 640);
  useEffect(() => {
    const check = () => setIsMobile(window.innerWidth <= 640);
    window.addEventListener('resize', check);
    return () => window.removeEventListener('resize', check);
  }, []);
  useEffect(() => { setMenuOpen(false); }, [page]);

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

  return (
    <nav style={{
      position: 'fixed', top: 0, left: 0, right: 0, zIndex: 50,
      padding: 'clamp(12px, 2vw, 16px) clamp(18px, 3vw, 32px)',
      background: scrolled ? 'rgba(10,14,26,0.72)' : 'transparent',
      backdropFilter: scrolled ? 'blur(16px) saturate(140%)' : 'none',
      WebkitBackdropFilter: scrolled ? 'blur(16px) saturate(140%)' : 'none',
      borderBottom: scrolled ? '1px solid var(--bg-line)' : '1px solid transparent',
      transition: 'all 0.3s ease',
    }}>
      <div style={{
        maxWidth: 1280, margin: '0 auto',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      }}>
        <Logo onClick={(e) => { e.preventDefault(); setPage('home'); }} />
        <div className="nav-links" style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
          {pages.map(p => (
            <NavLink key={p.id} label={p.label} current={page === p.id}
              onClick={() => setPage(p.id)} />
          ))}
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <button
            className="nav-hamburger"
            aria-label={menuOpen ? 'Close menu' : 'Open menu'}
            aria-expanded={menuOpen}
            onClick={() => setMenuOpen(o => !o)}
            style={{
              background: 'none', border: '1px solid var(--bg-line)',
              borderRadius: 8, width: 36, height: 36,
              display: 'none',
              alignItems: 'center', justifyContent: 'center',
              color: 'var(--ink)', cursor: 'pointer',
            }}
          >
            <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round">
              {menuOpen ? (
                <><path d="M3 3 L13 13"/><path d="M13 3 L3 13"/></>
              ) : (
                <><path d="M2 4 L14 4"/><path d="M2 8 L14 8"/><path d="M2 12 L14 12"/></>
              )}
            </svg>
          </button>
          <a className="btn btn-ghost nav-cta-ghost" style={{ fontSize: 13 }}
            href="mailto:hello@timegainai.com">
            Email us
          </a>
          <button className="btn btn-primary nav-cta-demo" style={{ fontSize: 13 }}
            onClick={() => setPage('contact')}>
            Request a demo
            <svg width="12" height="12" viewBox="0 0 12 12"><path d="M2 6h8M7 3l3 3-3 3" stroke="currentColor" strokeWidth="1.5" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
          </button>
        </div>
      </div>
      {isMobile && menuOpen && (
        <div style={{
          position: 'fixed', top: 80, left: 16, right: 16,
          backdropFilter: 'blur(16px) saturate(140%)',
          WebkitBackdropFilter: 'blur(16px) saturate(140%)',
          border: '1px solid var(--bg-line)', borderRadius: 14,
          background: 'color-mix(in srgb, var(--bg) 94%, transparent)',
          padding: 12, zIndex: 49,
          display: 'flex', flexDirection: 'column', gap: 4,
        }}>
          {pages.map(p => (
            <button key={p.id} onClick={() => { setPage(p.id); }}
              style={{
                background: 'none', border: 'none',
                color: page === p.id ? 'var(--ink)' : 'var(--ink-dim)',
                textAlign: 'left', padding: '14px 16px', borderRadius: 8,
                fontSize: 15, fontFamily: 'var(--font-sans)', cursor: 'pointer',
                minHeight: 44,
              }}>
              {p.label}
            </button>
          ))}
          <a href="mailto:hello@timegainai.com"
            style={{ padding: '14px 16px', color: 'var(--ink-dim)', fontSize: 15, textDecoration: 'none', minHeight: 44, display: 'flex', alignItems: 'center' }}>
            Email us
          </a>
          <button className="btn btn-primary" style={{ marginTop: 4, padding: '14px 16px', justifyContent: 'center' }}
            onClick={() => setPage('contact')}>
            Request a demo
          </button>
        </div>
      )}
    </nav>
  );
}

window.Nav = Nav;
window.Logo = Logo;
