// ─────────────────────────────────────────────────────────────────────
// Shared scaffolding for the four Company pages, all routed under
// /company/<slug>/ :
//   /company/about-us/
//   /company/our-approach/
//   /company/global-workforce/
//   /company/security-and-compliance/
//
// Exposes on window:
//   - CompanyHero    : the dark-green motion-blur hero, parameterised
//                      by H1 / subhead / hero intro / hero photo / the
//                      active route id for the pill bar in the eyebrow
//                      slot.
//   - CompanyRoutes  : the horizontal pill bar that sits in the hero's
//                      eyebrow slot, used as a page-level nav across
//                      the four Company routes. The active route is
//                      highlighted as a solid white pill; the others
//                      are glass-transparent links.
//   - SectionLabel   : the small uppercase eyebrow used on every
//                      section.
//   - FinalCTA       : the shared "Learn how Argos Data can support
//                      your enterprise AI program." CTA, identical
//                      across all four routes, taken verbatim from
//                      COMPANY.md §Final CTA.
//
// The hero uses the exact same recipe as the existing site heroes
// (Hero / SolutionHero), so these pages sit visually inside the system
// rather than next to it. The tonal shift toward "warmer, more
// photographic" lives in the page bodies (more imagery, more cream
// panels), not in the hero treatment.
// ─────────────────────────────────────────────────────────────────────

// Page-level nav rendered in the hero eyebrow slot. Each pill is a
// real <a>; the active route is styled as a solid white pill, the
// others stay glass-transparent. Active state is set per-page via
// the CompanyHero `route` prop.
// CountUp — animates 0→target the first time the element scrolls
// into view (cubic ease-out, ~1600ms default). Mirrors the
// implementation used on the homepage so the four Company pages
// feel native to the rest of the site. Respects
// prefers-reduced-motion by skipping the animation and rendering
// the final value. Supports an optional prefix (e.g. "L") and
// suffix (e.g. "+", "K+"), plus decimal places for non-integer
// targets.
const CountUp = ({ to, prefix = "", suffix = "", decimals = 0, duration = 1600 }) => {
  const [value, setValue] = React.useState(0);
  const ref = React.useRef(null);
  const startedRef = React.useRef(false);

  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    if (typeof window !== "undefined" &&
        window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches) {
      setValue(to);
      startedRef.current = true;
      return;
    }
    const run = () => {
      if (startedRef.current) return;
      startedRef.current = true;
      const start = performance.now();
      const factor = Math.pow(10, decimals);
      const ease = (t) => 1 - Math.pow(1 - t, 3);
      const tick = (now) => {
        const t = Math.min((now - start) / duration, 1);
        setValue(Math.round(to * factor * ease(t)) / factor);
        if (t < 1) requestAnimationFrame(tick);
      };
      requestAnimationFrame(tick);
    };
    if (typeof IntersectionObserver === "undefined") { run(); return; }
    const obs = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) { run(); obs.disconnect(); }
      });
    }, { threshold: 0.4 });
    obs.observe(el);
    return () => obs.disconnect();
  }, [to, duration, decimals]);

  return <span ref={ref}>{prefix}{value.toFixed(decimals)}{suffix}</span>;
};

const COMPANY_ROUTES = [
  { id: "about",     label: "About Us",              href: "/company/about-us/" },
  { id: "approach",  label: "Our Approach",          href: "/company/our-approach/" },
  { id: "workforce", label: "Global Workforce",      href: "/company/global-workforce/" },
  { id: "security",  label: "Security & Compliance", href: "/company/security-and-compliance/" },
];

// Session-storage key for remembering the previously-active route so
// the pill bar on the next page can render its sliding indicator
// starting from where it was, then animate to the new active pill.
const PREV_ROUTE_KEY = "argosCompanyPrevRoute";

