// ─── All Page Sections ────────────────────────────────────────────────────────

// ─── Mosaic Tile Background ────────────────────────────────────────────────────
function MosaicTiles() {
  const cols = 18, rows = 14;
  const tileSize = 52, gap = 3;
  const colors = ['#10B981', '#0891B2', '#1D4ED8', '#3B82F6', '#059669', '#0369A1'];

  const tiles = [];
  for (let r = 0; r < rows; r++) {
    for (let c = 0; c < cols; c++) {
      // Distance from top-left corner of the mosaic field
      const distFromLeft = c / cols;
      const distFromCenter = Math.sqrt(Math.pow((c - cols * 0.3) / cols, 2) + Math.pow((r - rows * 0.5) / rows, 2));
      // Fade: strong on the right, fade to nothing on the left third
      const baseOpacity = Math.max(0, (distFromLeft - 0.15) * 1.4) * (1 - distFromCenter * 0.8);
      if (baseOpacity < 0.02) continue;

      const color = colors[Math.floor((r * cols + c + r * 3 + c * 7) % colors.length)];
      const opacity = Math.min(0.55, baseOpacity * (0.2 + Math.random() * 0.35));
      const x = c * (tileSize + gap);
      const y = r * (tileSize + gap);
      const isSmall = (r + c) % 5 === 0;
      const sz = isSmall ? tileSize * 0.55 : tileSize;
      const offset = isSmall ? (tileSize - sz) / 2 : 0;

      tiles.push({ x: x + offset, y: y + offset, sz, color, opacity, key: `${r}-${c}` });
    }
  }

  const svgW = cols * (tileSize + gap);
  const svgH = rows * (tileSize + gap);

  return (
    <div style={{
      position: 'absolute',
      top: 0, right: 0,
      width: '65%',
      height: '100%',
      pointerEvents: 'none',
      zIndex: 0,
      maskImage: 'linear-gradient(to left, rgba(0,0,0,0.6) 0%, rgba(0,0,0,0.3) 40%, transparent 80%)',
      WebkitMaskImage: 'linear-gradient(to left, rgba(0,0,0,0.6) 0%, rgba(0,0,0,0.3) 40%, transparent 80%)',
      overflow: 'hidden',
    }}>
      <svg
        width="100%" height="100%"
        viewBox={`0 0 ${svgW} ${svgH}`}
        preserveAspectRatio="xMidYMid slice"
        xmlns="http://www.w3.org/2000/svg"
      >
        {tiles.map(t => (
          <rect
            key={t.key}
            x={t.x} y={t.y}
            width={t.sz} height={t.sz}
            rx="5"
            fill={t.color}
            opacity={t.opacity}
          />
        ))}
      </svg>
    </div>
  );
}

// ─── HERO ─────────────────────────────────────────────────────────────────────
function HeroSection() {
  return (
    <section id="hero" style={{
      background: 'var(--dark)',
      minHeight: '100vh',
      display: 'flex',
      flexDirection: 'column',
      justifyContent: 'center',
      position: 'relative',
      overflow: 'hidden',
      paddingTop: 80,
    }}>
      {/* Radial glows */}
      <div style={{ position:'absolute', top: '10%', left: '60%', width: 600, height: 600,
        background: 'radial-gradient(circle, rgba(16,185,129,0.12) 0%, transparent 70%)',
        pointerEvents: 'none' }} />
      <div style={{ position:'absolute', bottom: '5%', left: '20%', width: 500, height: 500,
        background: 'radial-gradient(circle, rgba(8,145,178,0.1) 0%, transparent 70%)',
        pointerEvents: 'none' }} />

      {/* Tessellated mosaic tiles */}
      <MosaicTiles />

      <div className="container" style={{ position: 'relative', zIndex: 1, padding: '80px 24px 100px' }}>
        <div className="fade-up">
          <Eyebrow>AI &amp; Data Analytics for Oil &amp; Gas</Eyebrow>
        </div>

        <h1 className="fade-up delay-1" style={{
          fontSize: 'clamp(38px, 6vw, 76px)',
          fontWeight: 700,
          letterSpacing: '-0.03em',
          lineHeight: 1.08,
          color: '#fff',
          maxWidth: 860,
          marginBottom: 28,
        }}>
          <span style={{
            display: 'block',
            background: 'linear-gradient(90deg, #10B981, #0891B2, #1D4ED8)',
            WebkitBackgroundClip: 'text',
            WebkitTextFillColor: 'transparent',
            backgroundClip: 'text',
            marginBottom: '0.15em',
            fontSize: '1.25em',
            letterSpacing: '-0.04em',
          }}>Tessera</span>
          Reservoir Intelligence,<br />
          custom-built for{' '}
          <span style={{
            background: 'linear-gradient(90deg, #10B981, #0891B2)',
            WebkitBackgroundClip: 'text',
            WebkitTextFillColor: 'transparent',
            backgroundClip: 'text',
          }}>operators.</span>
        </h1>

        <p className="fade-up delay-2" style={{
          fontSize: 'clamp(16px, 2vw, 19px)',
          color: 'rgba(255,255,255,0.58)',
          maxWidth: 580,
          lineHeight: 1.7,
          marginBottom: 40,
          fontWeight: 400,
        }}>
          AI-native production optimization, reservoir characterization, and decision-ready tools — built with your team, owned by your team.
        </p>

        <div className="fade-up delay-3" style={{ display: 'flex', gap: 14, flexWrap: 'wrap', marginBottom: 48 }}>
          <GradBtn href="#contact">Book a scoping call</GradBtn>
          <GhostBtn href="#examples">See what we build</GhostBtn>
        </div>

        {/* Trust pills */}
        <div className="fade-up delay-4" style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
          {['AI-native', 'No lock-in', 'Your cloud, your data', 'Subsurface + AI in one team'].map(pill => (
            <span key={pill} style={{
              display: 'inline-flex', alignItems: 'center', gap: 6,
              padding: '6px 14px',
              background: 'rgba(255,255,255,0.05)',
              border: '1px solid rgba(255,255,255,0.12)',
              borderRadius: 100,
              fontSize: 12,
              fontWeight: 500,
              color: 'rgba(255,255,255,0.65)',
              letterSpacing: '0.01em',
            }}>
              <span style={{ width: 5, height: 5, borderRadius: '50%', background: 'var(--green)', display: 'block', flexShrink: 0 }} />
              {pill}
            </span>
          ))}
        </div>
      </div>
    </section>
  );
}

