/* MCA, AI Solutions page (bespoke) */

const { useState: useS, useEffect: useE, useRef: useR } = React;

/* ---------- Hero visual: living neural network field ----------
   Canvas-based constellation of drifting nodes connected by proximity
   links, with teal signal pulses traveling the edges. Intentionally
   distinct from the Growth & Scale concentric-orbit background. */
function AINeuralField() {
  const canvasRef = useR(null);

  useE(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext("2d");
    const reduce = window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches;

    let w = 0, h = 0, dpr = Math.min(window.devicePixelRatio || 1, 2);
    let nodes = [];
    let pulses = [];
    let raf = 0;
    const mouse = { x: -9999, y: -9999 };

    const TEAL = [0, 165, 161];
    const LINK_DIST = 168;          // px proximity for drawing a link
    const LINK_DIST2 = LINK_DIST * LINK_DIST;

    function resize() {
      const rect = canvas.getBoundingClientRect();
      w = rect.width; h = rect.height;
      canvas.width = Math.round(w * dpr);
      canvas.height = Math.round(h * dpr);
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
      // node density scales with area
      const count = Math.max(34, Math.min(96, Math.round(w * h / 17000)));
      nodes = Array.from({ length: count }).map(() => ({
        x: Math.random() * w,
        y: Math.random() * h,
        vx: (Math.random() - 0.5) * 0.22,
        vy: (Math.random() - 0.5) * 0.22,
        r: Math.random() * 1.6 + 1.1,
        ph: Math.random() * Math.PI * 2 // twinkle phase
      }));
      pulses = [];
    }

    function spawnPulse() {
      if (nodes.length < 2) return;
      const a = (Math.random() * nodes.length) | 0;
      // find a nearby node to travel toward
      let best = -1, bestD = LINK_DIST2;
      for (let i = 0; i < nodes.length; i++) {
        if (i === a) continue;
        const dx = nodes[i].x - nodes[a].x, dy = nodes[i].y - nodes[a].y;
        const d = dx * dx + dy * dy;
        if (d < bestD && Math.random() < 0.5) { bestD = d; best = i; }
      }
      if (best === -1) return;
      pulses.push({ a, b: best, t: Math.random() * 0.2, speed: 0.006 + Math.random() * 0.01 });
    }

    let t0 = performance.now();
    function frame(now) {
      const dt = Math.min(40, now - t0); t0 = now;
      ctx.clearRect(0, 0, w, h);

      // update + draw links
      for (let i = 0; i < nodes.length; i++) {
        const n = nodes[i];
        n.x += n.vx * dt * 0.06;
        n.y += n.vy * dt * 0.06;
        // gentle mouse repulsion
        const mdx = n.x - mouse.x, mdy = n.y - mouse.y;
        const md2 = mdx * mdx + mdy * mdy;
        if (md2 < 150 * 150) {
          const f = (1 - Math.sqrt(md2) / 150) * 0.5;
          n.x += (mdx / (Math.sqrt(md2) || 1)) * f;
          n.y += (mdy / (Math.sqrt(md2) || 1)) * f;
        }
        if (n.x < -20) n.x = w + 20; else if (n.x > w + 20) n.x = -20;
        if (n.y < -20) n.y = h + 20; else if (n.y > h + 20) n.y = -20;
      }

      // links
      for (let i = 0; i < nodes.length; i++) {
        for (let j = i + 1; j < nodes.length; j++) {
          const a = nodes[i], b = nodes[j];
          const dx = a.x - b.x, dy = a.y - b.y;
          const d2 = dx * dx + dy * dy;
          if (d2 < LINK_DIST2) {
            const alpha = (1 - d2 / LINK_DIST2) * 0.5;
            ctx.strokeStyle = `rgba(${TEAL[0]},${TEAL[1]},${TEAL[2]},${alpha})`;
            ctx.lineWidth = 1;
            ctx.beginPath();
            ctx.moveTo(a.x, a.y);
            ctx.lineTo(b.x, b.y);
            ctx.stroke();
          }
        }
      }

      // nodes (twinkling teal dots with glow)
      const tt = now * 0.001;
      for (let i = 0; i < nodes.length; i++) {
        const n = nodes[i];
        const tw = 0.6 + 0.4 * Math.sin(tt * 1.4 + n.ph);
        ctx.beginPath();
        ctx.arc(n.x, n.y, n.r * 3.2, 0, Math.PI * 2);
        ctx.fillStyle = `rgba(${TEAL[0]},${TEAL[1]},${TEAL[2]},${0.10 * tw})`;
        ctx.fill();
        ctx.beginPath();
        ctx.arc(n.x, n.y, n.r, 0, Math.PI * 2);
        ctx.fillStyle = `rgba(120,235,232,${0.7 * tw + 0.25})`;
        ctx.fill();
      }

      // signal pulses traveling along edges
      if (!reduce && Math.random() < 0.06) spawnPulse();
      for (let i = pulses.length - 1; i >= 0; i--) {
        const p = pulses[i];
        const a = nodes[p.a], b = nodes[p.b];
        if (!a || !b) { pulses.splice(i, 1); continue; }
        p.t += p.speed * dt * 0.06 * 16;
        if (p.t >= 1) { pulses.splice(i, 1); continue; }
        const x = a.x + (b.x - a.x) * p.t;
        const y = a.y + (b.y - a.y) * p.t;
        ctx.beginPath();
        ctx.arc(x, y, 7, 0, Math.PI * 2);
        ctx.fillStyle = "rgba(64,224,224,0.18)";
        ctx.fill();
        ctx.beginPath();
        ctx.arc(x, y, 2.4, 0, Math.PI * 2);
        ctx.fillStyle = "rgba(180,255,252,0.95)";
        ctx.fill();
      }

      raf = requestAnimationFrame(frame);
    }

    function onMove(e) {
      const rect = canvas.getBoundingClientRect();
      mouse.x = e.clientX - rect.left;
      mouse.y = e.clientY - rect.top;
    }
    function onLeave() { mouse.x = -9999; mouse.y = -9999; }

    resize();
    window.addEventListener("resize", resize);
    canvas.addEventListener("pointermove", onMove);
    canvas.addEventListener("pointerleave", onLeave);
    if (reduce) {
      // draw a single static frame
      frame(performance.now());
      cancelAnimationFrame(raf);
    } else {
      raf = requestAnimationFrame(frame);
    }

    return () => {
      cancelAnimationFrame(raf);
      window.removeEventListener("resize", resize);
      canvas.removeEventListener("pointermove", onMove);
      canvas.removeEventListener("pointerleave", onLeave);
    };
  }, []);

  return <canvas ref={canvasRef} className="ai-neural" aria-hidden="true" />;
}