const CompanyRoutes = ({ active }) => {
  const navRef = React.useRef(null);
  const btnRefs = React.useRef({});
  // pos.animated controls whether the CSS transition is enabled:
  // - First paint after navigation: we snap (animated: false) to the
  //   PREVIOUS route's position, then on the next frame switch to
  //   animated: true and update to the CURRENT route — giving us the
  //   slide.
  // - If there is no previous route (first visit), we just snap to
  //   the active position and never animate.
  // - Window resize keeps everything snapped, no animation.
  const [pos, setPos] = React.useState({ x: 0, w: 0, animated: false, ready: false });

  const measure = React.useCallback((id) => {
    const nav = navRef.current;
    const btn = btnRefs.current[id];
    if (!nav || !btn) return null;
    const navRect = nav.getBoundingClientRect();
    const btnRect = btn.getBoundingClientRect();
    return { x: btnRect.left - navRect.left, w: btnRect.width };
  }, []);

  React.useLayoutEffect(() => {
    // Read previous route from sessionStorage. If absent / invalid /
    // same as the current route, treat it as a no-animation snap.
    let prev = null;
    try { prev = sessionStorage.getItem(PREV_ROUTE_KEY); } catch (e) {}
    if (!prev || !btnRefs.current[prev]) prev = active;

    const startPos = measure(prev);
    if (!startPos) return;
    // Initial: place indicator at the PREVIOUS route's slot, no anim.
    setPos({ ...startPos, animated: false, ready: true });

    if (prev !== active) {
      // After two frames (one to let React commit the initial pos,
      // one for the browser to paint it), flip on animation and move
      // to the active route.
      const r1 = requestAnimationFrame(() => {
        const r2 = requestAnimationFrame(() => {
          const endPos = measure(active);
          if (endPos) setPos({ ...endPos, animated: true, ready: true });
        });
        // store the inner rAF so we can cancel if unmounted
        navRef.current && (navRef.current.__rafInner = r2);
      });
      navRef.current && (navRef.current.__rafOuter = r1);
    }

    // Remember this route as the "previous" for the next navigation.
    try { sessionStorage.setItem(PREV_ROUTE_KEY, active); } catch (e) {}

    return () => {
      if (navRef.current) {
        if (navRef.current.__rafOuter) cancelAnimationFrame(navRef.current.__rafOuter);
        if (navRef.current.__rafInner) cancelAnimationFrame(navRef.current.__rafInner);
      }
    };
  }, [active, measure]);

  // Keep the indicator aligned if the viewport resizes (font reflow,
  // breakpoint changes, etc.). Always snap on resize — no animation.
  React.useEffect(() => {
    const onResize = () => {
      const p = measure(active);
      if (p) setPos({ ...p, animated: false, ready: true });
    };
    window.addEventListener("resize", onResize);
    return () => window.removeEventListener("resize", onResize);
  }, [active, measure]);

  // Save current as "previous" right before the browser navigates,
  // belt-and-braces alongside the useLayoutEffect write — covers
  // cases where the page commits before the effect runs.
  const recordPrev = () => {
    try { sessionStorage.setItem(PREV_ROUTE_KEY, active); } catch (e) {}
  };

  return (
    <nav aria-label="Company pages" ref={navRef} style={{
      position: "relative",
      display: "inline-flex", alignItems: "center",
      gap: 0, padding: 6,
      background: "rgba(255,255,255,0.08)",
      border: "1px solid rgba(255,255,255,0.18)",
      borderRadius: 999,
      backdropFilter: "blur(10px) saturate(140%)",
      WebkitBackdropFilter: "blur(10px) saturate(140%)",
      width: "fit-content",
      // Isolate so the difference-blend on the pill labels is contained
      // to this stacking context and doesn't leak onto the hero.
      isolation: "isolate",
    }}>
      {/* Sliding indicator pill. Lives at z-index 0 underneath the
          labels; the labels use mix-blend-mode: difference so their
          color flips automatically as the indicator slides over them. */}
      <div aria-hidden="true" style={{
        position: "absolute",
        top: 6, bottom: 6,
        left: 0,
        width: pos.w,
        transform: `translateX(${pos.x}px)`,
        background: "#FFFFFF",
        borderRadius: 999,
        transition: pos.animated
          ? "transform 460ms cubic-bezier(0.22, 0.8, 0.26, 1), width 460ms cubic-bezier(0.22, 0.8, 0.26, 1)"
          : "none",
        opacity: pos.ready ? 1 : 0,
        zIndex: 0,
        pointerEvents: "none",
      }}/>
      {COMPANY_ROUTES.map((r) => (
        <a key={r.id} href={r.href}
          ref={(el) => { btnRefs.current[r.id] = el; }}
          onClick={recordPrev}
          style={{
            position: "relative", zIndex: 1,
            display: "inline-flex", alignItems: "center",
            padding: "10px 18px", borderRadius: 999,
            fontFamily: "var(--font-display)",
            fontSize: 13, fontWeight: 500, letterSpacing: "0.01em",
            textDecoration: "none",
            color: "#FFFFFF",
            // Difference blend gives us automatic legibility on both
            // the glass nav background AND the white indicator pill:
            // white XOR white ≈ black, white XOR dark ≈ light.
            mixBlendMode: "difference",
            whiteSpace: "nowrap",
          }}>
          {r.label}
        </a>
      ))}
    </nav>
  );
};