// ─── PROBLEM ──────────────────────────────────────────────────────────────────
function ProblemSection() {
  const ref1 = useFadeUp(), ref2 = useFadeUp(), ref3 = useFadeUp(), ref4 = useFadeUp();
  const cards = [
    {
      icon: <svg width="22" height="22" viewBox="0 0 22 22" fill="none"><rect x="3" y="3" width="7" height="7" rx="1.5" stroke="#10B981" strokeWidth="1.5"/><rect x="12" y="3" width="7" height="7" rx="1.5" stroke="#10B981" strokeWidth="1.5" strokeDasharray="2 1.5"/><rect x="3" y="12" width="7" height="7" rx="1.5" stroke="#10B981" strokeWidth="1.5" strokeDasharray="2 1.5"/><rect x="12" y="12" width="7" height="7" rx="1.5" stroke="#10B981" strokeWidth="1.5" strokeDasharray="2 1.5"/></svg>,
      title: 'Paying for answers you don\'t own',
      body: 'Annual subscriptions to rent interpretations. Seats scale with your team, not your upside. You re-up every cycle and nothing compounds.',
    },
    {
      icon: <svg width="22" height="22" viewBox="0 0 22 22" fill="none"><circle cx="5" cy="11" r="2.5" stroke="#0891B2" strokeWidth="1.5"/><circle cx="17" cy="5" r="2.5" stroke="#0891B2" strokeWidth="1.5"/><circle cx="17" cy="17" r="2.5" stroke="#0891B2" strokeWidth="1.5"/><path d="M7.5 11h4M14.5 5.8l-4 3.6M14.5 16.2l-4-3.6" stroke="#0891B2" strokeWidth="1.5" strokeLinecap="round" strokeDasharray="2 1.5"/></svg>,
      title: 'Data that never becomes a system',
      body: 'Geochem, microseismic, frac hits, RTA, completions — all live in different silos. Your team builds one-off dashboards instead of working models.',
    },
    {
      icon: <svg width="22" height="22" viewBox="0 0 22 22" fill="none"><path d="M3 16l5-5 4 3 7-9" stroke="#1D4ED8" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/><path d="M3 19h16" stroke="#1D4ED8" strokeWidth="1.5" strokeLinecap="round" strokeDasharray="2 1.5"/></svg>,
      title: 'Models that don\'t move with the basin',
      body: 'Drainage assumed, not solved. Infill above/below left on the table. Completion design frozen two years ago. The basin moved; your models didn\'t.',

    },
  ];

  return (
    <section id="problem" style={{ background: 'var(--bg-light)', padding: '100px 0 0' }}>
      <div className="container">
        <div ref={ref1} className="fade-up">
          <Eyebrow light>Where operators lose money and barrels</Eyebrow>
          <h2 style={{
            fontSize: 'clamp(28px, 3.5vw, 46px)',
            fontWeight: 700,
            letterSpacing: '-0.025em',
            color: 'var(--text-dark)',
            maxWidth: 640,
            lineHeight: 1.15,
            marginBottom: 56,
          }}>Subscriptions, not solutions. Fragmented data.<br />Models that don't evolve.</h2>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: 24, marginBottom: 64 }}>
          {cards.map((c, i) => {
            const refs = [ref2, ref3, ref4];
            return (
              <div key={i} ref={refs[i]} className={`fade-up delay-${i+1}`} style={{
                background: '#fff',
                border: '1px solid #E2E8F0',
                borderRadius: 12,
                padding: '32px 28px',
                transition: 'box-shadow 0.25s, border-color 0.25s',
              }}
                onMouseEnter={e => { e.currentTarget.style.boxShadow = '0 8px 32px rgba(8,145,178,0.1)'; e.currentTarget.style.borderColor = 'rgba(8,145,178,0.3)'; }}
                onMouseLeave={e => { e.currentTarget.style.boxShadow = 'none'; e.currentTarget.style.borderColor = '#E2E8F0'; }}
              >
                <div style={{ marginBottom: 18 }}>{c.icon}</div>
                <h3 style={{ fontSize: 17, fontWeight: 600, color: 'var(--text-dark)', marginBottom: 12, lineHeight: 1.3 }}>{c.title}</h3>
                <p style={{ fontSize: 14, color: 'var(--text-muted)', lineHeight: 1.7 }}>{c.body}</p>
              </div>
            );
          })}
        </div>
      </div>

      {/* Callout strip */}
      <div style={{
        background: 'var(--dark)',
        padding: '28px 24px',
        textAlign: 'center',
      }}>
        <p style={{
          fontFamily: 'var(--font)',
          fontSize: 'clamp(14px, 2vw, 16px)',
          color: 'rgba(255,255,255,0.65)',
          maxWidth: 780,
          margin: '0 auto',
          lineHeight: 1.6,
          fontStyle: 'italic',
        }}>
          "The result: you pay a premium for answers you don't own, on data that hasn't been made to work together."
        </p>
      </div>
    </section>
  );
}

