// shared/chrome.jsx — Nav, Footer, scroll-reveal observer, page-transition init.
// Exposes globals: WhitenNav, WhitenFooter, WhitenAnnouncement, useReveal, Mark, Arrow

const Mark = ({ size = 28 }) => (
  <span className="mark" style={{ width: size, height: size, fontSize: size * 0.72 }}>w</span>
);

const Arrow = ({ size = 14, dir = "right" }) => {
  const rot = { right: 0, up: -45, down: 135, left: 180 }[dir] || 0;
  return (
    <svg className="ico-arr" viewBox="0 0 14 14" width={size} height={size}
         style={{ transform: `rotate(${rot}deg)` }} aria-hidden="true">
      <path d="M2 7h10M8 3l4 4-4 4" stroke="currentColor" strokeWidth="1.4" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  );
};

// ─── responsive helper ───
// Inline styles can't be overridden by CSS media queries (specificity), so
// layout defined in JSX switches via this matchMedia-backed hook.
function useIsMobile(maxWidth = 760) {
  const query = `(max-width: ${maxWidth}px)`;
  const read = () => (typeof window !== 'undefined' && window.matchMedia ? window.matchMedia(query).matches : false);
  const [match, setMatch] = React.useState(read);
  React.useEffect(() => {
    const mq = window.matchMedia(query);
    const onChange = () => setMatch(mq.matches);
    onChange();
    mq.addEventListener ? mq.addEventListener('change', onChange) : mq.addListener(onChange);
    return () => { mq.removeEventListener ? mq.removeEventListener('change', onChange) : mq.removeListener(onChange); };
  }, [query]);
  return match;
}

