import { useState, useEffect, useCallback, useRef, useMemo } from 'react';
import { Link } from 'react-router-dom';
import { Menu, X, Ruler, Map, Boxes, Hammer, ShieldAlert, LayoutDashboard, Users, FolderKanban, FileChartColumn, Settings, Gauge, Lock } from 'lucide-react';
import { base44 } from '@/api/base44Client';
import StableViewportCore from '@/components/workshop3d/StableViewportCore';
import ViewportLabelLayer from '@/components/workshop3d/ViewportLabelLayer';
import ViewportDiagnostics from '@/components/workshop3d/ViewportDiagnostics';
import SceneComposer from '@/components/workshop3d/SceneComposer';
import ProjectTree from '@/components/workshop3d/panels/ProjectTree';
import ViewportToolbar from '@/components/workshop3d/panels/ViewportToolbar';
import ContextPanel from '@/components/workshop3d/panels/ContextPanel';
import StationTable from '@/components/workshop3d/panels/StationTable';
import MeasurementInspector from '@/components/workshop3d/panels/MeasurementInspector';
import StatusCards from '@/components/workshop3d/panels/StatusCards';
import SafetyBoundary from '@/components/workshop3d/panels/SafetyBoundary';
import TopBar from '@/components/workshop3d/panels/TopBar';
import VerticalToolStrip from '@/components/workshop3d/panels/VerticalToolStrip';
import ViewportErrorBoundary from '@/components/ViewportErrorBoundary';
import MeasurementStudio3D from '@/components/workshop3d/workflows/MeasurementStudio3D';
import SensitiveZoneMapper from '@/components/workshop3d/workflows/SensitiveZoneMapper';
import ProsthesisMapper from '@/components/workshop3d/workflows/ProsthesisMapper';
import CoverBuilder from '@/components/workshop3d/workflows/CoverBuilder';
import { customerService } from '@/services/customerService';
import { limbProfileService } from '@/services/limbProfileService';
import { prosthesisService } from '@/services/prosthesisService';
import { projectService } from '@/services/projectService';
import { componentService } from '@/services/componentService';
import { dimensionService } from '@/services/dimensionService';
import { measurementService } from '@/services/measurementService';
import { dimensionAnalysis } from '@/services/dimensionAnalysis';

const COMPONENT_CATEGORIES = ['Socket', 'Knee', 'Pylon', 'Ankle', 'Foot'];

// Nav items that navigate to a real route
const NAV_LINKS = [
  { to: '/dashboard', label: 'Dashboard', icon: LayoutDashboard },
  { to: '/customers', label: 'Customers', icon: Users },
  { to: '/new-cover', label: 'New Cover', icon: FolderKanban },
  { to: '/projects', label: 'Cover Projects', icon: FolderKanban },
  { to: '/components', label: 'Component Library', icon: Boxes },
  { to: '/reports', label: 'Reports', icon: FileChartColumn },
  { to: '/migration-readiness', label: 'Migration Readiness', icon: Gauge },
  { to: '/settings', label: 'Settings', icon: Settings },
];

// Nav items that switch the in-workshop workflow (stay on the 3D page)
const WORKFLOW_LINKS = [
  { id: null, label: 'Measurement Studio', icon: Ruler },
  { id: 'assembly', label: 'Prosthesis Mapper', icon: Boxes },
  { id: 'sensitive', label: 'Sensitive Zones', icon: Map },
  { id: 'cover', label: 'Cover Build', icon: Hammer },
];