/* ---------- Hero ---------- */
function AIHero({ navigate }) {
  return (
    <section className="ai-hero ai-hero--center">
      <div className="ai-hero__bg" aria-hidden="true">
        <div className="ai-hero__blob ai-hero__blob--teal" />
        <div className="ai-hero__blob ai-hero__blob--deep" />
        <div className="ai-hero__blob ai-hero__blob--tealSoft" />
        <div className="ai-hero__blob ai-hero__blob--ink" />
        <AINeuralField />
        <div className="ai-hero__grain" />
        <div className="ai-hero__veil" />
      </div>

      <div className="container ai-hero__inner">
        <h1 className="ai-hero__title">
          AI Automation <em style={{ color: "rgb(255, 255, 255)" }}>&amp;</em> Strategic Advisory
        </h1>

        <p className="ai-hero__sub">
          We design and deploy custom AI solutions across sales, marketing, operations, and
          finance, helping organizations stay competitive, compound performance, and drive
          measurable outcomes.
        </p>

        <div className="ai-hero__ctas">
          <Button variant="teal" size="lg" onClick={() => window.open("https://form.typeform.com/to/j6nKhXw5", "_blank", "noopener")} withArrow>Schedule a Free Consultation</Button>
        </div>
      </div>
    </section>);

}

/* ---------- Section: The Intelligence Shift ---------- */
function IntelligenceShift({ navigate }) {
  const items = [
  { title: "Redesign Operations",
    desc: "Integrate intelligence into your workflows to reduce friction, accelerate execution, and operate with far greater efficiency." },
  { title: "Make the Move",
    desc: "Build new products, services, and revenue streams that were not possible before." },
  { title: "Deploy AI Smart",
    desc: "AI creating value isn't the question. Where you apply it, how you structure it, and how you turn it into lasting advantage is." }];

  return (
    <section className="section ai-shift">
      <div className="container">
        <div className="ai-shift__head">
          <span className="eyebrow">THE INTELLIGENCE SHIFT</span>
          <h2 className="h2 ai-shift__title">
            Helping Companies Operate <em>with Intelligence.</em>
          </h2>
          <p className="ai-shift__lede">
            This is a turning point that reshapes how companies operate and create value.
          </p>
        </div>

        <div className="ai-shift__grid">
          {items.map((it, i) =>
          <div key={i} className="ai-shift__card">
              <div className="ai-shift__cardTitle">{it.title}</div>
              <p className="ai-shift__cardDesc">{it.desc}</p>
              <div className="ai-shift__rule" />
            </div>
          )}
        </div>
      </div>
    </section>);

}

/* ---------- Section: Measurable Impact (dashboard of animated charts) ---------- */

