// sections.jsx — Nav, Hero (3 variants), and content sections
const { useEffect: useE, useRef: useR, useState: useS } = React;

// Auto-apply sage active class from query param immediately to avoid layout flash
if (typeof window !== "undefined") {
  const applySageTheme = () => {
    const params = new URLSearchParams(window.location.search);
    if (params.get("sage") === "true") {
      document.body.classList.add("sage-active");
    }
  };
  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", applySageTheme);
  } else {
    applySageTheme();
  }
}

function SageLogo({ size = 28 }) {
  const isArticle = typeof window !== "undefined" && window.location.pathname.includes("/articles/");
  const src = isArticle ? "../assets/sageLogopng.png" : "assets/sageLogopng.png";
  return (
    <div style={{ display: "flex", alignItems: "center" }}>
      <img src={src} alt="Sage Logo" style={{ height: size, objectFit: "contain" }} />
    </div>
  );
}
window.SageLogo = SageLogo;

/* ---------------- parallax for floating hero elements ---------------- */
function useParallax(ref) {
  useE(() => {
    const root = ref.current; if (!root) return;
    if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
    let raf = 0, tx = 0, ty = 0, cx = 0, cy = 0;
    const onMove = (e) => {
      const w = window.innerWidth, h = window.innerHeight;
      tx = (e.clientX / w - 0.5) * 2; ty = (e.clientY / h - 0.5) * 2;
      if (!raf) raf = requestAnimationFrame(tick);
    };
    const tick = () => {
      cx += (tx - cx) * 0.06; cy += (ty - cy) * 0.06;
      root.querySelectorAll("[data-depth]").forEach((el) => {
        const d = parseFloat(el.dataset.depth);
        el.style.transform = `translate3d(${cx * d * 26}px, ${cy * d * 26}px, 0)`;
      });
      raf = (Math.abs(tx - cx) > 0.001 || Math.abs(ty - cy) > 0.001) ? requestAnimationFrame(tick) : 0;
    };
    window.addEventListener("mousemove", onMove);
    return () => { window.removeEventListener("mousemove", onMove); cancelAnimationFrame(raf); };
  }, []);
}

/* ====================================================================
   NAV
   ==================================================================== */
