// Site shell — TopNav and Footer extracted so every page shares them and
// gets the focus-pull motion on the logo for free.
//
// `active` selects which top-nav item gets the underline ("home", "about",
// "services", "contact"). Each item links to the corresponding HTML page.

function NavLink({ href, children, active }) {
  return (
    <a href={href} className="hf-ulink" style={{
      fontSize: 14, fontWeight: 500, color: 'var(--fg)',
      position: 'relative',
    }}>
      {children}
      {active && <span style={{
        position: 'absolute', left: 0, right: 0, bottom: -3, height: 1.5,
        background: 'var(--ember)',
      }} />}
    </a>
  );
}

function TopNav({ active = 'home' }) {
  const isMobile = window.useIsMobile ? useIsMobile() : false;

  // Hash scroll — handles two cases the browser can't on its own:
  //   1. Cross-page link with #hash: browser scrolls to top before React
  //      has rendered the target section, so the hash effectively does
  //      nothing. We wait for the element to exist, then scroll to it.
  //   2. Same-page in-page links (e.g. the chip nav on services) need
  //      smooth scroll + sticky-nav offset.
  React.useEffect(() => {
    const navHeight = () => (isMobile ? 60 : 72) + 12; // breathing room
    const scrollToId = (id) => {
      const el = document.getElementById(id);
      if (!el) return false;
      const top = el.getBoundingClientRect().top + window.scrollY - navHeight();
      window.scrollTo({ top, behavior: 'smooth' });
      return true;
    };

    // Initial: poll briefly for the target element so React has a chance
    // to render the section into the DOM.
    if (window.location.hash) {
      const id = window.location.hash.slice(1);
      let tries = 0;
      const tick = () => {
        if (scrollToId(id)) return;
        if (tries++ < 30) setTimeout(tick, 40);
      };
      tick();
    }

    // Same-page hash changes
    const onHash = () => {
      const id = window.location.hash.slice(1);
      if (id) scrollToId(id);
    };
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, [isMobile]);

  return (
    <nav style={{
      position: 'sticky', top: 0, zIndex: 50,
      backdropFilter: 'saturate(140%) blur(14px)',
      WebkitBackdropFilter: 'saturate(140%) blur(14px)',
      background: 'var(--nav-bg)',
      borderBottom: '1px solid var(--line-soft)',
    }}>
      <div className="container" style={{
        height: isMobile ? 60 : 72,
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      }}>
        <a href="index.html" style={{ display: 'flex', alignItems: 'center' }} aria-label="HyperFocus">
          <FocusPull><AnimatedLogo size={isMobile ? 20 : 22} /></FocusPull>
        </a>
        {isMobile ? (
          <MobileNavTrigger active={active} />
        ) : (
          <>
            <div style={{ display: 'flex', alignItems: 'center', gap: 32 }}>
              <NavLink href="about.html"    active={active === 'about'}>About</NavLink>
              <NavLink href="services.html" active={active === 'services'}>Services</NavLink>
              <NavLink href="index.html#approach" active={active === 'approach'}>Approach</NavLink>
              <NavLink href="index.html#process"  active={active === 'process'}>Process</NavLink>
              <NavLink href="contact.html" active={active === 'contact'}>Contact</NavLink>
            </div>
            <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
              <span style={{
                display: 'inline-flex', alignItems: 'center', gap: 8,
                padding: '5px 10px 5px 8px', borderRadius: 999, background: 'var(--bg-subtle)',
              }}>
                <span className="hf-pulse" style={{ width: 7, height: 7, borderRadius: '50%', background: 'var(--ember)' }} />
                <span className="mono" style={{ fontSize: 11, color: 'var(--fg-muted)', letterSpacing: '0.06em' }}>AU · accepting Q3</span>
              </span>
              {window.ThemeToggle ? <ThemeToggle /> : null}
              <Btn size="sm" className="hf-btn" as="a" href="contact.html">Start a project <Arrow /></Btn>
            </div>
          </>
        )}
      </div>
    </nav>
  );
}

// MobileNavTrigger — hamburger button + slide-in sheet for narrow screens.
// Sheet contains: nav links, status pill, theme toggle, primary CTA.
function MobileNavTrigger({ active }) {
  const [open, setOpen] = React.useState(false);
  // Lock body scroll while the sheet is open.
  React.useEffect(() => {
    if (!open) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => { document.body.style.overflow = prev; };
  }, [open]);
  // Escape closes.
  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') setOpen(false); };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [open]);
  const close = () => setOpen(false);
  const linkStyle = (isActive) => ({
    display: 'flex', alignItems: 'center', justifyContent: 'space-between',
    padding: '16px 4px', fontSize: 22, fontWeight: 600,
    letterSpacing: '-0.02em', color: 'var(--fg)',
    borderBottom: '1px solid var(--line)',
    minHeight: 56, /* hit target */
  });
  return (
    <>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        {window.ThemeToggle ? <ThemeToggle /> : null}
        <button
          aria-label={open ? 'Close menu' : 'Open menu'}
          aria-expanded={open}
          onClick={() => setOpen(o => !o)}
          className="hf-btn"
          style={{
            width: 44, height: 44, borderRadius: 999,
            border: '1px solid var(--line)', background: 'var(--bg-subtle)',
            color: 'var(--fg)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            padding: 0,
          }}
        >
          {open ? (
            <svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true">
              <path d="M3 3L13 13M13 3L3 13" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" />
            </svg>
          ) : (
            <svg width="18" height="18" viewBox="0 0 18 18" fill="none" aria-hidden="true">
              <path d="M2 5h14M2 9h14M2 13h14" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" />
            </svg>
          )}
        </button>
      </div>

      {/* Backdrop + sheet */}
      <div
        onClick={close}
        style={{
          position: 'fixed', inset: 0, zIndex: 100,
          background: 'rgba(0,0,0,0.4)',
          opacity: open ? 1 : 0,
          pointerEvents: open ? 'auto' : 'none',
          transition: 'opacity .25s cubic-bezier(.2,.7,.2,1)',
        }}
      />
      <div
        role="dialog"
        aria-label="Menu"
        onClick={(e) => e.stopPropagation()}
        style={{
          position: 'fixed', top: 0, right: 0, bottom: 0, zIndex: 101,
          width: 'min(86vw, 360px)',
          background: 'var(--bg)',
          borderLeft: '1px solid var(--line)',
          boxShadow: 'var(--shadow-lift)',
          transform: open ? 'translateX(0)' : 'translateX(100%)',
          transition: 'transform .3s cubic-bezier(.2,.7,.2,1)',
          display: 'flex', flexDirection: 'column',
          padding: '20px 22px 24px',
          overflowY: 'auto',
        }}
      >
        {/* Sheet header */}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14 }}>
          <span className="mono" style={{ fontSize: 10, letterSpacing: '0.2em', textTransform: 'uppercase', color: 'var(--fg-muted)' }}>Menu</span>
          <button
            onClick={close}
            aria-label="Close menu"
            className="hf-btn"
            style={{
              width: 36, height: 36, borderRadius: 999, border: '1px solid var(--line)',
              background: 'var(--bg-subtle)', color: 'var(--fg)',
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            }}
          >
            <svg width="14" height="14" viewBox="0 0 16 16" fill="none"><path d="M3 3L13 13M13 3L3 13" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" /></svg>
          </button>
        </div>

        {/* Links */}
        <nav style={{ display: 'flex', flexDirection: 'column' }}>
          <a href="index.html" style={linkStyle(active === 'home')} onClick={close}>
            <span>Home</span>{active === 'home' && <Dot />}
          </a>
          <a href="about.html" style={linkStyle(active === 'about')} onClick={close}>
            <span>About</span>{active === 'about' && <Dot />}
          </a>
          <a href="services.html" style={linkStyle(active === 'services')} onClick={close}>
            <span>Services</span>{active === 'services' && <Dot />}
          </a>
          <a href="index.html#approach" style={linkStyle(false)} onClick={close}>
            <span>Approach</span>
          </a>
          <a href="index.html#process" style={linkStyle(false)} onClick={close}>
            <span>Process</span>
          </a>
          <a href="contact.html" style={{ ...linkStyle(active === 'contact'), borderBottom: 'none' }} onClick={close}>
            <span>Contact</span>{active === 'contact' && <Dot />}
          </a>
        </nav>

        {/* Status + CTA */}
        <div style={{ marginTop: 20, display: 'flex', flexDirection: 'column', gap: 14 }}>
          <span style={{
            display: 'inline-flex', alignItems: 'center', gap: 10,
            padding: '8px 14px', borderRadius: 999, background: 'var(--bg-subtle)',
            alignSelf: 'flex-start',
          }}>
            <span className="hf-pulse" style={{ width: 7, height: 7, borderRadius: '50%', background: 'var(--ember)' }} />
            <span className="mono" style={{ fontSize: 11, color: 'var(--fg-muted)', letterSpacing: '0.06em', textTransform: 'uppercase' }}>AU · accepting Q3</span>
          </span>
          <Btn className="hf-btn" size="lg" as="a" href="contact.html" onClick={close}>Start a project <Arrow /></Btn>
        </div>

        {/* Footer note */}
        <div style={{ marginTop: 'auto', paddingTop: 24 }}>
          <span className="mono" style={{ fontSize: 10, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--fg-muted)' }}>
            // hyperfocusoz.com
          </span>
        </div>
      </div>
    </>
  );
}