// ─── WHAT WE BUILD ────────────────────────────────────────────────────────────
function WhatWeBuildSection() {
  const r1 = useFadeUp(), r2 = useFadeUp(), r3 = useFadeUp();
  const valueProps = [
    { title: 'AI-native, not bolted-on', body: 'Built around your data, your basin, your workflows.' },
    { title: 'No lock-in, no black box', body: 'You keep the code, the models, the weights, the data.' },
    { title: 'Subsurface + AI under one roof', body: 'Reservoir engineers and ML engineers on the same team.' },
  ];
  const appLinks = [
    { icon: '⬡', name: 'Prod Alloc + Drainage', desc: 'AI allocation & pseudo-sim drainage', href: '#ex-01' },
    { icon: '⬡', name: 'AutoML for Completions', desc: 'Pad, cube & completion optimization', href: '#ex-02' },
    { icon: '⬡', name: 'Custom RTA', desc: 'Workflow designed with your engineers', href: '#ex-03' },
    { icon: '⬡', name: 'Infill & Inventory', desc: 'Above/below candidates, acreage grading', href: '#ex-04' },
  ];

  return (
    <section id="what-we-build" style={{
      background: 'var(--dark)',
      padding: '100px 0',
      position: 'relative',
      overflow: 'hidden',
    }}>
      <div style={{ position:'absolute', top: '20%', right: '-5%', width: 500, height: 500,
        background: 'radial-gradient(circle, rgba(29,78,216,0.12) 0%, transparent 65%)', pointerEvents: 'none' }} />

      <div className="container">
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 80, alignItems: 'start' }}>
          {/* Left */}
          <div ref={r1} className="fade-up">
            <Eyebrow>The Tessera Difference</Eyebrow>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 36, marginTop: 8 }}>
              {valueProps.map((v, i) => (
                <div key={i}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
                    <div style={{ width: 20, height: 2, background: 'var(--grad)', borderRadius: 1 }} />
                    <h3 style={{ fontSize: 17, fontWeight: 600, color: '#fff', letterSpacing: '-0.01em' }}>{v.title}</h3>
                  </div>
                  <p style={{ fontSize: 14, color: 'rgba(255,255,255,0.52)', lineHeight: 1.7, paddingLeft: 30 }}>{v.body}</p>
                </div>
              ))}
            </div>
          </div>

          {/* Right */}
          <div ref={r2} className="fade-up delay-2">
            <h3 style={{ fontSize: 22, fontWeight: 600, color: '#fff', marginBottom: 6, letterSpacing: '-0.01em' }}>
              Examples of apps we build
            </h3>
            <p style={{ fontSize: 13, color: 'rgba(255,255,255,0.4)', marginBottom: 28 }}>
              A sample of the custom tools we've built for operators.
            </p>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
              {appLinks.map((a, i) => (
                <a key={i} href={a.href} style={{
                  display: 'flex', alignItems: 'center', gap: 16,
                  padding: '14px 18px',
                  background: 'rgba(255,255,255,0.03)',
                  border: '1px solid rgba(255,255,255,0.07)',
                  borderRadius: 8,
                  textDecoration: 'none',
                  transition: 'background 0.2s, border-color 0.2s',
                  marginBottom: 6,
                }}
                  onMouseEnter={e => { e.currentTarget.style.background = 'rgba(16,185,129,0.08)'; e.currentTarget.style.borderColor = 'rgba(16,185,129,0.25)'; }}
                  onMouseLeave={e => { e.currentTarget.style.background = 'rgba(255,255,255,0.03)'; e.currentTarget.style.borderColor = 'rgba(255,255,255,0.07)'; }}
                >
                  <div style={{ width: 32, height: 32, borderRadius: 6, background: 'linear-gradient(135deg, rgba(16,185,129,0.2), rgba(29,78,216,0.2))', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                    <span style={{ fontSize: 14, color: 'var(--teal)' }}>0{i+1}</span>
                  </div>
                  <div>
                    <div style={{ fontSize: 14, fontWeight: 600, color: '#fff' }}>{a.name}</div>
                    <div style={{ fontSize: 12, color: 'rgba(255,255,255,0.4)', marginTop: 2 }}>{a.desc}</div>
                  </div>
                  <div style={{ marginLeft: 'auto', color: 'rgba(255,255,255,0.2)', fontSize: 16 }}>→</div>
                </a>
              ))}
            </div>
          </div>
        </div>

        {/* Bottom tagline */}
        <div ref={r3} className="fade-up delay-3" style={{
          textAlign: 'center',
          marginTop: 72,
          padding: '28px 0',
          borderTop: '1px solid rgba(255,255,255,0.07)',
        }}>
          <p style={{
            fontSize: 'clamp(15px, 2vw, 18px)',
            color: 'rgba(255,255,255,0.45)',
            letterSpacing: '0.01em',
          }}>
            You describe the problem.{' '}
            <span style={{ color: 'rgba(255,255,255,0.75)', fontWeight: 500 }}>We build the system.</span>{' '}
            Your team owns it.
          </p>
        </div>
      </div>

      <style>{`
        @media (max-width: 768px) {
          #what-we-build .container > div:first-child { grid-template-columns: 1fr !important; gap: 48px !important; }
        }
      `}</style>
    </section>
  );
}

