// Home page — segment routing + methodology snapshot.

function HomeHero() {
  const isMobile = useMediaQuery('(max-width: 760px)');
  return (
    <section
      style={{
        position: 'relative',
        padding: isMobile ? '56px 22px 72px' : '104px 56px 120px',
        overflow: 'hidden',
      }}
    >
      <div style={{ maxWidth: 1120, margin: '0 auto', position: 'relative' }}>
        <h1
          style={{
            fontFamily: FONT_SERIF,
            fontWeight: 500,
            fontSize: isMobile ? 38 : 'clamp(44px, 5.6vw, 78px)',
            lineHeight: isMobile ? 1.08 : 1.04,
            letterSpacing: '-0.02em',
            margin: 0,
            maxWidth: 960,
          }}
        >
          Reliability software for{' '}
          <span style={{ fontFamily: FONT_SERIF_ITALIC, fontStyle: 'italic' }}>
            AI-infrastructure operators.
          </span>
        </h1>
        <p
          style={{
            margin: isMobile ? '24px 0 0' : '32px 0 0',
            maxWidth: 760,
            fontSize: isMobile ? 16 : 18,
            lineHeight: 1.55,
            color: GREGIS_MUTED,
          }}
        >
          Calibrated SLA-breach probabilities and prescriptive operations decisions
          across the cluster's life. The software runs inside your environment. Telemetry,
          contracts, and outputs stay within your walls.
        </p>
        <div
          style={{
            marginTop: isMobile ? 32 : 48,
            display: 'flex',
            flexWrap: 'wrap',
            gap: 12,
          }}
        >
          <PrimaryLink href="/operators/">Talk to us about your fleet →</PrimaryLink>
          <SecondaryLink href="/underwriters/">Talk to us about underwriting →</SecondaryLink>
          <SecondaryLink href="/enterprises/">Talk to us about your private clusters →</SecondaryLink>
        </div>
      </div>
    </section>
  );
}

function ProblemPanels() {
  const isMobile = useMediaQuery('(max-width: 760px)');
  const panels = [
    {
      tag: '01',
      title: 'SLA breach during a training run is uncapped downside.',
      body:
        'A single bad batch of PSUs or a cascading HBM event takes the cluster below its availability target during a training run worth more than the cluster itself. Independent-failure spreadsheets cannot see this risk.',
    },
    {
      tag: '02',
      title: 'Heuristics misprice the marginal call.',
      body:
        'A reliability team at fleet scale makes hundreds of swap, replace, and redistribute calls a week. The bulk are obvious; the marginal cases are where SLA credits and uptime leak. Pulling a chip too early burns capex; holding it too long routes a training job through a marginal component.',
    },
    {
      tag: '03',
      title: 'No defensible model exists today.',
      body:
        'The failure data that would settle the question is locked inside a small number of operators. Reliability teams defend numbers no one can audit. Underwriters price in the dark.',
    },
  ];
  return (
    <Section id="problem">
      <Eyebrow>§ 01 · The problem</Eyebrow>
      <h2
        style={{
          fontFamily: FONT_SERIF,
          fontWeight: 500,
          fontSize: isMobile ? 28 : 'clamp(32px, 3.6vw, 46px)',
          lineHeight: 1.1,
          letterSpacing: '-0.015em',
          margin: '0 0 48px',
          maxWidth: 820,
        }}
      >
        Reliability decisions on AI clusters are made without a model that holds up to scrutiny.
      </h2>
      <div
        style={{
          display: 'grid',
          gridTemplateColumns: isMobile ? '1fr' : 'repeat(3, 1fr)',
          gap: isMobile ? 28 : 24,
        }}
      >
        {panels.map((p) => (
          <div
            key={p.tag}
            style={{
              borderTop: `1px solid ${GREGIS_INK}`,
              paddingTop: 20,
            }}
          >
            <div
              style={{
                fontFamily: FONT_MONO,
                fontSize: 11,
                letterSpacing: '0.18em',
                color: GREGIS_MUTED,
                marginBottom: 16,
              }}
            >
              {p.tag}
            </div>
            <h3
              style={{
                fontFamily: FONT_SERIF,
                fontWeight: 500,
                fontSize: 22,
                lineHeight: 1.2,
                letterSpacing: '-0.01em',
                margin: '0 0 12px',
              }}
            >
              {p.title}
            </h3>
            <p style={{ margin: 0, fontSize: 15, lineHeight: 1.6, color: GREGIS_MUTED }}>
              {p.body}
            </p>
          </div>
        ))}
      </div>
    </Section>
  );
}

