// Shared: router, Nav, Footer, CTA, reveal helpers
const { useState, useEffect, useRef, useMemo, createContext, useContext } = React;

const RouterCtx = createContext({ path: "home", go: () => {} });

const PAGE_TITLES = {
  home: "Your team works hard. Your systems should too. | CoPowr",
  services: "Automation, Integrations, and AI Services | CoPowr",
  process: "How We Work, The CoPowr Delivery Process",
  about: "What CoPowr Believes and Why We Exist",
  contact: "Let's Talk, Book a Discovery Call with CoPowr",
  privacy: "Privacy Policy | CoPowr",
  terms: "Terms of Service | CoPowr",
};

const Router = ({ children, initial = "home" }) => {
  const [path, setPath] = useState(() => {
    const saved = localStorage.getItem("copowr_route");
    // migrate away from removed faq route
    return (saved && PAGE_TITLES[saved]) ? saved : initial;
  });
  const go = (p) => {
    if (!PAGE_TITLES[p]) p = "home";
    setPath(p);
    localStorage.setItem("copowr_route", p);
    window.scrollTo({ top: 0, behavior: "instant" });
  };
  useEffect(() => { document.title = PAGE_TITLES[path] || PAGE_TITLES.home; }, [path]);
  return <RouterCtx.Provider value={{ path, go }}>{children}</RouterCtx.Provider>;
};

const Link = ({ to, children, className = "", ...rest }) => {
  const { go, path } = useContext(RouterCtx);
  const active = path === to ? "active" : "";
  return (
    <a className={`${className} ${active}`} onClick={(e) => { e.preventDefault(); go(to); }} href={`#${to}`} {...rest}>
      {children}
    </a>
  );
};

function useReveal(ref, threshold = 0.12) {
  useEffect(() => {
    const el = ref.current; if (!el) return;
    const io = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) { el.classList.add("is-in"); io.disconnect(); }
    }, { threshold });
    io.observe(el);
    return () => io.disconnect();
  }, [ref, threshold]);
}
const Reveal = ({ delay = 0, as: Tag = "div", className = "", children, ...rest }) => {
  const r = useRef(null); useReveal(r);
  const cls = `reveal ${delay ? `d${delay}` : ""} ${className}`.trim();
  return <Tag ref={r} className={cls} {...rest}>{children}</Tag>;
};

const AnnBar = () => {
  const { go } = useContext(RouterCtx);
  return (
    <div className="annbar">
      <strong>Now booking</strong>
      Spring 2026 discovery calls for mid-market operations teams
      <a onClick={(e) => { e.preventDefault(); go("contact"); }} href="#contact">Book a discovery call →</a>
    </div>
  );
};