// Reveal-on-scroll hook
function useInView(threshold) {
  const ref = useR(null);
  const [on, setOn] = useS(false);
  useE(() => {
    const el = ref.current;
    if (!el) return;
    if (typeof IntersectionObserver === "undefined") { setOn(true); return; }
    const io = new IntersectionObserver(
      (entries) => entries.forEach((e) => { if (e.isIntersecting) { setOn(true); io.disconnect(); } }),
      { threshold: threshold || 0.3 }
    );
    io.observe(el);
    return () => io.disconnect();
  }, []);
  return [ref, on];
}

// Catmull-Rom → cubic-bezier smoothing for chart lines
function smoothPath(pts) {
  if (pts.length < 2) return "";
  let d = `M${pts[0][0]} ${pts[0][1]}`;
  for (let i = 0; i < pts.length - 1; i++) {
    const p0 = pts[i - 1] || pts[i];
    const p1 = pts[i];
    const p2 = pts[i + 1];
    const p3 = pts[i + 2] || p2;
    const c1x = p1[0] + (p2[0] - p0[0]) / 6, c1y = p1[1] + (p2[1] - p0[1]) / 6;
    const c2x = p2[0] - (p3[0] - p1[0]) / 6, c2y = p2[1] - (p3[1] - p1[1]) / 6;
    d += ` C${c1x.toFixed(1)} ${c1y.toFixed(1)} ${c2x.toFixed(1)} ${c2y.toFixed(1)} ${p2[0]} ${p2[1]}`;
  }
  return d;
}

// CARD 1, Operational savings (ascending growth area)
function CostChart({ on }) {
  const pts = [[0, 196], [100, 188], [200, 164], [300, 128], [400, 92], [500, 64], [600, 44]];
  const line = smoothPath(pts);
  const band = `${line} L600 210 L0 210 Z`;
  return (
    <svg className={`impact-svg ${on ? "is-on" : ""}`} viewBox="0 0 600 210" preserveAspectRatio="none" aria-hidden="true">
      <defs>
        <linearGradient id="costFill" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="rgba(0,165,161,0.34)" />
          <stop offset="100%" stopColor="rgba(0,165,161,0.02)" />
        </linearGradient>
      </defs>
      {[44, 96, 148, 200].map((y) => (
        <line key={y} x1="0" y1={y} x2="600" y2={y} className="impact-gridline" vectorEffect="non-scaling-stroke" />
      ))}
      <path d={band} fill="url(#costFill)" className="impact-fill" />
      <path d={line} className="impact-stroke impact-stroke--draw" vectorEffect="non-scaling-stroke" pathLength="1" />
      <circle className="impact-dot impact-dot--end" cx="600" cy="44" r="4" />
    </svg>
  );
}

// CARD 5, Conversion / revenue (ascending area)
function RevenueChart({ on }) {
  const pts = [[0, 188], [90, 178], [180, 158], [270, 150], [360, 116], [450, 100], [540, 66], [600, 48]];
  const line = smoothPath(pts);
  const band = `${line} L600 200 L0 200 Z`;
  return (
    <svg className={`impact-svg ${on ? "is-on" : ""}`} viewBox="0 0 600 210" preserveAspectRatio="none" aria-hidden="true">
      <defs>
        <linearGradient id="revFill" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="rgba(0,165,161,0.40)" />
          <stop offset="100%" stopColor="rgba(0,165,161,0.02)" />
        </linearGradient>
      </defs>
      <path d={band} fill="url(#revFill)" className="impact-fill" />
      <path d={line} className="impact-stroke impact-stroke--draw" vectorEffect="non-scaling-stroke" pathLength="1" />
      <circle className="impact-dot impact-dot--end" cx="600" cy="48" r="4" />
    </svg>
  );
}

// CARD 3, Productivity gauge (ring sweep to 40%)
function GaugeRing({ on, pct }) {
  const r = 78, c = 2 * Math.PI * r;
  return (
    <svg className={`impact-gauge ${on ? "is-on" : ""}`} viewBox="0 0 200 200" aria-hidden="true">
      <circle cx="100" cy="100" r={r} className="impact-gauge__track" />
      <circle
        cx="100" cy="100" r={r}
        className="impact-gauge__value"
        transform="rotate(-90 100 100)"
        strokeDasharray={c}
        strokeDashoffset={on ? c * (1 - pct) : c}
      />
    </svg>
  );
}

// CARD 2, Faster execution (throughput bars)
function SpeedBars({ on }) {
  const rows = [
    { label: "Manual baseline", w: 20, v: "1×", muted: true },
    { label: "AI-assisted", w: 62, v: "3×" },
    { label: "Fully automated", w: 100, v: "5×" }
  ];
  return (
    <div className={`impact-bars ${on ? "is-on" : ""}`}>
      {rows.map((row, i) => (
        <div className="impact-bar" key={i} style={{ transitionDelay: `${i * 120}ms` }}>
          <div className="impact-bar__meta">
            <span>{row.label}</span>
            <span className="impact-bar__v">{row.v}</span>
          </div>
          <div className="impact-bar__track">
            <div
              className={`impact-bar__fill ${row.muted ? "impact-bar__fill--muted" : ""}`}
              style={{ width: on ? `${row.w}%` : "0%", transitionDelay: `${i * 120}ms` }}
            />
          </div>
        </div>
      ))}
    </div>
  );
}