function AudiencePanels() {
  const isMobile = useMediaQuery('(max-width: 760px)');
  const panels = [
    {
      tag: 'For Operators',
      href: '/operators/',
      title: 'Operate a GPU fleet under a calibrated posterior.',
      body:
        'Software that runs inside your environment, ingests your existing cluster telemetry, and turns the marginal swap, redistribute, and repair calls your heuristics get wrong into fewer SLA-credit payouts and more uptime from the fleet you operate. Advisor mode by default; automation within your safety bounds when your team is ready.',
      cta: 'Read for operators →',
    },
    {
      tag: 'For Underwriters',
      href: '/underwriters/',
      title: 'Price parametric AI-infrastructure cover.',
      body:
        'Actuarial outputs generated by software inside the insured\'s environment and shared with you on the insured\'s terms — failure-rate distributions with credible intervals, expected loss given event, and correlated-failure structure conditioned on real telemetry the operator never has to surrender.',
      cta: 'Read for underwriters →',
    },
    {
      tag: 'For Enterprises',
      href: '/enterprises/',
      title: 'Hit your availability target on a private cluster.',
      body:
        'A reliability policy that meets your availability target at your chosen confidence level, calibrated against your fleet’s failure-rate posterior. Operations-time decisions across the cluster’s life; minimum-cost sparing falls out as one downstream output.',
      cta: 'Read for enterprises →',
    },
  ];
  return (
    <Section id="audiences" background={GREGIS_LINE_SOFT}>
      <Eyebrow>§ 02 · Who we serve</Eyebrow>
      {/* <h2
        style={{
          fontFamily: FONT_SERIF,
          fontWeight: 500,
          fontSize: isMobile ? 28 : 'clamp(32px, 3.6vw, 46px)',
          lineHeight: 1.1,
          letterSpacing: '-0.015em',
          margin: '0 0 48px',
          maxWidth: 820,
        }}
      >
  
      </h2> */}
      <div
        style={{
          display: 'grid',
          gridTemplateColumns: isMobile ? '1fr' : 'repeat(3, 1fr)',
          gap: 2,
          background: GREGIS_LINE,
          border: `1px solid ${GREGIS_LINE}`,
        }}
      >
        {panels.map((p) => (
          <a
            key={p.tag}
            href={p.href}
            style={{
              background: '#fff',
              padding: isMobile ? 24 : 32,
              textDecoration: 'none',
              color: GREGIS_INK,
              display: 'flex',
              flexDirection: 'column',
              gap: 16,
              minHeight: isMobile ? 220 : 320,
            }}
          >
            <div
              style={{
                fontFamily: FONT_MONO,
                fontSize: 11,
                letterSpacing: '0.18em',
                textTransform: 'uppercase',
                color: GREGIS_BLUE,
              }}
            >
              {p.tag}
            </div>
            <h3
              style={{
                fontFamily: FONT_SERIF,
                fontWeight: 500,
                fontSize: 22,
                lineHeight: 1.2,
                letterSpacing: '-0.01em',
                margin: 0,
              }}
            >
              {p.title}
            </h3>
            <p style={{ margin: 0, fontSize: 15, lineHeight: 1.6, color: GREGIS_MUTED, flex: 1 }}>
              {p.body}
            </p>
            <div
              style={{
                marginTop: 'auto',
                fontFamily: FONT_MONO,
                fontSize: 12,
                letterSpacing: '0.05em',
                color: GREGIS_BLUE,
              }}
            >
              {p.cta}
            </div>
          </a>
        ))}
      </div>

      <div
        style={{
          marginTop: isMobile ? 28 : 36,
          paddingTop: isMobile ? 24 : 28,
          borderTop: `1px solid ${GREGIS_LINE}`,
          display: 'grid',
          gridTemplateColumns: isMobile ? '1fr' : 'minmax(140px, 0.45fr) minmax(0, 1.6fr) auto',
          gap: isMobile ? 14 : 36,
          alignItems: isMobile ? 'flex-start' : 'center',
        }}
      >
        <div
          style={{
            fontFamily: FONT_MONO,
            fontSize: 11,
            letterSpacing: '0.18em',
            textTransform: 'uppercase',
            color: GREGIS_MUTED,
          }}
        >
          For OEMs · Channel
        </div>
        <p
          style={{
            margin: 0,
            fontSize: 14,
            lineHeight: 1.6,
            color: GREGIS_MUTED,
            maxWidth: 640,
          }}
        >
          Channel partnership to embed our reliability optimizer in your AI cluster sales
          motion. Calibrated, customer-defensible recommendations on availability, operations,
          and the spares that follow from them.
        </p>
        <a
          href="/contact/?subject=OEM%20partnership#other"
          style={{
            fontFamily: FONT_MONO,
            fontSize: 12,
            letterSpacing: '0.05em',
            color: GREGIS_INK,
            textDecoration: 'none',
            borderBottom: `1px solid ${GREGIS_INK}`,
            paddingBottom: 2,
            whiteSpace: 'nowrap',
            alignSelf: isMobile ? 'flex-start' : 'center',
          }}
        >
          Partner with us →
        </a>
      </div>
    </Section>
  );
}

