// Main page sections

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

/* Render a heading/phrase that may contain [[italic accent text]] markers.
   Preserves the exact inline styling used before: <span className="italic-accent ...">. */
function RichText({ text, accentClass = 'italic-accent', newline = false }) {
  if (!text) return null;
  const parts = String(text).split(/(\[\[[^\]]+\]\])/g);
  const nodes = parts.map((p, i) => {
    if (/^\[\[[^\]]+\]\]$/.test(p)) {
      return <span key={i} className={accentClass}>{p.slice(2, -2)}</span>;
    }
    if (newline && p.includes('\n')) {
      const lines = p.split('\n');
      return lines.map((ln, j) => (
        <React.Fragment key={`${i}-${j}`}>
          {j > 0 && <br/>}
          {ln}
        </React.Fragment>
      ));
    }
    return <React.Fragment key={i}>{p}</React.Fragment>;
  });
  return <>{nodes}</>;
}

function getContent() {
  return (typeof useContent === 'function') ? useContent() : window.CONTENT_FALLBACK;
}

/* ——— Nav ——— */
function Nav() {
  const content = getContent();
  const nav = content.nav || {};
  const site = content.site || {};
  const items = nav.items || [];
  return (
    <nav className="nav">
      <div className="nav-inner">
        <div className="nav-logo">
          <div className="nav-logo-mark">
            {site.logo_image ? (
              <img src={site.logo_image} alt="" width="28" height="28" style={{display:'block'}}/>
            ) : (
              <svg width="28" height="28" viewBox="0 0 28 28" fill="none">
                <circle cx="14" cy="14" r="11" stroke="currentColor" strokeWidth="1.2"/>
                <ellipse cx="14" cy="14" rx="11" ry="5" stroke="currentColor" strokeWidth="1.2"/>
                <ellipse cx="14" cy="14" rx="5" ry="11" stroke="currentColor" strokeWidth="1.2"/>
                <circle cx="14" cy="14" r="1.6" fill="currentColor"/>
              </svg>
            )}
          </div>
          <span>{site.brand_name || 'Ai GeoLAB'}</span>
        </div>
        <div className="nav-links">
          {items.map((it, i) => (
            <a key={i} href={it.href}>{it.label}</a>
          ))}
        </div>
        <div className="nav-cta">
          {nav.show_status ? (
            <div className="nav-status">
              <span className="status-dot" />
              <span>{nav.status_label}</span>
            </div>
          ) : null}
          <a href={nav.cta_href || '#contact'} className="btn btn-primary" style={{padding:'10px 18px', fontSize: 13}}>
            {nav.cta_label}
          </a>
        </div>
      </div>
    </nav>
  );
}

/* ——— Who We Are ——— */
function WhoWeAre() {
  const content = getContent();
  const wwa = content.wwa || {};
  const creds = wwa.credentials || [];
  const stats = wwa.stats || [];
  return (
    <section id="who" className="section bone">
      <div className="container">
        <Reveal>
          <div className="section-head">
            <div>
              <span className="eyebrow ink">{wwa.eyebrow}</span>
              <h2 className="h2" style={{marginTop: 24}}>
                <RichText text={wwa.heading} accentClass="italic-accent ink"/>
              </h2>
            </div>
            <div>
              <p className="lead">{wwa.lead}</p>
              <div style={{display:'flex', gap:14, marginTop: 28}}>
                <a href={wwa.primary_href || '#contact'} className="btn btn-ink">
                  {wwa.primary_cta} <span className="arrow">→</span>
                </a>
                <a href={wwa.secondary_href || '#specialize'} className="btn"
                   style={{border:'1px solid var(--line-ink-strong)', color:'var(--ink)'}}>
                  {wwa.secondary_cta} <span className="arrow">→</span>
                </a>
              </div>
            </div>
          </div>
        </Reveal>

        <div className="wwa-grid" style={{marginTop: 20}}>
          <Reveal>
            <div>
              <TopoIllustration tl={wwa.topo_marker_tl} br={wwa.topo_marker_br}/>
            </div>
          </Reveal>
          <Reveal delay={120}>
            <div>
              <div style={{display:'grid', gap:14}}>
                {creds.map((c, i) => (
                  <CredItem key={i} num={c.num} title={c.title} desc={c.description}/>
                ))}
              </div>

              <div className="wwa-stats">
                {stats.map((s, i) => (
                  <div key={i} className="stat-cell">
                    <div className="stat-num">
                      {s.render === 'split-98' ? (
                        <>98.<Counter value={Number(s.value) || 0} decimals={s.decimals || 0}/>
                        <span className="suffix">{s.suffix}</span></>
                      ) : (
                        <><Counter value={Number(s.value) || 0} decimals={s.decimals || 0}/>
                        <span className="suffix">{s.suffix}</span></>
                      )}
                    </div>
                    <div className="stat-label">{s.label}</div>
                  </div>
                ))}
              </div>
            </div>
          </Reveal>
        </div>
      </div>
    </section>
  );
}