// CARD 4, Task reliability (segmented uptime bar; one faint gap = the 1%)
function ReliabilityGrid({ on }) {
  const total = 60;
  const miss = new Set([43]);
  return (
    <div className={`impact-segs ${on ? "is-on" : ""}`}>
      {Array.from({ length: total }).map((_, i) => (
        <span
          key={i}
          className={`impact-seg ${miss.has(i) ? "impact-seg--miss" : ""}`}
          style={{ transitionDelay: `${i * 16}ms` }}
        />
      ))}
    </div>
  );
}

function ImpactDashboard() {
  const [ref, on] = useInView(0.2);
  return (
    <section className="section ai-impact" id="ai-impact">
      <div className="container">
        <div className="ai-impact__head">
          <span className="eyebrow">MEASURABLE IMPACT</span>
          <h2 className="h2 ai-impact__title">
            AI-Driven Operations <em>&amp; Growth Infrastructure</em>
          </h2>
          <p className="ai-impact__lede">
            Intelligence isn&apos;t abstract. Deployed in the right places, it compounds into
            cost, speed, productivity, and revenue gains you can measure on day one.
          </p>
        </div>

        <div className="impact-grid" ref={ref}>
          {/* 1, Cost reduction */}
          <article className="impact-card impact-card--cost">
            <header className="impact-card__head">
              <span className="impact-card__eyebrow">OPERATIONAL SAVINGS · 6 MO</span>
              <span className="impact-card__pill impact-card__pill--down">▴ workflows automated</span>
            </header>
            <div className="impact-card__stat">
              <span className="impact-card__num">30–70<span className="impact-card__unit">%</span></span>
              <span className="impact-card__label">Operational savings</span>
            </div>
            <div className="impact-card__chart impact-card__chart--lg">
              <CostChart on={on} />
            </div>
            <p className="impact-card__desc">
              Automate repetitive workflows and cut operational overhead across support,
              finance, and internal operations.
            </p>
          </article>

          {/* 2, Faster execution */}
          <article className="impact-card impact-card--fast">
            <header className="impact-card__head">
              <span className="impact-card__eyebrow">PROCESS EXECUTION</span>
            </header>
            <div className="impact-card__stat">
              <span className="impact-card__num">3–5<span className="impact-card__unit">×</span></span>
              <span className="impact-card__label">Faster execution</span>
            </div>
            <SpeedBars on={on} />
            <p className="impact-card__desc">
              Accelerate core processes through AI-driven automation and intelligent task orchestration.
            </p>
          </article>

          {/* 3, Productivity gauge */}
          <article className="impact-card impact-card--prod">
            <header className="impact-card__head">
              <span className="impact-card__eyebrow">PRODUCTIVITY / EMPLOYEE</span>
            </header>
            <div className="impact-card__gaugeWrap">
              <GaugeRing on={on} pct={0.4} />
              <div className="impact-card__gaugeCenter">
                <span className="impact-card__num impact-card__num--sm">+40<span className="impact-card__unit">%</span></span>
                <span className="impact-card__label">Up to</span>
              </div>
            </div>
            <p className="impact-card__desc">
              Free teams from manual, low-value tasks so they focus on high-impact strategic work.
            </p>
          </article>

          {/* 4, Task reliability */}
          <article className="impact-card impact-card--rt">
            <header className="impact-card__head">
              <span className="impact-card__eyebrow">TASK RELIABILITY</span>
              <span className="impact-card__pill impact-card__pill--down">▴ standardized</span>
            </header>
            <div className="impact-card__stat">
              <span className="impact-card__num">99<span className="impact-card__unit">%</span></span>
              <span className="impact-card__label">AI-augmented operations</span>
            </div>
            <div className="impact-card__segsWrap">
              <ReliabilityGrid on={on} />
            </div>
            <p className="impact-card__desc">
              Reduce human error in repetitive workflows by standardizing execution, for
              consistent, predictable business output.
            </p>
          </article>

          {/* 5, Conversion & revenue */}
          <article className="impact-card impact-card--conv">
            <header className="impact-card__head">
              <span className="impact-card__eyebrow">CONVERSION & REVENUE</span>
              <span className="impact-card__pill impact-card__pill--down">▴ funnel optimized</span>
            </header>
            <div className="impact-card__stat">
              <span className="impact-card__num">+20–50<span className="impact-card__unit">%</span></span>
              <span className="impact-card__label">Revenue efficiency</span>
            </div>
            <div className="impact-card__chart">
              <RevenueChart on={on} />
            </div>
            <p className="impact-card__desc">
              Optimize funnels, personalize journeys, and surface hidden revenue opportunities.
            </p>
          </article>
        </div>
      </div>
    </section>
  );
}

