// Shared layout: top nav + footer + router
// Global scope: no exports, attaches to window.

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

// ---- Simple hash router ----
function useRoute() {
  const [route, setRoute] = useState(() => (location.hash.replace(/^#\/?/, '') || 'home'));
  useEffect(() => {
    const onRouteChange = () => {
      const r = location.hash.replace(/^#\/?/, '') || 'home';
      setRoute(r);
      window.scrollTo({ top: 0, behavior: 'instant' });
    };
    window.addEventListener('hashchange', onRouteChange);
    window.addEventListener('popstate', onRouteChange);
    return () => {
      window.removeEventListener('hashchange', onRouteChange);
      window.removeEventListener('popstate', onRouteChange);
    };
  }, []);
  return [route, (r) => {
    if (r === 'home') {
      history.pushState(null, '', location.pathname + location.search);
      setRoute('home');
      window.scrollTo({ top: 0, behavior: 'instant' });
      return;
    }
    location.hash = '#/' + r;
  }];
}

// ---- Logo ----
function Logo({ inverse = false }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center' }}>
      <img src="assets/logo.svg" alt="Synchronize"
        style={{ height: 28, width: 'auto', filter: inverse ? 'brightness(0) invert(1)' : 'none' }}/>
    </div>
  );
}

// ---- Nav ----
function Nav({ route, go }) {
  const [mobileOpen, setMobileOpen] = useState(false);
  const links = [
    { id: 'home', label: 'Home' },
    { id: 'how-it-works', label: 'How it works' },
    { id: 'pricing', label: 'Pricing' },
  ];
  const productActive = route === 'product' || route.startsWith('product-');
  useEffect(() => setMobileOpen(false), [route]);
  useEffect(() => {
    if (!mobileOpen) return undefined;
    const closeOnEscape = (event) => {
      if (event.key === 'Escape') setMobileOpen(false);
    };
    window.addEventListener('keydown', closeOnEscape);
    return () => window.removeEventListener('keydown', closeOnEscape);
  }, [mobileOpen]);
  const mobileGo = (event, destination) => {
    event.preventDefault();
    setMobileOpen(false);
    go(destination);
  };
  const mobileLinkClass = (destination) => (
    'mobile-nav-link' + (route === destination ? ' active' : '')
  );
  return (
    <div className={`nav${mobileOpen ? ' nav--mobile-open' : ''}`}>
      <div className="nav-inner">
        <a href="#/home" onClick={(e) => { e.preventDefault(); setMobileOpen(false); go('home'); }} className="nav-logo">
          <Logo />
        </a>
        <div className="nav-links">
          <a href="#/home" onClick={(e) => { e.preventDefault(); go('home'); }} className={'nav-link' + (route === 'home' ? ' active' : '')}>Home</a>
          <div className="nav-product-menu">
            <a href="#/product"
               onClick={(e) => { e.preventDefault(); go('product'); }}
               className={'nav-link nav-product-trigger' + (productActive ? ' active' : '')}
               aria-haspopup="true">
              Product <span aria-hidden="true">⌄</span>
            </a>
            <div className="nav-product-dropdown" aria-label="Product pages">
              <a href="#/product-circle" onClick={(e) => { e.preventDefault(); go('product-circle'); }}>
                <ProductMark src="assets/circle.png" alt="" className="product-mark--circle"/>
                <span><strong>Synchronize for Circle</strong><small>Deep Circle integration</small></span>
              </a>
              <a href="#/product-slack" onClick={(e) => { e.preventDefault(); go('product-slack'); }}>
                <ProductMark src="assets/slack.png" alt=""/>
                <span><strong>Synchronize for Slack</strong><small>A complete community layer</small></span>
              </a>
              <a href="#/product-core" onClick={(e) => { e.preventDefault(); go('product-core'); }}>
                <span className="nav-core-mark"><img src="assets/logo-mark.svg" alt=""/></span>
                <span><strong>Synchronize Core</strong><small>Platform + managed migration</small></span>
              </a>
              <a href="#/product" className="nav-product-all" onClick={(e) => { e.preventDefault(); go('product'); }}>
                Compare all products <span aria-hidden="true">→</span>
              </a>
            </div>
          </div>
          {links.slice(1).map(l => (
            <a key={l.id}
               href={`#/${l.id}`}
               onClick={(e) => { e.preventDefault(); go(l.id); }}
               className={'nav-link' + (route === l.id ? ' active' : '')}>
              {l.label}
            </a>
          ))}
        </div>
        <div className="nav-cta">
          <a href="https://admin.synchronize.so" className="nav-link nav-login-link">Log in</a>
          <a href="#/get-started" onClick={(e) => { e.preventDefault(); go('get-started'); }} className="btn btn-primary btn-sm">
            Book a demo
          </a>
        </div>
        <button
          type="button"
          className="nav-mobile-toggle"
          aria-label={mobileOpen ? 'Close navigation menu' : 'Open navigation menu'}
          aria-expanded={mobileOpen}
          aria-controls="mobile-navigation"
          onClick={() => setMobileOpen(open => !open)}>
          <span></span><span></span><span></span>
        </button>
      </div>
      <nav id="mobile-navigation" className="mobile-nav" aria-label="Mobile navigation" aria-hidden={!mobileOpen}>
        <div className="mobile-nav-inner">
          <a href="#/home" onClick={(e) => mobileGo(e, 'home')} className={mobileLinkClass('home')}>Home</a>
          <div className="mobile-nav-product">
            <div className="mobile-nav-label">Product</div>
            <a href="#/product-circle" onClick={(e) => mobileGo(e, 'product-circle')} className={mobileLinkClass('product-circle')}>
              <ProductMark src="assets/circle.png" alt="" className="product-mark--circle"/>
              <span>Synchronize for Circle</span>
            </a>
            <a href="#/product-slack" onClick={(e) => mobileGo(e, 'product-slack')} className={mobileLinkClass('product-slack')}>
              <ProductMark src="assets/slack.png" alt=""/>
              <span>Synchronize for Slack</span>
            </a>
            <a href="#/product-core" onClick={(e) => mobileGo(e, 'product-core')} className={mobileLinkClass('product-core')}>
              <span className="nav-core-mark"><img src="assets/logo-mark.svg" alt=""/></span>
              <span>Synchronize Core</span>
            </a>
            <a href="#/product" onClick={(e) => mobileGo(e, 'product')} className={mobileLinkClass('product')}>Compare all products <span aria-hidden="true">→</span></a>
          </div>
          <a href="#/how-it-works" onClick={(e) => mobileGo(e, 'how-it-works')} className={mobileLinkClass('how-it-works')}>How it works</a>
          <a href="#/pricing" onClick={(e) => mobileGo(e, 'pricing')} className={mobileLinkClass('pricing')}>Pricing</a>
          <div className="mobile-nav-actions">
            <a href="https://admin.synchronize.so" className="btn btn-soft">Log in</a>
            <a href="#/get-started" onClick={(e) => mobileGo(e, 'get-started')} className="btn btn-primary">Book a demo</a>
          </div>
        </div>
      </nav>
    </div>
  );
}

// ---- Footer ----
function Footer({ go }) {
  const footerLink = (route, label) => (
    <a href={`#/${route}`} onClick={(e)=>{e.preventDefault();go(route);}}>{label}</a>
  );
  return (
    <footer className="footer">
      <div className="footer-inner">
        <div className="footer-brand-column">
          <Logo inverse />
          <p className="footer-tag">
            Meet your members <em>where they already are.</em>
          </p>
        </div>
        <div>
          <h4>Explore</h4>
          {footerLink('home', 'Home')}
          {footerLink('product-circle', 'Synchronize for Circle')}
          {footerLink('product-slack', 'Synchronize for Slack')}
          {footerLink('product-core', 'Synchronize Core')}
          {footerLink('how-it-works', 'How it works')}
          {footerLink('pricing', 'Pricing')}
        </div>
        <div>
          <h4>Company</h4>
          {footerLink('about', 'About')}
          {footerLink('security', 'Security')}
          {footerLink('terms-conditions', 'Terms & conditions')}
          {footerLink('privacy-policy', 'Privacy Policy')}
          {footerLink('terms-of-use', 'Terms of Use')}
        </div>
        <div className="footer-demo-column">
          <h4>See it in action</h4>
          <p>Bring your real community setup. We’ll show you what Synchronize can unlock.</p>
          <a href="#/get-started" onClick={(e)=>{e.preventDefault();go('get-started');}} className="btn footer-demo-button">
            Book a demo <span aria-hidden="true">→</span>
          </a>
        </div>
      </div>
      <div className="footer-bottom">
        <div>© 2026 Synchronize Communities Limited.</div>
      </div>
    </footer>
  );
}

// ---- Reveal on scroll hook ----
function useReveal() {
  const reducedMotion = useReducedMotion();
  useEffect(() => {
    const els = document.querySelectorAll('.reveal:not(.in)');
    if (reducedMotion || !('IntersectionObserver' in window)) {
      els.forEach(el => el.classList.add('in'));
      return;
    }
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting) { e.target.classList.add('in'); io.unobserve(e.target); }
      });
    }, { threshold: 0.12 });
    els.forEach(el => io.observe(el));
    return () => io.disconnect();
  }, [reducedMotion]);
}

// ---- Motion preference hook ----
function useReducedMotion() {
  const [reducedMotion, setReducedMotion] = useState(() => (
    typeof window !== 'undefined' && window.matchMedia
      ? window.matchMedia('(prefers-reduced-motion: reduce)').matches
      : false
  ));

  useEffect(() => {
    if (!window.matchMedia) return undefined;
    const query = window.matchMedia('(prefers-reduced-motion: reduce)');
    const update = event => setReducedMotion(event.matches);
    setReducedMotion(query.matches);
    if (query.addEventListener) query.addEventListener('change', update);
    else query.addListener(update);
    return () => {
      if (query.removeEventListener) query.removeEventListener('change', update);
      else query.removeListener(update);
    };
  }, []);

  return reducedMotion;
}

// ---- Scroll-y hook ----
function useScrollY() {
  const [y, setY] = useState(0);
  useEffect(() => {
    const on = () => setY(window.scrollY);
    window.addEventListener('scroll', on, { passive: true });
    return () => window.removeEventListener('scroll', on);
  }, []);
  return y;
}

Object.assign(window, { Logo, Nav, Footer, useRoute, useReveal, useReducedMotion, useScrollY });