function CredItem({ num, title, desc }) {
  return (
    <div style={{display:'grid', gridTemplateColumns:'40px 1fr', gap:20, paddingTop:20, borderTop:'1px solid var(--line-ink)'}}>
      <div className="mono" style={{fontSize:11, color:'var(--slate-600)', letterSpacing:'0.1em', paddingTop:6}}>{num}</div>
      <div>
        <div style={{fontFamily:'var(--sans)', fontSize:18, fontWeight:500, letterSpacing:'-0.01em', marginBottom:6}}>{title}</div>
        <div style={{fontSize:14, color:'#555f6e', lineHeight:1.55}}>{desc}</div>
      </div>
    </div>
  );
}

function TopoIllustration({ tl, br }) {
  return (
    <div className="topo-frame cornered">
      <svg viewBox="0 0 400 500" width="100%" height="100%" preserveAspectRatio="xMidYMid slice" style={{position:'absolute', inset:0}}>
        <defs>
          <linearGradient id="topoFill" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0" stopColor="#d9d0bb"/>
            <stop offset="1" stopColor="#c5b894"/>
          </linearGradient>
          <pattern id="dotGrid" x="0" y="0" width="16" height="16" patternUnits="userSpaceOnUse">
            <circle cx="1" cy="1" r="0.6" fill="rgba(10,20,36,0.15)"/>
          </pattern>
        </defs>
        <rect width="400" height="500" fill="url(#topoFill)"/>
        <rect width="400" height="500" fill="url(#dotGrid)"/>

        {[...Array(14)].map((_,i)=> {
          return (
            <path key={i}
              d={`M ${-20 + i*5} ${120 + i*6} Q 120 ${60 + i*10} 280 ${100 + i*12} T 420 ${280 + i*6}`}
              fill="none" stroke="rgba(30,64,50,0.45)" strokeWidth="0.7"/>
          );
        })}
        {[...Array(10)].map((_,i)=> (
          <path key={'b'+i}
            d={`M ${-40} ${280 + i*16} Q 150 ${260 + i*20} 440 ${300 + i*18}`}
            fill="none" stroke="rgba(30,64,50,0.35)" strokeWidth="0.6"/>
        ))}

        <path d="M 50 40 Q 120 150 90 240 T 140 420 L 180 500" fill="none" stroke="rgba(88,140,180,0.6)" strokeWidth="3"/>
        <path d="M 50 40 Q 120 150 90 240 T 140 420 L 180 500" fill="none" stroke="rgba(88,140,180,0.25)" strokeWidth="8"/>

        <path d="M 240 320 Q 300 290 360 310 Q 370 380 320 410 Q 260 420 230 380 Z"
              fill="rgba(45,106,79,0.25)" stroke="rgba(30,64,50,0.6)" strokeWidth="0.8"/>

        <g stroke="rgba(10,20,36,0.3)" strokeWidth="0.6" fill="none">
          <rect x="220" y="120" width="140" height="140"/>
          <line x1="220" y1="160" x2="360" y2="160"/>
          <line x1="220" y1="200" x2="360" y2="200"/>
          <line x1="260" y1="120" x2="260" y2="260"/>
          <line x1="310" y1="120" x2="310" y2="260"/>
        </g>

        <g>
          <circle cx="90" cy="180" r="5" fill="#2d6a4f"/>
          <circle cx="90" cy="180" r="11" fill="none" stroke="#2d6a4f" strokeWidth="0.8" opacity="0.5"/>
          <circle cx="280" cy="180" r="5" fill="#0a1424"/>
          <circle cx="150" cy="370" r="5" fill="#e8a948"/>
          <circle cx="150" cy="370" r="11" fill="none" stroke="#e8a948" strokeWidth="0.8" opacity="0.6"/>
        </g>

        <g transform="translate(350, 40)">
          <circle r="18" fill="rgba(244,241,234,0.85)" stroke="rgba(10,20,36,0.5)"/>
          <path d="M 0 -12 L 4 0 L 0 4 L -4 0 Z" fill="#0a1424"/>
          <text y="-22" textAnchor="middle" fontFamily="JetBrains Mono" fontSize="8" fill="#0a1424">N</text>
        </g>

        <g transform="translate(20, 470)">
          <line x1="0" y1="0" x2="80" y2="0" stroke="#0a1424" strokeWidth="1"/>
          <line x1="0" y1="-4" x2="0" y2="4" stroke="#0a1424"/>
          <line x1="40" y1="-2" x2="40" y2="2" stroke="#0a1424"/>
          <line x1="80" y1="-4" x2="80" y2="4" stroke="#0a1424"/>
          <text x="0" y="16" fontFamily="JetBrains Mono" fontSize="8" fill="#0a1424">0 · 1 · 2 km</text>
        </g>
      </svg>

      <div className="topo-marker" style={{top: 24, left: 20}}>{tl}</div>
      <div className="topo-marker" style={{bottom: 24, right: 20}}>{br}</div>
    </div>
  );
}

