// Content loader — fetches /api/content and exposes it via window.useContent().
// Fallback defaults mirror the original hardcoded values so the site renders
// identically if the API is unreachable (e.g. when opening index.html directly).

const { useState: useSC, useEffect: useEC, createContext: createCtxC, useContext: useCtxC } = React;

const FALLBACK = {
  site: {
    site_title: 'Ai GeoLAB — Intelligent Land. Smarter Maps. Better Decisions.',
    brand_name: 'Ai GeoLAB',
    tagline: 'Intelligent Land. Smarter Maps. Better Decisions.',
    logo_image: null, favicon: null, meta_description: '', og_image: null,
  },
  nav: {
    status_label: 'OPS · LIVE', show_status: 1,
    cta_label: 'Request Demo', cta_href: '#contact',
    items: [
      { label: 'Who We Are',  href: '#who' },
      { label: 'Capabilities', href: '#specialize' },
      { label: 'Industries',   href: '#industries' },
      { label: 'Field Work',   href: '#work' },
      { label: 'Trust',        href: '#trust' },
    ],
  },
  hero: {
    eyebrow: '— AI · GEOSPATIAL · 2026',
    title_line_1: 'Intelligent Land.',
    title_line_2: 'Smarter Maps.',
    title_line_3a: 'Better',
    title_line_3b: 'Decisions.',
    lead: 'Ai GeoLAB fuses AI, remote sensing, and spatial analysis into decision-grade intelligence — helping governments, operators and planners read the land with clarity, at continental scale.',
    primary_cta: 'Request a Demo', primary_href: '#contact',
    secondary_cta: 'Explore Solutions', secondary_href: '#specialize',
    meta_coord_n: 'N 23°48′36″', meta_coord_e: 'E 90°24′32″',
    meta_altitude: 'ALT 1,287km', meta_status: 'SYSTEMS NOMINAL',
    cards: [
      { slot: 'top-left', label: 'LAND COVER · NDVI', accent_color: '#7bc99d', value: '0.74', suffix: ' Δ+0.06', sub: 'Scene 2026-04-18 · Sentinel-2', card_type: 'sparkline' },
      { slot: 'top-right', label: 'LIVE SCENES', accent_color: '#58d6ff', value: '1248', sub: 'processing · 12 regions', card_type: 'counter' },
      { slot: 'bottom-left', label: 'AOI · 23.81°N, 90.41°E', accent_color: '#e8a948', card_type: 'grid',
        extra: { cells: [['PARCEL','4,217'], ['FLAGGED','38']] } },
      { slot: 'bottom-right', label: 'MODEL CONFIDENCE', accent_color: '#58d6ff', value: '98.2', suffix: '%', card_type: 'confidence', extra: { percent: 98.2 } },
    ],
  },
  wwa: {
    eyebrow: '— 01 · Who We Are',
    heading: "A specialist atelier for [[geospatial intelligence]], built for decision-makers who can't afford to guess.",
    lead: 'Ai GeoLAB unites remote-sensing scientists, machine-learning engineers, and GIS practitioners under a single mandate: turn raw Earth observation into decision-grade intelligence. We work alongside ministries, utilities, and planning bodies on problems that demand precision, auditability, and scale.',
    primary_cta: 'Book a Briefing', primary_href: '#contact',
    secondary_cta: 'What we do', secondary_href: '#specialize',
    topo_marker_tl: 'SURVEY AOI-7 · RAJSHAHI',
    topo_marker_br: 'NDVI Δ +0.18 · Q1 ’26',
    credentials: [
      { num: '01', title: 'Decision-grade by design', description: 'Every layer we deliver is versioned, validated and defensible — built to survive audit, inquiry, and public scrutiny.' },
      { num: '02', title: 'Multi-sensor, multi-source', description: 'Sentinel, Landsat, Planet, SAR, LiDAR, drone and cadastral feeds reconciled into a single spatial truth.' },
      { num: '03', title: 'Sovereign deployments', description: 'On-prem, air-gapped, or private cloud. Data sovereignty and national-security posture maintained end-to-end.' },
      { num: '04', title: 'Scientist-operated', description: 'Mixed teams of geographers, ML researchers and field operators. Not an off-the-shelf platform.' },
    ],
    stats: [
      { value: 4.2, decimals: 1, suffix: 'M km²', label: 'Area under monitoring', render: 'counter' },
      { value: 38,  decimals: 0, suffix: ' gov',  label: 'Agencies served', render: 'counter' },
      { value: 1.8, decimals: 1, suffix: 'PB',    label: 'Imagery processed / yr', render: 'counter' },
      { value: 6,   decimals: 0, suffix: '%',     label: 'Avg classifier accuracy', render: 'split-98' },
    ],
  },
  specialize: {
    eyebrow: '— 02 · What We Specialize In',
    heading: 'Seven disciplines. [[One operating picture.]]',
    lead: 'Every engagement composes from the same vocabulary — data pipelines, models, spatial analytics, and decision interfaces — tailored to the terrain of your mission.',
    custom_title: 'Custom Programs',
    custom_desc: "Need something that doesn't fit a card? That's most of our work.",
    custom_cta: 'START A BRIEF →',
    custom_href: '#contact',
    items: [
      { num: '01', title: 'Land Intelligence', icon: 'map', description: 'Cadastral reconciliation, tenure classification, and parcel-level change detection at national scale.' },
      { num: '02', title: 'GIS & Spatial Analysis', icon: 'layers', description: 'Multi-layer spatial modeling, network analysis, and scenario simulations for infrastructure planning.' },
      { num: '03', title: 'Remote Sensing', icon: 'satellite', description: 'Optical, SAR and hyperspectral pipelines — from ingestion and atmospheric correction to analysis-ready cubes.' },
      { num: '04', title: 'AI Mapping Automation', icon: 'brain', description: 'Semantic segmentation, foundation models for Earth observation, and self-supervised feature extraction.' },
      { num: '05', title: 'Environmental Monitoring', icon: 'leaf', description: 'Forest cover, water bodies, methane plumes, and climate-risk indicators refreshed on operational cadence.' },
      { num: '06', title: 'Infrastructure Insights', icon: 'route', description: 'Right-of-way analytics, corridor risk, encroachment detection, and predictive asset-condition models.' },
      { num: '07', title: 'Decision Dashboards', icon: 'chart', description: 'Purpose-built command surfaces tuned to the rhythm of ministries, utilities, and response cells.' },
    ],
  },
  industries: {
    eyebrow: '— 03 · Industries We Serve',
    heading: 'The same rigor, [[applied across terrains.]]',
    lead: "Each vertical brings its own vocabulary and its own stakes. We bring the same scientific discipline, tuned to what the mission requires.",
    items: [
      { key: 'gov', label: 'Government & Public Sector', icon: 'shield', title: 'Sovereign geospatial capacity.',
        description: 'Ministries and defense bodies operate on decision-grade land intelligence — from border monitoring and cadastral modernization to flood response and national land-use planning.',
        kpis: [['24h','Response cadence'],['11','Nat. programs'],['PB-scale','Archive']],
        bullets: ['Air-gapped deployments','Multi-classification handling','Agency-grade documentation','Interoperable with national SDIs'] },
      { key: 'agri', label: 'Agriculture', icon: 'tractor', title: 'From scene to silo.',
        description: 'Crop type mapping, yield forecasting, irrigation efficiency and drought risk for public programs, insurers, and private operators — delivered at parcel resolution.',
        kpis: [['96%','Crop-type F1'],['5m','Resolution'],['14d','Refresh']],
        bullets: ['Parcel-level yield forecasting','Drought & irrigation stress indices','Insurance-grade loss assessment','Field-validated models'] },
      { key: 'urban', label: 'Urban Planning', icon: 'city', title: 'Cities, read honestly.',
        description: 'Growth dynamics, informal settlement mapping, transit corridors and land-value modeling for metro authorities and strategic planners navigating real urbanization pressures.',
        kpis: [['23','Metro regions'],['2.1M','Parcels mapped'],['10cm','Orthomosaics']],
        bullets: ['Informal settlement analytics','Land-value surface modeling','Heat & green-cover audits','Transit-oriented scenario modeling'] },
      { key: 'dra', label: 'Disaster Risk Assessment', icon: 'alert', title: 'Forewarned is forearmed.',
        description: 'Pre-event exposure modeling, rapid post-event damage assessment, and multi-hazard risk layers for emergency operations centers and reinsurance workflows.',
        kpis: [['<6h','Damage assess.'],['7','Hazard layers'],['99.1%','Uptime']],
        bullets: ['Pre-event exposure inventories','SAR-based flood extraction','Building damage classification','OGC-compliant delivery'] },
      { key: 'env', label: 'Environment & Climate', icon: 'wind', title: 'Evidence for the stewards.',
        description: 'Forest integrity, carbon stock estimation, methane plume detection, wetland change, and water resource monitoring at the scale climate policy demands.',
        kpis: [['12','Biomes tracked'],['10m','Forest res.'],['Daily','Methane scans']],
        bullets: ['MRV-ready carbon baselines','Methane plume attribution','Deforestation alerting','Wetland & water body dynamics'] },
      { key: 'infra', label: 'Infrastructure & Utilities', icon: 'bolt', title: 'Corridors that hold.',
        description: 'Transmission, pipeline and rail corridors monitored for vegetation encroachment, subsidence, right-of-way integrity, and predictive asset-condition signals.',
        kpis: [['38k km','Corridors'],['Weekly','Refresh'],['4x','Incident reduction']],
        bullets: ['Vegetation encroachment index','InSAR subsidence monitoring','Right-of-way integrity','Asset condition scoring'] },
    ],
  },
  work: {
    eyebrow: '— 04 · Work in the Field',
    heading: 'Evidence, [[not adjectives.]]',
    lead: "A selection of live and completed engagements. Most of what we do can't be shown — these are the ones we can.",
    cta_label: 'Request full briefing pack', cta_href: '#contact',
    items: [
      { col_span: 3, row_span: 2, tag: 'DISASTER · SE ASIA', title: '2025 monsoon flood — 72-hour damage atlas', outcome: '1.2M parcels · 6h turnaround', viz_kind: 'flood' },
      { col_span: 3, row_span: 1, tag: 'ENV · ANDES',        title: 'Andean glacier retreat longitudinal study', outcome: 'Δ-14.2% · 2000-25', viz_kind: 'glacier' },
      { col_span: 2, row_span: 1, tag: 'AGRI · PUNJAB',      title: 'Wheat-rice rotation classifier', outcome: '96% F1', viz_kind: 'crop' },
      { col_span: 1, row_span: 1, tag: 'INFRA',              title: 'Transmission corridor', outcome: '38k km', viz_kind: 'corridor' },
      { col_span: 3, row_span: 1, tag: 'URBAN · DHAKA',      title: 'Informal settlement growth index, 2018–2025', outcome: '+312 ha/yr', viz_kind: 'urban' },
      { col_span: 2, row_span: 1, tag: 'CARBON',             title: 'MRV baseline — 8.2 Mha biome atlas', outcome: 'Audit-ready', viz_kind: 'biome' },
      { col_span: 2, row_span: 1, tag: 'DEFENSE',            title: 'Automated change detection pipeline', outcome: '99.1% uptime', viz_kind: 'change' },
      { col_span: 2, row_span: 1, tag: 'WATER',              title: 'Reservoir capacity — dry-season forecast', outcome: '± 3.8%', viz_kind: 'water' },
    ],
  },
  why: {
    eyebrow: '— 05 · Why Ai GeoLAB',
    heading: 'Five reasons [[the serious work lands here.]]',
    items: [
      { num: '01', title: 'AI fused with deep geospatial craft', description: 'Foundation models for Earth observation delivered by teams who built the GIS methodology underneath — not ML researchers who discovered maps last year.', tag: 'APPROACH' },
      { num: '02', title: 'Precision at continental scale', description: 'Petabyte-class pipelines that preserve parcel-level accuracy from ingestion through inference, validated against independent ground truth.', tag: 'SCALE' },
      { num: '03', title: 'Decision-grade, not dashboard-grade', description: 'Every layer we deliver is versioned, auditable, and built to survive the scrutiny of ministry reviews, litigation, and public oversight.', tag: 'OUTPUTS' },
      { num: '04', title: 'Custom workflows — not a platform', description: 'We build instruments for specific missions. No forced onboarding to a generic SaaS. No fit-the-problem-to-the-tool gymnastics.', tag: 'FIT' },
      { num: '05', title: 'Long-horizon partnership', description: 'Most of our engagements exceed five years. We operate with your team as an embedded capability, not a vendor behind a ticketing portal.', tag: 'MODEL' },
    ],
  },
  trust: {
    eyebrow: '— 06 · Trusted By',
    heading: 'Trusted by governments.\n[[Built for the future.]]',
    lead: 'Our work underwrites national monitoring programs, climate accounting, and long-horizon infrastructure decisions across four continents.',
    stats: [
      { value: 93, plus: '+',  label: 'Active Engagements', sub: 'Across ministries, utilities, multilaterals & research consortia.' },
      { value: 7,  plus: 'y',  label: 'Avg. Partnership',    sub: 'Long-horizon collaboration is our operating default.' },
      { value: 38, plus: '',   label: 'Government Agencies', sub: 'Including sovereign & defense-sensitive deployments.' },
      { value: 15, plus: 'PB', label: 'Imagery Under Management', sub: 'Optical, SAR, hyperspectral, LiDAR — continuously refreshed.' },
    ],
    partners: [
      { name: 'Min. of Land' }, { name: 'Geodesy Board' }, { name: 'PowerCorp' },
      { name: 'WaterGrid' }, { name: 'ClimateFund' }, { name: 'National Survey' },
    ],
    testimonials: [
      { quote: 'The only team that could deliver parcel-level damage assessment inside our 72-hour window. We now plan around their cadence.', author: 'Director, National Disaster Response Cell' },
      { quote: 'Not a platform vendor. They embed with our analysts and ship models we can defend in parliament.', author: 'Deputy Secretary, Ministry of Land' },
      { quote: 'The carbon baseline Ai GeoLAB produced became our reporting ground truth, full stop.', author: 'Head of MRV, National Climate Fund' },
    ],
  },
  contact: {
    eyebrow: "— 07 · Let's Work Together",
    heading: "Let's build the future of [[land intelligence.]]",
    form_label: 'FORM · 01',
    form_title: 'Request a briefing.',
    form_cta: 'Send Briefing Request',
    direct_line_label: 'DIRECT LINE',
    direct_line_title: 'For time-sensitive missions, reach us directly.',
    interest_options: ['Government & Public Sector','Agriculture & Food Security','Urban & Regional Planning','Disaster Risk & Response','Environment, Carbon & Climate','Infrastructure & Utilities','Other'],
    posture_label: 'CURRENT POSTURE',
    info: [
      { label: 'SECURE CHANNEL', value: 'ops@aigeolab.io' },
      { label: 'OPERATIONS DESK', value: '+880 2 9104 7288' },
      { label: 'HQ', value: 'House 47 · Dhaka 1212 · Bangladesh' },
      { label: 'REGIONAL', value: 'Singapore · Nairobi · London' },
    ],
    status: [
      { label: 'Response', value: '<24h' },
      { label: 'Uptime', value: '99.9%' },
      { label: 'Scenes/day', value: '284' },
    ],
  },
  footer: {
    tagline: 'Intelligent Land. Smarter Maps. Better Decisions.',
    description: 'A geospatial intelligence atelier serving governments and long-horizon operators across four continents.',
    copyright: '© 2026 Ai GeoLAB · All rights reserved',
    coords: '23.810°N · 90.412°E · GMT+6',
    columns: [
      { heading: 'Capabilities', links: [
        { label: 'Land Intelligence', href: '#' }, { label: 'GIS & Analysis', href: '#' },
        { label: 'Remote Sensing', href: '#' }, { label: 'AI Automation', href: '#' },
        { label: 'Env. Monitoring', href: '#' },
      ]},
      { heading: 'Company', links: [
        { label: 'About', href: '#' }, { label: 'Careers', href: '#' },
        { label: 'Field Work', href: '#' }, { label: 'Press', href: '#' },
        { label: 'Contact', href: '#' },
      ]},
      { heading: 'Policy', links: [
        { label: 'Privacy', href: '#' }, { label: 'Data Posture', href: '#' },
        { label: 'Security', href: '#' }, { label: 'Responsible AI', href: '#' },
      ]},
    ],
  },
};

const ContentContext = createCtxC(FALLBACK);

function ContentProvider({ children }) {
  const [content, setContent] = useSC(FALLBACK);
  useEC(() => {
    let aborted = false;
    fetch('/api/content', { cache: 'no-cache' })
      .then(r => r.ok ? r.json() : null)
      .then(data => {
        if (aborted || !data) return;
        // Merge fetched data onto FALLBACK so any partial response still renders the rest.
        setContent(prev => ({ ...prev, ...data }));
        // Update <title> from DB if different.
        if (data.site && data.site.site_title) document.title = data.site.site_title;
        if (data.site && data.site.favicon) {
          let link = document.querySelector("link[rel~='icon']");
          if (!link) { link = document.createElement('link'); link.rel = 'icon'; document.head.appendChild(link); }
          link.href = data.site.favicon;
        }
      })
      .catch(() => { /* offline or direct file open — keep fallback */ });
    return () => { aborted = true; };
  }, []);
  return React.createElement(ContentContext.Provider, { value: content }, children);
}

function useContent() { return useCtxC(ContentContext); }

window.ContentProvider = ContentProvider;
window.useContent = useContent;
window.CONTENT_FALLBACK = FALLBACK;