function DeploymentModel() {
  const isMobile = useMediaQuery('(max-width: 760px)');
  const items = [
    {
      title: 'Runs inside your environment',
      body:
        'Gregis ships as software the customer deploys and operates. There is no central Gregis service that ingests your telemetry; the model lives with the fleet.',
    },
    {
      title: 'Reads operator-side telemetry only',
      body:
        'Hardware and operating-condition signals from your existing observability stack. No workload payloads, no model weights, no customer data.',
    },
    {
      title: 'Returns nothing by default',
      body:
        'Telemetry, contract terms, and outputs do not leave your walls without your explicit consent. The default is no egress; anything else is yours to choose.',
    },
    {
      title: 'Built for procurement and security review',
      body:
        'The pilot deployment is the permanent deployment — security review covers one artifact, not two. Standard for environments with data-residency, supervisory, or classification constraints.',
    },
  ];
  return (
    <Section id="deployment">
      <Eyebrow>§ 03 · Deployment & data</Eyebrow>
      <h2
        style={{
          fontFamily: FONT_SERIF,
          fontWeight: 500,
          fontSize: isMobile ? 28 : 'clamp(32px, 3.6vw, 46px)',
          lineHeight: 1.1,
          letterSpacing: '-0.015em',
          margin: '0 0 24px',
          maxWidth: 820,
        }}
      >
        The software runs inside your environment. Your data does not leave it.
      </h2>
      <p
        style={{
          margin: '0 0 48px',
          maxWidth: 760,
          fontSize: 16,
          lineHeight: 1.65,
          color: GREGIS_MUTED,
        }}
      >
        Workload-blindness is a property of how the software is built.
        The model never sees the data, because the data never leaves the operator's environment.
      </p>
      <div
        style={{
          display: 'grid',
          gridTemplateColumns: isMobile ? '1fr' : 'repeat(2, 1fr)',
          gap: isMobile ? 28 : 32,
        }}
      >
        {items.map((it, i) => (
          <div
            key={i}
            style={{
              borderTop: `1px solid ${GREGIS_INK}`,
              paddingTop: 20,
            }}
          >
            <h3
              style={{
                fontFamily: FONT_SERIF,
                fontWeight: 500,
                fontSize: 22,
                lineHeight: 1.2,
                letterSpacing: '-0.01em',
                margin: '0 0 12px',
              }}
            >
              {it.title}
            </h3>
            <p style={{ margin: 0, fontSize: 15, lineHeight: 1.6, color: GREGIS_MUTED }}>
              {it.body}
            </p>
          </div>
        ))}
      </div>
    </Section>
  );
}

