// Panels: left (layers), right (inspector), and inline UI atoms
const { useState: useStateP } = React;

// Small icon set (line SVGs)
function I({ name, size = 16 }) {
  const s = { width: size, height: size };
  const common = { fill: 'none', stroke: 'currentColor', strokeWidth: 1.6, strokeLinecap: 'round', strokeLinejoin: 'round' };
  switch(name) {
    case 'select':   return <svg style={s} viewBox="0 0 24 24" {...common}><path d="M4 3l7 17 2-7 7-2z"/></svg>;
    case 'pan':      return <svg style={s} viewBox="0 0 24 24" {...common}><path d="M9 11V6a2 2 0 114 0v4"/><path d="M13 8a2 2 0 114 0v4"/><path d="M17 10a2 2 0 114 0v4a7 7 0 01-7 7h-2a6 6 0 01-4.4-1.9L4 15a2 2 0 012.8-2.8l1.2 1.2V6a2 2 0 114 0v5"/></svg>;
    case 'measure':  return <svg style={s} viewBox="0 0 24 24" {...common}><path d="M3 12L12 3l9 9-9 9z"/><path d="M7 8v2M9 10v2M11 12v2M13 14v2M15 16v2"/></svg>;
    case 'draw':     return <svg style={s} viewBox="0 0 24 24" {...common}><path d="M12 20h9"/><path d="M16.5 3.5a2.1 2.1 0 013 3L7 19l-4 1 1-4z"/></svg>;
    case 'polygon':  return <svg style={s} viewBox="0 0 24 24" {...common}><polygon points="12 3 21 9 18 20 6 20 3 9"/></svg>;
    case 'edit':     return <svg style={s} viewBox="0 0 24 24" {...common}><rect x="4" y="4" width="6" height="6"/><rect x="14" y="4" width="6" height="6"/><rect x="4" y="14" width="6" height="6"/><rect x="14" y="14" width="6" height="6"/></svg>;
    case 'query':    return <svg style={s} viewBox="0 0 24 24" {...common}><circle cx="11" cy="11" r="7"/><path d="M21 21l-4-4"/></svg>;
    case 'buffer':   return <svg style={s} viewBox="0 0 24 24" {...common}><circle cx="12" cy="12" r="9"/><circle cx="12" cy="12" r="5"/><circle cx="12" cy="12" r="1.5" fill="currentColor"/></svg>;
    case 'ai':       return <svg style={s} viewBox="0 0 24 24" {...common}><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M9 3v18M15 3v18M3 9h18M3 15h18"/></svg>;
    case '3d':       return <svg style={s} viewBox="0 0 24 24" {...common}><path d="M12 2l10 5v10l-10 5L2 17V7z"/><path d="M12 12L2 7M12 12l10-5M12 12v10"/></svg>;
    case 'layer':    return <svg style={s} viewBox="0 0 24 24" {...common}><polygon points="12 2 22 8 12 14 2 8"/><polyline points="2 16 12 22 22 16"/></svg>;
    case 'route':    return <svg style={s} viewBox="0 0 24 24" {...common}><circle cx="6" cy="19" r="2"/><circle cx="18" cy="5" r="2"/><path d="M6 17V9a4 4 0 014-4h4a4 4 0 014 4"/></svg>;
    case 'sat':      return <svg style={s} viewBox="0 0 24 24" {...common}><path d="M5 5l3 3M14 14l4 4"/><path d="M12 2l3 3-2 2-3-3zM17 7l5 5-2 2-5-5zM7 17l5 5-2 2-5-5zM2 12l5 5-2 2-5-5z"/></svg>;
    case 'drone':    return <svg style={s} viewBox="0 0 24 24" {...common}><circle cx="5" cy="5" r="2"/><circle cx="19" cy="5" r="2"/><circle cx="5" cy="19" r="2"/><circle cx="19" cy="19" r="2"/><rect x="9" y="9" width="6" height="6"/><path d="M7 7l2 2M17 7l-2 2M7 17l2-2M17 17l-2-2"/></svg>;
    case 'download': return <svg style={s} viewBox="0 0 24 24" {...common}><path d="M12 3v14M6 11l6 6 6-6M3 21h18"/></svg>;
    case 'upload':   return <svg style={s} viewBox="0 0 24 24" {...common}><path d="M12 21V7M6 13l6-6 6 6M3 3h18"/></svg>;
    case 'chart':    return <svg style={s} viewBox="0 0 24 24" {...common}><path d="M3 3v18h18"/><path d="M7 14l4-4 4 3 5-6"/></svg>;
    case 'save':     return <svg style={s} viewBox="0 0 24 24" {...common}><path d="M19 21H5a2 2 0 01-2-2V5a2 2 0 012-2h11l5 5v11a2 2 0 01-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/></svg>;
    case 'print':    return <svg style={s} viewBox="0 0 24 24" {...common}><path d="M6 9V2h12v7"/><rect x="2" y="9" width="20" height="9" rx="2"/><rect x="6" y="14" width="12" height="8"/></svg>;
    case 'settings': return <svg style={s} viewBox="0 0 24 24" {...common}><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 00.33 1.82l.06.06a2 2 0 11-2.83 2.83l-.06-.06a1.65 1.65 0 00-1.82-.33 1.65 1.65 0 00-1 1.51V21a2 2 0 11-4 0v-.09A1.65 1.65 0 009 19.4a1.65 1.65 0 00-1.82.33l-.06.06a2 2 0 11-2.83-2.83l.06-.06a1.65 1.65 0 00.33-1.82 1.65 1.65 0 00-1.51-1H3a2 2 0 110-4h.09A1.65 1.65 0 004.6 9a1.65 1.65 0 00-.33-1.82l-.06-.06a2 2 0 112.83-2.83l.06.06a1.65 1.65 0 001.82.33H9a1.65 1.65 0 001-1.51V3a2 2 0 114 0v.09a1.65 1.65 0 001 1.51 1.65 1.65 0 001.82-.33l.06-.06a2 2 0 112.83 2.83l-.06.06a1.65 1.65 0 00-.33 1.82V9a1.65 1.65 0 001.51 1H21a2 2 0 110 4h-.09a1.65 1.65 0 00-1.51 1z"/></svg>;
    case 'compass':  return <svg style={s} viewBox="0 0 24 24" {...common}><circle cx="12" cy="12" r="10"/><polygon points="16.24 7.76 14.12 14.12 7.76 16.24 9.88 9.88 16.24 7.76"/></svg>;
    case 'grid':     return <svg style={s} viewBox="0 0 24 24" {...common}><rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/></svg>;
    default: return null;
  }
}