/* ——— Specializations ——— */
function Specializations() {
  const content = getContent();
  const sec = content.specialize || {};
  const items = sec.items || [];
  const total = items.length;
  return (
    <section id="specialize" className="section deep" style={{borderTop:'1px solid var(--line)'}}>
      <div className="scanline"/>
      <div className="container" style={{position:'relative'}}>
        <Reveal>
          <div className="section-head">
            <div>
              <span className="eyebrow">{sec.eyebrow}</span>
              <h2 className="h2" style={{marginTop:24}}>
                <RichText text={sec.heading}/>
              </h2>
            </div>
            <div>
              <p className="lead">{sec.lead}</p>
            </div>
          </div>
        </Reveal>

        <Reveal delay={80}>
          <div className="grid-cards dark">
            {items.map((s, i) => (
              <div className="card dark" key={s.num || i}>
                <div className="card-num">{s.num} / {String(total).padStart(2,'0')}</div>
                <div className="card-icon"><Icon name={s.icon} size={36} stroke={1.1}/></div>
                <div className="card-arrow"><Icon name="arrow" size={14}/></div>
                <div>
                  <div className="card-title">{s.title}</div>
                  <div className="card-desc">{s.description || s.desc}</div>
                </div>
              </div>
            ))}
            <div className="card dark" style={{display:'flex',flexDirection:'column',justifyContent:'space-between'}}>
              <div className="card-num">{String(total + 1).padStart(2,'0')} / {String(total).padStart(2,'0')}</div>
              <div>
                <div className="card-title" style={{color:'var(--cyan)'}}>{sec.custom_title}</div>
                <div className="card-desc">{sec.custom_desc}</div>
                <a href={sec.custom_href || '#contact'} className="mono"
                   style={{fontSize:11,color:'var(--cyan)',letterSpacing:'0.1em',marginTop:18,display:'inline-block'}}>
                  {sec.custom_cta}
                </a>
              </div>
            </div>
          </div>
        </Reveal>
      </div>
    </section>
  );
}

/* ——— Industries ——— */
function Industries() {
  const content = getContent();
  const sec = content.industries || {};
  const items = sec.items || [];
  const [active, setActive] = useS(items[0] ? items[0].key : '');
  useE(() => { if (items[0] && !items.find(i => i.key === active)) setActive(items[0].key); }, [items]);
  const cur = items.find(i => i.key === active) || items[0];
  if (!cur) return null;
  return (
    <section id="industries" className="section bone">
      <div className="container">
        <Reveal>
          <div className="section-head">
            <div>
              <span className="eyebrow ink">{sec.eyebrow}</span>
              <h2 className="h2" style={{marginTop:24}}>
                <RichText text={sec.heading} accentClass="italic-accent ink"/>
              </h2>
            </div>
            <div>
              <p className="lead">{sec.lead}</p>
            </div>
          </div>
        </Reveal>

        <Reveal>
          <div className="industries">
            <div className="ind-tabs">
              {items.map((it, i) => (
                <button key={it.key} className={"ind-tab" + (active === it.key ? " active" : "")}
                        onClick={() => setActive(it.key)}>
                  <span className="tab-num">0{i+1}</span>
                  <Icon name={it.icon} size={18} stroke={1.2}/>
                  <span>{it.label}</span>
                </button>
              ))}
            </div>
            <div className="ind-content" key={active}>
              <div className="mono" style={{fontSize:10,color:'var(--cyan)',letterSpacing:'0.15em',marginBottom:18}}>
                VERTICAL · {(cur.label || '').toUpperCase()}
              </div>
              <div className="ind-title">{cur.title}</div>
              <div className="ind-desc">{cur.description || cur.desc}</div>
              <div className="ind-kpis">
                {(cur.kpis || []).map(([v,l],i) => (
                  <div key={i} className="ind-kpi">
                    <div className="ind-kpi-v">{v}</div>
                    <div className="ind-kpi-l">{l}</div>
                  </div>
                ))}
              </div>
              <ul className="ind-bullets">
                {(cur.bullets || []).map((b,i) => <li key={i}>{b}</li>)}
              </ul>
            </div>
          </div>
        </Reveal>
      </div>
    </section>
  );
}