function MethodologySnapshot() {
  const isMobile = useMediaQuery('(max-width: 760px)');
  const bullets = [
    {
      title: 'Physics-of-failure scaling',
      body:
        'Reliability-physics scaling laws translate operating conditions — temperature, current, voltage and frequency cycling, mechanical wear — into per-component hazard rates under your fleet\'s real operating regime.',
    },
    {
      title: 'Bayesian hierarchical models',
      body:
        'Pool failure data from public anchors — LLM training papers, HPC lab disclosures, vendor reliability studies — into a posterior with explicit credible intervals.',
    },
    {
      title: 'Correlated-failure modeling',
      body:
        'A self-exciting layer over per-component hazards captures catastrophic clustering — bad PSU batches propagating, HBM cascades — that independent-failure models systematically under-price.',
    },
    {
      title: 'Event-driven simulator',
      body:
        'Tree topology, type-pooled spares, partial-failure semantics. The same environment used at procurement and operations time.',
    },
    {
      title: 'Two-phase policy optimization',
      body:
        'A reinforcement-learning policy acting on live telemetry across the operating life; a greedy submodular allocation at procurement time. Both phases share the same posterior and the same simulator.',
    },
    {
      title: 'Robust uncertainty propagation',
      body:
        'Both phases sample failure rates from the Bayesian posterior during training and evaluation. Policies are robust to parameter uncertainty rather than overfit to point estimates.',
    },
  ];
  return (
    <Section id="methodology">
      <Eyebrow>§ 04 · Methodology snapshot</Eyebrow>
      <h2
        style={{
          fontFamily: FONT_SERIF,
          fontWeight: 500,
          fontSize: isMobile ? 28 : 'clamp(32px, 3.6vw, 46px)',
          lineHeight: 1.1,
          letterSpacing: '-0.015em',
          margin: '0 0 48px',
          maxWidth: 820,
        }}
      >
        How we predict
      </h2>
      <div
        style={{
          display: 'grid',
          gridTemplateColumns: isMobile ? '1fr' : 'repeat(2, 1fr)',
          gap: isMobile ? 28 : 32,
        }}
      >
        {bullets.map((b, i) => (
          <div
            key={i}
            style={{
              display: 'grid',
              gridTemplateColumns: '32px 1fr',
              gap: 16,
              alignItems: 'baseline',
            }}
          >
            <span
              style={{
                fontFamily: FONT_MONO,
                fontSize: 12,
                color: GREGIS_BLUE,
                letterSpacing: '0.05em',
              }}
            >
              {String(i + 1).padStart(2, '0')}
            </span>
            <div>
              <h3
                style={{
                  fontFamily: FONT_SANS,
                  fontWeight: 600,
                  fontSize: 17,
                  margin: '0 0 8px',
                }}
              >
                {b.title}
              </h3>
              <p style={{ margin: 0, fontSize: 15, lineHeight: 1.6, color: GREGIS_MUTED }}>
                {b.body}
              </p>
            </div>
          </div>
        ))}
      </div>
      <div style={{ marginTop: 40 }}>
        <SecondaryLink href="/approach/">Read the full approach →</SecondaryLink>
      </div>
    </Section>
  );
}