// ---------- Ribbon ----------
function Ribbon({ activeTool, setActiveTool }) {
  const groups = [
    {
      label: 'File',
      tools: [
        { id: 'open',   icon: 'upload',   label: 'Open' },
        { id: 'save',   icon: 'save',     label: 'Save' },
        { id: 'export', icon: 'download', label: 'Export' },
        { id: 'print',  icon: 'print',    label: 'Print' },
      ]
    },
    {
      label: 'Navigate',
      tools: [
        { id: 'select', icon: 'select',  label: 'Select' },
        { id: 'pan',    icon: 'pan',     label: 'Pan' },
        { id: 'zoom',   icon: 'query',   label: 'Zoom' },
        { id: 'measure',icon: 'measure', label: 'Measure' },
      ]
    },
    {
      label: 'Edit',
      tools: [
        { id: 'draw',   icon: 'draw',    label: 'Draw' },
        { id: 'polygon',icon: 'polygon', label: 'Polygon' },
        { id: 'vertex', icon: 'edit',    label: 'Vertex' },
      ]
    },
    {
      label: 'Analyze',
      tools: [
        { id: 'buffer',   icon: 'buffer',    label: 'Buffer' },
        { id: 'overlay',  icon: 'layer',     label: 'Overlay' },
        { id: 'route',    icon: 'route',     label: 'Route' },
        { id: 'chart',    icon: 'chart',     label: 'Charts' },
      ]
    },
    {
      label: 'AI / Remote Sensing',
      tools: [
        { id: 'aidet',  icon: 'ai',    label: 'Detect' },
        { id: 'segm',   icon: 'grid',  label: 'Segment' },
        { id: 'sat',    icon: 'sat',   label: 'Imagery' },
        { id: 'drone',  icon: 'drone', label: 'Drone' },
      ]
    },
    {
      label: '3D & Twin',
      tools: [
        { id: '3d',    icon: '3d',      label: '3D View' },
        { id: 'globe', icon: 'compass', label: 'Globe' },
      ]
    },
    {
      label: 'System',
      tools: [
        { id: 'settings', icon: 'settings', label: 'Settings' },
      ]
    },
  ];
  return (
    <div className="ribbon">
      {groups.map(g => (
        <div className="rgroup" key={g.label}>
          <div className="rgroup-tools">
            {g.tools.map(t => (
              <button key={t.id}
                className={`rtool ${activeTool === t.id ? 'active' : ''}`}
                onClick={() => setActiveTool(t.id)}
                title={t.label}
              >
                <div className="ri"><I name={t.icon} size={18}/></div>
                <div className="rl">{t.label}</div>
              </button>
            ))}
          </div>
          <div className="rgroup-label">{g.label}</div>
        </div>
      ))}
    </div>
  );
}