function Dot() {
  return <span style={{ width: 8, height: 8, borderRadius: '50%', background: 'var(--ember)' }} />;
}

// Logo whose dot animates in *after* the wordmark when used inside FocusPull.
function AnimatedLogo({ size = 22 }) {
  return (
    <span style={{
      fontFamily: '"Hanken Grotesk", sans-serif',
      fontWeight: 700, fontSize: size, lineHeight: 0.9,
      letterSpacing: '-0.045em', color: 'var(--fg)',
      display: 'inline-flex', alignItems: 'baseline',
    }}>
      hyperfocus<span className="hf-dot-snap" style={{
        display: 'inline-block',
        width: size * 0.20, height: size * 0.20, borderRadius: '50%',
        background: 'var(--ember)',
        marginLeft: size * 0.04, transform: `translateY(${size * -0.02}px)`,
      }} />
    </span>
  );
}

function FCol({ title, links }) {
  return (
    <div>
      <div className="mono" style={{ fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'rgba(243,238,228,0.5)' }}>{title}</div>
      <ul style={{ listStyle: 'none', padding: 0, margin: '14px 0 0', display: 'flex', flexDirection: 'column', gap: 10 }}>
        {links.map(l => (
          <li key={l.label || l}>
            <a href={l.href || '#'} className="hf-ulink" style={{ fontSize: 14, color: 'rgba(243,238,228,0.85)' }}>
              {l.label || l}
            </a>
          </li>
        ))}
      </ul>
    </div>
  );
}