/* ——— Work / Field Impact ——— */
function Work() {
  const content = getContent();
  const sec = content.work || {};
  const items = sec.items || [];
  return (
    <section id="work" className="section deep">
      <div className="container">
        <Reveal>
          <div className="section-head">
            <div>
              <span className="eyebrow">{sec.eyebrow}</span>
              <h2 className="h2" style={{marginTop:24}}>
                <RichText text={sec.heading}/>
              </h2>
            </div>
            <div>
              <p className="lead">{sec.lead}</p>
              <a href={sec.cta_href || '#contact'} className="btn btn-ghost" style={{marginTop:24}}>
                {sec.cta_label} <span className="arrow">→</span>
              </a>
            </div>
          </div>
        </Reveal>

        <Reveal>
          <div className="work-grid">
            {items.map((w, i) => (
              <div key={i} className="work-tile"
                   style={{
                     gridColumn: `span ${w.col_span || 1}`,
                     gridRow:    `span ${w.row_span || 1}`,
                   }}>
                <div className="work-tile-inner">
                  {w.image_path
                    ? <img src={w.image_path} alt={w.title} style={{width:'100%',height:'100%',objectFit:'cover',display:'block'}}/>
                    : <WorkViz kind={w.viz_kind}/>}
                </div>
                <div className="work-outcome">{w.outcome}</div>
                <div className="work-label">
                  <div className="work-label-tag">{w.tag}</div>
                  <div className="work-label-title">{w.title}</div>
                </div>
              </div>
            ))}
          </div>
        </Reveal>
      </div>
    </section>
  );
}