// ─── EXAMPLES ─────────────────────────────────────────────────────────────────
function ExamplesSection() {
  const examples = [
    {
      id: 'ex-01', num: '01', cat: 'Production Allocation & Drainage',
      headline: 'Allocation and drainage solved from your own data.',
      body: 'A custom app that allocates production per well without paying per sample, and stands up a pseudo-simulation drainage model — recovery and well-to-well interference — without the cost of full-physics simulation. Trained on your production, completion, and subsurface data. Glass-box, auditable, refreshed on your cadence. You own the pipeline.',
      benefits: ['On-demand allocation', 'Auditable drainage & interference', '100% model & data ownership'],
      placeholder: '[ product screenshot: production allocation dashboard\nwell-level allocation chart + drainage map overlay ]',
    },
    {
      id: 'ex-02', num: '02', cat: 'AutoML for Completions',
      headline: 'Every well, a model of its own.',
      body: 'A custom AutoML engine that ingests public and private wells, generates a model per zone per bench per landing target, and ranks cube-design and completion-design scenarios with glass-box feature importance. Retrains as new wells come online.',
      benefits: ['Custom models for your acreage', 'Glass-box feature importance', 'Retrained as your asset evolves'],
      placeholder: '[ product screenshot: AutoML completions optimizer\nzone/bench model grid + feature importance chart ]',
    },
    {
      id: 'ex-03', num: '03', cat: 'Custom RTA',
      headline: 'An RTA application built around your workflow.',
      body: 'Production analysis software — DCA, analytical, numerical methods — designed with your engineers, running inside your cloud. Microseismic, geochem, frac-hit flags, and lookbacks wired into the same session. One build, full handover.',
      benefits: ['Designed with your team', 'Runs inside your cloud', 'Integrated diagnostics', 'Own it end-to-end'],
      placeholder: '[ product screenshot: custom RTA app\nDCA curves + microseismic overlay + frac-hit flags ]',
    },
    {
      id: 'ex-04', num: '04', cat: 'Infill & Inventory Expansion',
      headline: 'Find the wells you already own — above, below, and next door.',
      body: 'Screens existing pads for un-drilled above/below candidates, grades new acreage on data rather than analogs, and rolls the output into your AFE and reserves workflow. A live inventory, not a once-a-year PDF.',
      benefits: ['Above/below infill screening', 'AI-graded new-acreage type curves', 'Refreshes as offsets come online'],
      placeholder: '[ product screenshot: infill inventory map\nacreage grading heatmap + candidate well table ]',
    },
  ];

  return (
    <section id="examples" style={{ background: 'var(--bg-light)', padding: '100px 0' }}>
      <div className="container">
        <div className="fade-up" ref={useFadeUp()}>
          <Eyebrow light>Examples</Eyebrow>
          <h2 style={{
            fontSize: 'clamp(26px, 3.5vw, 44px)',
            fontWeight: 700,
            letterSpacing: '-0.025em',
            color: 'var(--text-dark)',
            maxWidth: 520,
            lineHeight: 1.15,
            marginBottom: 64,
          }}>Four applications we've built for operators.</h2>
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 80 }}>
          {examples.map((ex, i) => {
            const r = useFadeUp();
            const isEven = i % 2 === 0;
            return (
              <div key={ex.id} id={ex.id} ref={r} className="fade-up" style={{
                display: 'grid',
                gridTemplateColumns: '1fr 1fr',
                gap: 60,
                alignItems: 'center',
              }}>
                {/* Text side */}
                <div style={{ order: isEven ? 0 : 1 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 16 }}>
                    <span style={{
                      fontSize: 11, fontWeight: 700, letterSpacing: '0.15em',
                      background: 'var(--grad)',
                      WebkitBackgroundClip: 'text', WebkitTextFillColor: 'transparent', backgroundClip: 'text',
                    }}>{ex.num}</span>
                    <span style={{ fontSize: 11, fontWeight: 600, letterSpacing: '0.1em', color: 'var(--text-muted)', textTransform: 'uppercase' }}>{ex.cat}</span>
                  </div>
                  <h3 style={{ fontSize: 'clamp(20px, 2.5vw, 28px)', fontWeight: 700, color: 'var(--text-dark)', lineHeight: 1.2, marginBottom: 16, letterSpacing: '-0.02em' }}>{ex.headline}</h3>
                  <GradUnderline />
                  <p style={{ fontSize: 15, color: 'var(--text-muted)', lineHeight: 1.75, margin: '20px 0 24px' }}>{ex.body}</p>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                    {ex.benefits.map(b => (
                      <div key={b} style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                        <CheckIcon />
                        <span style={{ fontSize: 14, color: 'var(--text-dark)', fontWeight: 500 }}>{b}</span>
                      </div>
                    ))}
                  </div>
                </div>

                {/* Screenshot side */}
                <div style={{ order: isEven ? 1 : 0 }}>
                  <ScreenPlaceholder label={ex.placeholder} />
                </div>
              </div>
            );
          })}
        </div>
      </div>

      <style>{`
        @media (max-width: 768px) {
          #examples .container > div > div { grid-template-columns: 1fr !important; gap: 32px !important; }
          #examples .container > div > div > div { order: unset !important; }
        }
      `}</style>
    </section>
  );
}

