// Sybre — Header, Footer, Page wrapper, hooks
const { useState, useEffect, useRef, useCallback } = React;

// ── Hash router ───────────────────────────────────────────────
function useRoute() {
  const [route, setRoute] = useState(() => window.location.hash.slice(1) || '/');
  useEffect(() => {
    const onHash = () => setRoute(window.location.hash.slice(1) || '/');
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);
  return route;
}
function navigate(path) {
  window.location.hash = path;
  window.scrollTo({ top: 0, behavior: 'instant' });
}

// ── Reveal hook (IntersectionObserver) ────────────────────────
function useReveal() {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    // If already in viewport at mount, reveal immediately (no animation needed).
    const rect = el.getBoundingClientRect();
    if (rect.top < window.innerHeight && rect.bottom > 0) {
      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, rootMargin: '0px 0px -40px 0px' });
    io.observe(el);
    return () => io.disconnect();
  }, []);
  return ref;
}

// ── Smart link ────────────────────────────────────────────────
function Link({ to, children, className, ...rest }) {
  return (
    <a href={'#' + to}
    className={className}
    onClick={(e) => {e.preventDefault();navigate(to);}}
    {...rest}>
      {children}
    </a>);

}

// ── Header ────────────────────────────────────────────────────
const SERVICE_LINKS = [
{ to: '/services/managed-it', title: 'Managed IT', sub: 'Proactive monitoring & support' },
{ to: '/services/cybersecurity', title: 'Cybersecurity', sub: 'Detection, response, compliance' },
{ to: '/services/ai', title: 'AI infrastructure', sub: 'Local LLMs, RAG, automation' },
{ to: '/services/ai/roi', title: 'AI ROI calculator', sub: 'Model the return on AI adoption', sage: true },
{ to: '/services/consulting', title: 'Consulting & design', sub: 'Architecture & integrations' }];


function SiteHeader({ route }) {
  const [scrolled, setScrolled] = useState(false);
  const [ddOpen, setDdOpen] = useState(false);
  const [mobileOpen, setMobileOpen] = useState(false);
  const ddTimer = useRef(null);

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

  // close mobile on route change
  useEffect(() => {setMobileOpen(false);setDdOpen(false);}, [route]);

  const openDD = () => {clearTimeout(ddTimer.current);setDdOpen(true);};
  const closeDD = () => {ddTimer.current = setTimeout(() => setDdOpen(false), 140);};

  const isActive = (path) => route === path || path !== '/' && route.startsWith(path);

  return (
    <>
      <header className={'site-header' + (scrolled ? ' scrolled' : '')}>
        <div className="header-inner">
          <Link to="/" className="logo-link" aria-label="Sybre — home">
            <img src="assets/Branding/sybre_logo_alternate_reversed.png" alt="Sybre" />
          </Link>

          <nav className="nav" aria-label="Primary">
            <div style={{ position: 'relative' }} onMouseEnter={openDD} onMouseLeave={closeDD}>
              <button
                className={'nav-link nav-trigger' + (isActive('/services') ? ' active' : '')}
                onClick={() => navigate('/services')}
                aria-haspopup="true"
                aria-expanded={ddOpen}>
                Services
                <svg width="10" height="6" viewBox="0 0 10 6" aria-hidden="true">
                  <path d="M1 1l4 4 4-4" fill="none" stroke="currentColor" strokeWidth="1.5" />
                </svg>
              </button>
              <div className={'nav-dropdown' + (ddOpen ? ' open' : '')} role="menu">
                {SERVICE_LINKS.map((s) =>
                <Link key={s.to} to={s.to} role="menuitem">
                    <span className="dd-title">{s.title}</span>
                    <span className="dd-sub">{s.sub}</span>
                  </Link>
                )}
              </div>
            </div>
            <Link to="/about" className={'nav-link' + (isActive('/about') ? ' active' : '')}>About</Link>
            <Link to="/insights" className={'nav-link' + (isActive('/insights') ? ' active' : '')}>Insights</Link>
            <Link to="/contact" className={'nav-link' + (isActive('/contact') ? ' active' : '')}>Contact</Link>
          </nav>

          <Link to="/contact" className="btn btn-primary header-cta">Contact us</Link>
          <button className={'menu-btn' + (mobileOpen ? ' open' : '')} onClick={() => setMobileOpen((o) => !o)} aria-label="Menu" aria-expanded={mobileOpen}>
            <span></span>
          </button>
        </div>
      </header>

      <div className={'mobile-nav' + (mobileOpen ? ' open' : '')} role="dialog" aria-label="Menu">
        <Link to="/services">Services</Link>
        {SERVICE_LINKS.map((s) => <Link key={s.to} to={s.to} className="sub">— {s.title}</Link>)}
        <Link to="/about">About</Link>
        <Link to="/insights">Insights</Link>
        <Link to="/contact">Contact</Link>
        <Link to="/contact" className="btn btn-primary mobile-cta">Contact us</Link>
      </div>
    </>);

}