function Nav({ sageMode: propSageMode, toggleSageMode }) {
  const [solid, setSolid] = useS(false);
  const [sageMode, setSageMode] = useS(false);

  useE(() => {
    const on = () => setSolid(window.scrollY > 30);
    window.addEventListener("scroll", on); on();
    return () => window.removeEventListener("scroll", on);
  }, []);

  useE(() => {
    if (propSageMode !== undefined) {
      setSageMode(propSageMode);
    } else {
      const params = new URLSearchParams(window.location.search);
      setSageMode(params.get("sage") === "true");
    }
  }, [propSageMode]);

  const handleSageClick = (e) => {
    if (toggleSageMode) {
      toggleSageMode(e);
    } else {
      // If we are on a subpage (e.g. team or blogs), trigger transition and redirect to home
      if (window.triggerSageTransition) {
        window.triggerSageTransition(e, () => {
          const isSage = !sageMode;
          setSageMode(isSage);
          if (isSage) {
            document.body.classList.add("sage-active");
            // Set styles manually for subpage during transition
            const r = document.documentElement.style;
            r.setProperty("--primary", "#769772");
            r.setProperty("--primary-soft", "#a4c2a0");
            r.setProperty("--accent", "#9caf88");
            r.setProperty("--bg-0", "#0a0f0b");
            r.setProperty("--ink", "#ffffff");
            r.setProperty("--ink-dim", "#a4c2a0");
            r.setProperty("--ink-faint", "#769772");
            window.location.href = "index.html?sage=true";
          } else {
            document.body.classList.remove("sage-active");
            window.location.href = "index.html";
          }
        });
      } else {
        const isSage = !sageMode;
        window.location.href = isSage ? "index.html?sage=true" : "index.html";
      }
    }
  };

  const getLink = (base) => {
    if (!sageMode) return base;
    if (base.includes("#")) {
      const [path, hash] = base.split("#");
      return `${path || "index.html"}?sage=true#${hash}`;
    }
    return `${base}?sage=true`;
  };

  return (
    React.createElement("header", {
      style: {
        position: "fixed", top: 0, left: 0, right: 0, zIndex: 100,
        transition: "all .35s ease", isolation: "isolate",
        padding: solid ? "10px 0" : "20px 0",
      }
    },
      React.createElement("div", {
        className: "wrap",
        style: { display: "flex", alignItems: "center", justifyContent: "space-between" }
      },
        // brand
        React.createElement("a", { href: getLink("index.html"), style: { display: "flex", alignItems: "center", gap: 12 } },
          sageMode ?
            React.createElement(SageLogo, null) :
            React.createElement("img", { src: "assets/logo.png", alt: "Blackstone AI", style: { height: 36, objectFit: "contain" } }),
        ),
        // links (glass pill)
        React.createElement("nav", {
          style: {
            display: "flex", gap: 4, padding: 6, borderRadius: 999,
            fontSize: 15, alignItems: "center",
            transform: "translateZ(0)", isolation: "isolate",
            background: sageMode ? "rgba(11, 18, 12, 0.85)" : "rgba(255,255,255,0.05)",
            border: sageMode ? "1px solid rgba(0, 214, 57, 0.2)" : "1px solid rgba(255,255,255,0.10)",
            WebkitBackdropFilter: sageMode ? "blur(12px)" : "blur(16px) saturate(150%)",
            backdropFilter: sageMode ? "blur(12px)" : "blur(16px) saturate(150%)",
            boxShadow: sageMode ? "0 10px 30px rgba(0,0,0,0.5), 0 0 0 1px rgba(0, 214, 57, 0.05)" : "inset 0 1px 0 rgba(255,255,255,0.14), 0 6px 22px rgba(0,0,0,0.22)",
          }
        },
          React.createElement("a", { href: getLink("index.html#integrate"), style: { padding: "8px 16px", borderRadius: 999, color: "var(--ink)", fontWeight: 500, textDecoration: "none" } }, "Work"),
          React.createElement("a", { href: getLink("team.html"), style: { padding: "8px 16px", borderRadius: 999, color: "var(--ink-dim)", textDecoration: "none" } }, "Team"),
          React.createElement("a", { href: getLink("blogs.html"), style: { padding: "8px 16px", borderRadius: 999, color: "var(--ink-dim)", textDecoration: "none" } }, "Blog"),
          React.createElement("a", { href: getLink("index.html#contact"), style: { padding: "8px 16px", borderRadius: 999, color: "var(--ink-dim)", textDecoration: "none" } }, "Contact")
        ),
        React.createElement("div", { style: { display: "flex", gap: 10, alignItems: "center" } },
          React.createElement("button", {
            onClick: handleSageClick,
            className: "btn btn-sage",
            style: { padding: "12px 22px", fontSize: 15, border: "none", cursor: "pointer" }
          }, sageMode ? "Exit Sage" : "Sage Version"),
          React.createElement("a", { href: getLink("index.html#start"), className: "btn btn-primary", style: { padding: "12px 22px", fontSize: 15 } }, "Start a project")
        )
      )
    )
  );
}

/* ====================================================================
   FLOATING GLASS DECOR (shared across hero variants)
   ==================================================================== */