function WorkViz({ kind }) {
  const common = { width: '100%', height: '100%', preserveAspectRatio: 'xMidYMid slice' };
  if (kind === 'flood') return (
    <svg viewBox="0 0 400 400" {...common}>
      <defs>
        <linearGradient id="fb" x1="0" y1="0" x2="1" y2="1">
          <stop offset="0" stopColor="#1a2c52"/><stop offset="1" stopColor="#0a1424"/>
        </linearGradient>
      </defs>
      <rect width="400" height="400" fill="url(#fb)"/>
      {[...Array(24)].map((_,i)=>(
        <path key={i} d={`M ${-20 + i*22} 0 Q ${-20 + i*22 + 30} 200 ${-20 + i*22} 400`} stroke="rgba(88,214,255,0.08)" fill="none"/>
      ))}
      <path d="M 80 120 Q 180 100 260 140 Q 320 180 300 240 Q 240 300 140 280 Q 60 240 80 120Z"
            fill="rgba(88,214,255,0.35)" stroke="#58d6ff" strokeWidth="1.2"/>
      <path d="M 150 160 Q 200 150 240 180 Q 260 210 220 230 Q 170 240 150 200Z"
            fill="rgba(255,107,74,0.4)" stroke="#ff6b4a" strokeWidth="1"/>
      <circle cx="220" cy="200" r="3" fill="#ff6b4a"/>
      <circle cx="220" cy="200" r="14" fill="none" stroke="#ff6b4a" opacity="0.5"/>
      <g fontFamily="JetBrains Mono" fontSize="9" fill="rgba(255,255,255,0.6)">
        <text x="16" y="24">FLOOD EXTENT · SAR Δ · 72H</text>
        <text x="16" y="390">22.4°N, 90.3°E → 23.1°N, 90.9°E</text>
      </g>
    </svg>
  );
  if (kind === 'glacier') return (
    <svg viewBox="0 0 400 200" {...common}>
      <rect width="400" height="200" fill="#0d1a30"/>
      {[0.9, 0.7, 0.5, 0.3].map((o,i)=>(
        <path key={i} d={`M 0 ${60+i*15} Q 100 ${40+i*10} 200 ${70+i*12} T 400 ${80+i*14} L 400 200 L 0 200 Z`}
              fill={`rgba(88,214,255,${0.08 + i*0.05})`}/>
      ))}
      <path d="M 0 100 Q 100 70 200 105 T 400 120" stroke="#58d6ff" strokeWidth="1.4" fill="none"/>
      <path d="M 0 130 Q 100 105 200 140 T 400 155" stroke="#7bc99d" strokeWidth="1" fill="none" strokeDasharray="3 3"/>
      <g fontFamily="JetBrains Mono" fontSize="9" fill="rgba(255,255,255,0.6)">
        <text x="16" y="24">GLACIER EXTENT · 2000 → 2025</text>
        <text x="300" y="190">Δ -14.2%</text>
      </g>
    </svg>
  );
  if (kind === 'crop') return (
    <svg viewBox="0 0 400 200" {...common}>
      <rect width="400" height="200" fill="#0a1424"/>
      {[...Array(8)].map((_,r)=>
        [...Array(16)].map((_,c)=>{
          const v = Math.random();
          const color = v > 0.7 ? '#2d6a4f' : v > 0.4 ? '#e8a948' : '#1a2c52';
          return <rect key={r+'_'+c} x={c*25} y={r*25} width="24" height="24" fill={color} opacity={0.55 + Math.random()*0.4}/>;
        })
      )}
      <g stroke="rgba(255,255,255,0.08)">
        {[...Array(17)].map((_,i)=><line key={i} x1={i*25} y1="0" x2={i*25} y2="200"/>)}
        {[...Array(9)].map((_,i)=><line key={i} x1="0" y1={i*25} x2="400" y2={i*25}/>)}
      </g>
      <g fontFamily="JetBrains Mono" fontSize="9" fill="rgba(255,255,255,0.75)">
        <text x="16" y="24">CROP-TYPE · PARCEL GRID</text>
      </g>
    </svg>
  );
  if (kind === 'corridor') return (
    <svg viewBox="0 0 200 200" {...common}>
      <rect width="200" height="200" fill="#0d1a30"/>
      <path d="M 20 180 L 180 20" stroke="#58d6ff" strokeWidth="1.2"/>
      <path d="M 20 180 L 180 20" stroke="rgba(88,214,255,0.2)" strokeWidth="20"/>
      {[...Array(6)].map((_,i)=>(
        <circle key={i} cx={30 + i*28} cy={170 - i*28} r="3" fill="#58d6ff"/>
      ))}
      <g fontFamily="JetBrains Mono" fontSize="8" fill="rgba(255,255,255,0.6)">
        <text x="10" y="20">CORRIDOR</text>
      </g>
    </svg>
  );
  if (kind === 'urban') return (
    <svg viewBox="0 0 400 200" {...common}>
      <rect width="400" height="200" fill="#0a1424"/>
      {[...Array(40)].map((_,i)=>{
        const x = Math.random()*390, y = Math.random()*190;
        const w = 6 + Math.random()*16, h = 6 + Math.random()*16;
        const age = Math.random();
        const fill = age > 0.7 ? 'rgba(255,107,74,0.5)' : age > 0.4 ? 'rgba(232,169,72,0.45)' : 'rgba(88,214,255,0.25)';
        return <rect key={i} x={x} y={y} width={w} height={h} fill={fill} stroke="rgba(255,255,255,0.08)" strokeWidth="0.5"/>;
      })}
      <g stroke="rgba(255,255,255,0.1)" strokeWidth="1">
        <line x1="0" y1="60" x2="400" y2="60"/>
        <line x1="0" y1="140" x2="400" y2="140"/>
        <line x1="130" y1="0" x2="130" y2="200"/>
        <line x1="280" y1="0" x2="280" y2="200"/>
      </g>
      <g fontFamily="JetBrains Mono" fontSize="9" fill="rgba(255,255,255,0.7)">
        <text x="16" y="24">SETTLEMENT GROWTH · 2018–2025</text>
      </g>
    </svg>
  );
  if (kind === 'biome') return (
    <svg viewBox="0 0 400 200" {...common}>
      <rect width="400" height="200" fill="#0d1a30"/>
      {[...Array(160)].map((_,i)=>{
        const x = Math.random()*400, y = Math.random()*200;
        const c = ['#2d6a4f','#40916c','#e8a948','#58d6ff'][Math.floor(Math.random()*4)];
        return <circle key={i} cx={x} cy={y} r={1 + Math.random()*2} fill={c} opacity="0.7"/>;
      })}
      <g fontFamily="JetBrains Mono" fontSize="9" fill="rgba(255,255,255,0.7)">
        <text x="16" y="24">CARBON MRV BASELINE</text>
        <text x="16" y="190">8.2 Mha · 12 biome classes</text>
      </g>
    </svg>
  );
  if (kind === 'change') return (
    <svg viewBox="0 0 400 200" {...common}>
      <rect width="400" height="200" fill="#0a1424"/>
      <g>
        <rect x="0" y="0" width="200" height="200" fill="url(#lg1)"/>
        <rect x="200" y="0" width="200" height="200" fill="url(#lg2)"/>
      </g>
      <defs>
        <linearGradient id="lg1" x1="0" y1="0" x2="1" y2="1">
          <stop offset="0" stopColor="#1a2c52"/><stop offset="1" stopColor="#0a1424"/>
        </linearGradient>
        <linearGradient id="lg2" x1="0" y1="0" x2="1" y2="1">
          <stop offset="0" stopColor="#2d6a4f"/><stop offset="1" stopColor="#0a1424"/>
        </linearGradient>
      </defs>
      <line x1="200" y1="0" x2="200" y2="200" stroke="#58d6ff" strokeDasharray="4 4"/>
      {[...Array(8)].map((_,i)=><circle key={i} cx={Math.random()*400} cy={Math.random()*200} r="4" fill="#ff6b4a" opacity="0.7"/>)}
      <g fontFamily="JetBrains Mono" fontSize="9" fill="rgba(255,255,255,0.7)">
        <text x="10" y="20">T-1</text>
        <text x="210" y="20">T-0 · Δ DETECTED</text>
      </g>
    </svg>
  );
  if (kind === 'water') return (
    <svg viewBox="0 0 400 200" {...common}>
      <rect width="400" height="200" fill="#0d1a30"/>
      <path d="M 0 120 Q 80 80 160 110 Q 240 140 320 100 Q 370 80 400 110 L 400 200 L 0 200 Z"
            fill="rgba(88,214,255,0.4)"/>
      <path d="M 0 120 Q 80 80 160 110 Q 240 140 320 100 Q 370 80 400 110"
            stroke="#58d6ff" fill="none" strokeWidth="1.2"/>
      <path d="M 0 150 Q 80 130 160 145 Q 240 160 320 140 Q 370 125 400 140"
            stroke="#7bc99d" fill="none" strokeWidth="1" strokeDasharray="3 3"/>
      <g fontFamily="JetBrains Mono" fontSize="9" fill="rgba(255,255,255,0.7)">
        <text x="16" y="24">RESERVOIR · DRY-SEASON CAPACITY</text>
        <text x="300" y="190">± 3.8%</text>
      </g>
    </svg>
  );
  return <div style={{background:'#1a2c52', width:'100%', height:'100%'}}/>;
}