/* ---------- Section: AI Systems Across Your Business (bento) ---------- */
function AISystems() {
  const cards = [
  { n: "01", title: "Customer-Facing Automation",
    desc: "Review responses, appointment booking, lead follow-up, and customer Q&A, handled by AI agents that work 24/7 inside your existing tools.",
    span: "lg", icon: "agent" },
  { n: "02", title: "Back-Office & Operations Engineering",
    desc: "Invoice processing, report generation, data entry, inventory alerts, the repetitive tasks that eat your team's day, fully automated.",
    span: "md", icon: "gears" },
  { n: "03", title: "AI Search Optimization (AEO + LLM)",
    desc: "AI search visibility, structured content, and entity authority that get your brand cited and recommended by AI systems.",
    span: "md", icon: "search" },
  { n: "04", title: "Supply Chain & Logistics Intelligence",
    desc: "Optimize procurement, inventory, and logistics with intelligent systems that track, predict, and automate.",
    span: "md", icon: "graph" },
  { n: "05", title: "Financial & Decision Optimization",
    desc: "Build intelligent layers for forecasting, reporting, and strategic decision-making.",
    span: "md", icon: "chart" },
  { n: "06", title: "Custom AI Systems Development",
    desc: "Unique workflow or legacy infrastructure? We design, build, and deploy tailored systems to fit.",
    span: "lg", icon: "cube" }];

  return (
    <section className="section ai-systems" id="ai-systems">
      <div className="container">
        <div className="ai-systems__head">
          <span className="eyebrow">END-TO-END AI SYSTEMS</span>
          <h2 className="h2 ai-systems__title">
            AI Systems Across <em>Your Business.</em>
          </h2>
          <p className="lede ai-systems__lede">
            We design and deploy intelligent systems across customer-facing workflows,
            operations, finance, and growth, helping teams move faster, operate smarter,
            and scale with precision.
          </p>
        </div>

        <div className="ai-bento">
          {cards.map((c, i) =>
          <div key={i} className={`ai-bento__card ai-bento__card--${c.span}`}>
              <div className="ai-bento__top">
                <span className="ai-bento__glyph" aria-hidden="true">
                  <BentoGlyph kind={c.icon} />
                </span>
              </div>
              <div className="ai-bento__title">{c.title}</div>
              <p className="ai-bento__desc">{c.desc}</p>
              <div className="ai-bento__hover">
                <span>EXPLORE</span>
                <ArrowUpRight />
              </div>
            </div>
          )}
        </div>
      </div>
    </section>);

}

function BentoGlyph({ kind }) {
  // Subtle abstract glyphs, geometric primitives only (no AI-slop drawings).
  switch (kind) {
    case "agent":
      return (
        <svg width="40" height="40" viewBox="0 0 40 40" fill="none">
          <circle cx="20" cy="14" r="5" stroke="currentColor" strokeWidth="1.2" />
          <path d="M8 32c2.5-5.5 7-8 12-8s9.5 2.5 12 8" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round" />
        </svg>);

    case "gears":
      return (
        <svg width="40" height="40" viewBox="0 0 40 40" fill="none">
          <rect x="6" y="6" width="12" height="12" stroke="currentColor" strokeWidth="1.2" />
          <rect x="22" y="22" width="12" height="12" stroke="currentColor" strokeWidth="1.2" />
          <path d="M18 12h6M16 24h-6M22 28v-6" stroke="currentColor" strokeWidth="1.2" />
        </svg>);

    case "search":
      return (
        <svg width="40" height="40" viewBox="0 0 40 40" fill="none">
          <circle cx="17" cy="17" r="9" stroke="currentColor" strokeWidth="1.2" />
          <path d="M24 24l8 8" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round" />
        </svg>);

    case "graph":
      return (
        <svg width="40" height="40" viewBox="0 0 40 40" fill="none">
          <circle cx="10" cy="12" r="3" stroke="currentColor" strokeWidth="1.2" />
          <circle cx="30" cy="10" r="3" stroke="currentColor" strokeWidth="1.2" />
          <circle cx="22" cy="28" r="3" stroke="currentColor" strokeWidth="1.2" />
          <circle cx="8" cy="30" r="3" stroke="currentColor" strokeWidth="1.2" />
          <path d="M12 13l16-2M11 28l8-4M28 12l-5 13" stroke="currentColor" strokeWidth="1" />
        </svg>);

    case "chart":
      return (
        <svg width="40" height="40" viewBox="0 0 40 40" fill="none">
          <path d="M6 32V8M6 32h28" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round" />
          <path d="M10 26l6-10 6 4 10-14" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" />
        </svg>);

    case "cube":
      return (
        <svg width="40" height="40" viewBox="0 0 40 40" fill="none">
          <path d="M20 6l12 7v14l-12 7-12-7V13z" stroke="currentColor" strokeWidth="1.2" strokeLinejoin="round" />
          <path d="M20 20l12-7M20 20v14M20 20L8 13" stroke="currentColor" strokeWidth="1.2" />
        </svg>);

    default:
      return null;
  }
}

