// ─── 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 and 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="#what-we-build">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: 'Wells, Production, D&C, G&G, Diagnostics, and Operations data, all live in different silos. One-off dashboards instead of working systems.',
    },
    {
      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">
          <p style={{
            fontFamily: 'var(--font)',
            fontSize: 14,
            fontWeight: 600,
            letterSpacing: '0.18em',
            textTransform: 'uppercase',
            color: 'var(--teal)',
            marginBottom: 16,
          }}>Where operators lose money and barrels</p>
          <h2 style={{
            fontSize: 'clamp(26px, 3.1vw, 42px)',
            fontWeight: 700,
            letterSpacing: '-0.025em',
            color: 'var(--text-dark)',
            maxWidth: 800,
            lineHeight: 1.2,
            marginBottom: 56,
          }}>Fragmented data. One-off models.<br />Insights that never become action.</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 DataFlowAnimation() {
  const wrapRef = React.useRef(null);

  React.useEffect(() => {
    const wrap = wrapRef.current;
    if (!wrap) return;

    const svg = wrap.querySelector('.df-conn-svg');
    const routeMap = [
      [0, 3],
      [1, 4],
      [0, 2],
      [2, 3],
      [1, 4],
    ];
    let current = 0;
    let intervalId = null;

    function getRight(el) {
      const w = wrap.getBoundingClientRect(), r = el.getBoundingClientRect();
      return { x: r.right - w.left, y: r.top - w.top + r.height / 2 };
    }
    function getLeft(el) {
      const w = wrap.getBoundingClientRect(), r = el.getBoundingClientRect();
      return { x: r.left - w.left, y: r.top - w.top + r.height / 2 };
    }
    function engineEdges() {
      const eng = wrap.querySelector('.df-engine-box');
      const w = wrap.getBoundingClientRect(), r = eng.getBoundingClientRect();
      const cy = r.top - w.top + r.height / 2;
      return { left: { x: r.left - w.left, y: cy }, right: { x: r.right - w.left, y: cy } };
    }
    function curvePath(p1, p2) {
      const dx = (p2.x - p1.x) * 0.45;
      return `M${p1.x},${p1.y} C${p1.x+dx},${p1.y} ${p2.x-dx},${p2.y} ${p2.x},${p2.y}`;
    }
    function buildLines() {
      svg.innerHTML = '';
      svg.setAttribute('width', wrap.offsetWidth);
      svg.setAttribute('height', wrap.offsetHeight);
      const eng = engineEdges();
      for (let i = 0; i < 5; i++) {
        const inEl = wrap.querySelector('#df-in-' + i);
        const d = curvePath(getRight(inEl), eng.left);
        const bg = document.createElementNS('http://www.w3.org/2000/svg', 'path');
        bg.setAttribute('d', d); bg.setAttribute('class', 'df-conn-line'); svg.appendChild(bg);
        const an = document.createElementNS('http://www.w3.org/2000/svg', 'path');
        an.setAttribute('d', d); an.setAttribute('class', 'df-conn-animated'); an.id = 'df-anim-in-' + i; svg.appendChild(an);
      }
      for (let j = 0; j < 5; j++) {
        const outEl = wrap.querySelector('#df-out-' + j);
        const d = curvePath(eng.right, getLeft(outEl));
        const bg = document.createElementNS('http://www.w3.org/2000/svg', 'path');
        bg.setAttribute('d', d); bg.setAttribute('class', 'df-conn-line'); svg.appendChild(bg);
        const an = document.createElementNS('http://www.w3.org/2000/svg', 'path');
        an.setAttribute('d', d); an.setAttribute('class', 'df-conn-animated df-out'); an.id = 'df-anim-out-' + j; svg.appendChild(an);
      }
    }
    function resetAll() {
      for (let i = 0; i < 5; i++) {
        wrap.querySelector('#df-in-' + i).classList.remove('df-active');
        wrap.querySelector('#df-out-' + i).classList.remove('df-lit');
        ['df-anim-in-'+i, 'df-anim-out-'+i].forEach(id => {
          const el = wrap.querySelector('#' + id);
          if (el) { el.classList.remove('df-running'); void el.offsetWidth; }
        });
      }
    }
    function runCycle(idx) {
      resetAll();
      wrap.querySelector('#df-in-' + idx).classList.add('df-active');
      const inLine = wrap.querySelector('#df-anim-in-' + idx);
      if (inLine) { void inLine.offsetWidth; inLine.classList.add('df-running'); }
      setTimeout(() => {
        routeMap[idx].forEach((outIdx, i) => {
          setTimeout(() => {
            const ol = wrap.querySelector('#df-anim-out-' + outIdx);
            if (ol) { void ol.offsetWidth; ol.classList.add('df-running'); }
            setTimeout(() => {
              wrap.querySelector('#df-out-' + outIdx).classList.add('df-lit');
            }, 1100);
          }, i * 170);
        });
      }, 1050);
    }
    function tick() { runCycle(current); current = (current + 1) % 5; }

    const t = setTimeout(() => { buildLines(); tick(); intervalId = setInterval(tick, 3400); }, 100);
    const onResize = () => buildLines();
    window.addEventListener('resize', onResize);
    return () => { clearTimeout(t); clearInterval(intervalId); window.removeEventListener('resize', onResize); };
  }, []);

  return (
    <div ref={wrapRef} style={{
      background: '#1a3244',
      borderRadius: 16,
      padding: '36px 28px 36px',
      position: 'relative',
      overflow: 'hidden',
    }}>
      <style>{`
        .df-wrap::before { content:''; position:absolute; inset:0; background:radial-gradient(ellipse 60% 50% at 50% 50%, rgba(0,200,140,0.07) 0%, transparent 70%); pointer-events:none; }
        .df-input-node, .df-output-node { display:flex; align-items:center; gap:10px; border-radius:10px; padding:10px 14px; position:relative; overflow:hidden; transition:border-color 0.35s, background 0.35s; }
        .df-input-node { background:rgba(255,255,255,0.10); border:1px solid rgba(255,255,255,0.16); }
        .df-output-node { background:rgba(255,255,255,0.09); border:1px solid rgba(255,255,255,0.14); }
        .df-input-node.df-active { border-color:rgba(0,200,140,0.55); background:rgba(0,200,140,0.14); }
        .df-input-node.df-active .df-node-icon { color:#00c88c; }
        .df-input-node.df-active .df-node-label { color:rgba(255,255,255,0.95); }
        .df-output-node.df-lit { border-color:rgba(0,168,200,0.55); background:rgba(0,168,200,0.14); }
        .df-output-node.df-lit .df-out-icon { color:#00a8c8; }
        .df-output-node.df-lit .df-out-label { color:rgba(255,255,255,0.95); }
        .df-node-icon, .df-out-icon { font-size:15px; flex-shrink:0; line-height:1; width:20px; text-align:center; color:rgba(255,255,255,0.55); transition:color 0.35s; }
        .df-node-label { font-size:13px; font-weight:500; line-height:1.25; letter-spacing:0.01em; color:rgba(255,255,255,0.78); transition:color 0.35s; }
        .df-out-label  { font-size:13px; font-weight:500; line-height:1.25; letter-spacing:0.01em; color:rgba(255,255,255,0.72); transition:color 0.35s; }
        .df-input-node.df-active::after { content:''; position:absolute; left:-60%; top:0; width:50%; height:100%; background:linear-gradient(90deg, transparent, rgba(0,200,140,0.12), transparent); animation:df-shimmer 1.3s ease-in-out forwards; }
        .df-output-node.df-lit::after { content:''; position:absolute; left:-60%; top:0; width:50%; height:100%; background:linear-gradient(90deg, transparent, rgba(0,168,200,0.13), transparent); animation:df-shimmer 1s ease-in-out forwards; }
        @keyframes df-shimmer { 0%{left:-60%} 100%{left:130%} }
        .df-engine-pulse { position:absolute; inset:-10px; border-radius:24px; border:1px solid rgba(0,200,140,0.18); animation:df-pulse-ring 2.6s ease-out infinite; }
        .df-engine-pulse:nth-child(2) { inset:-20px; border-radius:30px; animation-delay:0.9s; border-color:rgba(0,200,140,0.09); }
        @keyframes df-pulse-ring { 0%{opacity:1;transform:scale(1)} 100%{opacity:0;transform:scale(1.07)} }
        .df-conn-svg { position:absolute; top:0; left:0; width:100%; height:100%; pointer-events:none; z-index:0; }
        .df-conn-line { fill:none; stroke:rgba(255,255,255,0.12); stroke-width:1.2; }
        .df-conn-animated { fill:none; stroke:#00c88c; stroke-width:1.5; stroke-dasharray:70 200; stroke-dashoffset:270; opacity:0; }
        .df-conn-animated.df-out { stroke:#00a8c8; }
        .df-conn-animated.df-running { opacity:1; animation:df-dash-flow 1.5s cubic-bezier(0.4,0,0.6,1) forwards; }
        @keyframes df-dash-flow { 0%{stroke-dashoffset:270;opacity:0.9} 75%{opacity:0.6} 100%{stroke-dashoffset:-10;opacity:0} }
      `}</style>

      <svg className="df-conn-svg"></svg>

      <div style={{ display:'grid', gridTemplateColumns:'1fr auto 1fr', alignItems:'center', position:'relative', zIndex:1 }}>
        {/* Inputs */}
        <div style={{ display:'flex', flexDirection:'column', gap:11, paddingRight:16 }}>
          {[['🛢️','Wells'],['📈','Production'],['⚙️','D&C'],['🗺️','G&G'],['🔬','Diagnostics']].map(([icon, label], i) => (
            <div key={i} id={'df-in-'+i} className="df-input-node">
              <span className="df-node-icon">{icon}</span>
              <span className="df-node-label">{label}</span>
            </div>
          ))}
        </div>

        {/* Engine */}
        <div style={{ display:'flex', justifyContent:'center', alignItems:'center', padding:'0 8px' }}>
          <div className="df-engine-box" style={{
            background:'rgba(0,200,140,0.07)', border:'1px solid rgba(0,200,140,0.28)',
            borderRadius:18, width:114, height:114,
            display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center',
            position:'relative', flexShrink:0,
            boxShadow:'0 0 36px rgba(0,200,140,0.1), inset 0 0 20px rgba(0,200,140,0.04)',
          }}>
            <div className="df-engine-pulse"></div>
            <div className="df-engine-pulse"></div>
            <div style={{ fontSize:24, marginBottom:5, lineHeight:1 }}>⬡</div>
            <div style={{ fontSize:11, fontWeight:600, color:'#00c88c', letterSpacing:'0.07em', textTransform:'uppercase' }}>Tessera</div>
            <div style={{ fontSize:9, color:'rgba(0,200,140,0.5)', letterSpacing:'0.09em', textTransform:'uppercase', marginTop:2 }}>AI Engine</div>
          </div>
        </div>

        {/* Outputs */}
        <div style={{ display:'flex', flexDirection:'column', gap:11, paddingLeft:16 }}>
          {[['🧩','Pad Optimization'],['⚡','RTAi / Production Intelligence'],['💧','Drainage Modeling'],['📋','Inventory / Recovery Optimization'],['🎛️','Base Optimization']].map(([icon, label], j) => (
            <div key={j} id={'df-out-'+j} className="df-output-node">
              <span className="df-out-icon">{icon}</span>
              <span className="df-out-label">{label}</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function WhatWeBuildSection() {
  const r1 = useFadeUp(), r2 = useFadeUp(), r3 = useFadeUp();
  const valueProps = [
    { title: 'AI-native, not bolted-on', body: 'Built around your data, your basin, and your workflows.' },
    { title: 'Transparent by design', body: 'No black box. No unnecessary lock-in. Built so your team can understand, trust, and use the solution.' },
    { title: 'Subsurface + AI under one roof', body: 'Subsurface expertise and AI/ML builders on the same team.' },
  ];

  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 1.8fr', gap: 80, alignItems: 'start' }}>
          {/* Left */}
          <div ref={r1} className="fade-up">
            <p style={{ fontFamily:'var(--font)', fontSize:13, fontWeight:600, letterSpacing:'0.2em', textTransform:'uppercase', color:'var(--green)', marginBottom:16 }}>The Tessera Difference</p>
            <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: 19, 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: 10 }}>{v.body}</p>
                </div>
              ))}
            </div>
          </div>

          {/* Right */}
          <div ref={r2} className="fade-up delay-2">
            <DataFlowAnimation />
          </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>
  );
}