export default function Workshop3D() {
  const [dbTree, setDbTree] = useState([]);
  const [loading, setLoading] = useState(true);
  const [customers, setCustomers] = useState([]);
  const [limbs, setLimbs] = useState([]);
  const [prostheses, setProstheses] = useState([]);
  const [projects, setProjects] = useState([]);
  const [sessions, setSessions] = useState([]);
  const [componentsList, setComponentsList] = useState([]);
  const [selected, setSelected] = useState(null);
  const [selectedId, setSelectedId] = useState(null);

  const [viewPreset, setViewPreset] = useState('perspective');
  const [ortho, setOrtho] = useState(false);
  const [transparency, setTransparency] = useState(1);
  const [sectionCut, setSectionCut] = useState(false);
  const [display, setDisplay] = useState({ measurements: true, sensitive: true, keepOut: true, access: true, cover: true, movement: true, logo: true });
  const [activeWorkflow, setActiveWorkflow] = useState(null);
  const [activeTool, setActiveTool] = useState('select');

  const [component, setComponent] = useState(null);
  const [dimensions, setDimensions] = useState([]);
  const [stations, setStations] = useState([]);
  const [accessPoints, setAccessPoints] = useState([]);
  const [keepOutZones, setKeepOutZones] = useState([]);
  const [movementPositions, setMovementPositions] = useState([]);
  const [missingInfo, setMissingInfo] = useState([]);
  const [session, setSession] = useState(null);
  const [highlightedStation, setHighlightedStation] = useState(-1);
  const [selectedAngle, setSelectedAngle] = useState(null);

  const [sensitiveZones, setSensitiveZones] = useState([]);
  const [zoneHistory, setZoneHistory] = useState([]);
  const [redoStack, setRedoStack] = useState([]);
  const [paintSettings, setPaintSettings] = useState({ type: 'No contact', color: '#ef4444', brushSize: 15 });

  const [assembly, setAssembly] = useState([]);
  const [coverParams, setCoverParams] = useState({ clearance: 6, wallThickness: 3, sensitiveClearance: 10, panelCount: 2, shellType: 'clam', seamOrientation: 'medial-lateral', ventilationDensity: 30, logoSize: 40, logoDepth: 1.5 });
  const [exploded, setExploded] = useState(false);

  const [leftOpen, setLeftOpen] = useState(false);
  const [rightOpen, setRightOpen] = useState(false);
  const [navOpen, setNavOpen] = useState(false);
  const [compatibility, setCompatibility] = useState(false);
  const [diagOpen, setDiagOpen] = useState(false);

  const mounted = useRef(true);
  useEffect(() => { mounted.current = true; return () => { mounted.current = false; }; }, []);

  useEffect(() => {
    mounted.current = true;
    Promise.all([
      customerService.list(),
      limbProfileService.list(),
      prosthesisService.list(),
      projectService.list(),
      componentService.list(),
      measurementService.sessions().catch(() => []),
    ]).then(([custs, limbs, pros, projs, comps, sess]) => {
      if (!mounted.current) return;
      const activeCusts = (custs || []).filter(c => c.record_state !== 'archived');
      const activeLimbs = (limbs || []).filter(l => l.record_state !== 'archived');
      const activePros = (pros || []).filter(p => p.record_state !== 'archived');
      const activeProjs = (projs || []).filter(p => p.record_state !== 'archived');
      const activeComps = (comps || []).filter(c => c.record_state !== 'archived' && c.status !== 'obsolete');
      const activeSessions = (sess || []).filter(s => s.record_state !== 'archived');

      setCustomers(activeCusts);
      setLimbs(activeLimbs);
      setProstheses(activePros);
      setProjects(activeProjs);
      setComponentsList(activeComps);
      setSessions(activeSessions);

      const treeData = activeCusts.map(c => ({
        type: 'customer',
        label: c.full_name || c.preferred_name || c.customer_number,
        uuid: c.uuid,
        data: c,
        children: activeLimbs.filter(l => l.customer_uuid === c.uuid).map(l => ({
          type: 'limb',
          label: l.profile_name || l.configuration,
          uuid: l.uuid,
          data: l,
          children: activePros.filter(p => p.customer_uuid === c.uuid && p.limb_profile_uuid === l.uuid).map(p => ({
            type: 'prosthesis',
            label: p.name || `${p.manufacturer || ''} ${p.model || ''}`.trim() || 'Prosthesis',
            uuid: p.uuid,
            data: p,
            children: buildAssemblyChildren(activeComps, p),
          })),
        })),
      }));
      setDbTree(treeData);
      setLoading(false);
    }).catch(() => { if (mounted.current) setLoading(false); });
  }, []);

  function buildAssemblyChildren(comps, prosthesis) {
    const assemblyCompUuids = prosthesis.component_uuids || [];
    const linked = comps.filter(c => assemblyCompUuids.includes(c.uuid));
    const children = [];
    for (const cat of COMPONENT_CATEGORIES) {
      const matching = linked.filter(c => c.category === cat);
      if (matching.length > 0) {
        children.push(...matching.map(c => ({ type: 'component', label: `${cat}: ${c.manufacturer} ${c.model}`, uuid: c.uuid, data: c, category: cat })));
      } else {
        children.push({ type: 'component', label: cat, uuid: `placeholder-${cat}`, category: cat, placeholder: true });
      }
    }
    children.push({ type: 'sensitive', label: 'Sensitive Zones', uuid: 'sensitive-group' });
    children.push({ type: 'access', label: 'Access Zones', uuid: 'access-group' });
    children.push({ type: 'cover', label: 'Cover Panels', uuid: 'cover-group' });
    children.push({ type: 'logo', label: 'SHiRE Logo', uuid: 'logo-group' });
    return children;
  }

  function buildVisualAssembly(currentStations) {
    const list = currentStations && currentStations.length ? currentStations : [
      { station_name: 'Bottom Boundary' }, { station_name: 'Pylon Diameter' },
      { station_name: 'Socket Distal Station' }, { station_name: 'Socket Mid Station' },
      { station_name: 'Socket Upper Station' }, { station_name: 'Top Boundary' },
    ];
    const stationNodes = list.map((s, i) => ({
      type: 'station',
      uuid: String(i),
      index: i,
      data: s,
      label: `${String(i + 1).padStart(2, '0')} — ${s.station_name || s.name || `Station ${i + 1}`}`,
    }));
    return {
      type: 'assembly-group',
      label: 'Visual Assembly (generic)',
      uuid: 'assembly-group',
      children: [
        { type: 'part', partId: 'residual', label: 'Residual Limb / Liner', uuid: 'residual' },
        { type: 'part', partId: 'socket', label: 'Socket', uuid: 'socket' },
        { type: 'part', partId: 'adapter', label: 'Distal Socket Adapter', uuid: 'adapter' },
        { type: 'part', partId: 'pylon', label: 'Pylon', uuid: 'pylon' },
        { type: 'part', partId: 'clamp', label: 'Tube Clamp', uuid: 'clamp' },
        { type: 'part', partId: 'ankle', label: 'Ankle Adapter', uuid: 'ankle' },
        { type: 'part', partId: 'foot', label: 'Foot', uuid: 'foot' },
        { type: 'cover', label: 'Conceptual Cover', uuid: 'preview' },
        { type: 'logo', label: 'SHiRE Logo (mandatory)', uuid: 'mark' },
        { type: 'stations-group', label: 'Measurement Stations', uuid: 'stations-group', children: stationNodes },
      ],
    };
  }

  const tree = useMemo(() => [buildVisualAssembly(stations), ...dbTree], [dbTree, stations]); // eslint-disable-line react-hooks/exhaustive-deps

  const loadComponent3DData = useCallback(async (comp) => {
    setComponent(comp);
    const [dims, stns, access, keepout, moves] = await Promise.all([
      dimensionService.dimensions(comp.uuid),
      dimensionService.stations(comp.uuid),
      dimensionService.accessPoints(comp.uuid),
      dimensionService.keepOutZones(comp.uuid),
      dimensionService.movementPositions(comp.uuid),
    ]);
    if (!mounted.current) return;
    setDimensions(dims || []);
    setStations(stns || []);
    setAccessPoints(access || []);
    setKeepOutZones(keepout || []);
    setMovementPositions(moves || []);
    try {
      const analysis = await dimensionAnalysis.completeness(comp);
      if (mounted.current) setMissingInfo(analysis.blocking || []);
    } catch { if (mounted.current) setMissingInfo([]); }
  }, []);

  useEffect(() => {
    if (selected?.type === 'component' && selected.data && !selected.placeholder) {
      loadComponent3DData(selected.data);
      measurementService.sessions().then(ss => {
        if (!mounted.current) return;
        const found = ss.find(s => s.component_uuid === selected.data.uuid && s.status !== 'Complete');
        if (found) setSession(found);
      });
    }
  }, [selectedId]); // eslint-disable-line react-hooks/exhaustive-deps

  const handleTreeSelect = (node) => {
    setSelected(node);
    setSelectedId(`${node.type}-${node.uuid || node.id}`);
    setLeftOpen(false);
  };

  const handle3DSelect = (type, index, data) => {
    setSelected({ type, index, data });
    setSelectedId(`${type}-${index}`);
    if (type === 'station') setHighlightedStation(index);
    if (type === 'movement') setSelectedAngle(data?.angle_degrees);
    setRightOpen(true);
  };

  const handleView = (view) => {
    if (view === 'ortho') { setOrtho(!ortho); return; }
    setViewPreset(view);
  };
  const handleToggle = (key) => setDisplay(d => ({ ...d, [key]: !d[key] }));

  const handlePaint = useCallback((point) => {
    if (activeWorkflow !== 'sensitive') return;
    const zone = { ...paintSettings, position: [point.x, point.y, point.z] };
    setZoneHistory(h => [...h, sensitiveZones]);
    setSensitiveZones(z => [...z, zone]);
    setRedoStack([]);
  }, [activeWorkflow, paintSettings, sensitiveZones]);

  const handleUndo = () => {
    if (zoneHistory.length === 0) return;
    setRedoStack(r => [...r, sensitiveZones]);
    setSensitiveZones(zoneHistory[zoneHistory.length - 1]);
    setZoneHistory(h => h.slice(0, -1));
  };
  const handleRedo = () => {
    if (redoStack.length === 0) return;
    setZoneHistory(h => [...h, sensitiveZones]);
    setSensitiveZones(redoStack[redoStack.length - 1]);
    setRedoStack(r => r.slice(0, -1));
  };
  const handleRemoveZone = (i) => {
    setZoneHistory(h => [...h, sensitiveZones]);
    setSensitiveZones(z => z.filter((_, idx) => idx !== i));
    setRedoStack([]);
  };

  const handleLock = () => { base44.auth.logout('/login'); };

  const mode = component && component.category === 'Knee' ? 'component' : 'limb';

  const isStation = selected?.type === 'station';

  const renderRightPanel = () => {
    if (activeWorkflow === 'measure') {
      return <MeasurementStudio3D session={session} onGuidedView={setViewPreset} onHighlightStation={setHighlightedStation} onComplete={() => setActiveWorkflow(null)} />;
    }
    if (activeWorkflow === 'sensitive') {
      return <SensitiveZoneMapper zones={sensitiveZones} onSettingsChange={setPaintSettings} onRemoveZone={handleRemoveZone} onUndo={handleUndo} onRedo={handleRedo} canUndo={zoneHistory.length > 0} canRedo={redoStack.length > 0} />;
    }
    if (activeWorkflow === 'assembly') {
      return <ProsthesisMapper assembly={assembly} onAdd={(c) => setAssembly(a => [...a, c])} onRemove={(i) => setAssembly(a => a.filter((_, idx) => idx !== i))} onUpdate={(i, d) => setAssembly(a => a.map((x, idx) => idx === i ? { ...x, ...d } : x))} onReorder={(i, dir) => setAssembly(a => { const j = i + dir; if (j < 0 || j >= a.length) return a; const copy = [...a]; [copy[i], copy[j]] = [copy[j], copy[i]]; return copy; })} />;
    }
    if (activeWorkflow === 'cover') {
      return <CoverBuilder params={coverParams} onParamChange={setCoverParams} onExplodeView={() => setExploded(!exploded)} exploded={exploded} />;
    }
    // Browse mode
    return (
      <>
        {isStation ? (
          <MeasurementInspector
            selected={selected}
            stationIndex={selected.index}
            previousValue={selected.data?.prev}
            onSave={() => setHighlightedStation(-1)}
            onMeasureAgain={() => setHighlightedStation(selected.index)}
            onNotApplicable={() => setSelected(null)}
          />
        ) : (
          <ContextPanel selected={selected} component={component} dimensions={dimensions} stations={stations} accessPoints={accessPoints} keepOutZones={keepOutZones} movementPositions={movementPositions} missingInfo={missingInfo} context={{ customers, limbs, prostheses, projects, components: componentsList, sessions }} coverParams={coverParams} display={display} />
        )}
        <div className="border-t border-white/10" />
        <StatusCards />
        <div className="border-t border-white/10 px-4 pb-4">
          <Link to="/measurements" className="btn-secondary w-full !min-h-10">View All Measurements</Link>
        </div>
      </>
    );
  };

  const sessionStatus = session?.status === 'Complete' ? 'Session Complete' : session ? 'Live Capture' : 'Missing Measurements';

  return (
    <div className="flex h-screen flex-col bg-workshop">
      <TopBar route="/customers/ACME-0421/measurements" onLock={handleLock} />

      <div className="flex flex-1 overflow-hidden">
        {/* Left panel — Navigation + Project Tree */}
        <aside className={`fixed inset-y-0 left-0 z-40 w-72 border-r border-white/10 bg-[#0d1318] transition-transform lg:static lg:translate-x-0 ${leftOpen ? 'translate-x-0' : '-translate-x-full'}`}>
          <div className="flex h-full flex-col">
            <div className="flex items-center justify-between border-b border-white/10 px-4 py-3">
              <span className="text-sm font-bold tracking-[0.16em] text-cyan-300">SHiRE LimbForge</span>
              <button onClick={() => setLeftOpen(false)} className="icon-btn lg:hidden"><X className="h-4 w-4" /></button>
            </div>

            {/* Navigation */}
            <nav className="overflow-y-auto px-2 py-2">
              {WORKFLOW_LINKS.map(l => {
                const Icon = l.icon;
                const active = activeWorkflow === l.id;
                return (
                  <button key={l.label} onClick={() => { setActiveWorkflow(l.id); setRightOpen(true); }} className={`nav-link w-full ${active ? 'nav-link-active' : ''}`}>
                    <Icon className="h-5 w-5" />{l.label}
                  </button>
                );
              })}
              <div className="my-2 h-px bg-white/10" />
              {NAV_LINKS.map(l => {
                const Icon = l.icon;
                return (
                  <Link key={l.to} to={l.to} className="nav-link">
                    <Icon className="h-5 w-5" />{l.label}
                  </Link>
                );
              })}
              <button onClick={handleLock} className="nav-link w-full"><Lock className="h-5 w-5" />Lock Workshop</button>
            </nav>

            {/* Project Tree */}
            <div className="min-h-0 flex-1 border-t border-white/10">
              <ProjectTree tree={tree} selectedId={selectedId} onSelect={handleTreeSelect} />
            </div>

            <div className="flex items-center justify-between border-t border-white/10 px-4 py-2 text-[10px] text-slate-500">
              <span>v2.3.1</span>
              <span className="flex items-center gap-1.5 text-emerald-400"><span className="h-1.5 w-1.5 rounded-full bg-emerald-400" />All systems operational</span>
            </div>
          </div>
        </aside>

        {leftOpen && <div className="fixed inset-0 z-30 bg-black/50 lg:hidden" onClick={() => setLeftOpen(false)} />}

        {/* Center — Viewport column */}
        <div className="flex min-w-0 flex-1 flex-col">
          {/* Mobile top controls */}
          <div className="flex items-center gap-2 border-b border-white/10 bg-[#0d1318]/90 px-3 py-2 lg:hidden">
            <button onClick={() => setLeftOpen(true)} className="icon-btn"><Menu className="h-4 w-4" /></button>
            <button onClick={() => setRightOpen(true)} className="btn-secondary !px-3">Inspector</button>
          </div>

          {/* Viewport header */}
          <div className="shrink-0 px-4 py-3">
            <div className="flex items-center gap-3">
              <div>
                <h1 className="text-lg font-semibold text-white">Measurement Studio</h1>
                <p className="text-xs text-slate-500">Guided 3D capture with live measurement markers and design-ready prosthetic mapping.</p>
              </div>
              <span className="ml-auto inline-flex items-center gap-1.5 rounded-full border border-cyan-400/40 bg-cyan-400/10 px-3 py-1 text-xs font-semibold text-cyan-300">
                <span className="h-1.5 w-1.5 animate-pulse rounded-full bg-cyan-400" />{sessionStatus}
              </span>
            </div>
            <div className="mt-3">
              <SafetyBoundary compact />
            </div>
          </div>

          <ViewportToolbar viewPreset={viewPreset} onView={handleView} ortho={ortho} display={display} onToggle={handleToggle} transparency={transparency} onTransparency={setTransparency} onFit={() => setViewPreset('fit')} onReset={() => setViewPreset('reset')} onSection={() => setSectionCut(!sectionCut)} />

          {/* Viewport area */}
          <div className="flex min-h-0 flex-1">
            <VerticalToolStrip activeTool={activeTool} onTool={setActiveTool} />
            <div className="relative min-w-0 flex-1">
              <ViewportErrorBoundary
                onReset={() => { setViewPreset('reset'); setDisplay(d => ({ ...d, measurements: true })); setCompatibility(false); }}
                onCompatibility={() => setCompatibility(true)}
              >
                <StableViewportCore viewPreset={viewPreset} ortho={ortho} onBackgroundClick={() => { setSelected(null); setSelectedId(null); setHighlightedStation(-1); }} onCoreFailure={() => setDiagOpen(true)}>
                  <SceneComposer
                    mode={mode}
                    component={component}
                    dimensions={dimensions}
                    stations={stations}
                    accessPoints={accessPoints}
                    keepOutZones={keepOutZones}
                    movementPositions={movementPositions}
                    sensitiveZones={sensitiveZones}
                    selectedId={selectedId}
                    onSelect={handle3DSelect}
                    highlightedStation={highlightedStation}
                    selectedAngle={selectedAngle}
                    show={display}
                    transparency={transparency}
                    coverClearance={coverParams.clearance}
                    coverThickness={coverParams.wallThickness}
                    onPaint={activeWorkflow === 'sensitive' ? handlePaint : null}
                    paintColor={paintSettings.color}
                    compatibility={compatibility}
                  />
                </StableViewportCore>
              </ViewportErrorBoundary>

              {/* DOM label overlay — outside the Canvas, projected from the live camera */}
              <ViewportLabelLayer />

              {compatibility && (
                <div className="absolute right-4 top-4 z-20 flex items-center gap-2 rounded-lg border border-amber-400/40 bg-[#0b0f13]/95 px-3 py-1.5 text-xs text-amber-300">
                  <ShieldAlert className="h-4 w-4" />
                  <span>Compatibility Mode — transparency, movement &amp; zones disabled</span>
                  <button onClick={() => setCompatibility(false)} className="ml-1 rounded border border-amber-400/40 px-2 py-0.5 text-[11px] hover:bg-amber-400/10">Exit</button>
                </div>
              )}

              {!component && (
                <div className="pointer-events-none absolute left-1/2 top-6 -translate-x-1/2 rounded-xl border border-white/10 bg-[#0b0f13]/90 px-4 py-2 text-sm text-slate-400 backdrop-blur">
                  Select a component from the project tree to load its 3D model — a generic measurement model is shown meanwhile.
                </div>
              )}

              {activeWorkflow === 'sensitive' && (
                <div className="pointer-events-none absolute left-1/2 bottom-6 -translate-x-1/2 rounded-xl border border-purple-400/30 bg-[#0b0f13]/90 px-4 py-2 text-sm text-purple-300 backdrop-blur">
                  <ShieldAlert className="mr-1.5 inline h-4 w-4" />Paint mode active — click on the 3D model to place zones
                </div>
              )}
              {sectionCut && (
                <div className="absolute left-4 top-4 rounded-lg border border-cyan-400/30 bg-[#0b0f13]/90 px-3 py-1.5 text-xs text-cyan-300">Section cut active</div>
              )}
            </div>
          </div>

          {/* Station table */}
          {component && stations.length > 0 && (
            <div className="max-h-52 shrink-0 overflow-y-auto border-t border-white/10 bg-[#0d1318]/90 backdrop-blur">
              <StationTable stations={stations} selectedId={selectedId} onSelect={handle3DSelect} onAdd={() => {}} onDuplicate={() => {}} onDelete={() => {}} onSetSpacing={() => {}} />
            </div>
          )}
        </div>

        {/* Right panel — Inspector + Status */}
        <aside className={`fixed inset-x-0 bottom-0 z-40 max-h-[75vh] overflow-hidden border-t border-white/10 bg-[#0d1318] transition-transform lg:static lg:max-h-none lg:w-80 lg:border-t-0 lg:border-l ${rightOpen ? 'translate-y-0' : 'translate-y-full lg:translate-y-0'}`}>
          <div className="flex h-full flex-col">
            <div className="flex items-center justify-between border-b border-white/10 px-4 py-2 lg:hidden">
              <span className="text-xs font-semibold text-slate-400">INSPECTOR</span>
              <button onClick={() => setRightOpen(false)} className="icon-btn"><X className="h-4 w-4" /></button>
            </div>
            <div className="min-h-0 flex-1 overflow-y-auto">
              {renderRightPanel()}
            </div>
          </div>
        </aside>

        {!rightOpen && (
          <button onClick={() => setRightOpen(true)} className="fixed bottom-4 right-4 z-30 rounded-full bg-cyan-400 px-4 py-3 text-sm font-semibold text-slate-950 shadow-lg lg:hidden">
            Inspector
          </button>
        )}

        {/* Stable viewport diagnostics (workshop-owner) */}
        <button onClick={() => setDiagOpen(true)} className="fixed bottom-4 left-4 z-30 inline-flex items-center gap-1.5 rounded-full border border-white/10 bg-[#0d1318]/90 px-3 py-2 text-xs font-medium text-slate-300 shadow-lg hover:text-cyan-300">
          <Gauge className="h-4 w-4" /> Diagnostics
        </button>
        <ViewportDiagnostics
          open={diagOpen}
          onClose={() => setDiagOpen(false)}
          onResetCamera={() => setViewPreset('reset')}
          onDisableLayers={() => setDisplay({ measurements: false, access: false, keepOut: false, sensitive: false, movement: false, cover: false, logo: false })}
          onReloadLayers={() => setDisplay({ measurements: true, access: true, keepOut: true, sensitive: true, movement: true, cover: true, logo: true })}
        />
      </div>
    </div>
  );
}