/* ---------- Section: Operators (pillars + stack) ---------- */
function Operators() {
  const pillars = [
  { num: "P · 01", title: "Operational Depth",
    desc: "Operators, builders, and advisors who have scaled in complex markets. We understand real constraints, and what it takes to execute beyond strategy." },
  { num: "P · 02", title: "AI & Systems Expertise",
    desc: "We design and deploy intelligent systems that integrate into core workflows. From automation to decision systems, everything is built for real-world scale." },
  { num: "P · 03", title: "Strategic Advantage",
    desc: "We operate at the intersection of business, technology, and capital. From growth strategy to M&A, we help structure moves that create long-term advantage." }];

  const stack = ["OpenAI", "Anthropic", "Google Gemini", "Mistral", "Meta Llama", "xAI", "Cohere", "Pinecone", "Weaviate", "LangChain", "n8n", "Zapier", "Make", "Replicate", "Hugging Face", "Vercel AI"];
  return (
    <section className="section ai-ops">
      <div className="container">
        <div className="ai-ops__head">
          <span className="eyebrow">THE TEAM BEHIND IT</span>
          <h2 className="h2 ai-ops__title">
            Operators Who Execute. <em>Strategists Who Build.</em>
          </h2>
          <p className="lede ai-ops__lede">
            We combine deep operating experience with advanced AI, professional audit
            backgrounds &amp; financial expertise, working alongside decision makers to
            design systems, identify efficiencies, and help scale.
          </p>
        </div>

        <div className="ai-ops__grid">
          {pillars.map((p, i) =>
          <div key={i} className="ai-ops__pillar">
              <div className="ai-ops__pTitle">{p.title}</div>
              <p className="ai-ops__pDesc">{p.desc}</p>
            </div>
          )}
        </div>

        <div className="ai-stack">
          <div className="ai-stack__label">POWERED BY ADVANCED AI SYSTEMS</div>
          <div className="ai-stack__row">
            <div className="ai-stack__track">
              {[...stack, ...stack].map((s, i) =>
              <span key={i} className="ai-stack__pill">
                  <span className="ai-stack__pillDot" />{s}
                </span>
              )}
            </div>
          </div>
        </div>
      </div>
    </section>);

}

/* ---------- Section: How We Partner ---------- */
function HowWePartner() {
  const blocks = [
  {
    title: "AI & Strategic Transformation",
    desc: "We identify where intelligence and strategy create the highest leverage, across operations, growth, and capital, and guide execution end-to-end.",
    bullets: [
    "Opportunity mapping & value identification",
    "Strategic roadmap & positioning",
    "Process redesign & team enablement",
    "Long-term capability building"]

  },
  {
    title: "AI Systems & Execution",
    desc: "We design and deploy systems that integrate directly into your workflows, or create entirely new products and capabilities.",
    bullets: [
    "AI agents & automation systems",
    "AI-native products & internal tools",
    "Scalable data & infrastructure",
    "Deployment, iteration & ongoing support"]

  }];

  const steps = [
  { n: "01", title: "Define the Leverage",
    desc: "We identify where intelligence creates the most value across your operations, growth, and strategy." },
  { n: "02", title: "Execute Fast",
    desc: "We deploy targeted systems that quickly deliver measurable impact and real operational value." },
  { n: "03", title: "Build the Engine",
    desc: "We turn early wins into scalable, secure systems that support long-term execution and continuous improvement." },
  { n: "04", title: "Scale the Advantage",
    desc: "We expand intelligence across the business, embedding it into workflows, decisions, and strategy." }];

  return (
    <section className="section ai-partner">
      <div className="container">
        <div className="ai-partner__head">
          <span className="eyebrow">INTELLIGENT BUSINESS SYSTEMS</span>
          <h2 className="h2 ai-partner__title">
            How We <em>Partner.</em>
          </h2>
          <p className="lede ai-partner__lede">
            We work as an extension of your team, aligning strategy with execution at every
            step. Whether redesigning operations or building systems, we focus on what
            unlocks real growth.
          </p>
        </div>

        <div className="ai-partner__grid">
          {blocks.map((b, i) =>
          <div key={i} className="ai-partner__card">
              <h3 className="ai-partner__cTitle">{b.title}</h3>
              <p className="ai-partner__cDesc">{b.desc}</p>
              <ul className="ai-partner__list">
                {b.bullets.map((bl, j) =>
              <li key={j}>
                    <span className="ai-partner__check" aria-hidden="true">
                      <svg width="10" height="10" viewBox="0 0 10 10" fill="none">
                        <path d="M2 5l2 2 4-5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                      </svg>
                    </span>
                    {bl}
                  </li>
              )}
              </ul>
            </div>
          )}
        </div>

        <div className="ai-partner__process">
          <div className="ai-partner__processLabel">THE METHOD · FROM LEVERAGE TO SCALE</div>
          <div className="ai-how__rail">
            <div className="ai-how__line" aria-hidden="true" />
            {steps.map((s, i) =>
            <div key={i} className="ai-how__step">
                <div className="ai-how__node" aria-hidden="true">
                  <span className="ai-how__nodeRing" />
                  <span className="ai-how__nodeDot" />
                </div>
                <div className="ai-how__num">{s.n}</div>
                <div className="ai-how__sTitle">{s.title}</div>
                <p className="ai-how__sDesc">{s.desc}</p>
              </div>
            )}
          </div>
        </div>
      </div>
    </section>);

}