function CompanyGraph({ mouse, reducedMotion }) {
  const containerRef = React.useRef(null);
  const [visible, setVisible] = React.useState(false);
  const [time, setTime] = React.useState(0);

  React.useEffect(() => {
    if (!containerRef.current) return;
    const io = new IntersectionObserver(
      ([e]) => {
        if (e.isIntersecting) {
          setVisible(true);
          io.disconnect();
        }
      },
      { threshold: 0.05 }
    );
    io.observe(containerRef.current);
    return () => io.disconnect();
  }, []);

  React.useEffect(() => {
    if (!visible || reducedMotion) return;
    let raf;
    let start = null;
    const tick = (t) => {
      if (start === null) start = t;
      setTime((t - start) / 1000);
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [visible, reducedMotion]);

  // Tree topology: root → 3 branches → 8 sub-branches → ~20 leaves.
  // Positions are in 0..1 space, scaled into a 1200x360 viewBox below.
  const TREE = React.useMemo(() => {
    const nodes = [];
    const edges = [];
    let id = 0;

    const root = { id: id++, depth: 0, x: 0.05, y: 0.5, phase: 0 };
    nodes.push(root);

    const d1Ys = [0.22, 0.5, 0.78];
    const d1 = d1Ys.map((y, i) => {
      const n = { id: id++, depth: 1, x: 0.26, y, phase: i * 0.7 };
      edges.push({ a: root.id, b: n.id, base: 0.94 - i * 0.02, phase: i * 0.5 });
      nodes.push(n);
      return n;
    });

    const subCounts = [3, 3, 2];
    const d2 = [];
    d1.forEach((p, idx) => {
      const count = subCounts[idx];
      const span = 0.22;
      for (let i = 0; i < count; i++) {
        const t = count === 1 ? 0.5 : i / (count - 1);
        const y = p.y + (t - 0.5) * span;
        const n = { id: id++, depth: 2, x: 0.54, y, phase: id * 0.31 };
        edges.push({ a: p.id, b: n.id, base: 0.82 - (i + idx) * 0.03, phase: id * 0.27 });
        nodes.push(n);
        d2.push(n);
      }
    });

    d2.forEach((p, idx) => {
      const count = 2 + (idx % 2);
      const span = 0.11;
      for (let i = 0; i < count; i++) {
        const t = count === 1 ? 0.5 : i / (count - 1);
        const y = p.y + (t - 0.5) * span;
        const x = 0.84 + (i % 2 === 0 ? 0 : 0.05);
        const n = { id: id++, depth: 3, x, y, phase: id * 0.19 };
        edges.push({ a: p.id, b: n.id, base: 0.72 - (i + idx) * 0.02, phase: id * 0.13 });
        nodes.push(n);
      }
    });

    return { nodes, edges };
  }, []);

  const W = 1200;
  const H = 360;
  const REPULSE_R = 0.13;
  const REPULSE_S = 0.018;

  const positions = TREE.nodes.map((n) => {
    let x = n.x;
    let y = n.y;
    if (mouse && !reducedMotion) {
      const dx = x - mouse.x;
      const dy = y - mouse.y;
      const d = Math.sqrt(dx * dx + dy * dy);
      if (d > 0 && d < REPULSE_R) {
        const k = (1 - d / REPULSE_R) ** 2 * REPULSE_S;
        x += (dx / d) * k;
        y += (dy / d) * k;
      }
    }
    if (!reducedMotion && visible) {
      const tt = time + n.phase * 1.7;
      x += Math.sin(tt * 0.28) * 0.0025;
      y += Math.cos(tt * 0.21) * 0.0025;
    }
    return { id: n.id, depth: n.depth, x: x * W, y: y * H };
  });
  const posById = {};
  positions.forEach((p) => {
    posById[p.id] = p;
  });

  return (
    <div
      ref={containerRef}
      aria-hidden="true"
      style={{
        position: 'absolute',
        inset: 0,
        pointerEvents: 'none',
        zIndex: 0,
      }}
    >
      <svg
        viewBox={`0 0 ${W} ${H}`}
        preserveAspectRatio="xMidYMid slice"
        style={{ width: '100%', height: '100%', display: 'block', opacity: 0.17 }}
      >
        {TREE.edges.map((e, i) => {
          const a = posById[e.a];
          const b = posById[e.b];
          const fluct = reducedMotion ? 0 : Math.sin(time * 0.55 + e.phase) * 0.35;
          const sw = Math.max(0.4, e.base * 2.4 + fluct);
          return (
            <line
              key={i}
              x1={a.x}
              y1={a.y}
              x2={b.x}
              y2={b.y}
              stroke={GREGIS_INK}
              strokeWidth={sw}
              strokeLinecap="round"
              strokeOpacity={0.5 + e.base * 0.45}
            />
          );
        })}
        {positions.map((p) => {
          const r = Math.max(1.6, 5 - p.depth * 0.9);
          return <circle key={p.id} cx={p.x} cy={p.y} r={r} fill={GREGIS_INK} />;
        })}
      </svg>
    </div>
  );
}

function CompanyHome() {
  const isMobile = useMediaQuery('(max-width: 760px)');
  const reducedMotion = useMediaQuery('(prefers-reduced-motion: reduce)');
  const sectionRef = React.useRef(null);
  const [mouse, setMouse] = React.useState(null);

  const onMouseMove = (e) => {
    if (reducedMotion || !sectionRef.current) return;
    const rect = sectionRef.current.getBoundingClientRect();
    setMouse({
      x: (e.clientX - rect.left) / rect.width,
      y: (e.clientY - rect.top) / rect.height,
    });
  };

  return (
    <section
      id="company"
      ref={sectionRef}
      onMouseMove={onMouseMove}
      onMouseLeave={() => setMouse(null)}
      style={{
        position: 'relative',
        borderTop: `1px solid ${GREGIS_LINE}`,
        padding: isMobile ? '80px 22px' : '128px 56px',
        overflow: 'hidden',
        background: '#fff',
      }}
    >
      <CompanyGraph mouse={mouse} reducedMotion={reducedMotion} />
      <div
        style={{
          position: 'relative',
          zIndex: 1,
          maxWidth: 760,
          margin: '0 auto',
        }}
      >
        <Eyebrow>§ 05 · Company</Eyebrow>
        <h2
          style={{
            fontFamily: FONT_SERIF,
            fontWeight: 500,
            fontSize: isMobile ? 28 : 'clamp(32px, 3.6vw, 46px)',
            lineHeight: 1.1,
            letterSpacing: '-0.015em',
            margin: '0 0 24px',
          }}
        >
          The statistical layer underneath the AI infrastructure layer.
        </h2>
        <p
          style={{
            margin: 0,
            fontSize: 15,
            lineHeight: 1.65,
            color: GREGIS_MUTED,
            maxWidth: 680,
          }}
        >
          We use reinforcement learning, Bayesian inference,
          and physics-of-failure modeling to give you the best predictions
          of your compute's behavior.
        </p>
        <div style={{ marginTop: 32 }}>
          <SecondaryLink href="/company/">Read about the team →</SecondaryLink>
        </div>
      </div>
    </section>
  );
}

function HomePage() {
  return (
    <PageShell active="home">
      <HomeHero />
      <ProblemPanels />
      <AudiencePanels />
      <DeploymentModel />
      <MethodologySnapshot />
      <CompanyHome />
    </PageShell>
  );
}

window.HomePage = HomePage;