/* ——— Why us ——— */
function WhyUs() {
  const content = getContent();
  const sec = content.why || {};
  const items = sec.items || [];
  return (
    <section id="why" className="section deep" style={{paddingTop: 100}}>
      <div className="container">
        <Reveal>
          <div className="section-head" style={{marginBottom: 50}}>
            <div>
              <span className="eyebrow">{sec.eyebrow}</span>
              <h2 className="h2" style={{marginTop:24}}>
                <RichText text={sec.heading}/>
              </h2>
            </div>
          </div>
        </Reveal>
        <div>
          {items.map((r,i) => (
            <Reveal key={r.num || i} delay={i*60}>
              <div className="why-row">
                <div className="why-num">{r.num}</div>
                <div className="why-title">{r.title}</div>
                <div className="why-desc">{r.description || r.desc}</div>
                <div className="why-tag">{r.tag}</div>
              </div>
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ——— Trust ——— */
function Trust() {
  const content = getContent();
  const sec = content.trust || {};
  const stats = sec.stats || [];
  const partners = sec.partners || [];
  const testimonials = sec.testimonials || [];
  return (
    <section id="trust" className="section deep" style={{paddingTop: 40}}>
      <div className="container">
        <Reveal>
          <div className="section-head">
            <div>
              <span className="eyebrow">{sec.eyebrow}</span>
              <h2 className="h2" style={{marginTop:24}}>
                <RichText text={sec.heading} newline={true}/>
              </h2>
            </div>
            <div>
              <p className="lead">{sec.lead}</p>
            </div>
          </div>
        </Reveal>

        <Reveal>
          <div className="trust-hero">
            {stats.map((s, i) => (
              <div key={i} className="trust-cell">
                <div className="trust-num"><Counter value={Number(s.value) || 0}/><span className="plus">{s.plus}</span></div>
                <div className="trust-label">{s.label}</div>
                <div className="trust-sub">{s.sub}</div>
              </div>
            ))}
          </div>
        </Reveal>

        <Reveal delay={100}>
          <div className="logo-strip">
            {partners.map((p,i) => (
              <div className="logo-cell" key={i}>
                {p.logo_image
                  ? <img src={p.logo_image} alt={p.name} style={{maxHeight:28, display:'block'}}/>
                  : p.name}
              </div>
            ))}
          </div>
        </Reveal>

        <Reveal delay={160}>
          <div style={{marginTop: 60, display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:40, paddingTop:40, borderTop:'1px solid var(--line-strong)'}} className="testimonial-grid">
            {testimonials.map((t,i)=>(
              <div key={i}>
                <div className="serif" style={{fontSize:22, lineHeight:1.35, marginBottom:24}}>
                  <span className="italic-accent" style={{fontStyle:'italic'}}>"</span>
                  <span dangerouslySetInnerHTML={{ __html: t.quote }}/>
                  <span className="italic-accent" style={{fontStyle:'italic'}}>"</span>
                </div>
                <div className="mono" style={{fontSize:11, color:'var(--slate-500)', letterSpacing:'0.08em', textTransform:'uppercase'}}>— {t.author || t.who}</div>
              </div>
            ))}
          </div>
        </Reveal>
      </div>
      <style>{`
        @media (max-width: 900px) { .testimonial-grid { grid-template-columns: 1fr !important; gap: 32px !important; } }
      `}</style>
    </section>
  );
}

/* ——— Contact ——— */
function Contact() {
  const content = getContent();
  const sec = content.contact || {};
  const info = sec.info || [];
  const status = sec.status || [];
  const options = sec.interest_options || [];
  const [sent, setSent] = useS(false);

  async function submit(e) {
    e.preventDefault();
    const form = e.currentTarget;
    const payload = {
      first_name: form.first_name.value,
      last_name:  form.last_name.value,
      email:      form.email.value,
      organization: form.organization.value,
      interest:   form.interest.value,
      brief:      form.brief.value,
    };
    try {
      await fetch('/api/messages', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });
    } catch (_) { /* still show thank-you; backend may not be running */ }
    setSent(true);
  }

  return (
    <section id="contact" className="section forest">
      <div style={{position:'absolute', inset:0, backgroundImage:`linear-gradient(rgba(88,214,255,0.04) 1px, transparent 1px), linear-gradient(90deg, rgba(88,214,255,0.04) 1px, transparent 1px)`, backgroundSize:'80px 80px', maskImage:'radial-gradient(ellipse 80% 70% at 50% 40%, black 30%, transparent 80%)'}}/>
      <div className="container" style={{position:'relative'}}>
        <Reveal>
          <div style={{maxWidth: 820, marginBottom: 60}}>
            <span className="eyebrow">{sec.eyebrow}</span>
            <h2 className="display" style={{marginTop:24, fontSize:'clamp(42px, 6vw, 88px)'}}>
              <RichText text={sec.heading}/>
            </h2>
          </div>
        </Reveal>

        <div className="cta-grid">
          <Reveal>
            <div className="cta-form">
              {sent ? (
                <div style={{minHeight: 420, display:'grid', placeItems:'center', textAlign:'center'}}>
                  <div>
                    <div style={{fontFamily:'var(--mono)', fontSize:11, color:'var(--forest-500)', letterSpacing:'0.15em', marginBottom:16}}>✓ TRANSMISSION RECEIVED</div>
                    <div className="serif" style={{fontSize:36, lineHeight:1.1, marginBottom:12}}>We'll be in touch<br/>within one business day.</div>
                    <div style={{color:'#555f6e', fontSize:14}}>A specialist will review your brief and schedule a briefing call.</div>
                  </div>
                </div>
              ) : (
                <form onSubmit={submit}>
                  <div className="mono" style={{fontSize:11, color:'var(--slate-600)', letterSpacing:'0.1em', marginBottom:4}}>{sec.form_label}</div>
                  <div style={{fontFamily:'var(--serif)', fontSize:30, lineHeight:1.1, marginBottom:36, letterSpacing:'-0.01em'}}>{sec.form_title}</div>

                  <div className="cta-row">
                    <div className="cta-field"><label>First Name</label><input name="first_name" required/></div>
                    <div className="cta-field"><label>Last Name</label><input name="last_name" required/></div>
                  </div>
                  <div className="cta-row">
                    <div className="cta-field"><label>Work Email</label><input name="email" type="email" required/></div>
                    <div className="cta-field"><label>Organization</label><input name="organization" required/></div>
                  </div>
                  <div className="cta-field">
                    <label>Interest</label>
                    <select name="interest">
                      {options.map((o,i) => <option key={i}>{o}</option>)}
                    </select>
                  </div>
                  <div className="cta-field">
                    <label>Brief</label>
                    <textarea name="brief" rows="3" placeholder="What's the decision you need to make?"></textarea>
                  </div>
                  <button type="submit" className="btn btn-ink" style={{width:'100%', justifyContent:'center', padding:'18px 22px', marginTop:12}}>
                    {sec.form_cta} <span className="arrow">→</span>
                  </button>
                </form>
              )}
            </div>
          </Reveal>

          <Reveal delay={120}>
            <div className="cta-info">
              <div className="mono" style={{fontSize:11, color:'var(--cyan)', letterSpacing:'0.15em', marginBottom: 24}}>
                <span className="status-dot" style={{display:'inline-block',verticalAlign:'middle',marginRight:8}}/>
                {sec.direct_line_label}
              </div>
              <div className="serif" style={{fontSize:28, lineHeight:1.15, marginBottom:28, letterSpacing:'-0.01em'}}>
                {sec.direct_line_title}
              </div>

              <div style={{display:'grid', gap:20, marginBottom: 40}}>
                {info.map((it,i) => <InfoLine key={i} label={it.label} v={it.value}/>)}
              </div>

              <div style={{marginTop:'auto', paddingTop:24, borderTop:'1px solid var(--line-strong)'}}>
                <div className="mono" style={{fontSize:10, color:'var(--slate-500)', letterSpacing:'0.1em', marginBottom:12}}>{sec.posture_label}</div>
                <div style={{display:'flex', gap:24}}>
                  {status.map((s,i) => <StatusBlock key={i} label={s.label} val={s.value}/>)}
                </div>
              </div>
            </div>
          </Reveal>
        </div>
      </div>
    </section>
  );
}

function InfoLine({ label, v }) {
  return (
    <div>
      <div className="mono" style={{fontSize:10, color:'var(--slate-500)', letterSpacing:'0.1em', marginBottom:4}}>{label}</div>
      <div style={{fontSize:16, fontFamily:'var(--sans)'}}>{v}</div>
    </div>
  );
}
function StatusBlock({ label, val }) {
  return (
    <div>
      <div style={{fontFamily:'var(--serif)', fontSize:24, lineHeight:1}}>{val}</div>
      <div className="mono" style={{fontSize:10, color:'var(--slate-500)', marginTop:4, letterSpacing:'0.08em'}}>{label}</div>
    </div>
  );
}

/* ——— Footer ——— */
function Footer() {
  const content = getContent();
  const f = content.footer || {};
  const site = content.site || {};
  const columns = f.columns || [];
  return (
    <footer>
      <div className="container">
        <div className="footer-grid">
          <div>
            <div className="nav-logo" style={{marginBottom:20}}>
              <div className="nav-logo-mark">
                {site.logo_image ? (
                  <img src={site.logo_image} alt="" width="28" height="28" style={{display:'block'}}/>
                ) : (
                  <svg width="28" height="28" viewBox="0 0 28 28" fill="none">
                    <circle cx="14" cy="14" r="11" stroke="currentColor" strokeWidth="1.2"/>
                    <ellipse cx="14" cy="14" rx="11" ry="5" stroke="currentColor" strokeWidth="1.2"/>
                    <ellipse cx="14" cy="14" rx="5" ry="11" stroke="currentColor" strokeWidth="1.2"/>
                    <circle cx="14" cy="14" r="1.6" fill="currentColor"/>
                  </svg>
                )}
              </div>
              <span>{site.brand_name || 'Ai GeoLAB'}</span>
            </div>
            <div className="serif" style={{fontSize:24, lineHeight:1.2, marginBottom:16}}>
              {f.tagline}
            </div>
            <div style={{fontSize:13, color:'var(--slate-500)'}}>
              {f.description}
            </div>
          </div>
          {columns.map((col, i) => (
            <div key={i} className="footer-col">
              <h4>{col.heading}</h4>
              <ul>
                {(col.links || []).map((l, j) => (
                  <li key={j}><a href={l.href}>{l.label}</a></li>
                ))}
              </ul>
            </div>
          ))}
        </div>
        <div className="footer-bottom">
          <div>{f.copyright}</div>
          <div>{f.coords}</div>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { Nav, WhoWeAre, Specializations, Industries, Work, WhyUs, Trust, Contact, Footer });