// ── Footer ────────────────────────────────────────────────────
function SiteFooter() {
  return (
    <footer className="site-footer">
      <div className="container">
        <div className="footer-grid">
          <div className="footer-brand">
            <img src="assets/Branding/sybre_logo_alternate_reversed.png" alt="Sybre" />
            <p>A boutique managed services provider in North Sydney. Senior engineers, local AI where it matters, and a single number to call.</p>
          </div>
          <div className="footer-col">
            <h4>Services</h4>
            <Link to="/services/managed-it">Managed IT</Link>
            <Link to="/services/cybersecurity">Cybersecurity</Link>
            <Link to="/services/ai">AI infrastructure</Link>
            <Link to="/services/ai/roi">AI ROI calculator</Link>
            <Link to="/services/consulting">Consulting & design</Link>
          </div>
          <div className="footer-col">
            <h4>Company</h4>
            <Link to="/about">About</Link>
            <Link to="/insights">Insights</Link>
            <Link to="/contact">Contact</Link>
            <Link to="/spec">Spec & guidelines</Link>
          </div>
          <div className="footer-col">
            <h4>Contact</h4>
            <a href="mailto:info@sybre.com.au">info@sybre.com.au</a>
            <a href="tel:+61272341455">(02) 7234 1455</a>
            <span style={{ display: 'block', fontSize: 13, color: 'var(--fg4)', lineHeight: 1.6, marginTop: 8 }}>
              Suite 203, Level 8<br />99 Walker St<br />North Sydney NSW 2060
            </span>
          </div>
        </div>
        <div className="footer-bottom">
          <span>© 2026 Sybre Pty Ltd · ABN <span className="placeholder">ABN — needs human input</span></span>
          <span style={{ display: 'flex', gap: 24 }}>
            <Link to="/spec">Privacy</Link>
            <Link to="/spec">Terms</Link>
          </span>
        </div>
      </div>
    </footer>);

}

// ── Section block — eyebrow + title + lead pattern ───────────
function SectionHead({ num, label, title, lead, accent = true }) {
  const ref = useReveal();
  return (
    <div ref={ref} className="reveal" style={{ marginBottom: 48, maxWidth: 720 }}>
      {/* numbered section headers removed — headings carry the section (rev 2026-07-04) */}
      <h2 className="h-section" dangerouslySetInnerHTML={{ __html: title }} />
      {lead && <p className="lead" style={{ marginTop: 20 }}>{lead}</p>}
    </div>);

}

// ── Reveal wrapper ───────────────────────────────────────────
function Reveal({ children, stagger = false, style, className = '', as: Tag = 'div' }) {
  const ref = useReveal();
  return (
    <Tag ref={ref} className={(stagger ? 'reveal-stagger ' : 'reveal ') + className} style={style}>
      {children}
    </Tag>);

}

// ── Page wrapper ─────────────────────────────────────────────
function Page({ children }) {
  return <main className="route-fade" key={Math.random()}>{children}</main>;
}

// ── Final CTA band — used on most pages ─────────────────────
function FinalCTA({ num = '04', label = 'Next step', title = "Let's <em>talk</em>." }) {
  return (
    <section className="section">
      <div className="container">
        <Reveal>
          {/* Solid orange closing block — the action accent (Variant C) */}
          <div className="card accent" style={{ textAlign: 'center', padding: '72px 48px' }}>
            <h2 className="h-section" style={{ color: 'var(--sybre-white)' }} dangerouslySetInnerHTML={{ __html: title }} />
            <p className="lead" style={{ margin: '20px auto 32px', maxWidth: 560 }}>A short conversation. We listen, ask the important questions
and tell you how we can help.
            </p>
            <div style={{ display: 'flex', gap: 12, justifyContent: 'center', flexWrap: 'wrap' }}>
              <Link to="/contact" className="btn btn-inverse">Contact us</Link>
            </div>
          </div>
        </Reveal>
      </div>
    </section>);

}

Object.assign(window, { useRoute, navigate, useReveal, Link, SiteHeader, SiteFooter, SectionHead, Reveal, Page, FinalCTA });