/* ---------- Section: How We Work (4-step timeline) ---------- */
function HowWeWork() {
  const steps = [
  { n: "01", title: "Define the Leverage",
    desc: "We identify where intelligence creates the most value across your operations, growth, and strategy." },
  { n: "02", title: "Execute Fast",
    desc: "We deploy targeted systems that quickly deliver measurable impact and real operational value." },
  { n: "03", title: "Build the Engine",
    desc: "We turn early wins into scalable, secure systems that support long-term execution and continuous improvement." },
  { n: "04", title: "Scale the Advantage",
    desc: "We expand intelligence across the business, embedding it into workflows, decisions, and strategy." }];

  return (
    <section className="section ai-how" id="ai-how">
      <div className="container">
        <div className="ai-how__head">
          <span className="eyebrow">THE METHOD</span>
          <h2 className="h2 ai-how__title">
            How We <em>Work.</em>
          </h2>
          <p className="lede ai-how__lede">
            A focused approach to building, deploying, and scaling intelligence across your
            business.
          </p>
        </div>

        <div className="ai-how__rail">
          <div className="ai-how__line" aria-hidden="true" />
          {steps.map((s, i) =>
          <div key={i} className="ai-how__step">
              <div className="ai-how__node" aria-hidden="true">
                <span className="ai-how__nodeRing" />
                <span className="ai-how__nodeDot" />
              </div>
              <div className="ai-how__sTitle">{s.title}</div>
              <p className="ai-how__sDesc">{s.desc}</p>
            </div>
          )}
        </div>
      </div>
    </section>);

}

/* ---------- Section: Why MCA + code window ---------- */
function WhyMCA() {
  const code = [
  { l: 1, t: 'class', n: ' AutomationAgent', op: ':' },
  { l: 2, raw: '    def __init__(self, activation_limit):' },
  { l: 3, raw: '        self.activation_limit = activation_limit' },
  { l: 4, raw: '        self.current_mode = "idle"' },
  { l: 5, raw: '' },
  { l: 6, raw: '    def evaluate_task(self, workload_value):' },
  { l: 7, raw: '        if workload_value > self.activation_limit:' },
  { l: 8, raw: '            self.current_mode = "engaged"' },
  { l: 9, raw: '            return "Automation agent activated."' },
  { l: 10, raw: '        return "No activation needed. Agent stays idle."' },
  { l: 11, raw: '' },
  { l: 12, raw: '    def get_current_mode(self):' },
  { l: 13, raw: '        return f"Current operational mode: {self.current_mode}"' }];

  return (
    <section className="section ai-why">
      <div className="container ai-why__inner">
        <div className="ai-why__copy">
          <span className="eyebrow ai-why__eyebrow">WHY MCA</span>
          <h2 className="h2 ai-why__title">
            AI Embedded in <em>Core Operations</em>
          </h2>
          <p className="ai-why__p ai-why__p--lead">
            We embed AI directly into how your business runs, combining operators, engineers,
            and strategists to design systems that drive real execution, not surface-level
            automation.
          </p>
          <div className="ai-why__tags">
            <span>OPERATORS</span>
            <span>ENGINEERS</span>
            <span>STRATEGISTS</span>
          </div>
        </div>

        <div className="ai-why__code">
          <div className="ai-why__codeBar">
            <span className="ai-why__dots">
              <span className="ai-why__dot ai-why__dot--r" />
              <span className="ai-why__dot ai-why__dot--y" />
              <span className="ai-why__dot ai-why__dot--g" />
            </span>
            <span className="ai-why__file">AI_development.py</span>
            <span className="ai-why__lang">PY · 3.12</span>
          </div>
          <pre className="ai-why__codeBody">
            {code.map((row, i) => {
              const text = row.raw !== undefined ? row.raw : row.t + row.n + row.op;
              return (
                <div key={i} className="ai-why__codeRow">
                  <span className="ai-why__codeNo">{String(row.l).padStart(2, "0")}</span>
                  <span className="ai-why__codeText" dangerouslySetInnerHTML={{ __html: highlightPy(text) }} />
                </div>);

            })}
          </pre>
          <div className="ai-why__codeFoot">
            <span className="ai-why__codeBlink" />
            <span>agent.evaluate_task(workload_value=87)</span>
            <span className="ai-why__codeReturn">→ "Automation agent activated."</span>
          </div>
        </div>
      </div>
    </section>);

}