// ─── HOW WE ENGAGE ────────────────────────────────────────────────────────────
function HowWeWorkSection() {
  const r1 = useFadeUp();
  const steps = [
    { num: '01', title: 'Scope', desc: '1-2 week focused discovery on one real use case and dataset. We come back with a written deliverable.' },
    { num: '02', title: 'Build', desc: 'Side-by-side with your engineers, in your stack. Frequent demos. No surprises.' },
    { num: '03', title: 'Deploy', desc: 'Inside your cloud. Your data, your models. We deploy into an approved environment that fits your security.' },
    { num: '04', title: 'Own', desc: 'Full handover: Solution, config, output, and operating workflows. Extensions only if you want them.' },
  ];

  return (
    <section id="how-we-work" style={{
      background: 'var(--bg-light)',
      padding: '100px 0',
      position: 'relative',
      overflow: 'hidden',
    }}>
      <div className="container">
        <div ref={r1} className="fade-up" style={{ marginBottom: 64 }}>
          <p style={{ fontFamily:'var(--font)', fontSize:13, fontWeight:600, letterSpacing:'0.2em', textTransform:'uppercase', color:'var(--teal)', marginBottom:16 }}>How We Work</p>
          <h2 style={{
            fontSize: 'clamp(28px, 3.5vw, 46px)',
            fontWeight: 700,
            letterSpacing: '-0.025em',
            color: 'var(--text-dark)',
            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: '#fff',
                border: '1px solid #E2E8F0',
                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: 'var(--text-dark)', marginBottom: 10, letterSpacing: '-0.01em' }}>{s.title}</h3>
                <p style={{ fontSize: 13, color: 'var(--text-muted)', 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>
  );
}



// ─── FAQ ──────────────────────────────────────────────────────────────────────
function FAQSection() {
  const [open, setOpen] = useState(null);
  const r1 = useFadeUp();
  const faqs = [
    { q: 'Do you sell software or services?', a: 'We build AI-native solutions around your data, workflows, and business problems. We are not a traditional SaaS platform, and we are not a slide-deck consulting firm. We deliver working systems that your team can use, operate, and trust.' },
    { q: 'Where does our data live?', a: 'In your environment or in a secure environment approved by your team. We design around your IT, security, and data governance requirements.' },
    { q: 'What happens if we stop working with you?', a: 'Your team keeps using the deployed solution. Your data, configurations, outputs, and operating workflows remain yours. No hidden black box. No unnecessary lock-in.' },
    { q: 'How long does a typical engagement take?', a: 'Most projects start with 1–2 weeks of focused scoping, followed by build-to-deploy cycle depending on the use case, data readiness, and integration needs.' },
    { 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, Databricks, or GCP, we work there.' },
  ];

  return (
    <section id="faq" style={{ background: 'var(--dark)', padding: '100px 0' }}>
      <div className="container" style={{ maxWidth: 760 }}>
        <div ref={r1} className="fade-up" style={{ marginBottom: 48 }}>
          <p style={{ fontFamily:'var(--font)', fontSize:13, fontWeight:600, letterSpacing:'0.2em', textTransform:'uppercase', color:'var(--teal)', marginBottom:16 }}>FAQ</p>
          <h2 style={{
            fontSize: 'clamp(28px, 3.5vw, 42px)',
            fontWeight: 700,
            letterSpacing: '-0.025em',
            color: '#fff',
            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 rgba(255,255,255,0.1)' }}>
                <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: '#fff', paddingRight: 24, lineHeight: 1.4 }}>{f.q}</span>
                  <span style={{
                    width: 24, height: 24, borderRadius: '50%',
                    background: isOpen ? 'var(--green)' : 'rgba(255,255,255,0.12)',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    flexShrink: 0,
                    transition: 'background 0.2s',
                    fontSize: 14,
                    color: '#fff',
                  }}>{isOpen ? '−' : '+'}</span>
                </button>
                <div style={{
                  maxHeight: isOpen ? 200 : 0,
                  overflow: 'hidden',
                  transition: 'max-height 0.35s ease',
                }}>
                  <p style={{
                    fontSize: 15,
                    color: 'rgba(255,255,255,0.55)',
                    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/xojrqrod', {
        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.
            </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>

          {/* 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://www.linkedin.com/company/tessera-analytics/" 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,
  HowWeWorkSection, FAQSection, ContactSection, Footer
});