// ─── inline brand/contact icons ───
const IconMail = ({ size = 16 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor"
       strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"
       aria-hidden="true" style={{ flexShrink: 0 }}>
    <rect x="3" y="5" width="18" height="14" rx="2" />
    <path d="m3.5 7.5 8.5 6 8.5-6" />
  </svg>
);

const IconLinkedIn = ({ size = 16 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor"
       aria-hidden="true" style={{ flexShrink: 0 }}>
    <path d="M20.45 20.45h-3.56v-5.57c0-1.33-.03-3.04-1.85-3.04-1.86 0-2.14 1.45-2.14 2.94v5.67H9.35V9h3.41v1.56h.05c.48-.9 1.64-1.85 3.37-1.85 3.6 0 4.27 2.37 4.27 5.46v6.28zM5.34 7.43a2.06 2.06 0 1 1 0-4.13 2.06 2.06 0 0 1 0 4.13zM7.12 20.45H3.56V9h3.56v11.45zM22.22 0H1.77C.8 0 0 .78 0 1.73v20.54C0 23.22.8 24 1.77 24h20.45c.98 0 1.78-.78 1.78-1.73V1.73C24 .78 23.2 0 22.22 0z" />
  </svg>
);

const NAV_ITEMS = [
  { href: "index.html",         label: "Home",       key: "home" },
  { href: "services.html",      label: "Services",   key: "services" },
  { href: "workflows.html",     label: "Workflows",  key: "workflows" },
  { href: "case-studies.html",  label: "Case studies", key: "cases" },
  { href: "how-it-works.html",  label: "How it works", key: "how" },
  { href: "pricing.html",       label: "Pricing",      key: "pricing" }
];

function WhitenAnnouncement({ children }) {
  return (
    <div className="ann">
      <span className="dot"></span>
      {children || <>Now booking June 2026 — 3 build slots left</>}
    </div>
  );
}

function WhitenNav({ active }) {
  const isMobile = useIsMobile(860);
  const [open, setOpen] = React.useState(false);

  // close the menu whenever we grow back to desktop
  React.useEffect(() => { if (!isMobile) setOpen(false); }, [isMobile]);

  return (
    <header className="nav-host">
      <nav className="nav">
        <a href="index.html" className="nav-brand" aria-label="WhitenApp home">
          <Mark />
          <span>Whiten<span className="wm">App</span></span>
        </a>

        {!isMobile && (
          <div className="nav-links">
            {NAV_ITEMS.map(it => (
              <a key={it.key} href={it.href} className={active === it.key ? "active" : ""}>{it.label}</a>
            ))}
          </div>
        )}

        {!isMobile && (
          <a href="index.html#book" className="nav-cta">
            Book a free assessment <span className="arr"><Arrow size={14} /></span>
          </a>
        )}

        {isMobile && (
          <button
            className="nav-toggle"
            aria-label={open ? "Close menu" : "Open menu"}
            aria-expanded={open}
            onClick={() => setOpen(o => !o)}
          >
            <span className={`nav-burger ${open ? "is-open" : ""}`} aria-hidden="true">
              <i></i><i></i><i></i>
            </span>
          </button>
        )}
      </nav>

      {isMobile && open && (
        <div className="nav-mobile">
          {NAV_ITEMS.map(it => (
            <a key={it.key} href={it.href}
               className={active === it.key ? "active" : ""}
               onClick={() => setOpen(false)}>
              {it.label}
            </a>
          ))}
          <a href="index.html#book" className="nav-cta nav-cta-block" onClick={() => setOpen(false)}>
            Book a free assessment <span className="arr"><Arrow size={14} /></span>
          </a>
        </div>
      )}
    </header>
  );
}

function WhitenFooter() {
  const isMobile = useIsMobile(760);
  return (
    <footer className="footer">
      <div style={{ maxWidth: 1440, margin: "0 auto" }}>
        {/* brand statement — a small human moment above the footer links */}
        <p style={{
          textAlign: "center", margin: isMobile ? "0 auto 40px" : "0 auto 56px",
          maxWidth: 640, fontSize: isMobile ? 15 : 17, lineHeight: 1.55,
          color: "rgba(244,241,234,.55)"
        }}>
          We build the automations Australian businesses have been putting off for years.
        </p>

        <div style={{
          display: "grid",
          gridTemplateColumns: isMobile ? "1fr 1fr" : "1.4fr 1fr 1fr 1fr",
          gap: isMobile ? "36px 24px" : "48px",
          alignItems: "start"
        }}>
          <div style={{ gridColumn: isMobile ? "1 / -1" : "auto" }}>
            <div className="nav-brand" style={{ fontSize: 22, color: "var(--bg)" }}>
              <Mark size={36} />
              <span>Whiten<span className="wm" style={{ color: "var(--accent)" }}>App</span></span>
            </div>
            <p style={{ marginTop: 18, maxWidth: 360, color: "rgba(244,241,234,.6)", fontSize: 15, lineHeight: 1.55 }}>
              An AI &amp; automation studio for mid-market ops teams who'd rather their people did the interesting work.
            </p>
            <a href="index.html#book" className="btn btn-accent" style={{ marginTop: 28 }}>
              Book a free assessment <Arrow />
            </a>
          </div>

          <FooterCol title="Site" links={[
            ["Home", "index.html"],
            ["Services", "services.html"],
            ["Workflows", "workflows.html"],
            ["Case studies", "case-studies.html"],
            ["How it works", "how-it-works.html"],
            ["Pricing", "pricing.html"]
          ]} />
          <FooterCol title="Company" links={[
            ["About", "#"], ["Reviews", "#"], ["Blog", "#"], ["Privacy", "#"]
          ]} />

          <div style={{ gridColumn: isMobile ? "1 / -1" : "auto" }}>
            <div style={{
              fontFamily: "var(--f-mono)", fontSize: 11, letterSpacing: ".12em",
              textTransform: "uppercase", color: "rgba(244,241,234,.4)", marginBottom: 16
            }}>Connect</div>
            <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 12 }}>
              <li>
                <a href="mailto:aki@whitenapp.com.au" style={{
                  display: "inline-flex", alignItems: "center", gap: 10,
                  color: "rgba(244,241,234,.85)", fontSize: 15, overflowWrap: "anywhere"
                }}>
                  <IconMail /> aki@whitenapp.com.au
                </a>
              </li>
              <li>
                <a href="https://www.linkedin.com/company/whitenapp-ai/" target="_blank" rel="noopener noreferrer" style={{
                  display: "inline-flex", alignItems: "center", gap: 10,
                  color: "rgba(244,241,234,.85)", fontSize: 15
                }}>
                  <IconLinkedIn /> LinkedIn
                </a>
              </li>
            </ul>
          </div>
        </div>

        <div className="ft-wm">WhitenApp</div>

        <div style={{
          display: "flex", justifyContent: "space-between", alignItems: "center",
          flexWrap: "wrap", gap: 10,
          marginTop: 30, paddingTop: 24, borderTop: "1px solid rgba(244,241,234,.12)",
          fontSize: 12.5, color: "rgba(244,241,234,.4)", fontFamily: "var(--f-mono)"
        }}>
          <span>© 2026 WhitenApp AI · Sydney / Remote</span>
          <span>Built for owners who are doing everything</span>
        </div>
      </div>
    </footer>
  );
}