const CompanyHero = ({
  route,
  h1,
  subhead,
  intro,
  image,
}) => (
  <section data-screen-label="Hero" data-nav-tone="dark" className="full-bleed" style={{
    position: "relative",
    minHeight: "min(820px, 100svh)",
    maxHeight: "min(1000px, 100svh)",
    padding: "clamp(180px, 20vh, 280px) clamp(20px, 6vw, 96px) clamp(48px, 8vh, 120px)",
    fontFamily: "var(--font-display)",
    color: "#FFFFFF",
    overflow: "hidden",
    display: "flex", flexDirection: "column",
    background:
      "radial-gradient(120% 90% at 78% 55%, #1F6E5C 0%, #0F3D34 38%, #061C18 78%, #020A09 100%)",
  }}>
    <div aria-hidden="true" style={{
      position: "absolute", inset: 0,
      backgroundImage: `url('${image}')`,
      backgroundSize: "cover",
      backgroundPosition: "center right",
      backgroundRepeat: "no-repeat",
      mixBlendMode: "screen",
      opacity: 0.95,
      maskImage:
        "linear-gradient(to right, transparent 0%, rgba(0,0,0,0.25) 18%, #000 50%, #000 100%)",
      WebkitMaskImage:
        "linear-gradient(to right, transparent 0%, rgba(0,0,0,0.25) 18%, #000 50%, #000 100%)",
    }}/>
    <div aria-hidden="true" style={{
      position: "absolute", inset: 0,
      background:
        "linear-gradient(180deg, rgba(0,0,0,0.10) 0%, rgba(0,0,0,0) 35%, rgba(0,0,0,0.45) 100%), " +
        "linear-gradient(90deg, rgba(2,10,9,0.55) 0%, rgba(2,10,9,0) 45%)",
      pointerEvents: "none",
    }}/>

    <div style={{ position: "relative", maxWidth: 1600, margin: "0 auto",
      width: "100%", flex: 1, display: "flex", flexDirection: "column",
      justifyContent: "flex-end", gap: 56 }}>
      {/* Headline group — bottom-left, sits above the pill bar. */}
      <div>
        <h1 style={{
          fontSize: 84, fontWeight: 700, lineHeight: 1.02,
          letterSpacing: "-0.035em", margin: 0, maxWidth: 1300,
          textWrap: "balance", color: "#FFFFFF",
        }}>{h1}</h1>

        {subhead ? (
          <p style={{
            margin: "24px 0 0", maxWidth: 880, fontSize: 22, lineHeight: 1.35,
            fontWeight: 500, color: "rgba(255,255,255,0.92)",
            letterSpacing: "-0.01em",
          }}>{subhead}</p>
        ) : null}

        {intro ? (
          <p style={{
            margin: "20px 0 0", maxWidth: 720, fontSize: 17, lineHeight: 1.55,
            fontWeight: 400, color: "rgba(255,255,255,0.72)",
          }}>{intro}</p>
        ) : null}
      </div>

      {/* Pill bar — anchored to the very bottom of the hero,
          horizontally centered. Position is invariant across the
          four Company pages because the parent's flex-end keeps it
          glued to the bottom edge regardless of headline length. */}
      <div style={{ display: "flex", justifyContent: "center" }}>
        <CompanyRoutes active={route}/>
      </div>
    </div>
  </section>
);

