/* E.S. Wagner — shared site chrome (Nav + Footer).
   Responsive (desktop nav collapses to a drawer under 900px).
   Nav supports theme="light" (solid white) and theme="transparent"
   (overlays a dark hero, flips to solid white on scroll).
   Exposes window.ESWNav and window.ESWFooter. */

function useIsMobile(bp) {
  const q = "(max-width: " + (bp || 900) + "px)";
  const [m, setM] = React.useState(() => window.matchMedia(q).matches);
  React.useEffect(() => {
    const mq = window.matchMedia(q);
    const fn = (e) => setM(e.matches);
    mq.addEventListener("change", fn);
    return () => mq.removeEventListener("change", fn);
  }, [q]);
  return m;
}
window.useIsMobile = useIsMobile;

/* Shared scroll-reveal: progressive reveal on scroll + guaranteed fallback. */
function useReveal() {
  React.useEffect(() => {
    document.documentElement.classList.add("has-js");
    const els = Array.from(document.querySelectorAll(".reveal"));
    let io = null;
    if ("IntersectionObserver" in window) {
      io = new IntersectionObserver((ents) => {
        ents.forEach((e) => { if (e.isIntersecting) { e.target.classList.add("in"); io.unobserve(e.target); } });
      }, { threshold: 0.12, rootMargin: "0px 0px -8% 0px" });
      els.forEach((el) => io.observe(el));
    } else {
      els.forEach((el) => el.classList.add("in"));
    }
    // Safety net: never leave content stuck hidden (captures, print, edge timing).
    const t = setTimeout(() => els.forEach((el) => el.classList.add("in")), 1400);
    return () => { if (io) io.disconnect(); clearTimeout(t); };
  }, []);
}
window.useReveal = useReveal;

const ESW_NAV = [
  { id: "about", label: "About Us" },
  { id: "work", label: "Our Work" },
  { id: "culture", label: "Our Culture" },
  { id: "careers", label: "Careers" },
  { id: "news", label: "News & Insights" },
];

function ESWNav({ theme }) {
  const { Button } = window.ESWagnerDesignSystem_ee40a0;
  const transparent = theme === "transparent";
  const [scrolled, setScrolled] = React.useState(false);
  const [drawer, setDrawer] = React.useState(false);
  const mobile = useIsMobile(960);

  React.useEffect(() => {
    // The preview/embed context doesn't reliably deliver window "scroll" events
    // or IntersectionObserver callbacks, so poll the scroll offset each frame.
    let raf, last = null;
    const read = () => {
      const y = window.pageYOffset || document.scrollingElement?.scrollTop || document.documentElement.scrollTop || 0;
      const next = y > 12;
      if (next !== last) { last = next; setScrolled(next); }
      raf = requestAnimationFrame(read);
    };
    raf = requestAnimationFrame(read);
    return () => cancelAnimationFrame(raf);
  }, []);
  React.useEffect(() => { if (window.lucide) window.lucide.createIcons(); });

  const solid = !transparent || scrolled;
  const ink = solid ? "var(--text-strong)" : "#fff";

  return (
    <header style={{
      position: transparent ? "fixed" : "sticky", top: 0, left: 0, right: 0, zIndex: 200,
      background: solid ? "rgba(255,255,255,0.97)" : "transparent",
      backdropFilter: solid ? "saturate(180%) blur(8px)" : "none",
      borderBottom: solid ? "1px solid var(--border-subtle)" : "1px solid transparent",
      boxShadow: solid && scrolled ? "var(--shadow-sm)" : "none",
      transition: "background .25s var(--ease-out), box-shadow .25s, border-color .25s",
    }}>
      <div style={{ maxWidth: "var(--container-max)", margin: "0 auto", padding: "0 var(--gutter)", height: 76, display: "flex", alignItems: "center", justifyContent: "space-between", gap: 24 }}>
        <a href="index.html" style={{ display: "flex", alignItems: "center", flexShrink: 0 }}>
          {solid
            ? <img src="assets/logos/esw-logo-horizontal.png" alt="E.S. Wagner Co." style={{ height: 34 }} />
            : <img src="assets/logos/esw-logo-horizontal-white.png" alt="E.S. Wagner Co." style={{ height: 32 }} />}
        </a>

        {!mobile && (
          <nav style={{ display: "flex", alignItems: "center", gap: 4 }}>
            {ESW_NAV.map((item) => (
              <a key={item.id} href="#" onClick={(e) => e.preventDefault()}
                style={{
                  fontFamily: "var(--font-heading)", fontWeight: 600, textTransform: "uppercase",
                  letterSpacing: "0.05em", fontSize: 14.5, color: ink, cursor: "pointer",
                  padding: "10px 14px", borderBottom: "2px solid transparent", transition: "color .2s, border-color .2s",
                }}
                onMouseEnter={(e) => { e.currentTarget.style.borderBottomColor = "var(--brand-primary)"; }}
                onMouseLeave={(e) => { e.currentTarget.style.borderBottomColor = "transparent"; }}>
                {item.label}
              </a>
            ))}
          </nav>
        )}

        {!mobile && (
          <Button variant={solid ? "primary" : "outline-light"} size="sm">Contact</Button>
        )}

        {mobile && (
          <button onClick={() => setDrawer(true)} aria-label="Menu"
            style={{ background: "none", border: "none", cursor: "pointer", color: ink, display: "flex", padding: 6 }}>
            <i data-lucide="menu" style={{ width: 28, height: 28 }} />
          </button>
        )}
      </div>

      {mobile && drawer && (
        <div style={{ position: "fixed", inset: 0, zIndex: 300 }}>
          <div onClick={() => setDrawer(false)} style={{ position: "absolute", inset: 0, background: "rgba(17,22,28,0.5)" }} />
          <div style={{ position: "absolute", top: 0, right: 0, bottom: 0, width: "min(82vw, 340px)", background: "var(--esw-navy)", color: "#fff", padding: "24px 26px", display: "flex", flexDirection: "column", gap: 4, boxShadow: "var(--shadow-lg)" }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 22 }}>
              <img src="assets/logos/esw-wordmark-white.png" alt="ESW" style={{ height: 26 }} />
              <button onClick={() => setDrawer(false)} aria-label="Close" style={{ background: "none", border: "none", cursor: "pointer", color: "#fff", display: "flex" }}>
                <i data-lucide="x" style={{ width: 26, height: 26 }} />
              </button>
            </div>
            {ESW_NAV.map((item) => (
              <a key={item.id} href="#" onClick={(e) => { e.preventDefault(); setDrawer(false); }}
                style={{ fontFamily: "var(--font-heading)", fontWeight: 600, textTransform: "uppercase", letterSpacing: "0.05em", fontSize: 19, color: "#fff", padding: "14px 0", borderBottom: "1px solid rgba(255,255,255,0.12)", cursor: "pointer" }}>
                {item.label}
              </a>
            ))}
            <div style={{ marginTop: 22 }}>
              <Button variant="primary" size="md" fullWidth>Contact</Button>
            </div>
          </div>
        </div>
      )}
    </header>
  );
}
window.ESWNav = ESWNav;