function HeroDecor({ sageMode }) {
  return (
    <div style={{ position: "absolute", inset: 0, pointerEvents: "none", zIndex: 1 }}>
      {/* <div data-depth="1.4" style={{ position: "absolute", left: "6%", top: "26%" }}>
        <GlassIcon glyph="mobile" tint="var(--primary)" size={78} /></div> */}
      <div data-depth="0.9" style={{ position: "absolute", right: "9%", top: "20%" }}>
        <GlassIcon glyph="spark" tint={sageMode ? "#9caf88" : "var(--accent)"} size={64} /></div>
      <div data-depth="1.8" style={{ position: "absolute", right: "16%", top: "62%" }}>
        <GlassIcon glyph="bars" tint={sageMode ? "#769772" : "#c026d3"} size={70} /></div>
      {/* <div data-depth="1.1" style={{ position: "absolute", left: "13%", top: "66%" }}>
        <GlassIcon glyph="link" tint="var(--accent)" size={58} /></div> */}
      <div data-depth="0.6" style={orbStyle("9%", "12%", 120, sageMode ? "#769772" : "var(--primary)")} />
      <div data-depth="2.2" style={orbStyle("82%", "78%", 90, sageMode ? "#9caf88" : "var(--accent)")} />
    </div>
  );
}
function orbStyle(left, top, size, tint) {
  return {
    position: "absolute", left, top, width: size, height: size, borderRadius: "50%",
    background: `radial-gradient(circle at 32% 30%, rgba(255,255,255,.7), ${tint} 60%, transparent 72%)`,
    opacity: .25, filter: "blur(2px)",
  };
}

/* ====================================================================
   HERO PHONE MOCKUP
   ==================================================================== */
function MobileDashboard({ sageMode }) {
  const stats = sageMode ? [
    { label: "SAGE SYNC", val: "ACTIVE", color: "#769772", percent: "100%" },
    { label: "API PIPELINE", val: "4 PLUGS", color: "#9caf88", percent: "90%" },
    { label: "DATA ERRORS", val: "0", color: "var(--accent)", percent: "0%" }
  ] : [
    { label: "REVENUE", val: "R84K", color: "var(--primary)", percent: "70%" },
    { label: "USERS", val: "2.4K", color: "var(--accent)", percent: "50%" },
    { label: "TASKS", val: "97%", color: "#c026d3", percent: "97%" }
  ];

  return (
    <div className="phone">
      <div className="screen" style={{ background: sageMode ? "#090c0a" : "#0a0814", display: "flex", flexDirection: "column", color: "white" }}>
        {/* Status bar */}
        <div style={{ display: "flex", justifyContent: "space-between", padding: "14px 20px 0", fontSize: 11, fontFamily: "var(--font-mono)", color: "var(--ink-dim)" }}>
          <span>9:41</span>
          <div style={{ display: "flex", gap: 5, alignItems: "center" }}>
            <GlassIcon glyph="bars" size={12} tint="#fff" />
            <div style={{ width: 22, height: 11, borderRadius: 3, border: "1px solid rgba(255,255,255,0.4)" }} />
          </div>
        </div>

        {/* Header */}
        <div style={{ padding: "24px 20px 20px", display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
          <div>
            <div style={{ fontSize: 9, fontFamily: "var(--font-mono)", letterSpacing: "0.1em", color: "var(--ink-faint)", textTransform: "uppercase", marginBottom: 4 }}>
              {sageMode ? "AUTOMATED SYSTEM" : "Good Morning"}
            </div>
            <div style={{ fontSize: 22, fontFamily: "var(--font-display)", fontWeight: 800, margin: 0, lineHeight: 1.1 }}>
              {sageMode ? "Sage Custom" : "Dashboard"}
            </div>
          </div>
          <div style={{ width: 34, height: 34, borderRadius: "50%", background: sageMode ? "#769772" : "#a855f7", display: "grid", placeItems: "center", fontWeight: 700, fontSize: 14 }}>
            {sageMode ? "S" : "J"}
          </div>
        </div>

        {/* Content */}
        <div style={{ padding: "0 16px", display: "flex", flexDirection: "column", gap: 14, flex: 1 }}>
          {stats.map((c, i) => (
            <div key={i} style={{
              background: "rgba(255,255,255,0.03)", border: "1px solid rgba(255,255,255,0.06)",
              borderRadius: 14, padding: "18px 20px",
            }}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 16 }}>
                <div style={{ fontSize: 11, fontFamily: "var(--font-mono)", color: "var(--ink-faint)" }}>{c.label}</div>
                <div style={{ fontSize: 18, fontFamily: "var(--font-display)", fontWeight: 700, color: c.color }}>{c.val}</div>
              </div>
              <div style={{ height: 4, borderRadius: 2, background: "rgba(255,255,255,0.08)", width: "100%", position: "relative" }}>
                <div style={{ height: "100%", position: "absolute", left: 0, top: 0, borderRadius: 2, background: c.color, width: c.percent, boxShadow: `0 0 10px ${c.color}` }} />
              </div>
            </div>
          ))}
          <div style={{ height: 30, background: "rgba(255,255,255,0.03)", border: "1px solid rgba(255,255,255,0.06)", borderRadius: 12, marginTop: 4 }} />
        </div>

        {/* Bottom Nav */}
        <div style={{ display: "flex", justifyContent: "space-around", padding: "16px 0 20px", borderTop: "1px solid rgba(255,255,255,0.05)" }}>
          <div style={{ width: 44, height: 44, borderRadius: 14, background: sageMode ? "rgba(118,151,114,0.15)" : "rgba(124,58,237,0.15)", border: sageMode ? "1px solid rgba(118,151,114,0.3)" : "1px solid rgba(124,58,237,0.3)", display: "grid", placeItems: "center" }}>
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke={sageMode ? "#769772" : "var(--primary)"} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"></path><polyline points="9 22 9 12 15 12 15 22"></polyline></svg>
          </div>
          <div style={{ width: 44, height: 44, display: "grid", placeItems: "center" }}>
            <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="var(--ink-faint)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="3" y1="12" x2="21" y2="12"></line><line x1="3" y1="6" x2="21" y2="6"></line><line x1="3" y1="18" x2="21" y2="18"></line></svg>
          </div>
          <div style={{ width: 44, height: 44, display: "grid", placeItems: "center" }}>
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="var(--ink-faint)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"></path><path d="M13.73 21a2 2 0 0 1-3.46 0"></path></svg>
          </div>
          <div style={{ width: 44, height: 44, display: "grid", placeItems: "center" }}>
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="var(--ink-faint)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="3"></circle></svg>
          </div>
        </div>
      </div>
    </div>
  );
}