function Footer() {
  const isMobile = window.useIsMobile ? useIsMobile() : false;
  return (
    <footer style={{ background: 'var(--bg-footer)', color: 'var(--fg-on-inverted)' }}>
      <div className="container" style={{ padding: isMobile ? '48px 20px 28px' : '64px 32px 32px' }}>
        <div style={{
          display: 'grid',
          gridTemplateColumns: isMobile ? '1fr' : '1.4fr 1fr 1fr 1fr',
          gap: isMobile ? 36 : 48,
        }}>
          <div>
            <DotLogoOnDark size={26} />
            <p style={{ fontSize: 14, lineHeight: 1.6, color: 'rgba(243,238,228,0.65)', maxWidth: 360, margin: '18px 0 0', textWrap: 'pretty' }}>
              IT professionals with 20+ years of experience per project lead, building modern, AI-powered solutions for businesses across Australia and beyond.
            </p>
            <div style={{ marginTop: 22, display: 'inline-flex', alignItems: 'center', gap: 8, padding: '6px 12px', borderRadius: 999, background: 'rgba(243,238,228,0.08)' }}>
              <span className="hf-pulse" style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--ember)' }} />
              <span className="mono" style={{ fontSize: 11, color: 'rgba(243,238,228,0.8)', letterSpacing: '0.06em' }}>accepting Q3 engagements</span>
            </div>
          </div>
          <FCol title="Site" links={[
            { label: 'Home', href: 'index.html' },
            { label: 'About', href: 'about.html' },
            { label: 'Services', href: 'services.html' },
            { label: 'Contact', href: 'contact.html' },
          ]} />
          <FCol title="Services" links={[
            { label: 'AI & Automation', href: 'services.html#ai' },
            { label: 'Custom Software', href: 'services.html#software' },
            { label: 'SaaS', href: 'services.html#saas' },
            { label: 'Integrations', href: 'services.html#integrations' },
            { label: 'Data & Analytics', href: 'services.html#data' },
            { label: 'IT Strategy', href: 'services.html#strategy' },
          ]} />
          <FCol title="Contact" links={[
            { label: 'hello@hyperfocusoz.com', href: 'mailto:hello@hyperfocusoz.com' },
            { label: 'Australia · GMT+10', href: '#' },
            { label: 'LinkedIn', href: '#' },
          ]} />
        </div>
        <div style={{
          marginTop: isMobile ? 36 : 48, paddingTop: 24,
          borderTop: '1px solid rgba(243,238,228,0.10)',
          display: 'flex', justifyContent: 'space-between',
          flexDirection: isMobile ? 'column' : 'row',
          gap: isMobile ? 10 : 0,
          color: 'rgba(243,238,228,0.5)',
        }}>
          <span className="mono" style={{ fontSize: 11, letterSpacing: '0.06em' }}>© 2026 HyperFocus · hyperfocusoz.com</span>
          <span className="mono" style={{ fontSize: 11, letterSpacing: '0.06em' }}>// IT solutions, powered by AI</span>
        </div>
      </div>
    </footer>
  );
}