function ESWFooter() {
  const D = window.ESW_HOME;
  React.useEffect(() => { if (window.lucide) window.lucide.createIcons(); });
  const col = { display: "flex", flexDirection: "column", gap: 10 };
  const head = { fontFamily: "var(--font-heading)", fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.08em", fontSize: 13, color: "#fff", marginBottom: 6 };
  const link = { fontFamily: "var(--font-body)", fontSize: 14, color: "rgba(255,255,255,0.7)", cursor: "pointer", textDecoration: "none" };

  return (
    <footer style={{ background: "var(--esw-asphalt)", color: "#fff" }}>
      <div className="esw-footer-grid" style={{ maxWidth: "var(--container-max)", margin: "0 auto", padding: "64px var(--gutter) 40px", display: "grid", gridTemplateColumns: "1.6fr 1fr 1fr 1.4fr", gap: 48 }}>
        <div>
          <img src="assets/logos/esw-logo-footer.png" alt="E.S. Wagner Co." style={{ height: 35, marginBottom: 18 }} />
          <p style={{ fontFamily: "var(--font-body)", fontSize: 14.5, lineHeight: 1.6, color: "rgba(255,255,255,0.72)", maxWidth: 320, margin: 0 }}>
            A multi-generational heavy-civil and site-development leader, trusted to deliver complex infrastructure with control, integrity, and purpose. <strong style={{ color: "#fff" }}>Since 1947.</strong>
          </p>
        </div>
        <div style={col}>
          <div style={head}>Company</div>
          <a style={link} href="#" onClick={(e)=>e.preventDefault()}>About Us</a>
          <a style={link} href="#" onClick={(e)=>e.preventDefault()}>Our Work</a>
          <a style={link} href="#" onClick={(e)=>e.preventDefault()}>Our Culture</a>
          <a style={link} href="#" onClick={(e)=>e.preventDefault()}>Careers</a>
          <a style={link} href="#" onClick={(e)=>e.preventDefault()}>News & Insights</a>
        </div>
        <div style={col}>
          <div style={head}>Sectors</div>
          {D.sectors.items.slice(0, 6).map((s) => (
            <a key={s.id} style={link} href="#" onClick={(e)=>e.preventDefault()}>{s.label}</a>
          ))}
        </div>
        <div style={col}>
          <div style={head}>Offices</div>
          {D.locations.offices.map((o) => (
            <div key={o.city} style={{ marginBottom: 8 }}>
              <div style={{ fontFamily: "var(--font-heading)", fontWeight: 600, textTransform: "uppercase", fontSize: 13, letterSpacing: "0.04em", color: "#fff" }}>{o.city}</div>
              <div style={{ fontFamily: "var(--font-body)", fontSize: 13, color: "rgba(255,255,255,0.65)", lineHeight: 1.5 }}>{o.role}</div>
            </div>
          ))}
          <div style={{ fontFamily: "var(--font-heading)", fontWeight: 700, fontSize: 16, color: "var(--esw-dozer)", letterSpacing: "0.02em", marginTop: 2 }}>{D.locations.phone}</div>
        </div>
      </div>
      <div style={{ borderTop: "1px solid rgba(255,255,255,0.12)" }}>
        <div style={{ maxWidth: "var(--container-max)", margin: "0 auto", padding: "20px var(--gutter)", display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 12 }}>
          <span style={{ fontFamily: "var(--font-body)", fontSize: 13, color: "rgba(255,255,255,0.5)" }}>© 2026 E.S. Wagner Co. All rights reserved.</span>
          <span style={{ fontFamily: "var(--font-heading)", textTransform: "uppercase", letterSpacing: "0.1em", fontSize: 12.5, color: "var(--esw-legacy-red)", fontWeight: 600 }}>Trusted Partner · Proven Results</span>
        </div>
      </div>
    </footer>
  );
}
window.ESWFooter = ESWFooter;