function HeroPhoneWrapper({ sageMode }) {
  return (
    <div style={{ position: "relative", width: "100%", maxWidth: 260, margin: "0 auto" }}>
      <MobileDashboard sageMode={sageMode} />

      <div data-depth="0.7" style={{
        position: "absolute", right: "-10%", top: "2%", zIndex: 10,
        display: "flex", alignItems: "center", gap: 10, padding: "10px 18px",
        background: "var(--glass-bg-2)", border: "1px solid var(--glass-brd)",
        borderRadius: 999, backdropFilter: "blur(12px)", WebkitBackdropFilter: "blur(12px)",
        color: "var(--ink-dim)", fontFamily: "var(--font-mono)", fontSize: 13,
        boxShadow: "0 10px 30px rgba(0,0,0,0.05), inset 0 1px 0 rgba(255,255,255,0.05)"
      }}>
        <div style={{ width: 6, height: 6, borderRadius: "50%", background: "var(--accent)", boxShadow: "0 0 10px var(--accent)" }} />
        {sageMode ? "ERP Pipeline" : "Live • v2.4.1"}
      </div>

      <div data-depth="1.6" style={{
        position: "absolute", left: "-15%", bottom: "2%", zIndex: 10,
        display: "flex", alignItems: "center", gap: 16, padding: "14px 20px",
        background: "var(--glass-bg-2)", border: "1px solid var(--glass-brd)",
        borderRadius: 20, backdropFilter: "blur(16px)", WebkitBackdropFilter: "blur(16px)",
        boxShadow: "0 20px 40px rgba(0,0,0,0.05), inset 0 1px 0 rgba(255,255,255,0.05)"
      }}>
        <div style={{
          width: 40, height: 40, borderRadius: 12, background: sageMode ? "#769772" : "#a855f7",
          display: "grid", placeItems: "center", flex: "none",
          boxShadow: sageMode ? "inset 0 1px 0 rgba(255,255,255,0.2), 0 4px 12px rgba(118,151,114,0.4)" : "inset 0 1px 0 rgba(255,255,255,0.2), 0 4px 12px rgba(168,85,247,0.4)"
        }}>
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12" /></svg>
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 3, textAlign: "left" }}>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.15em", textTransform: "uppercase", color: "var(--ink-dim)", lineHeight: 1 }}>{sageMode ? "Sage APIs" : "Shipped"}</div>
          <div style={{ fontWeight: 700, color: "white", fontSize: 15, letterSpacing: "-0.01em", lineHeight: 1.1 }}>{sageMode ? "100% Reliable." : "On time. Always."}</div>
        </div>
      </div>
    </div>
  );
}

