// Workstation shell — top bar, ribbon, panels, canvas, status bar
const { useState: useS, useEffect: useE } = React;

function Workstation() {
  const [activeTool, setActiveTool] = useS('select');
  const [viewMode, setViewMode]   = useS('2d');    // 2d | 3d | globe
  const [basemap, setBasemap]     = useS('streets');
  const [selected, setSelected]   = useS(null);
  const [hovered, setHovered]     = useS(null);
  const [cursor, setCursor]       = useS({ lat: 20.5, lon: 78.9, x: 300, y: 400 });

  const [layers, setLayers] = useS({
    states:    { on: true },
    districts: { on: true },
    cities:    { on: true },
    labels:    { on: true },
    rivers:    { on: true },
    roads:     { on: true },
    assets:    { on: true },
    ai:        { on: true },
    buffer:    { on: true },
    routes:    { on: true },
    heatmap:   { on: false },
    graticule: { on: true },
  });

  // Sync 3D/globe tool with view mode
  useE(() => {
    if (activeTool === '3d')    setViewMode('3d');
    if (activeTool === 'globe') setViewMode('globe');
    if (['select','pan','zoom','measure','draw','polygon','vertex'].includes(activeTool) && viewMode !== '2d') {
      // Keep it if user is doing analysis; only reset via basemap explicitly.
    }
  }, [activeTool]);

  // Command hint for the active tool
  const toolHints = {
    select:  { lbl: 'SELECT', desc: 'Click any feature to inspect · Shift-click to multi-select', kbd: 'S' },
    pan:     { lbl: 'PAN',    desc: 'Drag to move the map view',                                 kbd: 'P' },
    zoom:    { lbl: 'ZOOM',   desc: 'Draw a rectangle to zoom in',                               kbd: 'Z' },
    measure: { lbl: 'MEASURE',desc: 'Click points to measure distance and area',                 kbd: 'M' },
    draw:    { lbl: 'DRAW',   desc: 'Click to add vertices · double-click to finish',            kbd: 'D' },
    polygon: { lbl: 'POLYGON',desc: 'Create polygon feature with snapping enabled',              kbd: 'G' },
    vertex:  { lbl: 'VERTEX', desc: 'Edit individual vertices of a selected feature',            kbd: 'V' },
    buffer:  { lbl: 'BUFFER', desc: 'Generate 5/10/15 km buffer around a selection',             kbd: 'B' },
    overlay: { lbl: 'OVERLAY',desc: 'Intersect selected layers · output as new feature class',   kbd: 'O' },
    route:   { lbl: 'ROUTE',  desc: 'Compute shortest / least-cost path between origins',        kbd: 'R' },
    chart:   { lbl: 'CHARTS', desc: 'Open chart designer for selected layer',                    kbd: 'C' },
    aidet:   { lbl: 'AI DETECT', desc: 'Run object detection on active imagery layer',           kbd: 'A' },
    segm:    { lbl: 'AI SEGMENT', desc: 'Semantic segmentation via Segment Anything · U-Net',    kbd: 'S' },
    sat:     { lbl: 'IMAGERY',desc: 'Load Sentinel / Landsat / ISRO Bhuvan tiles',               kbd: 'I' },
    drone:   { lbl: 'DRONE',  desc: 'Ingest orthomosaic · DEM · point cloud from UAV mission',   kbd: 'U' },
    '3d':    { lbl: '3D VIEW',desc: 'Perspective tilt · terrain and buildings extruded',         kbd: '3' },
    globe:   { lbl: 'GLOBE',  desc: 'Spherical projection · full earth view',                    kbd: 'G' },
  };

  const hint = toolHints[activeTool];

  return (
    <div className="ws" data-screen-label="01 Workstation">
      {/* Top bar */}
      <div className="topbar">
        <div className="brand">
          <div className="brand-mark">भू</div>
          <div>
            <div className="brand-name">BhooChitra<span className="v">GIS · V3</span></div>
          </div>
          <div className="brand-sub">Enterprise Geospatial Platform</div>
        </div>
        <div style={{display:'flex', alignItems:'center', gap: 12}}>
          <div className="breadcrumb">
            <span>Karnataka LIS</span>
            <span className="sep">/</span>
            <span>Master Project</span>
            <span className="sep">/</span>
            <span className="cur">KA-LIS-2026-Q2.bcgp</span>
          </div>
          <input className="topbar-search" placeholder="Search features, layers, coordinates, or run a command…" />
        </div>
        <div className="topbar-right">
          <span className="tb-pill"><span className="dot"></span>PostGIS · ka_lis_prod</span>
          <span className="tb-pill">v3.4.1</span>
          <span className="tb-pill">GovCloud · MeitY</span>
          <div className="tb-user">AS</div>
        </div>
      </div>

      {/* Ribbon */}
      <Ribbon activeTool={activeTool} setActiveTool={setActiveTool} />

      {/* Main 3-column area */}
      <div className="main">
        <LayersPanel layers={layers} setLayers={setLayers} />

        <div className="canvas-wrap">
          <MapCanvas
            basemap={basemap}
            viewMode={viewMode}
            layers={layers}
            selectedId={selected ? `${selected.kind}:${selected.id}` : null}
            hoveredId={hovered}
            onSelectFeature={setSelected}
            onHoverFeature={setHovered}
            onCursorMove={setCursor}
            activeTool={activeTool}
          />

          {/* View switch (2D / 3D / Globe) */}
          <div className="canvas-widget view-switch">
            {['2d','3d','globe'].map(m => (
              <button key={m} className={viewMode===m?'active':''} onClick={() => setViewMode(m)}>{m}</button>
            ))}
          </div>

          {/* Basemap picker */}
          <div className="canvas-widget basemap-picker">
            {[
              {id:'streets',   lbl:'STREETS'},
              {id:'satellite', lbl:'SAT'},
              {id:'terrain',   lbl:'TERRAIN'},
              {id:'topo',      lbl:'TOPO'},
            ].map(b => (
              <button key={b.id} className={`basemap-thumb ${b.id} ${basemap===b.id?'active':''}`} onClick={() => setBasemap(b.id)}>{b.lbl}</button>
            ))}
          </div>

          {/* Zoom */}
          <div className="canvas-widget zoom-ctl">
            <button title="Zoom in">＋</button>
            <button title="Zoom out">−</button>
            <button title="Home"><I name="compass" size={14}/></button>
          </div>

          {/* Command bar */}
          {hint && (
            <div className="command-bar">
              <span className="lbl">▸ {hint.lbl}</span>
              <span className="desc">{hint.desc}</span>
              <span className="kbd">{hint.kbd}</span>
            </div>
          )}

          {/* Legend */}
          <div className="canvas-widget legend">
            <div className="legend-title">Legend</div>
            <div className="legend-row"><div className="legend-swatch" style={{background:'#0a1a35'}}></div><span>Metro city</span></div>
            <div className="legend-row"><div className="legend-swatch" style={{background:'#2d5aa0'}}></div><span>Tier-I city</span></div>
            <div className="legend-row"><div className="legend-swatch line" style={{background:'#4a90c8'}}></div><span>Major river</span></div>
            <div className="legend-row"><div className="legend-swatch line" style={{background:'#c94a3a'}}></div><span>National highway</span></div>
            <div className="legend-row"><div className="legend-swatch" style={{background:'repeating-linear-gradient(45deg,#d97706 0 2px,transparent 2px 4px)', border:'1px dashed #d97706'}}></div><span>AI detection</span></div>
            <div className="legend-row"><div className="legend-swatch" style={{background:'#2f7d4f'}}></div><span>Utility asset</span></div>
          </div>

          {/* Scale bar */}
          <div className="canvas-widget scalebar">
            <div className="scalebar-line">
              <div className="scalebar-bar"></div>
              <div className="scalebar-label">0 &nbsp;&nbsp; 250 &nbsp;&nbsp; 500 km</div>
            </div>
            <div style={{ fontSize: 10, color:'var(--ink-500)' }}>1:12,000,000</div>
          </div>

          {/* North arrow */}
          <div className="canvas-widget north">
            <svg width="32" height="32" viewBox="0 0 32 32">
              <circle cx="16" cy="16" r="14" fill="none" stroke="#0a1a35" strokeWidth="0.5"/>
              <polygon points="16,4 12,20 16,17 20,20" fill="#d97706" stroke="#0a1a35" strokeWidth="0.5"/>
              <polygon points="16,28 12,12 16,15 20,12" fill="#0a1a35" opacity="0.15"/>
              <text x="16" y="7" textAnchor="middle" fontSize="7" fontWeight="700" fill="#0a1a35">N</text>
            </svg>
          </div>

          {/* Minimap */}
          <div className="canvas-widget minimap">
            <div className="minimap-title">Overview · India</div>
            <div className="minimap-map">
              <svg viewBox="80 60 480 640" preserveAspectRatio="xMidYMid meet" style={{position:'absolute', inset:0, width:'100%', height:'100%'}}>
                {(window.INDIA_STATES || []).map(s => (
                  <path key={s.id} d={s.d} fill="#c8d0b8" stroke="#8a9a70" strokeWidth="0.5"/>
                ))}
                <rect x="150" y="180" width="180" height="230" fill="none" stroke="#d97706" strokeWidth="2" strokeDasharray="3 2"/>
              </svg>
            </div>
          </div>

          {/* Coord readout */}
          <div className="coord-readout">
            <span><span style={{color:'var(--ink-500)'}}>LAT</span> {cursor.lat.toFixed(4)}° N</span>
            <span><span style={{color:'var(--ink-500)'}}>LON</span> {cursor.lon.toFixed(4)}° E</span>
            <span><span style={{color:'var(--ink-500)'}}>EPSG</span> 4326</span>
            <span><span style={{color:'var(--ink-500)'}}>Z</span> 6.24</span>
          </div>
        </div>

        <InspectorPanel selected={selected} activeTool={activeTool} />
      </div>

      {/* Status bar */}
      <div className="statusbar">
        <div className="sb-item"><span className="lbl">CRS</span><span className="val">EPSG:4326 · WGS84</span></div>
        <div className="sb-sep"></div>
        <div className="sb-item"><span className="lbl">Scale</span><span className="val">1:12,000,000</span></div>
        <div className="sb-sep"></div>
        <div className="sb-item"><span className="lbl">Cursor</span><span className="val">{cursor.lat.toFixed(4)}, {cursor.lon.toFixed(4)}</span></div>
        <div className="sb-sep"></div>
        <div className="sb-item"><span className="lbl">Selected</span><span className="val">{selected ? '1 feature' : '—'}</span></div>
        <div className="sb-sep"></div>
        <div className="sb-item"><span className="lbl">Layers</span><span className="val">{Object.values(layers).filter(l => l.on).length} / {Object.keys(layers).length} on</span></div>
        <div className="sb-spacer"></div>
        <div className="sb-item"><span className="lbl">Sync</span><span className="val" style={{color:'#7bc38c'}}>● live · PostGIS</span></div>
        <div className="sb-sep"></div>
        <div className="sb-item"><span className="lbl">Deployment</span><span className="val">Gov Cloud · MeitY</span></div>
        <div className="sb-sep"></div>
        <div className="sb-item"><span className="lbl">User</span><span className="val">a.sharma@ka.gov.in</span></div>
      </div>
    </div>
  );
}

window.Workstation = Workstation;