// Reusable page hero used by inner pages (About, Services, Contact).
// Big editorial headline, supporting copy, optional sidebar widget.
function PageHero({ eyebrow, title, sub, accent, kicker, children }) {
  const isMobile = window.useIsMobile ? useIsMobile() : false;
  return (
    <header style={{ position: 'relative', overflow: 'hidden', borderBottom: '1px solid var(--line)' }}>
      <div aria-hidden="true" style={{
        position: 'absolute',
        top: isMobile ? -120 : -200,
        right: isMobile ? -120 : -180,
        width: isMobile ? 340 : 520,
        height: isMobile ? 340 : 520,
        borderRadius: '50%', background: 'var(--ember)', opacity: 0.05, pointerEvents: 'none',
      }} />
      <div className="container" style={{ padding: isMobile ? '40px 20px 48px' : '64px 32px 72px', position: 'relative' }}>
        <FadeUp>
          <SectionLabel accent={accent}>{eyebrow}</SectionLabel>
        </FadeUp>
        <div style={{
          display: 'grid',
          gridTemplateColumns: isMobile ? '1fr' : (children ? '1.15fr 0.85fr' : '1fr'),
          gap: isMobile ? 28 : 56,
          marginTop: isMobile ? 18 : 26,
          alignItems: 'end',
        }}>
          <div>
            <FadeUp delay={80}>
              <h1 style={{
                fontSize: 'clamp(38px, 7.5vw, 72px)',
                fontWeight: 800, letterSpacing: '-0.04em', lineHeight: 1.0,
                margin: 0, textWrap: 'balance',
              }}>{title}</h1>
            </FadeUp>
            <FadeUp delay={160}>
              <p style={{
                fontSize: isMobile ? 17 : 19, lineHeight: 1.5, color: 'var(--fg-muted)',
                maxWidth: 620, marginTop: isMobile ? 18 : 26, textWrap: 'pretty',
              }}>{sub}</p>
            </FadeUp>
            {kicker && (
              <FadeUp delay={220}>
                <div style={{ marginTop: 24, display: 'inline-flex', alignItems: 'center', gap: 10 }}>
                  {kicker}
                </div>
              </FadeUp>
            )}
          </div>
          {children && <FadeUp delay={200}>{children}</FadeUp>}
        </div>
      </div>
    </header>
  );
}

Object.assign(window, { TopNav, Footer, AnimatedLogo, PageHero, NavLink, FCol });