/* ====================================================================
   HERO — three switchable directions
   ==================================================================== */
function Hero({ variant, sageMode }) {
  const ref = useR(null);
  useParallax(ref);

  if (sageMode) {
    return (
      <section id="top" ref={ref} style={{
        minHeight: "85vh", display: "flex", alignItems: "center", justifyContent: "center",
        paddingTop: 160, paddingBottom: 60, position: "relative", overflow: "hidden",
        background: "#050806"
      }}>
        <div className="wrap" style={{
          position: "relative", zIndex: 2, maxWidth: 840, textAlign: "center"
        }}>
          <div style={{ display: "flex", justifyContent: "center", marginBottom: 32 }} className="reveal in">
            <img src="assets/sageLogopng.png" alt="Sage Logo" style={{ height: 54, objectFit: "contain" }} />
          </div>
          <div className="reveal in">
            <h1 style={{ fontSize: "clamp(48px, 8vw, 110px)", letterSpacing: "-.04em", lineHeight: 1.0 }}>
              We Integrate <br />
              <span className="grad-text">With Sage.</span>
            </h1>
          </div>
          <p className="lead reveal in d1" style={{ margin: "24px auto 0", fontSize: "clamp(18px, 1.8vw, 24px)", color: "var(--ink-dim)", lineHeight: 1.5, textWrap: "balance", textAlign: "center" }}>
            Custom apps and automations built directly around your existing Sage system.
          </p>
        </div>
        <div style={{ position: "absolute", bottom: 28, left: "50%", transform: "translateX(-50%)", fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: ".3em", color: "var(--ink-faint)", textTransform: "uppercase", display: "flex", flexDirection: "column", alignItems: "center", gap: 8 }}>
          Scroll <span className="scroll-dot" />
        </div>
      </section>
    );
  }

  let head;
  if (variant === "conversational") {
    head = <h1 style={{ fontSize: "clamp(44px, 7vw, 100px)" }}>Got an idea?<br /><span className="grad-text">Let's build the app</span></h1>;
  } else if (variant === "kinetic") {
    head = <h1 style={{ fontSize: "clamp(44px, 7vw, 105px)" }}>Turn Your Idea Into<RotatingWord sageMode={sageMode} /><br />Into a Product</h1>;
  } else { // statement
    head = <h1 style={{ fontSize: "clamp(50px, 9vw, 140px)", letterSpacing: "-.035em" }}>Custom Apps <br /><span className="grad-text">Built to Solve</span></h1>;
  }

  const sub = variant === "statement"
    ? "We build custom apps that provide solutions to your business issues"
    : variant === "conversational"
      ? "From a note on the back of an envelope to something real in people's hands. We design it, build it, and ship it — no fuss."
      : "One team, every kind of app. Built to be simple, fast, and actually used.";

  return (
    <section id="top" ref={ref} style={{
      minHeight: "100vh", display: "flex", alignItems: "center", justifyContent: "center",
      paddingTop: 160, paddingBottom: 60, position: "relative", overflow: "hidden"
    }}>
      <HeroDecor sageMode={sageMode} />
      <div className="wrap" style={{
        position: "relative", zIndex: 2, maxWidth: 1160,
        display: "flex", flexWrap: "wrap", alignItems: "center", gap: "clamp(40px, 6vw, 80px)", justifyContent: "center"
      }}>
        <div style={{ flex: "1 1 500px", minWidth: 0, textAlign: "left" }}>
          {/* <div className="eyebrow reveal in" style={{ marginBottom: 26, justifyContent: "flex-start" }}>An app studio that ships</div> */}
          <div className="reveal in">{head}</div>
          <p className="lead reveal in d1" style={{ margin: "30px 0 0", textAlign: "left", fontSize: "clamp(18px,1.8vw,23px)" }}>{sub}</p>
          {/* <div className="reveal in d2" style={{ display: "flex", gap: 14, flexWrap: "wrap", marginTop: 38, justifyContent: "flex-start" }}>
            <a href="#start" className="btn btn-primary">Start a project <span className="arr">→</span></a>
            <a href="#make" className="btn btn-ghost">See what we make</a>
          </div> */}
          {/* <div className="reveal in d3 mono" style={{ marginTop: 30, fontSize: 13, color: "var(--ink-faint)", letterSpacing: ".04em", display: "flex", gap: 18, flexWrap: "wrap", justifyContent: "flex-start" }}>
            <span>Johannesburg, South Africa</span><span style={{ opacity: .4 }}>•</span><span>Quick to ship</span>
          </div> */}
        </div>
        <div className="reveal in d4" style={{ flex: "1 1 340px", minWidth: 0, display: "flex", justifyContent: "center" }}>
          <HeroPhoneWrapper sageMode={sageMode} />
        </div>
      </div>
      <div style={{ position: "absolute", bottom: 28, left: "50%", transform: "translateX(-50%)", fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: ".3em", color: "var(--ink-faint)", textTransform: "uppercase", display: "flex", flexDirection: "column", alignItems: "center", gap: 8 }}>
        Scroll <span className="scroll-dot" />
      </div>
    </section>
  );
}