// ---------- Left Panel — Layers ----------
function LayersPanel({ layers, setLayers }) {
  const [tab, setTab] = useStateP('layers');
  const toggle = (id) => setLayers(prev => ({ ...prev, [id]: { ...prev[id], on: !prev[id].on }}));

  const groups = [
    {
      label: 'AI / Analysis',
      layers: [
        { id: 'ai',       name: 'AI Detections',  swatch: '#d97706', count: 8, hatch: true },
        { id: 'buffer',   name: 'Buffer 5/10/15km', swatch: '#e8a33d', count: 3 },
        { id: 'routes',   name: 'Optimized Routes',  swatch: '#d97706', count: 2 },
        { id: 'heatmap',  name: 'Population Heatmap', swatch: '#c94a3a', count: '—' },
      ]
    },
    {
      label: 'Vector',
      layers: [
        { id: 'assets',    name: 'Utility Assets',     swatch: '#2f7d4f', count: 7 },
        { id: 'cities',    name: 'Cities & Towns',     swatch: '#0a1a35', count: 20 },
        { id: 'labels',    name: 'Place Labels',       swatch: 'transparent', count: '—' },
        { id: 'roads',     name: 'National Highways',  swatch: '#c94a3a', count: 15 },
        { id: 'rivers',    name: 'Rivers & Streams',   swatch: '#4a90c8', count: 8 },
      ]
    },
    {
      label: 'Boundaries',
      layers: [
        { id: 'districts', name: 'District Boundaries', swatch: '#7a8a68', count: 776 },
        { id: 'states',    name: 'State Boundaries',    swatch: '#3d5978', count: 36 },
      ]
    },
    {
      label: 'Reference',
      layers: [
        { id: 'graticule', name: 'Lat/Lon Graticule',   swatch: '#a8b8c8', count: '—' },
      ]
    }
  ];

  return (
    <div className="panel left">
      <div className="panel-tabs">
        <button className={`panel-tab ${tab==='layers'?'active':''}`} onClick={() => setTab('layers')}>Layers</button>
        <button className={`panel-tab ${tab==='data'?'active':''}`} onClick={() => setTab('data')}>Data</button>
        <button className={`panel-tab ${tab==='book'?'active':''}`} onClick={() => setTab('book')}>Bookmarks</button>
      </div>

      {tab === 'layers' && (
        <>
          <div className="panel-section">
            <div className="panel-section-title">
              <span>Project</span>
              <span className="mono" style={{color:'var(--amber-500)'}}>SAVED</span>
            </div>
            <div style={{padding:'2px 0 4px', fontSize: 13, fontWeight: 500}}>Karnataka LIS Master</div>
            <div style={{fontSize: 10, color:'var(--ink-500)', fontFamily:'var(--font-mono)'}}>KA-LIS-2026-Q2.bcgp • v3.4.1</div>
          </div>

          {groups.map(g => (
            <div className="panel-section" key={g.label}>
              <div className="panel-section-title">
                <span>{g.label}</span>
                <span style={{color:'var(--ink-400)', fontSize: 9}}>{g.layers.length} layers</span>
              </div>
              {g.layers.map(l => (
                <div key={l.id} className="layer-node" onClick={() => toggle(l.id)}>
                  <div className={`layer-vis ${layers[l.id]?.on ? 'on' : ''}`}></div>
                  <div className="layer-swatch" style={{
                    background: l.hatch
                      ? 'repeating-linear-gradient(45deg, #d97706 0 2px, transparent 2px 4px)'
                      : l.swatch,
                    borderColor: l.swatch === 'transparent' ? 'var(--ink-400)' : undefined
                  }}></div>
                  <div className="layer-name">{l.name}</div>
                  <div className="layer-count">{l.count}</div>
                </div>
              ))}
            </div>
          ))}
        </>
      )}

      {tab === 'data' && (
        <div className="panel-section">
          <div className="panel-section-title"><span>Connected Sources</span></div>
          {[
            { name: 'PostGIS · ka_lis_prod', kind: 'PostgreSQL 16 · PostGIS 3.4', st: 'ok', ct: 24 },
            { name: 'GeoServer · WMS/WFS',   kind: 'geoserver.bhoochitra.gov.in', st: 'ok', ct: 42 },
            { name: 'S3 · sentinel-imagery', kind: 'GeoTIFF · 4.2 TB',            st: 'ok', ct: 1204 },
            { name: 'Oracle Spatial · legacy',kind: 'Read-only replication',       st: 'warn', ct: 8 },
            { name: 'ISRO Bhuvan · WMTS',    kind: 'External tile service',        st: 'ok', ct: '—' },
          ].map((d, i) => (
            <div key={i} style={{ padding: '8px 0', borderBottom: '1px solid var(--paper-200)' }}>
              <div style={{ display:'flex', alignItems:'center', gap: 6 }}>
                <span className={`chip ${d.st}`} style={{padding:'0 6px', fontSize:9}}>{d.st.toUpperCase()}</span>
                <div style={{ fontSize: 12, fontWeight: 500 }}>{d.name}</div>
                <div style={{ marginLeft:'auto', fontFamily:'var(--font-mono)', color:'var(--ink-400)', fontSize:10 }}>{d.ct}</div>
              </div>
              <div style={{ fontSize: 10, color:'var(--ink-500)', marginTop: 2, fontFamily:'var(--font-mono)' }}>{d.kind}</div>
            </div>
          ))}
        </div>
      )}

      {tab === 'book' && (
        <div className="panel-section">
          <div className="panel-section-title"><span>Saved Views</span></div>
          {[
            { name: 'National Overview',       s: '1:12,000,000', by: 'default' },
            { name: 'NCR — Encroachment Scan', s: '1:80,000',     by: 'ai.workflow' },
            { name: 'Krishna Basin',           s: '1:1,200,000',  by: 'hydro.team' },
            { name: 'Mumbai Metro Utilities',  s: '1:20,000',     by: 'utility.mh' },
            { name: 'NE Forest Cover',         s: '1:800,000',    by: 'forest.dept' },
          ].map((b,i) => (
            <div key={i} style={{ padding: '8px 0', borderBottom: '1px solid var(--paper-200)', display:'flex', alignItems:'center', gap: 8 }}>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 12, fontWeight: 500 }}>{b.name}</div>
                <div style={{ fontSize: 10, color:'var(--ink-500)', fontFamily:'var(--font-mono)' }}>{b.s} · @{b.by}</div>
              </div>
              <div className="chip" style={{padding:'0 6px', fontSize:9}}>OPEN</div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

// ---------- Right Panel — Inspector ----------
function InspectorPanel({ selected, activeTool }) {
  const [tab, setTab] = useStateP('attr');

  const renderAttributes = () => {
    if (!selected) {
      return (
        <div style={{ padding: '48px 20px', textAlign: 'center', color: 'var(--ink-500)' }}>
          <div style={{ opacity: 0.4, marginBottom: 12 }}><I name="select" size={28}/></div>
          <div style={{ fontSize: 12, fontWeight: 500, color: 'var(--ink-700)' }}>No feature selected</div>
          <div style={{ fontSize: 11, marginTop: 6, lineHeight: 1.5 }}>Use the Select tool on the map — click a city, asset, AI detection, or state to inspect its attributes.</div>
        </div>
      );
    }

    if (selected.kind === 'city') {
      const c = selected.data;
      return (
        <>
          <div className="attr-header">
            <div className="kind">Populated Place · Tier {c.tier === 'metro' ? '01' : '02'}</div>
            <div className="name">{c.name}</div>
            <div className="id">FID · {c.id.toUpperCase()}-1832 · CRS EPSG:4326</div>
          </div>
          <div className="attr-table">
            {[
              ['Population',        c.pop],
              ['State',             c.state],
              ['Category',          c.tier === 'metro' ? 'Metropolitan' : 'Tier-I City'],
              ['Class',             'Municipal Corporation'],
              ['Latitude',          approxLatLon(c).lat.toFixed(5) + '° N'],
              ['Longitude',         approxLatLon(c).lon.toFixed(5) + '° E'],
              ['Elevation (SRTM)',  Math.round(60 + Math.random()*300) + ' m'],
              ['Land Area',         (300 + Math.random()*900).toFixed(1) + ' km²'],
              ['Last Updated',      '2026-06-12'],
              ['Source',            'Census + ULB verified'],
            ].map(([k,v]) => (
              <div className="attr-row" key={k}>
                <div className="k">{k}</div>
                <div className={"v " + (typeof v === 'string' && v.match(/[°]/) ? 'mono' : '')}>{v}</div>
              </div>
            ))}
            <div className="attr-row">
              <div className="k">Tags</div>
              <div className="v" style={{ display:'flex', flexWrap:'wrap', gap: 4 }}>
                <span className="chip navy">SMART_CITY</span>
                <span className="chip">ULB</span>
                <span className="chip amber">AMRUT</span>
              </div>
            </div>
          </div>
        </>
      );
    }

    if (selected.kind === 'ai') {
      const d = selected.data;
      const sev = d.conf > 0.9 ? 'HIGH' : d.conf > 0.85 ? 'MED' : 'LOW';
      return (
        <>
          <div className="attr-header">
            <div className="kind">AI Detection · GeoAI v2.7</div>
            <div className="name">{d.kind}</div>
            <div className="id">DET-{d.id.toUpperCase()}-{Math.floor(Math.random()*9999).toString().padStart(4,'0')}</div>
          </div>
          <div className="attr-table">
            <div className="attr-row"><div className="k">Confidence</div><div className="v mono">{(d.conf*100).toFixed(1)}%</div></div>
            <div className="attr-row"><div className="k">Severity</div><div className="v"><span className={`chip ${sev==='HIGH'?'err':sev==='MED'?'warn':'ok'}`}>{sev}</span></div></div>
            <div className="attr-row"><div className="k">Area</div><div className="v mono">{d.area}</div></div>
            <div className="attr-row"><div className="k">Model</div><div className="v mono">YOLOv8 · fine-tuned</div></div>
            <div className="attr-row"><div className="k">Source Imagery</div><div className="v mono">Sentinel-2 · 2026-07-11</div></div>
            <div className="attr-row"><div className="k">Ground Truth</div><div className="v">Pending field verification</div></div>
            <div className="attr-row"><div className="k">Assigned</div><div className="v">field.officer.mh_2</div></div>
            <div className="attr-row"><div className="k">Status</div><div className="v"><span className="chip warn">OPEN</span></div></div>
            <div className="attr-row"><div className="k">Detection Bounds</div><div className="v mono">{d.x-d.w/2},{d.y-d.h/2} → {d.x+d.w/2},{d.y+d.h/2}</div></div>
          </div>
          <div style={{ padding: 12, borderTop: '1px solid var(--paper-200)', display: 'flex', gap: 6 }}>
            <button className="chip amber" style={{padding:'4px 10px'}}>Verify in Field</button>
            <button className="chip navy" style={{padding:'4px 10px'}}>Export GeoJSON</button>
          </div>
        </>
      );
    }

    if (selected.kind === 'asset') {
      const a = selected.data;
      return (
        <>
          <div className="attr-header">
            <div className="kind">Utility Asset</div>
            <div className="name">{a.kind}</div>
            <div className="id">AST-{a.id.toUpperCase()}-91024</div>
          </div>
          <div className="attr-table">
            <div className="attr-row"><div className="k">Status</div><div className="v"><span className={`chip ${a.status}`}>{a.status.toUpperCase()}</span></div></div>
            <div className="attr-row"><div className="k">Owner</div><div className="v">Municipal Corp.</div></div>
            <div className="attr-row"><div className="k">Installed</div><div className="v mono">2019-03-14</div></div>
            <div className="attr-row"><div className="k">Last Inspection</div><div className="v mono">2026-05-22</div></div>
            <div className="attr-row"><div className="k">SLA Uptime</div><div className="v mono">99.94%</div></div>
            <div className="attr-row"><div className="k">Telemetry</div><div className="v"><span className="chip ok">LIVE via SCADA</span></div></div>
            <div className="attr-row"><div className="k">Load</div><div className="v mono">72% / rated</div></div>
            <div className="attr-row"><div className="k">Next Service</div><div className="v mono">2026-09-01</div></div>
          </div>
        </>
      );
    }

    if (selected.kind === 'state') {
      return (
        <>
          <div className="attr-header">
            <div className="kind">Administrative · Level 1</div>
            <div className="name">{selected.name}</div>
            <div className="id">STATE-{selected.id.toUpperCase()} · IN-{selected.id.toUpperCase()}</div>
          </div>
          <div className="attr-table">
            <div className="attr-row"><div className="k">Feature Type</div><div className="v">State / UT Polygon</div></div>
            <div className="attr-row"><div className="k">Source</div><div className="v">Survey of India</div></div>
            <div className="attr-row"><div className="k">Vertices</div><div className="v mono">{Math.floor(2000 + Math.random()*8000)}</div></div>
            <div className="attr-row"><div className="k">Topology</div><div className="v"><span className="chip ok">VALID</span></div></div>
            <div className="attr-row"><div className="k">CRS</div><div className="v mono">EPSG:4326 (WGS84)</div></div>
            <div className="attr-row"><div className="k">Last Edit</div><div className="v mono">2026-04-18 14:22</div></div>
          </div>
        </>
      );
    }
    return null;
  };

  return (
    <div className="panel right">
      <div className="panel-tabs">
        <button className={`panel-tab ${tab==='attr'?'active':''}`} onClick={() => setTab('attr')}>Attributes</button>
        <button className={`panel-tab ${tab==='ana'?'active':''}`} onClick={() => setTab('ana')}>Analytics</button>
        <button className={`panel-tab ${tab==='ai'?'active':''}`} onClick={() => setTab('ai')}>AI</button>
      </div>

      {tab === 'attr' && renderAttributes()}

      {tab === 'ana' && (
        <>
          <div className="analytics-grid">
            <div className="stat-tile">
              <div className="stat-label">Features Visible</div>
              <div className="stat-value">1,284,441</div>
              <div className="stat-delta" style={{color:'var(--ok)'}}>+18,240 this week</div>
            </div>
            <div className="stat-tile">
              <div className="stat-label">Selected</div>
              <div className="stat-value">{selected ? '1' : '0'}</div>
              <div className="stat-delta" style={{color:'var(--ink-500)'}}>—</div>
            </div>
            <div className="stat-tile">
              <div className="stat-label">Layer Count</div>
              <div className="stat-value">14</div>
              <div className="stat-delta" style={{color:'var(--ink-500)'}}>4 groups</div>
            </div>
            <div className="stat-tile">
              <div className="stat-label">Basemap Cache</div>
              <div className="stat-value">2.1<span style={{fontSize:12}}> GB</span></div>
              <div className="stat-delta" style={{color:'var(--ok)'}}>Offline ready</div>
            </div>
          </div>

          <div className="panel-section" style={{padding:'12px 14px'}}>
            <div className="panel-section-title"><span>Active Analysis</span></div>
            {[
              { name: 'Buffer 15 km @ Delhi',   status: 'DONE', kind: 'proximity' },
              { name: 'Overlay: LULC × Parcels',status: 'RUN',  kind: 'overlay'   },
              { name: 'Hotspot: Encroachment',  status: 'DONE', kind: 'hotspot'   },
              { name: 'Route: Del → Kol',       status: 'DONE', kind: 'route'     },
              { name: 'NDVI Δ 2024 → 2026',     status: 'RUN',  kind: 'raster'    },
            ].map((r,i) => (
              <div key={i} style={{ display:'flex', alignItems:'center', gap:8, padding:'6px 0', borderBottom:'1px solid var(--paper-200)', fontSize: 11.5 }}>
                <span className={`chip ${r.status==='DONE'?'ok':'warn'}`} style={{fontSize:9, padding:'0 6px'}}>{r.status}</span>
                <span style={{flex:1}}>{r.name}</span>
                <span className="mono" style={{color:'var(--ink-500)', fontSize:10}}>{r.kind}</span>
              </div>
            ))}
          </div>

          <div className="panel-section" style={{padding:'12px 14px'}}>
            <div className="panel-section-title"><span>Bar · Detections by class</span></div>
            <BarChart data={[
              { label: 'Building',      v: 42 },
              { label: 'Crop',          v: 38 },
              { label: 'Encroachment',  v: 24 },
              { label: 'Water Body',    v: 18 },
              { label: 'Deforestation', v: 15 },
              { label: 'Illegal Mining',v: 11 },
              { label: 'Flood Risk',    v: 9  },
            ]}/>
          </div>
        </>
      )}

      {tab === 'ai' && (
        <>
          <div className="panel-section" style={{padding:'12px 14px'}}>
            <div className="panel-section-title">
              <span>GeoAI Model Queue</span>
              <span style={{color:'var(--amber-500)', fontSize:9}}>4 RUNNING</span>
            </div>
            {[
              { name: 'YOLOv8 · Building Detection',   pct: 82, area: 'Karnataka' },
              { name: 'U-Net · Land Cover Classify',   pct: 47, area: 'Krishna Basin' },
              { name: 'SAM · Field Segmentation',      pct: 96, area: 'Punjab Kharif' },
              { name: 'LSTM · Flood Forecast 7d',      pct: 34, area: 'Assam' },
              { name: 'Change Detection · Δ2024',      pct: 100,area: 'Odisha Coast' },
            ].map((m,i) => (
              <div key={i} style={{ padding:'8px 0', borderBottom:'1px solid var(--paper-200)' }}>
                <div style={{ display:'flex', justifyContent:'space-between', fontSize:11.5, fontWeight:500 }}>
                  <span>{m.name}</span>
                  <span className="mono" style={{color:'var(--ink-500)', fontSize:10}}>{m.pct}%</span>
                </div>
                <div style={{ fontSize:10, color:'var(--ink-500)', fontFamily:'var(--font-mono)', margin:'2px 0 4px' }}>Region · {m.area}</div>
                <div style={{ height:3, background:'var(--paper-200)', borderRadius:2, overflow:'hidden' }}>
                  <div style={{ width:m.pct+'%', height:'100%', background: m.pct===100 ? 'var(--ok)' : 'var(--amber-500)' }}></div>
                </div>
              </div>
            ))}
          </div>

          <div className="panel-section" style={{padding:'12px 14px'}}>
            <div className="panel-section-title"><span>Prediction · Flood Risk (7d)</span></div>
            <Sparkline values={[3,4,6,8,12,18,26,32,28,24,22,26,34,42,48,52,60,58,54]} color="#d97706" />
            <div style={{ fontSize:10, color:'var(--ink-500)', marginTop:6, display:'flex', justifyContent:'space-between', fontFamily:'var(--font-mono)' }}>
              <span>Jul 15</span><span>peak: Jul 28</span><span>Jul 31</span>
            </div>
          </div>

          <div className="panel-section" style={{padding:'12px 14px'}}>
            <div className="panel-section-title"><span>Available Models</span></div>
            <div style={{ display:'flex', flexWrap:'wrap', gap:4 }}>
              {['building.det','road.seg','water.det','crop.seg','forest.mon','mining.det','encr.det','fire.det','flood.pred','landslide.pred','ndvi.calc','change.det','traffic.ana','geoai.gen'].map(m => (
                <span key={m} className="chip mono" style={{fontSize:10}}>{m}</span>
              ))}
            </div>
          </div>
        </>
      )}
    </div>
  );
}

// ---------- Small chart atoms ----------
function BarChart({ data }) {
  const max = Math.max(...data.map(d => d.v));
  return (
    <div style={{ display:'flex', flexDirection:'column', gap: 4 }}>
      {data.map(d => (
        <div key={d.label} style={{ display:'flex', alignItems:'center', gap: 6, fontSize: 11 }}>
          <div style={{ width: 100, color:'var(--ink-700)' }}>{d.label}</div>
          <div style={{ flex: 1, height: 10, background: 'var(--paper-200)', borderRadius: 1 }}>
            <div style={{ width: (d.v/max*100)+'%', height:'100%', background:'var(--navy-700)' }}></div>
          </div>
          <div className="mono" style={{ width: 28, textAlign:'right', color:'var(--ink-500)', fontSize:10 }}>{d.v}</div>
        </div>
      ))}
    </div>
  );
}
function Sparkline({ values, color }) {
  const w = 280, h = 44;
  const max = Math.max(...values), min = Math.min(...values);
  const step = w / (values.length - 1);
  const norm = (v) => h - ((v - min) / (max - min || 1)) * (h - 4) - 2;
  const path = values.map((v,i) => `${i===0?'M':'L'}${i*step},${norm(v)}`).join(' ');
  const area = path + ` L${w},${h} L0,${h} Z`;
  return (
    <svg width="100%" viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none" style={{ display:'block' }}>
      <path d={area} fill={color} opacity="0.15" />
      <path d={path} fill="none" stroke={color} strokeWidth="1.5" strokeLinejoin="round" />
    </svg>
  );
}

// Approximate SVG coord → lat/lon
function approxLatLon(c) {
  const lon = 68 + (c.x / 612) * (97 - 68);
  const lat = 37 - (c.y / 696) * (37 - 8);
  return { lat, lon };
}

Object.assign(window, { Ribbon, LayersPanel, InspectorPanel, I, BarChart, Sparkline, approxLatLon });
