// Nav — desktop: centered pill with hover mega-menu; mobile: burger + slide-in drawer
const NAV_SERVICES = [
  { group:'Websites & software', items: [
    { href:'services/web-design.html', title:'Website Design', blurb:'Fast, considered sites.' },
    { href:'services/software.html',   title:'Software Development', blurb:'Custom tools & integrations.' },
    { href:'services/web-apps.html',   title:'Web Apps', blurb:'Dashboards, portals, MVPs.' },
  ]},
  { group:'Get found & get leads', items: [
    { href:'services/seo.html',        title:'SEO', blurb:'Rank for what matters.' },
    { href:'services/google-ads.html', title:'Google Ads', blurb:'Search, display, shopping.' },
    { href:'services/meta-ads.html',   title:'Meta Ads', blurb:'Facebook & Instagram.' },
    { href:'services/social.html',     title:'Social Media', blurb:'Organic content, handled.' },
  ]},
  { group:'Tech & automation', items: [
    { href:'services/it.html',  title:'IT Support', blurb:'The devices & systems behind your team.' },
    { href:'services/ai.html',  title:'AI Automation', blurb:'Put boring work on autopilot.' },
  ]},
];

// Shared theme-toggle button used in both desktop nav and mobile drawer
const ThemeToggleButton = ({ theme, onClick, size = 34 }) => (
  <button
    onClick={onClick}
    aria-label={theme === 'dark' ? 'Switch to light theme' : 'Switch to dark theme'}
    title={theme === 'dark' ? 'Light mode' : 'Dark mode'}
    style={{
      display:'inline-flex', alignItems:'center', justifyContent:'center',
      width: size, height: size, borderRadius: 999,
      background: 'transparent', border: '1px solid var(--line)',
      color: 'var(--fg-2)', cursor: 'pointer',
      transition: 'background .2s, color .2s, border-color .2s',
    }}
  >
    {theme === 'dark' ? (
      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
        <circle cx="12" cy="12" r="4"/>
        <path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"/>
      </svg>
    ) : (
      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
        <path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/>
      </svg>
    )}
  </button>
);

// Mobile drawer — slides in from right, covers full height
const MobileDrawer = ({ isOpen, onClose, base, theme, onToggleTheme }) => {
  const [servicesOpen, setServicesOpen] = useState(false);

  // Scroll-lock body while open; restore on close
  useEffect(() => {
    if (!isOpen) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => {
      document.body.style.overflow = prev;
      window.removeEventListener('keydown', onKey);
    };
  }, [isOpen, onClose]);

  return (
    <>
      {/* backdrop */}
      <div
        onClick={onClose}
        style={{
          position: 'fixed', inset: 0, zIndex: 100,
          background: 'oklch(0 0 0 / .5)', backdropFilter: 'blur(4px)',
          opacity: isOpen ? 1 : 0,
          pointerEvents: isOpen ? 'auto' : 'none',
          transition: 'opacity .3s ease',
        }}
      />
      {/* drawer */}
      <aside
        aria-hidden={!isOpen}
        style={{
          position: 'fixed', top: 0, right: 0, bottom: 0, zIndex: 101,
          width: 'min(380px, 88vw)',
          background: 'var(--bg-2)',
          borderLeft: '1px solid var(--line)',
          transform: isOpen ? 'translateX(0)' : 'translateX(100%)',
          transition: 'transform .32s cubic-bezier(.22,.61,.36,1)',
          display: 'flex', flexDirection: 'column',
          boxShadow: '-20px 0 60px -20px oklch(0 0 0 / .5)',
          overflowY: 'auto',
        }}
      >
        {/* header */}
        <div style={{
          display:'flex', alignItems:'center', justifyContent:'space-between',
          padding: '20px 24px', borderBottom: '1px solid var(--line)',
        }}>
          <Logo />
          <button
            onClick={onClose}
            aria-label="Close menu"
            style={{
              width: 40, height: 40, borderRadius: 999,
              display:'inline-flex', alignItems:'center', justifyContent:'center',
              background: 'transparent', border: '1px solid var(--line)', color:'var(--fg)',
              cursor: 'pointer',
            }}
          >
            <Icon name="close" size={18} stroke={2}/>
          </button>
        </div>

        {/* primary links */}
        <nav style={{ display:'flex', flexDirection:'column', padding: '16px 0', flex: 1 }}>
          <a href={base + 'index.html'} onClick={onClose} style={drawerLinkStyle}>Home</a>

          {/* Services — expandable */}
          <button
            onClick={() => setServicesOpen(o => !o)}
            style={{
              ...drawerLinkStyle,
              display:'flex', justifyContent:'space-between', alignItems:'center',
              width: '100%', textAlign: 'left',
            }}
            aria-expanded={servicesOpen}
          >
            <span>Services</span>
            <Icon name="chev" size={14} stroke={2} style={{ transform: servicesOpen ? 'rotate(90deg)' : 'rotate(0)', transition: 'transform .2s' }}/>
          </button>
          {servicesOpen && (
            <div style={{ padding: '4px 0 12px', background: 'var(--card-bg)' }}>
              {NAV_SERVICES.flatMap(g => g.items).map(it => (
                <a key={it.href} href={base + it.href} onClick={onClose} style={{
                  ...drawerLinkStyle, padding: '12px 40px', fontSize: 15, color: 'var(--fg-2)',
                }}>
                  {it.title}
                </a>
              ))}
              <a href={base + 'services.html'} onClick={onClose} style={{
                ...drawerLinkStyle, padding: '12px 40px', fontSize: 14, color:'var(--accent)', fontFamily: 'var(--mono)',
              }}>
                See all services →
              </a>
            </div>
          )}

          <a href={base + 'pricing.html'} onClick={onClose} style={drawerLinkStyle}>Pricing</a>
          <a href={base + 'about.html'}   onClick={onClose} style={drawerLinkStyle}>About</a>
          <a href={base + 'blog.html'}    onClick={onClose} style={drawerLinkStyle}>Blog</a>
          <a href={base + 'locations.html'} onClick={onClose} style={drawerLinkStyle}>Locations</a>
          <a href={base + 'contact.html'} onClick={onClose} style={drawerLinkStyle}>Contact</a>
        </nav>

        {/* footer */}
        <div style={{
          padding: '20px 24px', borderTop: '1px solid var(--line)',
          display:'flex', alignItems:'center', justifyContent:'space-between', gap: 12,
        }}>
          <ThemeToggleButton theme={theme} onClick={onToggleTheme} size={40}/>
          <a href={base + 'contact.html'} onClick={onClose} className="btn btn-accent" style={{ flex: 1, justifyContent: 'center' }}>
            Say hello <Icon name="arrow" size={14}/>
          </a>
        </div>
      </aside>
    </>
  );
};