// ─── HOW WE ENGAGE ────────────────────────────────────────────────────────────
function HowWeWorkSection() {
  const r1 = useFadeUp();
  const steps = [
    { num: '01', title: 'Scope', desc: '2-week paid discovery on one real dataset. We come back with a written deliverable.' },
    { num: '02', title: 'Build', desc: 'Side-by-side with your engineers, in your stack. Weekly demos. No surprises.' },
    { num: '03', title: 'Deploy', desc: 'Inside your cloud. Your data, your models. We don\'t touch production unless invited.' },
    { num: '04', title: 'Own', desc: 'Full handover. Code, weights, pipeline — yours. Extensions only if you want them.' },
  ];

  return (
    <section id="how-we-work" style={{
      background: 'var(--dark)',
      padding: '100px 0',
      position: 'relative',
      overflow: 'hidden',
    }}>
      <div style={{ position:'absolute', bottom: 0, left: '30%', width: 600, height: 400,
        background: 'radial-gradient(ellipse, rgba(16,185,129,0.08) 0%, transparent 70%)', pointerEvents: 'none' }} />

      <div className="container">
        <div ref={r1} className="fade-up" style={{ marginBottom: 64 }}>
          <Eyebrow>How We Work</Eyebrow>
          <h2 style={{
            fontSize: 'clamp(28px, 3.5vw, 46px)',
            fontWeight: 700,
            letterSpacing: '-0.025em',
            color: '#fff',
            maxWidth: 480,
            lineHeight: 1.15,
          }}>Four steps from scope to ownership.</h2>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 20, position: 'relative' }}>
          {/* Connector line */}
          <div style={{
            position: 'absolute', top: 28, left: 'calc(12.5%)', right: 'calc(12.5%)',
            height: 2, background: 'linear-gradient(90deg, rgba(16,185,129,0.5), rgba(8,145,178,0.5), rgba(29,78,216,0.5))',
            zIndex: 0,
          }} />

          {steps.map((s, i) => {
            const r = useFadeUp();
            return (
              <div key={i} ref={r} className={`fade-up delay-${i+1}`} style={{
                background: 'rgba(255,255,255,0.03)',
                border: '1px solid rgba(255,255,255,0.08)',
                borderRadius: 12,
                padding: '28px 22px',
                position: 'relative',
                zIndex: 1,
              }}>
                {/* Gradient number dot */}
                <div style={{
                  width: 40, height: 40, borderRadius: '50%',
                  background: 'linear-gradient(135deg, #10B981, #0891B2, #1D4ED8)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  marginBottom: 20,
                  fontSize: 13, fontWeight: 700, color: '#fff',
                }}>{s.num}</div>
                <h3 style={{ fontSize: 18, fontWeight: 700, color: '#fff', marginBottom: 10, letterSpacing: '-0.01em' }}>{s.title}</h3>
                <p style={{ fontSize: 13, color: 'rgba(255,255,255,0.5)', lineHeight: 1.7 }}>{s.desc}</p>
              </div>
            );
          })}
        </div>
      </div>

      <style>{`
        @media (max-width: 768px) {
          #how-we-work .container > div:last-child { grid-template-columns: 1fr 1fr !important; }
          #how-we-work .container > div:last-child > div:nth-child(2) { display: none; }
        }
        @media (max-width: 480px) {
          #how-we-work .container > div:last-child { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </section>
  );
}

// ─── WHY TESSERA ──────────────────────────────────────────────────────────────
function WhyTesseraSection() {
  const r1 = useFadeUp(), r2 = useFadeUp();
  const cols = [
    ['AI-native, subsurface-fluent', 'No lock-in. No black box.', 'You own every line of code'],
    ['Glass-box models, auditable outputs', 'Your cloud, your data, your auth', 'Reservoir + ML under one roof'],
    ['Paid scoping, written deliverable', 'Ship working systems, not slides', 'No annual seats. No re-ups.'],
  ];
  const stats = [
    { val: '35+', label: 'Years combined subsurface experience' },
    { val: 'Multi-basin', label: 'Unconventional expertise' },
    { val: 'Stanford & Silicon Valley', label: 'AI research pedigree' },
  ];

  return (
    <section id="why-tessera" style={{ background: 'var(--bg-light)', padding: '100px 0' }}>
      <div className="container">
        <div ref={r1} className="fade-up" style={{ marginBottom: 56 }}>
          <Eyebrow light>Why Tessera</Eyebrow>
          <h2 style={{
            fontSize: 'clamp(28px, 3.5vw, 44px)',
            fontWeight: 700,
            letterSpacing: '-0.025em',
            color: 'var(--text-dark)',
            maxWidth: 480,
            lineHeight: 1.15,
          }}>Built different, by design.</h2>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 32, marginBottom: 64 }}>
          {cols.map((col, ci) => (
            <div key={ci} style={{
              background: '#fff',
              border: '1px solid #E2E8F0',
              borderRadius: 12,
              padding: '28px 24px',
            }}>
              {col.map((item, ii) => (
                <div key={ii} style={{ display: 'flex', alignItems: 'flex-start', gap: 12, marginBottom: ii < col.length - 1 ? 16 : 0 }}>
                  <div style={{ marginTop: 2, flexShrink: 0 }}><CheckIcon color="#0891B2" size={15} /></div>
                  <span style={{ fontSize: 14, fontWeight: 500, color: 'var(--text-dark)', lineHeight: 1.5 }}>{item}</span>
                </div>
              ))}
            </div>
          ))}
        </div>

        {/* Stat bar */}
        <div ref={r2} className="fade-up" style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(3, 1fr)',
          background: 'var(--dark)',
          borderRadius: 14,
          overflow: 'hidden',
        }}>
          {stats.map((s, i) => (
            <div key={i} style={{
              padding: '36px 32px',
              borderRight: i < 2 ? '1px solid rgba(255,255,255,0.07)' : 'none',
              textAlign: 'center',
            }}>
              <div style={{
                fontSize: 'clamp(20px, 2.5vw, 38px)',
                fontWeight: 700,
                background: 'var(--grad)',
                WebkitBackgroundClip: 'text',
                WebkitTextFillColor: 'transparent',
                backgroundClip: 'text',
                letterSpacing: '-0.02em',
                marginBottom: 6,
              }}>{s.val}</div>
              <div style={{ fontSize: 13, color: 'rgba(255,255,255,0.45)', lineHeight: 1.5 }}>{s.label}</div>
            </div>
          ))}
        </div>
      </div>

      <style>{`
        @media (max-width: 768px) {
          #why-tessera .container > div:nth-child(3) { grid-template-columns: 1fr !important; }
          #why-tessera .container > div:last-child { grid-template-columns: 1fr !important; }
          #why-tessera .container > div:last-child > div { border-right: none !important; border-bottom: 1px solid rgba(255,255,255,0.07); }
        }
      `}</style>
    </section>
  );
}

// ─── FAQ ──────────────────────────────────────────────────────────────────────
function FAQSection() {
  const [open, setOpen] = useState(null);
  const r1 = useFadeUp();
  const faqs = [
    { q: 'Do you sell software or services?', a: 'Neither. We build custom applications with you, and hand them over. You get the code, the models, the pipeline — we don\'t retain any access or ongoing dependency.' },
    { q: 'Where does our data live?', a: 'Inside your cloud. It never leaves your environment. We work inside your VPC or tenant from day one.' },
    { q: 'What happens if we stop working with you?', a: 'You keep running everything we built. Code, models, weights, pipeline — yours. Nothing stops working. Nothing phones home.' },
    { q: 'How long does a typical engagement take?', a: 'Scoping is 2 weeks. Build-to-deploy is typically 8–16 weeks depending on the app and data readiness.' },
    { q: 'Do you work with small operators?', a: 'Yes. If there\'s a real subsurface or production problem and the will to solve it properly, we\'ll talk.' },
    { q: 'Can you integrate with our existing stack?', a: 'Yes. We build around your data warehouse, your cloud, your auth — not around ours. If you\'re on Azure, AWS, or GCP, we work there.' },
    { q: 'Do you do pilots?', a: 'We do paid scoping engagements with a written deliverable. Not free pilots that die in PowerPoint.' },
  ];

  return (
    <section id="faq" style={{ background: 'var(--bg-light)', padding: '100px 0', borderTop: '1px solid #E2E8F0' }}>
      <div className="container" style={{ maxWidth: 760 }}>
        <div ref={r1} className="fade-up" style={{ marginBottom: 48 }}>
          <Eyebrow light>FAQ</Eyebrow>
          <h2 style={{
            fontSize: 'clamp(28px, 3.5vw, 42px)',
            fontWeight: 700,
            letterSpacing: '-0.025em',
            color: 'var(--text-dark)',
            lineHeight: 1.15,
          }}>Common questions.</h2>
        </div>

        <div style={{ display: 'flex', flexDirection: 'column' }}>
          {faqs.map((f, i) => {
            const isOpen = open === i;
            return (
              <div key={i} style={{ borderBottom: '1px solid #E2E8F0' }}>
                <button
                  onClick={() => setOpen(isOpen ? null : i)}
                  style={{
                    width: '100%', textAlign: 'left',
                    display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                    padding: '20px 0',
                    background: 'none', border: 'none', cursor: 'pointer',
                    fontFamily: 'var(--font)',
                  }}
                >
                  <span style={{ fontSize: 16, fontWeight: 600, color: 'var(--text-dark)', paddingRight: 24, lineHeight: 1.4 }}>{f.q}</span>
                  <span style={{
                    width: 24, height: 24, borderRadius: '50%',
                    background: isOpen ? 'var(--green)' : '#E2E8F0',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    flexShrink: 0,
                    transition: 'background 0.2s',
                    fontSize: 14,
                    color: isOpen ? '#fff' : 'var(--text-muted)',
                  }}>{isOpen ? '−' : '+'}</span>
                </button>
                <div style={{
                  maxHeight: isOpen ? 200 : 0,
                  overflow: 'hidden',
                  transition: 'max-height 0.35s ease',
                }}>
                  <p style={{
                    fontSize: 15,
                    color: 'var(--text-muted)',
                    lineHeight: 1.75,
                    paddingBottom: 20,
                  }}>{f.a}</p>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </section>
  );
}

// ─── CONTACT / CTA ────────────────────────────────────────────────────────────
function ContactSection() {
  const [form, setForm] = useState({ name: '', company: '', email: '', phone: '', problem: '' });
  const [submitted, setSubmitted] = useState(false);
  const [errors, setErrors] = useState({});
  const r1 = useFadeUp(), r2 = useFadeUp();

  const validate = () => {
    const e = {};
    if (!form.name.trim()) e.name = 'Required';
    if (!form.company.trim()) e.company = 'Required';
    if (!form.email.trim() || !form.email.includes('@')) e.email = 'Valid email required';
    if (!form.problem.trim()) e.problem = 'Required';
    return e;
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    const errs = validate();
    if (Object.keys(errs).length) { setErrors(errs); return; }

    try {
      const res = await fetch('https://formspree.io/f/xdayybep', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
        body: JSON.stringify({
          name: form.name,
          company: form.company,
          email: form.email,
          phone: form.phone || '(not provided)',
          problem: form.problem,
        }),
      });
      if (res.ok) {
        setSubmitted(true);
      } else {
        const data = await res.json();
        setErrors({ submit: data?.error || 'Submission failed. Please email us directly.' });
      }
    } catch {
      setErrors({ submit: 'Network error. Please email us at hello@tessera-analytics.ai' });
    }
  };

  const inputStyle = (field) => ({
    width: '100%',
    padding: '12px 16px',
    background: 'rgba(255,255,255,0.06)',
    border: `1px solid ${errors[field] ? 'rgba(239,68,68,0.6)' : 'rgba(255,255,255,0.15)'}`,
    borderRadius: 8,
    color: '#fff',
    fontFamily: 'var(--font)',
    fontSize: 14,
    outline: 'none',
    transition: 'border-color 0.2s',
  });

  const labelStyle = {
    display: 'block',
    fontSize: 12,
    fontWeight: 600,
    letterSpacing: '0.08em',
    color: 'rgba(255,255,255,0.5)',
    marginBottom: 8,
    textTransform: 'uppercase',
  };

  return (
    <section id="contact" style={{
      background: 'var(--dark)',
      padding: '100px 0',
      position: 'relative',
      overflow: 'hidden',
    }}>
      {/* Gradient border top */}
      <div style={{ position: 'absolute', top: 0, left: 0, right: 0, height: 2, background: 'var(--grad)' }} />

      <div style={{ position:'absolute', top: '30%', right: '-5%', width: 500, height: 500,
        background: 'radial-gradient(circle, rgba(16,185,129,0.1) 0%, transparent 70%)', pointerEvents: 'none' }} />

      <div className="container" style={{ maxWidth: 800 }}>
        <div ref={r1} className="fade-up" style={{ marginBottom: 48 }}>
          <h2 style={{
            fontSize: 'clamp(36px, 5vw, 62px)',
            fontWeight: 700,
            letterSpacing: '-0.03em',
            color: '#fff',
            marginBottom: 18,
          }}>Let's build.</h2>
          <p style={{ fontSize: 16, color: 'rgba(255,255,255,0.52)', lineHeight: 1.7, maxWidth: 580 }}>
            A 2-week scoping on a problem that's costing you real money. We come back with a written scope: what we'd build, what it costs, what we expect it to return. Then you decide.
          </p>
        </div>

        <div ref={r2} className="fade-up delay-1">
          {submitted ? (
            <div style={{
              background: 'rgba(16,185,129,0.1)',
              border: '1px solid rgba(16,185,129,0.3)',
              borderRadius: 12,
              padding: '40px 32px',
              textAlign: 'center',
            }}>
              <div style={{ fontSize: 28, marginBottom: 12 }}>
                <svg width="40" height="40" viewBox="0 0 40 40" fill="none" style={{ margin: '0 auto 16px', display: 'block' }}>
                  <circle cx="20" cy="20" r="19" stroke="#10B981" strokeWidth="1.5"/>
                  <path d="M12 20l6 6 11-12" stroke="#10B981" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
                </svg>
              </div>
              <h3 style={{ color: '#fff', fontSize: 20, fontWeight: 600, marginBottom: 10 }}>Request received.</h3>
              <p style={{ color: 'rgba(255,255,255,0.55)', fontSize: 15 }}>We'll be in touch within one business day.</p>
            </div>
          ) : (
            <form onSubmit={handleSubmit} noValidate>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20, marginBottom: 20 }}>
                <div>
                  <label style={labelStyle}>Name</label>
                  <input
                    type="text" placeholder="Jane Smith" value={form.name}
                    onChange={e => { setForm({...form, name: e.target.value}); setErrors({...errors, name: null}); }}
                    style={inputStyle('name')}
                    onFocus={e => e.target.style.borderColor = 'rgba(16,185,129,0.5)'}
                    onBlur={e => e.target.style.borderColor = errors.name ? 'rgba(239,68,68,0.6)' : 'rgba(255,255,255,0.15)'}
                  />
                  {errors.name && <p style={{ color: '#EF4444', fontSize: 11, marginTop: 4 }}>{errors.name}</p>}
                </div>
                <div>
                  <label style={labelStyle}>Company</label>
                  <input
                    type="text" placeholder="Operator Co." value={form.company}
                    onChange={e => { setForm({...form, company: e.target.value}); setErrors({...errors, company: null}); }}
                    style={inputStyle('company')}
                    onFocus={e => e.target.style.borderColor = 'rgba(16,185,129,0.5)'}
                    onBlur={e => e.target.style.borderColor = errors.company ? 'rgba(239,68,68,0.6)' : 'rgba(255,255,255,0.15)'}
                  />
                  {errors.company && <p style={{ color: '#EF4444', fontSize: 11, marginTop: 4 }}>{errors.company}</p>}
                </div>
              </div>

              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20, marginBottom: 20 }}>
                <div>
                  <label style={labelStyle}>Work Email</label>
                  <input
                    type="email" placeholder="jane@operatorco.com" value={form.email}
                    onChange={e => { setForm({...form, email: e.target.value}); setErrors({...errors, email: null}); }}
                    style={inputStyle('email')}
                    onFocus={e => e.target.style.borderColor = 'rgba(16,185,129,0.5)'}
                    onBlur={e => e.target.style.borderColor = errors.email ? 'rgba(239,68,68,0.6)' : 'rgba(255,255,255,0.15)'}
                  />
                  {errors.email && <p style={{ color: '#EF4444', fontSize: 11, marginTop: 4 }}>{errors.email}</p>}
                </div>
                <div>
                  <label style={labelStyle}>Phone <span style={{ color: 'rgba(255,255,255,0.25)', fontWeight: 400 }}>(optional)</span></label>
                  <input
                    type="tel" placeholder="+1 (555) 000-0000" value={form.phone}
                    onChange={e => setForm({...form, phone: e.target.value})}
                    style={inputStyle('phone')}
                    onFocus={e => e.target.style.borderColor = 'rgba(16,185,129,0.5)'}
                    onBlur={e => e.target.style.borderColor = 'rgba(255,255,255,0.15)'}
                  />
                </div>
              </div>

              <div style={{ marginBottom: 28 }}>
                <label style={labelStyle}>What problem are you trying to solve?</label>
                <textarea
                  rows={4} placeholder="Describe the subsurface or production problem — the more specific, the better."
                  value={form.problem}
                  onChange={e => { setForm({...form, problem: e.target.value}); setErrors({...errors, problem: null}); }}
                  style={{ ...inputStyle('problem'), resize: 'vertical', minHeight: 100 }}
                  onFocus={e => e.target.style.borderColor = 'rgba(16,185,129,0.5)'}
                  onBlur={e => e.target.style.borderColor = errors.problem ? 'rgba(239,68,68,0.6)' : 'rgba(255,255,255,0.15)'}
                />
                {errors.problem && <p style={{ color: '#EF4444', fontSize: 11, marginTop: 4 }}>{errors.problem}</p>}
              </div>

              <div style={{ display: 'flex', alignItems: 'center', gap: 24, flexWrap: 'wrap' }}>
                <GradBtn href={null} onClick={handleSubmit}>Request a scoping call</GradBtn>
                <span style={{ fontSize: 13, color: 'rgba(255,255,255,0.4)' }}>
                  Or email us — <a href="mailto:hello@tessera-analytics.ai" style={{ color: 'rgba(16,185,129,0.8)', textDecoration: 'none' }}>hello@tessera-analytics.ai</a>
                </span>
              </div>
              {errors.submit && (
                <p style={{ color: '#EF4444', fontSize: 13, marginTop: 12 }}>{errors.submit}</p>
              )}
            </form>
          )}
        </div>
      </div>

      <style>{`
        @media (max-width: 600px) {
          #contact form > div:first-child,
          #contact form > div:nth-child(2) { grid-template-columns: 1fr !important; }
        }
        input::placeholder, textarea::placeholder { color: rgba(255,255,255,0.25); }
      `}</style>
    </section>
  );
}

// ─── FOOTER ───────────────────────────────────────────────────────────────────
function Footer() {
  return (
    <footer style={{ background: 'var(--dark2)', borderTop: '1px solid rgba(255,255,255,0.07)' }}>
      {/* Gradient top border */}
      <div style={{ height: 2, background: 'var(--grad)' }} />

      <div className="container" style={{ padding: '56px 24px 40px' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1fr', gap: 48, marginBottom: 48 }}>
          {/* About */}
          <div>
            <div style={{ marginBottom: 20 }}>
              <Wordmark light />
            </div>
            <p style={{ fontSize: 13, color: 'rgba(255,255,255,0.4)', lineHeight: 1.75, maxWidth: 340 }}>
              Tessera Analytics AI is an AI-native firm focused on reservoir characterization and production optimization. We build custom AI applications for oil &amp; gas operators. You own the code, models, and data.
            </p>
            <p style={{ fontSize: 12, color: 'rgba(16,185,129,0.6)', marginTop: 14, fontStyle: 'italic', letterSpacing: '0.02em' }}>
              Your data. Your models. Your system.
            </p>
          </div>

          {/* Examples */}
          <div>
            <h4 style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.15em', textTransform: 'uppercase', color: 'rgba(255,255,255,0.3)', marginBottom: 20 }}>Examples</h4>
            {[
              ['Prod Alloc + Drainage', '#ex-01'],
              ['AutoML for Completions', '#ex-02'],
              ['Custom RTA', '#ex-03'],
              ['Infill & Inventory', '#ex-04'],
            ].map(([label, href]) => (
              <a key={href} href={href} style={{
                display: 'block', fontSize: 13, color: 'rgba(255,255,255,0.45)',
                textDecoration: 'none', marginBottom: 10,
                transition: 'color 0.2s',
              }}
                onMouseEnter={e => e.target.style.color = 'rgba(255,255,255,0.8)'}
                onMouseLeave={e => e.target.style.color = 'rgba(255,255,255,0.45)'}
              >{label}</a>
            ))}
          </div>

          {/* Contact */}
          <div>
            <h4 style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.15em', textTransform: 'uppercase', color: 'rgba(255,255,255,0.3)', marginBottom: 20 }}>Contact</h4>
            <a href="mailto:hello@tessera-analytics.ai" style={{
              display: 'block', fontSize: 13, color: 'rgba(255,255,255,0.45)',
              textDecoration: 'none', marginBottom: 10,
              transition: 'color 0.2s',
            }}
              onMouseEnter={e => e.target.style.color = 'rgba(16,185,129,0.8)'}
              onMouseLeave={e => e.target.style.color = 'rgba(255,255,255,0.45)'}
            >hello@tessera-analytics.ai</a>
            <a href="https://tessera-analytics.ai" target="_blank" rel="noreferrer" style={{
              display: 'block', fontSize: 13, color: 'rgba(255,255,255,0.45)',
              textDecoration: 'none', marginBottom: 10,
            }}
              onMouseEnter={e => e.target.style.color = 'rgba(255,255,255,0.8)'}
              onMouseLeave={e => e.target.style.color = 'rgba(255,255,255,0.45)'}
            >tessera-analytics.ai</a>
            <a href="https://linkedin.com" target="_blank" rel="noreferrer" style={{
              display: 'block', fontSize: 13, color: 'rgba(255,255,255,0.45)',
              textDecoration: 'none',
            }}
              onMouseEnter={e => e.target.style.color = 'rgba(255,255,255,0.8)'}
              onMouseLeave={e => e.target.style.color = 'rgba(255,255,255,0.45)'}
            >LinkedIn</a>
          </div>
        </div>

        {/* Copyright */}
        <div style={{
          borderTop: '1px solid rgba(255,255,255,0.07)',
          paddingTop: 24,
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          flexWrap: 'wrap',
          gap: 12,
        }}>
          <p style={{ fontSize: 12, color: 'rgba(255,255,255,0.25)' }}>
            © Tessera Analytics AI. All rights reserved.
          </p>
          <a href="https://tessera-analytics.ai" style={{ fontSize: 12, color: 'rgba(255,255,255,0.2)', textDecoration: 'none' }}>
            tessera-analytics.ai
          </a>
        </div>
      </div>

      <style>{`
        @media (max-width: 768px) {
          footer .container > div:first-child { grid-template-columns: 1fr !important; gap: 32px !important; }
        }
      `}</style>
    </footer>
  );
}

Object.assign(window, {
  HeroSection, ProblemSection, WhatWeBuildSection, ExamplesSection,
  HowWeWorkSection, WhyTesseraSection, FAQSection, ContactSection, Footer
});