function FooterCol({ title, links }) {
  return (
    <div>
      <div style={{
        fontFamily: "var(--f-mono)", fontSize: 11, letterSpacing: ".12em",
        textTransform: "uppercase", color: "rgba(244,241,234,.4)", marginBottom: 16
      }}>{title}</div>
      <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 10 }}>
        {links.map(([label, href]) => (
          <li key={label}>
            <a href={href} style={{ color: "rgba(244,241,234,.85)", fontSize: 15, overflowWrap: "anywhere" }}>{label}</a>
          </li>
        ))}
      </ul>
    </div>
  );
}

// ─── reveal-on-scroll observer ───
function useReveal() {
  React.useEffect(() => {
    const motionOff = document.documentElement.getAttribute('data-motion') === '0';
    if (motionOff) {
      document.querySelectorAll('.reveal').forEach(el => el.classList.add('in'));
    }

    // immediately reveal anything already in (or near) the viewport so the
    // first paint doesn't look blank
    const revealNow = (el) => {
      const r = el.getBoundingClientRect();
      if (r.top < window.innerHeight * 1.05 && r.bottom > 0) {
        const delay = parseFloat(getComputedStyle(el).getPropertyValue('--rd')) || 0;
        if (delay) setTimeout(() => el.classList.add('in'), delay * 1000);
        else el.classList.add('in');
        return true;
      }
      return false;
    };

    const io = new IntersectionObserver((entries) => {
      entries.forEach(en => {
        if (en.isIntersecting) {
          en.target.classList.add('in');
          io.unobserve(en.target);
        }
      });
    }, { threshold: 0.08, rootMargin: "0px 0px -6% 0px" });

    // process a single element (reveal if visible, else observe)
    const handle = (el) => {
      if (el.classList.contains('in')) return;
      if (motionOff) { el.classList.add('in'); return; }
      if (!revealNow(el)) io.observe(el);
    };

    document.querySelectorAll('.reveal').forEach(handle);

    // watch for .reveal nodes added later (filtering, view toggles, drawers) —
    // without this they would never be observed and stay invisible
    const mo = new MutationObserver((muts) => {
      muts.forEach(m => m.addedNodes.forEach(node => {
        if (node.nodeType !== 1) return;
        if (node.classList && node.classList.contains('reveal')) handle(node);
        if (node.querySelectorAll) node.querySelectorAll('.reveal').forEach(handle);
      }));
    });
    mo.observe(document.body, { childList: true, subtree: true });

    return () => { io.disconnect(); mo.disconnect(); };
  }, []);
}

Object.assign(window, {
  Mark, Arrow, WhitenNav, WhitenFooter, WhitenAnnouncement, useReveal, useIsMobile, NAV_ITEMS
});