const Nav = () => {
  const [scrolled, setScrolled] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false);
  const { go, path: route } = useContext(RouterCtx);
  useEffect(() => {
    const on = () => setScrolled(window.scrollY > 24);
    on(); window.addEventListener("scroll", on, { passive: true });
    return () => window.removeEventListener("scroll", on);
  }, []);
  // Close menu when route changes, or on Esc
  useEffect(() => { setMenuOpen(false); }, [route]);
  useEffect(() => {
    if (!menuOpen) return;
    const onKey = (e) => { if (e.key === "Escape") setMenuOpen(false); };
    document.body.style.overflow = "hidden";
    window.addEventListener("keydown", onKey);
    return () => {
      document.body.style.overflow = "";
      window.removeEventListener("keydown", onKey);
    };
  }, [menuOpen]);
  const goTo = (to) => { setMenuOpen(false); go(to); };
  return (
    <nav className={`nav ${scrolled ? "is-scrolled" : ""} ${menuOpen ? "is-menu-open" : ""}`}>
      <div className="container nav-row">
        <a href="#home" onClick={(e) => { e.preventDefault(); goTo("home"); }} aria-label="CoPowr home">
          <img className="nav-logo" src={window.__resources?.emblemColor || "assets/emblem-color.svg"} alt="CoPowr"/>
        </a>
        <div className="nav-links">
          <Link to="services">Services</Link>
          <Link to="process">Process</Link>
          <Link to="about">About</Link>
          <Link to="contact">Contact</Link>
        </div>
        <div className="nav-cta">
          <Link to="contact" className="btn btn-primary btn-sm nav-cta-desktop">Book a discovery call <Icon name="arrow" size={13}/></Link>
          <button
            type="button"
            className={`nav-burger ${menuOpen ? "is-open" : ""}`}
            aria-label={menuOpen ? "Close menu" : "Open menu"}
            aria-expanded={menuOpen}
            aria-controls="mobile-menu"
            onClick={() => setMenuOpen(v => !v)}
          >
            <span className="nav-burger-box" aria-hidden="true">
              <span></span><span></span><span></span>
            </span>
          </button>
        </div>
      </div>
      <div
        id="mobile-menu"
        className={`nav-mobile-menu ${menuOpen ? "is-open" : ""}`}
        aria-hidden={!menuOpen}
      >
        <div className="nav-mobile-inner">
          <ul className="nav-mobile-list">
            <li><a href="#services" onClick={(e)=>{e.preventDefault(); goTo("services");}} className={route === "services" ? "active" : ""}>Services</a></li>
            <li><a href="#process" onClick={(e)=>{e.preventDefault(); goTo("process");}} className={route === "process" ? "active" : ""}>Process</a></li>
            <li><a href="#about" onClick={(e)=>{e.preventDefault(); goTo("about");}} className={route === "about" ? "active" : ""}>About</a></li>
            <li><a href="#contact" onClick={(e)=>{e.preventDefault(); goTo("contact");}} className={route === "contact" ? "active" : ""}>Contact</a></li>
          </ul>
          <a
            href="#contact"
            className="btn btn-primary btn-lg nav-mobile-cta"
            onClick={(e)=>{e.preventDefault(); goTo("contact");}}
          >
            Book a discovery call <Icon name="arrow" size={14}/>
          </a>
          <div className="nav-mobile-contact">
            <a href="mailto:hi@copowr.com">hi@copowr.com</a>
          </div>
        </div>
      </div>
      <div
        className={`nav-scrim ${menuOpen ? "is-open" : ""}`}
        onClick={() => setMenuOpen(false)}
        aria-hidden="true"
      />
    </nav>
  );
};

const CtaBand = ({
  title = "Ready to talk?",
  body = "Book a discovery call. No pitch deck, no pressure, just a conversation about the work your team is doing by hand.",
  primaryLabel = "Book a discovery call",
  secondaryLabel,
}) => {
  const { go } = useContext(RouterCtx);
  return (
    <section className="section-sm">
      <Reveal as="div" className="cta-band">
        <h2>{title}</h2>
        <p>{body}</p>
        <div className="btns">
          <a onClick={(e)=>{e.preventDefault(); go("contact");}} href="#contact" className="btn btn-white btn-lg">{primaryLabel} <Icon name="arrow" size={15}/></a>
          {secondaryLabel && (
            <a onClick={(e)=>{e.preventDefault(); go("process");}} href="#process" className="btn btn-outline-white btn-lg">{secondaryLabel}</a>
          )}
        </div>
      </Reveal>
    </section>
  );
};

const Footer = () => {
  const { go } = useContext(RouterCtx);
  const L = ({ to, children }) => (
    <a onClick={(e)=>{e.preventDefault(); go(to);}} href={`#${to}`}>{children}</a>
  );
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer-grid">
          <div className="footer-brand">
            <div className="footer-logo-lockup" style={{justifyContent:"flex-start"}}>
              <img className="footer-wordmark" src="assets/wordmark-white.png" alt="CoPowr" style={{height:44}}/>
            </div>
          </div>
          <div className="footer-col">
            <h5>Get in touch</h5>
            <ul>
              <li><L to="contact">Book a discovery call</L></li>
              <li><a href="mailto:hi@copowr.com">hi@copowr.com</a></li>
            </ul>
          </div>
        </div>
        <div className="footer-bar">
          <span>© 2026 CoPowr. All rights reserved.</span>
          <span className="footer-legal">
            <L to="privacy">Privacy</L>
            <span className="dot">·</span>
            <L to="terms">Terms</L>
          </span>
        </div>
      </div>
    </footer>
  );
};

Object.assign(window, { Router, RouterCtx, Link, Reveal, AnnBar, Nav, Footer, CtaBand, useReveal });