function RotatingWord({ sageMode }) {
  const words = sageMode ? ["sage", "erp", "pastel", "evolution", "sync"] : ["web", "mobile", "internal", "smart", "desktop"];
  const tints = sageMode ? ["#9caf88", "#769772", "#a4c2a0", "#8fa382", "#b3d4ad"] : ["var(--primary-soft)", "var(--accent)", "#e879f9", "#c4b5fd", "#5eead4"];
  const [i, setI] = useS(0);
  useE(() => {
    if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
    const t = setInterval(() => setI((v) => (v + 1) % words.length), 1900);
    return () => clearInterval(t);
  }, []);
  return React.createElement("span", {
    key: i, className: "rot-word",
    style: { color: tints[i], display: "inline-block" }
  }, words[i]);
}

/* ====================================================================
   SECTION HEADER helper
   ==================================================================== */
function SecHead({ eyebrow, title, lead, align = "center" }) {
  return (
    React.createElement("div", { style: { textAlign: align, maxWidth: align === "center" ? 760 : 620, margin: align === "center" ? "0 auto" : 0 } },
      React.createElement("div", { className: "eyebrow reveal", style: { marginBottom: 20, justifyContent: align === "center" ? "center" : "flex-start" } }, eyebrow),
      React.createElement("h2", { className: "reveal d1", style: { fontSize: "clamp(36px, 5.5vw, 76px)" } }, title),
      lead && React.createElement("p", { className: "lead reveal d2", style: { margin: align === "center" ? "24px auto 0" : "24px 0 0", fontSize: "clamp(17px,1.6vw,21px)" } }, lead),
    )
  );
}

Object.assign(window, { Nav, Hero, HeroDecor, SecHead, useParallax, RotatingWord });