function highlightPy(line) {
  const esc = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
  // 1. pull string literals out into placeholders so later passes can't
  //    match keywords (class/self/…) inside the spans we insert.
  const strings = [];
  let s = line.replace(/(f?"[^"]*")/g, (m) => {
    strings.push(m);
    return `\u0000${strings.length - 1}\u0000`;
  });
  s = esc(s);
  // keywords
  s = s.replace(/\b(class|def|self|return|if|else|None|True|False)\b/g, '<span class="hl-kw">$1</span>');
  // numbers
  s = s.replace(/\b(\d+)\b/g, '<span class="hl-num">$1</span>');
  // function names after def
  s = s.replace(/<span class="hl-kw">def<\/span> (\w+)/g, '<span class="hl-kw">def</span> <span class="hl-fn">$1</span>');
  // class names
  s = s.replace(/<span class="hl-kw">class<\/span> (\w+)/g, '<span class="hl-kw">class</span> <span class="hl-cls">$1</span>');
  // 2. restore string literals as tinted spans
  s = s.replace(/\u0000(\d+)\u0000/g, (m, i) => `<span class="hl-str">${esc(strings[+i])}</span>`);
  return s;
}

/* ---------- Section: Industries + capabilities ---------- */
function Industries() {
  const industries = ["Finance", "Logistics", "Healthcare", "Manufacturing", "Retail", "Telecom", "Legal", "Real Estate", "Enterprise Ops", "Energy", "Insurance", "Media"];
  const services = [
  "AI Automation & Intelligent Systems",
  "Marketing, Content & Creator Systems",
  "Customer Experience & Support Automation",
  "Business Development & Sales",
  "Financial Strategy & Advisory",
  "Risk Assessment & Feasibility Studies",
  "Valuation, Modelling & Private Equity",
  "Mergers & Acquisitions (M&A)"];

  return (
    <section className="section ai-ind">
      <div className="container">
        <div className="ai-ind__head">
          <span className="eyebrow">WHERE WE CREATE IMPACT</span>
          <h2 className="h2 ai-ind__title">
            Industries We <em>Work Across.</em>
          </h2>
          <p className="lede ai-ind__lede">
            From automating workflows and optimizing supply chains to improving customer
            systems and decision-making, we focus on real operational impact. If your
            business runs on processes, data, and execution, we can help you scale it.
          </p>
        </div>

        <div className="ai-ind__grid">
          {industries.map((i, idx) =>
          <div key={idx} className="ai-ind__cell">
              <span className="ai-ind__cellName">{i}</span>
            </div>
          )}
        </div>
      </div>
    </section>);

}

/* ---------- Final CTA ---------- */
function AIFinalCTA({ navigate }) {
  return (
    <section className="section section--tight ai-final">
      <div className="container">
        <div className="ai-final__block">
          <div className="ai-final__grid" aria-hidden="true">
            {Array.from({ length: 6 * 12 }).map((_, i) => <span key={i} />)}
          </div>
          <div className="ai-final__inner">
            <span className="eyebrow ai-final__eyebrow">READY WHEN YOU ARE</span>
            <h2 className="ai-final__title">
              Advantage Isn't Coming. <em>It's Built.</em>
            </h2>
            <p className="ai-final__sub">
              If you're ready to move faster, operate smarter, and scale with precision,
              we're ready to work with you.
            </p>
            <div className="ai-final__ctas">
              <Button variant="teal" size="lg" onClick={() => window.open("https://form.typeform.com/to/j6nKhXw5", "_blank", "noopener")} withArrow>
                Let's Talk
              </Button>
              <Button variant="secondary" size="lg" onClick={() => navigate("/reports")}>
                See case studies
              </Button>
            </div>
          </div>
        </div>
      </div>
    </section>);

}

/* ---------- Page composition ---------- */
function AISolutionsPage({ navigate }) {
  return (
    <React.Fragment>
      <AIHero navigate={navigate} />
      <IntelligenceShift navigate={navigate} />
      <ImpactDashboard />
      <AISystems />
      <HowWePartner />
      <WhyMCA />
      <Industries />
      <AIFinalCTA navigate={navigate} />
    </React.Fragment>);

}

Object.assign(window, { AISolutionsPage });