const drawerLinkStyle = {
  display: 'block',
  padding: '14px 24px',
  fontSize: 17,
  fontWeight: 500,
  color: 'var(--fg)',
  background: 'transparent',
  border: 0,
  textDecoration: 'none',
};

const Nav = ({ base = '' }) => {
  const isMobile = useIsMobile();
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(null); // desktop mega-menu state
  const [drawerOpen, setDrawerOpen] = useState(false);
  const [theme, setTheme] = useState(() =>
    (typeof document !== 'undefined' && document.documentElement.getAttribute('data-theme')) || 'light'
  );
  const closeTimer = useRef(null);

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

  // Auto-close drawer when viewport grows back to desktop
  useEffect(() => {
    if (!isMobile && drawerOpen) setDrawerOpen(false);
  }, [isMobile, drawerOpen]);

  const toggleTheme = () => {
    const next = theme === 'dark' ? 'light' : 'dark';
    document.documentElement.setAttribute('data-theme', next);
    try { localStorage.setItem('tpp_theme', next); } catch (e) {}
    if (window.__TWEAKS__) window.__TWEAKS__.theme = next;
    setTheme(next);
  };

  const openMenu = (key) => {
    if (closeTimer.current) { clearTimeout(closeTimer.current); closeTimer.current = null; }
    setOpen(key);
  };
  const scheduleClose = () => {
    closeTimer.current = setTimeout(() => setOpen(null), 180);
  };

  // ── Mobile: compact bar with logo + burger ─────────────────────
  if (isMobile) {
    return (
      <>
        <header style={{
          position: 'fixed', top: 12, left: 12, right: 12, zIndex: 50,
          display: 'flex', justifyContent: 'space-between', alignItems: 'center',
          padding: '10px 14px 10px 18px',
          background: scrolled ? 'var(--nav-bg-scroll)' : 'var(--nav-bg)',
          backdropFilter: 'blur(22px) saturate(1.3)',
          border: '1px solid var(--line)',
          borderRadius: 999,
          boxShadow: scrolled ? '0 10px 40px -10px oklch(0 0 0 / .35)' : 'none',
          transition: 'background .25s, box-shadow .25s',
        }}>
          <a href={base + 'index.html'} style={{ display:'flex' }}><Logo/></a>
          <button
            onClick={() => setDrawerOpen(true)}
            aria-label="Open menu"
            aria-expanded={drawerOpen}
            style={{
              width: 42, height: 42, borderRadius: 999,
              display:'inline-flex', alignItems:'center', justifyContent:'center',
              background: 'transparent', border: '1px solid var(--line)', color:'var(--fg)',
              cursor: 'pointer',
            }}
          >
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
              <path d="M4 7h16M4 12h16M4 17h16"/>
            </svg>
          </button>
        </header>
        <MobileDrawer
          isOpen={drawerOpen}
          onClose={() => setDrawerOpen(false)}
          base={base}
          theme={theme}
          onToggleTheme={toggleTheme}
        />
      </>
    );
  }

  // ── Desktop: centered pill with hover mega-menu ────────────────
  const links = [
    { label:'Services', key:'services', href:base + 'services.html' },
    { label:'Work',    href: base + 'index.html#work' },
    { label:'Pricing', href: base + 'pricing.html' },
    { label:'About',   href: base + 'about.html' },
    { label:'Blog',    href: base + 'blog.html' },
    { label:'Locations', href: base + 'locations.html' },
    { label:'Contact', href: base + 'contact.html' },
  ];

  return (
    <header style={{
      position: 'fixed', top: 14, left: 0, right: 0, zIndex: 50,
      display: 'flex', justifyContent: 'center',
      transition: 'all .3s ease'
    }}>
      <div style={{ position:'relative', display:'flex', justifyContent:'center' }}>
        <nav className="hairline" style={{
          display: 'flex', alignItems: 'center', gap: 8,
          padding: '8px 10px 8px 20px',
          background: scrolled ? 'var(--nav-bg-scroll)' : 'var(--nav-bg)',
          backdropFilter: 'blur(22px) saturate(1.3)',
          borderRadius: 999,
          boxShadow: scrolled ? '0 10px 40px -10px oklch(0 0 0 / .5)' : 'none'
        }}>
          <a href={base + 'index.html'} style={{ display:'flex' }}><Logo /></a>
          <div style={{ width: 1, height: 22, background: 'var(--line)', margin: '0 14px' }}/>
          <div style={{ display: 'flex', gap: 4, fontSize: 13, fontWeight: 500 }}>
            {links.map(l => (
              <a key={l.label} href={l.href}
                onMouseEnter={(e) => {
                  e.currentTarget.style.color = 'var(--fg)';
                  e.currentTarget.style.background = 'var(--card-bg)';
                  if (l.key) openMenu(l.key);
                }}
                onMouseLeave={(e) => {
                  e.currentTarget.style.color = 'var(--fg-2)';
                  e.currentTarget.style.background = 'transparent';
                  if (l.key) scheduleClose();
                }}
                style={{
                  padding: '8px 14px', borderRadius: 999, color: 'var(--fg-2)', transition: 'all .2s',
                  display:'inline-flex', alignItems:'center', gap: 4,
                }}>
                {l.label}
                {l.key && <Icon name="chev" size={10} stroke={2} className="" />}
              </a>
            ))}
          </div>
          <div style={{ marginLeft: 6 }}>
            <ThemeToggleButton theme={theme} onClick={toggleTheme}/>
          </div>
          <a href={base + 'contact.html'} className="btn btn-accent" style={{ padding: '10px 18px', fontSize: 13, marginLeft: 8 }}>
            Say hello <Icon name="arrow" size={14}/>
          </a>
        </nav>

        {/* mega menu */}
        {open === 'services' && (
          <div
            onMouseEnter={() => openMenu('services')}
            onMouseLeave={scheduleClose}
            className="hairline"
            style={{
              position:'absolute', top: 'calc(100% + 10px)', left: '50%', transform:'translateX(-50%)',
              background: 'var(--nav-bg-scroll)', backdropFilter:'blur(22px) saturate(1.3)',
              borderRadius: 20, padding: 24,
              width: 'min(820px, 94vw)',
              boxShadow: '0 20px 60px -20px oklch(0 0 0 / .4)',
              animation: 'fadein .18s ease',
            }}>
            <div style={{ display:'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 24 }}>
              {NAV_SERVICES.map(col => (
                <div key={col.group}>
                  <div className="mono" style={{
                    fontSize: 10, color: 'var(--fg-3)', letterSpacing:'.14em',
                    textTransform:'uppercase', marginBottom: 10,
                  }}>{col.group}</div>
                  <div style={{ display:'flex', flexDirection:'column', gap: 2 }}>
                    {col.items.map(it => (
                      <a key={it.href} href={base + it.href} style={{
                        display:'block', padding: '10px 12px', borderRadius: 10,
                        transition: 'background .15s',
                      }}
                      onMouseEnter={e => e.currentTarget.style.background = 'var(--card-bg)'}
                      onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                        <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--fg)' }}>{it.title}</div>
                        <div style={{ fontSize: 12, color:'var(--fg-3)', marginTop: 2 }}>{it.blurb}</div>
                      </a>
                    ))}
                  </div>
                </div>
              ))}
            </div>
            <div style={{
              marginTop: 18, paddingTop: 14, borderTop: '1px dashed var(--line-2)',
              display:'flex', justifyContent:'space-between', alignItems:'center', gap: 12,
            }}>
              <div style={{ fontSize: 12, color:'var(--fg-2)' }}>
                Not sure which? <span className="mono" style={{ color:'var(--fg-3)' }}>we'll figure it out on the call.</span>
              </div>
              <a href={base + 'services.html'} className="mono" style={{
                fontSize: 11, color:'var(--accent)', letterSpacing:'.08em',
                display:'inline-flex', alignItems:'center', gap: 6,
              }}>
                See all services <Icon name="arrow" size={12}/>
              </a>
            </div>
          </div>
        )}
      </div>
    </header>
  );
};

window.Nav = Nav;