// Compact reusable eyebrow row used at the top of every section.
const SectionLabel = ({ children, onDark = false, style }) => (
  <div style={{
    fontSize: 13, fontWeight: 500,
    color: onDark ? "rgba(255,255,255,0.65)" : "#666",
    letterSpacing: "0.10em", textTransform: "uppercase",
    marginBottom: 24,
    ...style,
  }}>{children}</div>
);

// Shared Final CTA — appears at the bottom of all four company pages.
// Copy is verbatim from COMPANY.md §Final CTA.
const FinalCTA = () => (
  <section data-screen-label="Final CTA" data-nav-tone="dark" className="full-bleed" style={{
    position: "relative",
    fontFamily: "var(--font-display)",
    background: "#0E1F3E", color: "#FFFFFF",
    padding: "clamp(60px, 12vw, 140px) clamp(20px, 6vw, 96px)",
    overflow: "hidden",
  }}>
    {/* Soft warm glow on the right — picks up the yellow/green note
        from the photography palette without competing with content. */}
    <div aria-hidden="true" style={{
      position: "absolute", inset: 0,
      background:
        "radial-gradient(60% 80% at 92% 50%, rgba(238,227,107,0.18) 0%, rgba(238,227,107,0.04) 40%, rgba(14,31,62,0) 70%), " +
        "radial-gradient(40% 60% at 8% 30%, rgba(48,170,116,0.18) 0%, rgba(48,170,116,0) 60%)",
      pointerEvents: "none",
    }}/>

    <div style={{ position: "relative", maxWidth: 1600, margin: "0 auto",
      display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 96,
      alignItems: "end" }}>
      <div>
        <SectionLabel onDark style={{ color: "rgba(255,255,255,0.55)" }}>
          Talk to Argos Data
        </SectionLabel>
        <h2 style={{
          fontSize: 72, fontWeight: 700, lineHeight: 1.02,
          letterSpacing: "-0.035em", margin: 0, textWrap: "balance",
          maxWidth: 1100,
        }}>
          Learn how Argos Data can support your enterprise AI program.
        </h2>
      </div>
      <div style={{ display: "flex", flexDirection: "column", gap: 14,
        alignItems: "flex-start" }}>
        <a href="/contact-us/" style={{
          display: "inline-flex", alignItems: "center", gap: 10,
          background: "#FFFFFF", color: "#0E1F3E",
          padding: "16px 28px", borderRadius: 37,
          fontSize: 14, fontWeight: 500,
          fontFamily: "var(--font-display)",
          letterSpacing: "-0.005em", textDecoration: "none",
        }} data-dark-pill>
          <span style={{
            width: 7, height: 7, borderRadius: "50%",
            background: "#30AA74",
            boxShadow: "0 0 0 3px rgba(48,170,116,0.20)",
            display: "inline-block",
          }}/>
          Talk to an expert
        </a>
        <a href="/#solutions" data-arrow="right" style={{
          display: "inline-flex", alignItems: "center", gap: 8,
          padding: "14px 0",
          color: "rgba(255,255,255,0.85)",
          fontSize: 14, fontWeight: 500,
          textDecoration: "none",
          letterSpacing: "-0.005em",
          borderBottom: "1px solid rgba(255,255,255,0.30)",
        }}>
          Explore our solutions <span aria-hidden="true" className="arrow">→</span>
        </a>
      </div>
    </div>
  </section>
);

Object.assign(window, { CompanyHero, CompanyRoutes, SectionLabel, FinalCTA, CountUp });
