(() => {
const { useState, useEffect, useRef, useMemo, useCallback } = React;
const {
  Play, Pause, Square, RotateCcw, RotateCw, Trash2, Download, Upload,
  FilePlus, ZoomIn, ZoomOut, Maximize2, Hand, MousePointer, Search,
  ChevronDown, ChevronRight, AlertTriangle, AlertCircle, CheckCircle2,
  Activity, Sliders, FileSpreadsheet, Info, FolderOpen, BookOpen, Gauge,
  Undo2, Redo2, FlipHorizontal, FlipVertical, Copy, Clipboard, Layers,
  Settings, Image, FileCode, X, Cloud, Save,
} = window.HydraIcons;

// ============================================================================
// BACKEND CLOUD CIRCUITS MODAL
// ============================================================================

function CloudCircuitsModal({ currentTitle, currentDesc, backendOnline, onSaveCurrent, onLoadCloud, onClose }) {
  const [list, setList] = useState([]);
  const [loading, setLoading] = useState(true);
  const [source, setSource] = useState('server');
  const [saveName, setSaveName] = useState(currentTitle || 'Untitled Hydraulic Circuit');
  const [saveDesc, setSaveDesc] = useState(currentDesc || '');
  const [saving, setSaving] = useState(false);

  const refresh = useCallback(async () => {
    setLoading(true);
    const res = await HydraAPI.listCircuits();
    setList(res.circuits || []);
    setSource(res.source);
    setLoading(false);
  }, []);

  useEffect(() => { refresh(); }, [refresh]);

  const handleSave = async (e) => {
    e.preventDefault();
    setSaving(true);
    await onSaveCurrent(saveName, saveDesc);
    setSaving(false);
    refresh();
  };

  const handleDelete = async (id) => {
    await HydraAPI.deleteCircuit(id);
    refresh();
  };

  return (
    <div className="fixed inset-0 bg-slate-900/45 backdrop-blur-[1px] z-50 flex items-center justify-center p-4" onMouseDown={onClose}>
      <div className="bg-white border border-slate-300 rounded-lg shadow-2xl w-full max-w-xl overflow-hidden flex flex-col max-h-[85vh]" onMouseDown={(e) => e.stopPropagation()}>
        <div className="px-4 py-3 bg-slate-50 border-b border-slate-200 flex items-center justify-between">
          <div className="flex items-center gap-2">
            <Cloud size={16} className="text-sky-600" />
            <h2 className="text-sm font-bold text-slate-900">Backend Circuit Storage</h2>
            <span className={`text-[10px] font-semibold px-2 py-0.5 rounded-full ${backendOnline ? 'bg-emerald-100 text-emerald-700' : 'bg-amber-100 text-amber-700'}`}>
              {backendOnline ? 'Express API Connected' : 'Local Fallback Mode'}
            </span>
          </div>
          <button onClick={onClose} className="p-1 text-slate-400 hover:text-slate-700 rounded hover:bg-slate-200/70">
            <X size={16} />
          </button>
        </div>

        <form onSubmit={handleSave} className="p-4 border-b border-slate-200 bg-sky-50/40 space-y-2.5 text-xs">
          <div className="font-bold text-slate-700">Save Current Circuit to {source === 'server' ? 'Backend Server' : 'Browser Storage'}</div>
          <div className="grid grid-cols-1 gap-2">
            <input
              type="text"
              value={saveName}
              onChange={(e) => setSaveName(e.target.value)}
              placeholder="Circuit name"
              required
              className="w-full px-2.5 py-1.5 bg-white border border-slate-300 rounded text-xs focus:outline-none focus:border-sky-500"
            />
            <div className="flex gap-2">
              <input
                type="text"
                value={saveDesc}
                onChange={(e) => setSaveDesc(e.target.value)}
                placeholder="Optional description..."
                className="flex-1 px-2.5 py-1.5 bg-white border border-slate-300 rounded text-xs focus:outline-none focus:border-sky-500"
              />
              <button
                type="submit"
                disabled={saving}
                className="px-3.5 py-1.5 bg-sky-600 hover:bg-sky-700 text-white font-semibold rounded flex items-center gap-1.5 shadow-sm disabled:opacity-50"
              >
                <Save size={13} /> {saving ? 'Saving...' : 'Save Circuit'}
              </button>
            </div>
          </div>
        </form>

        <div className="p-4 overflow-y-auto flex-1 space-y-2 text-xs">
          <div className="text-[11px] font-bold uppercase tracking-wider text-slate-500">Saved Circuits ({list.length})</div>
          {loading ? (
            <div className="text-slate-400 py-6 text-center">Loading saved circuits...</div>
          ) : list.length === 0 ? (
            <div className="text-slate-400 py-6 text-center border border-dashed border-slate-200 rounded">
              No saved circuits yet. Save your current schematic above.
            </div>
          ) : (
            list.map((c) => (
              <div key={c.id} className="flex items-center justify-between gap-3 p-2.5 rounded border border-slate-200 hover:border-sky-300 hover:bg-slate-50">
                <div className="min-w-0">
                  <div className="font-semibold text-slate-800 truncate">{c.name}</div>
                  {c.description && <div className="text-[11px] text-slate-500 truncate">{c.description}</div>}
                  <div className="text-[10px] text-slate-400 font-mono mt-0.5">
                    {c.componentCount} components · {c.connectionCount} lines · {c.updatedAt ? new Date(c.updatedAt).toLocaleString() : ''}
                  </div>
                </div>
                <div className="flex items-center gap-1.5 shrink-0">
                  <button
                    onClick={() => onLoadCloud(c.id)}
                    className="px-2.5 py-1 bg-sky-600 hover:bg-sky-700 text-white font-medium rounded"
                  >
                    Load
                  </button>
                  <button
                    onClick={() => handleDelete(c.id)}
                    className="p-1.5 text-slate-400 hover:text-red-600 hover:bg-red-50 rounded"
                    title="Delete circuit"
                  >
                    <Trash2 size={13} />
                  </button>
                </div>
              </div>
            ))
          )}
        </div>
      </div>
    </div>
  );
}

// ============================================================================
// 9. MAIN HYDRASIM APPLICATION
// ============================================================================


const BROWSER_STORAGE_KEY = 'hydrosim_browser_state_v1';

function loadBrowserSavedState() {
  try {
    if (typeof window === 'undefined' || !window.localStorage) return null;
    const raw = window.localStorage.getItem(BROWSER_STORAGE_KEY);
    if (!raw) return null;
    const parsed = JSON.parse(raw);
    return parsed && typeof parsed === 'object' ? parsed : null;
  } catch (_) {
    return null;
  }
}

function saveBrowserSavedState(payload) {
  try {
    if (typeof window === 'undefined' || !window.localStorage) return;
    window.localStorage.setItem(BROWSER_STORAGE_KEY, JSON.stringify(payload));
  } catch (_) {}
}


function getOrthogonalSegments(p1, p2, midOffset = 0) {
  const dx = p2.x - p1.x;
  const dy = p2.y - p1.y;
  if (Math.abs(dx) < 2 || Math.abs(dy) < 2) {
    return [[p1, p2]];
  }
  if (Math.abs(dx) >= Math.abs(dy)) {
    const midX = p1.x + dx * 0.5 + midOffset;
    return [
      [p1, { x: midX, y: p1.y }],
      [{ x: midX, y: p1.y }, { x: midX, y: p2.y }],
      [{ x: midX, y: p2.y }, p2],
    ];
  }
  const midY = p1.y + dy * 0.5 + midOffset;
  return [
    [p1, { x: p1.x, y: midY }],
    [{ x: p1.x, y: midY }, { x: p2.x, y: midY }],
    [{ x: p2.x, y: midY }, p2],
  ];
}

function buildOrthogonalPathWithBridges(p1, p2, midOffset = 0, priorHorizSegments = []) {
  const segs = getOrthogonalSegments(p1, p2, midOffset);
  const parts = [];
  const R = 6;
  for (let i = 0; i < segs.length; i++) {
    const [a, b] = segs[i];
    if (i === 0) parts.push(`M ${a.x} ${a.y}`);
    const isVert = Math.abs(a.x - b.x) < 1.5 && Math.abs(a.y - b.y) > 4;
    if (!isVert || priorHorizSegments.length === 0) {
      parts.push(`L ${b.x} ${b.y}`);
      continue;
    }
    const x = a.x;
    const yMin = Math.min(a.y, b.y);
    const yMax = Math.max(a.y, b.y);
    const crossings = [];
    for (const [ha, hb] of priorHorizSegments) {
      const hy = ha.y;
      const hxMin = Math.min(ha.x, hb.x);
      const hxMax = Math.max(ha.x, hb.x);
      if (x > hxMin + 4 && x < hxMax - 4 && hy > yMin + R + 2 && hy < yMax - R - 2) {
        crossings.push(hy);
      }
    }
    if (crossings.length === 0) {
      parts.push(`L ${b.x} ${b.y}`);
      continue;
    }
    const dir = b.y > a.y ? 1 : -1;
    crossings.sort((u, v) => (dir > 0 ? u - v : v - u));
    for (const cy of crossings) {
      const yEntry = cy - dir * R;
      const yExit = cy + dir * R;
      const sweep = dir > 0 ? 1 : 0;
      parts.push(`L ${x} ${yEntry}`);
      parts.push(`A ${R} ${R} 0 0 ${sweep} ${x} ${yExit}`);
    }
    parts.push(`L ${b.x} ${b.y}`);
  }
  return parts.join(' ');
}



const DEFAULT_PRESSURE_COLORS = {
  lowMaxBar: 5,
  midMaxBar: 55,
  highMaxBar: 120,
  lowColor: '#3b82f6',
  midColor: '#10b981',
  highColor: '#d97706',
  peakColor: '#dc2626',
};

function getSchematicPressureColor(pBar, pcCfg) {
  const pc = { ...DEFAULT_PRESSURE_COLORS, ...(pcCfg || {}) };
  if (pBar < (Number(pc.lowMaxBar) || 5)) return pc.lowColor || '#3b82f6';
  if (pBar < (Number(pc.midMaxBar) || 55)) return pc.midColor || '#10b981';
  if (pBar < (Number(pc.highMaxBar) || 120)) return pc.highColor || '#d97706';
  return pc.peakColor || '#dc2626';
}

function createDefaultPlotTab(id = 'plot_1', title = 'Plot 1', seedChannels = {}) {
  return {
    id,
    title,
    enabledChannels: { ...seedChannels },
    plotGridVisible: true,
    plotGridCols: 8,
    plotGridRows: 4,
    plotGridColor: '#e2e8f0',
    plotTimeMin: '',
    plotTimeMax: '',
    plotYMin: '',
    plotYMax: '',
    datatipWidthPx: 208,
    datatipOpacity: 0.94,
    datatipFontSizePx: 11,
    lineStyles: {},
    datatips: [],
  };
}

function getDynamicRodPortWorldPos(comp, portId, metrics, groupLayouts) {
  if (portId === 'R' && (comp.type === 'cylinder' || comp.type === 'sa_cylinder' || comp.type === 'dr_cylinder')) {
    if (comp.groupId && groupLayouts && groupLayouts[comp.groupId]) {
      return getEffectivePortWorldPos(comp, portId, groupLayouts);
    }
    const p = comp.params || {};
    const strokeMm = p.stroke || (comp.type === 'sa_cylinder' ? 200 : 250);
    const defaultInit = comp.type === 'dr_cylinder' ? 125 : 0;
    const posMm = metrics?.posMm ?? (p.initPos ?? defaultInit);
    const frac = Math.max(0, Math.min(1, posMm / Math.max(1, strokeMm)));
    const localX = comp.type === 'dr_cylinder' ? (74 + frac * 72) : (76 + frac * 76);
    const localY = 0;
    const sc = comp.scale || 1;
    const fx = (comp.flipX ? -1 : 1) * sc;
    const fy = (comp.flipY ? -1 : 1) * sc;
    const lx = localX * fx;
    const ly = localY * fy;
    const rad = ((comp.rotation || 0) * Math.PI) / 180;
    const cos = Math.cos(rad);
    const sin = Math.sin(rad);
    return { x: comp.x + (lx * cos - ly * sin), y: comp.y + (lx * sin + ly * cos) };
  }
  return groupLayouts ? getEffectivePortWorldPos(comp, portId, groupLayouts) : getPortWorldPos(comp, portId);
}

function App() {
  const makeTabSnapshot = useCallback((id, title, desc, comps, conns, hist = [], sState = null, uStack = [], rStack = [], vState = { x: 24, y: 16, zoom: 1 }) => ({
    id,
    title,
    desc,
    components: structuredClone(comps),
    connections: structuredClone(conns),
    history: structuredClone(hist),
    simState: sState ? {
      ...sState,
      pressures: sState.pressures instanceof Float64Array ? Array.from(sState.pressures) : sState.pressures,
      cylinders: structuredClone(sState.cylinders || {}),
      motors: structuredClone(sState.motors || {}),
      accumulators: structuredClone(sState.accumulators || {}),
      spools: structuredClone(sState.spools || {}),
      compMetrics: structuredClone(sState.compMetrics || {}),
      portFlows: structuredClone(sState.portFlows || {}),
      connFlows: structuredClone(sState.connFlows || {}),
    } : null,
    undoStack: structuredClone(uStack),
    redoStack: structuredClone(rStack),
    view: { ...vState },
  }), []);

  const savedInitRef = useRef(null);
  if (savedInitRef.current === null) {
    savedInitRef.current = loadBrowserSavedState() || {};
  }
  const savedInit = savedInitRef.current;

  const initialPlotTabsFromSaved = () => {
    if (Array.isArray(savedInit.plotTabs) && savedInit.plotTabs.length > 0) return savedInit.plotTabs;
    const base = createDefaultPlotTab('plot_1', 'Plot 1', savedInit.enabledChannels || {});
    if (savedInit.plotGridVisible !== undefined) base.plotGridVisible = savedInit.plotGridVisible;
    if (savedInit.plotGridCols !== undefined) base.plotGridCols = savedInit.plotGridCols;
    if (savedInit.plotGridRows !== undefined) base.plotGridRows = savedInit.plotGridRows;
    if (savedInit.plotGridColor !== undefined) base.plotGridColor = savedInit.plotGridColor;
    if (savedInit.plotTimeMin !== undefined) base.plotTimeMin = savedInit.plotTimeMin;
    if (savedInit.plotTimeMax !== undefined) base.plotTimeMax = savedInit.plotTimeMax;
    if (savedInit.lineStyles) base.lineStyles = savedInit.lineStyles;
    if (Array.isArray(savedInit.datatips) && savedInit.datatips.length > 0) base.datatips = savedInit.datatips;
    return [base];
  };

  const [circuitTabs, setCircuitTabs] = useState(() => (
    Array.isArray(savedInit.circuitTabs) && savedInit.circuitTabs.length > 0
      ? savedInit.circuitTabs.map((t) => ({
          ...t,
          simSettings: t.simSettings ? { ...DEFAULT_SIM_SETTINGS, ...t.simSettings } : { ...DEFAULT_SIM_SETTINGS },
          unitPreset: t.unitPreset || 'metric',
          units: t.units ? { ...UNIT_PRESETS.metric, ...t.units } : { ...UNIT_PRESETS.metric },
          plotTabs: Array.isArray(t.plotTabs) && t.plotTabs.length > 0 ? t.plotTabs : [createDefaultPlotTab('plot_1', 'Plot 1', {})],
          activePlotTabId: t.activePlotTabId || (Array.isArray(t.plotTabs) && t.plotTabs[0]?.id) || 'plot_1',
          plotLayout: t.plotLayout || 'single',
          plotLayoutRows: t.plotLayoutRows || 1,
          plotLayoutCols: t.plotLayoutCols || 2,
        }))
      : [{
          id: 'tab_initial',
          title: EXAMPLE_CIRCUITS.doubleActing.name,
          desc: EXAMPLE_CIRCUITS.doubleActing.description,
          components: structuredClone(EXAMPLE_CIRCUITS.doubleActing.components),
          connections: structuredClone(EXAMPLE_CIRCUITS.doubleActing.connections),
          history: [],
          simState: null,
          undoStack: [],
          redoStack: [],
          view: { x: 24, y: 16, zoom: 1 },
          simSettings: savedInit.simSettings ? { ...DEFAULT_SIM_SETTINGS, ...savedInit.simSettings } : { ...DEFAULT_SIM_SETTINGS },
          unitPreset: savedInit.unitPreset || 'metric',
          units: savedInit.units ? { ...UNIT_PRESETS.metric, ...savedInit.units } : { ...UNIT_PRESETS.metric },
          plotTabs: initialPlotTabsFromSaved(),
          activePlotTabId: savedInit.activePlotTabId || 'plot_1',
          plotLayout: savedInit.plotLayout || 'single',
          plotLayoutRows: savedInit.plotLayoutRows || 1,
          plotLayoutCols: savedInit.plotLayoutCols || 2,
        }]
  ));
  const [activeTabId, setActiveTabId] = useState(() => savedInit.activeTabId || 'tab_initial');

  const [components, setComponents] = useState(() => (
    Array.isArray(savedInit.components)
      ? savedInit.components
      : structuredClone(EXAMPLE_CIRCUITS.doubleActing.components)
  ));
  const [connections, setConnections] = useState(() => (
    Array.isArray(savedInit.connections)
      ? savedInit.connections
      : structuredClone(EXAMPLE_CIRCUITS.doubleActing.connections)
  ));
  const [circuitTitle, setCircuitTitle] = useState(() => savedInit.circuitTitle || EXAMPLE_CIRCUITS.doubleActing.name);
  const [circuitDesc, setCircuitDesc] = useState(() => savedInit.circuitDesc || EXAMPLE_CIRCUITS.doubleActing.description);

  const [selectedIds, setSelectedIds] = useState(['v1']);
  const [selectedConnId, setSelectedConnId] = useState(null);
  const [clipboard, setClipboard] = useState(null);
  const [undoStack, setUndoStack] = useState([]);
  const [redoStack, setRedoStack] = useState([]);

  const [toolMode, setToolMode] = useState('select');
  const [pendingPort, setPendingPort] = useState(null);
  const [mouseWorld, setMouseWorld] = useState({ x: 0, y: 0 });
  const [view, setView] = useState({ x: 24, y: 16, zoom: 1 });
  const [dragState, setDragState] = useState(null);
  const [marquee, setMarquee] = useState(null);

  const [searchQuery, setSearchQuery] = useState('');
  const [collapsedCats, setCollapsedCats] = useState(() => ({
  }));
  const [rightTab, setRightTab] = useState('properties');
  const [showExamples, setShowExamples] = useState(false);
  const [showExportMenu, setShowExportMenu] = useState(false);
  const [showSettingsModal, setShowSettingsModal] = useState(false);
  const [signalModal, setSignalModal] = useState(null);
  const [bottomHeight, setBottomHeight] = useState(210);
  const [winState, setWinState] = useState({
    circuit: { min: false, max: false, floating: false, x: 120, y: 120, w: 740, h: 460 },
    plot:    { min: false, max: false, floating: false, x: 180, y: 260, w: 680, h: 280 },
    props:   { min: false, max: false, floating: false, x: 640, y: 130, w: 320, h: 480 },
  });

  const toggleWinFlag = useCallback((panelKey, flag) => {
    setWinState((prev) => {
      const cur = prev[panelKey];
      const next = { ...prev };
      if (flag === 'max') {
        const willMax = !cur.max;
        for (const k of Object.keys(next)) {
          next[k] = { ...next[k], max: k === panelKey ? willMax : false, min: k === panelKey && willMax ? false : next[k].min };
        }
        if (willMax) next[panelKey].floating = false;
      } else if (flag === 'min') {
        next[panelKey] = { ...cur, min: !cur.min, max: false };
      } else if (flag === 'floating') {
        next[panelKey] = { ...cur, floating: !cur.floating, max: false, min: false };
      }
      return next;
    });
  }, []);

  const handleResetLayout = useCallback(() => {
    setWinState({
      circuit: { min: false, max: false, floating: false, x: 120, y: 120, w: 740, h: 460 },
      plot:    { min: false, max: false, floating: false, x: 180, y: 260, w: 680, h: 280 },
      props:   { min: false, max: false, floating: false, x: 640, y: 130, w: 320, h: 480 },
    });
    setBottomHeight(210);
    notify('Workspace layout reset');
  }, [notify]);

  const startFloatDrag = useCallback((e, panelKey) => {
    if (!winState[panelKey]?.floating) return;
    if (e.target.closest('button, input, select')) return;
    e.preventDefault();
    const startX = e.clientX;
    const startY = e.clientY;
    const origX = winState[panelKey].x;
    const origY = winState[panelKey].y;
    const onMove = (ev) => {
      setWinState((prev) => ({
        ...prev,
        [panelKey]: {
          ...prev[panelKey],
          x: Math.max(0, origX + (ev.clientX - startX)),
          y: Math.max(58, origY + (ev.clientY - startY)),
        },
      }));
    };
    const onUp = () => {
      window.removeEventListener('mousemove', onMove);
      window.removeEventListener('mouseup', onUp);
    };
    window.addEventListener('mousemove', onMove);
    window.addEventListener('mouseup', onUp);
  }, [winState]);

  const WinControls = ({ panelKey }) => {
    const st = winState[panelKey];
    return (
      <div className="flex items-center gap-0.5 ml-1" onMouseDown={(e) => e.stopPropagation()}>
        <button type="button" onClick={() => toggleWinFlag(panelKey, 'min')} className="hs-win-btn" title={st.min ? 'Restore' : 'Minimize'}>
          {st.min ? '▢' : '—'}
        </button>
        <button type="button" onClick={() => toggleWinFlag(panelKey, 'floating')} className="hs-win-btn" title={st.floating ? 'Dock back' : 'Undock (float)'}>
          {st.floating ? '⧈' : '⧉'}
        </button>
        <button type="button" onClick={() => toggleWinFlag(panelKey, 'max')} className="hs-win-btn" title={st.max ? 'Restore' : 'Maximize'}>
          {st.max ? '⤡' : '⤢'}
        </button>
      </div>
    );
  };
  const [toast, setToast] = useState(null);

  const [simSettings, setSimSettings] = useState(() => (
    savedInit.simSettings ? { ...DEFAULT_SIM_SETTINGS, ...savedInit.simSettings } : DEFAULT_SIM_SETTINGS
  ));
  const [unitPreset, setUnitPreset] = useState(() => savedInit.unitPreset || 'metric');
  const [units, setUnits] = useState(() => (
    savedInit.units ? { ...UNIT_PRESETS.metric, ...savedInit.units } : UNIT_PRESETS.metric
  ));
  const [paramDrafts, setParamDrafts] = useState({});

  const [simStatus, setSimStatus] = useState('stopped');
  const [history, setHistory] = useState([]);
  const [plotTabs, setPlotTabs] = useState(() => initialPlotTabsFromSaved());
  const [activePlotTabId, setActivePlotTabId] = useState(() => savedInit.activePlotTabId || 'plot_1');
  const [plotLayout, setPlotLayout] = useState(() => savedInit.plotLayout || 'single');
  const [plotLayoutRows, setPlotLayoutRows] = useState(() => savedInit.plotLayoutRows || 1);
  const [plotLayoutCols, setPlotLayoutCols] = useState(() => savedInit.plotLayoutCols || 2);
  const [editingLineKey, setEditingLineKey] = useState(null);
  const [openChannelDropdownId, setOpenChannelDropdownId] = useState(null);
  const [plotCfgPos, setPlotCfgPos] = useState({ x: 340, y: 120 });

  const startPlotCfgDrag = useCallback((e) => {
    if (e.target.closest('button, input, select, label')) return;
    e.preventDefault();
    const startX = e.clientX;
    const startY = e.clientY;
    const origX = plotCfgPos.x;
    const origY = plotCfgPos.y;
    const onMove = (ev) => {
      const vw = typeof window !== 'undefined' ? window.innerWidth : 1200;
      const vh = typeof window !== 'undefined' ? window.innerHeight : 800;
      setPlotCfgPos({
        x: Math.max(8, Math.min(vw - 336, origX + (ev.clientX - startX))),
        y: Math.max(8, Math.min(vh - 120, origY + (ev.clientY - startY))),
      });
    };
    const onUp = () => {
      window.removeEventListener('mousemove', onMove);
      window.removeEventListener('mouseup', onUp);
    };
    window.addEventListener('mousemove', onMove);
    window.addEventListener('mouseup', onUp);
  }, [plotCfgPos]);
  const [hoverTimeFrac, setHoverTimeFrac] = useState(null);

  const availableChannels = useMemo(
    () => buildAvailableChannels(components, units),
    [components, units]
  );

  const activePlotTab = useMemo(
    () => plotTabs.find((pt) => pt.id === activePlotTabId) || plotTabs[0] || createDefaultPlotTab('plot_1', 'Plot 1', {}),
    [plotTabs, activePlotTabId]
  );
  const enabledChannels = activePlotTab.enabledChannels || {};
  const plotGridVisible = activePlotTab.plotGridVisible ?? true;
  const plotGridCols = activePlotTab.plotGridCols ?? 8;
  const plotGridRows = activePlotTab.plotGridRows ?? 4;
  const plotGridColor = activePlotTab.plotGridColor || '#e2e8f0';
  const plotTimeMin = activePlotTab.plotTimeMin ?? '';
  const plotTimeMax = activePlotTab.plotTimeMax ?? '';
  const lineStyles = activePlotTab.lineStyles || {};
  const datatips = activePlotTab.datatips || [];

  const updatePlotTabById = useCallback((ptId, updater) => {
    setPlotTabs((prev) =>
      prev.map((pt) => (pt.id === ptId ? (typeof updater === 'function' ? updater(pt) : { ...pt, ...updater }) : pt))
    );
  }, []);

  const updateActivePlotTab = useCallback((updater) => {
    updatePlotTabById(activePlotTab.id, updater);
  }, [activePlotTab.id, updatePlotTabById]);

  const setEnabledChannels = useCallback((updater) => {
    updateActivePlotTab((pt) => ({
      ...pt,
      enabledChannels: typeof updater === 'function' ? updater(pt.enabledChannels || {}) : updater,
    }));
  }, [updateActivePlotTab]);
  const setPlotGridVisible = useCallback((updater) => {
    updateActivePlotTab((pt) => ({
      ...pt,
      plotGridVisible: typeof updater === 'function' ? updater(pt.plotGridVisible ?? true) : updater,
    }));
  }, [updateActivePlotTab]);
  const setPlotGridCols = useCallback((v) => updateActivePlotTab({ plotGridCols: v }), [updateActivePlotTab]);
  const setPlotGridRows = useCallback((v) => updateActivePlotTab({ plotGridRows: v }), [updateActivePlotTab]);
  const setPlotGridColor = useCallback((v) => updateActivePlotTab({ plotGridColor: v }), [updateActivePlotTab]);
  const setPlotTimeMin = useCallback((v) => updateActivePlotTab({ plotTimeMin: v }), [updateActivePlotTab]);
  const setPlotTimeMax = useCallback((v) => updateActivePlotTab({ plotTimeMax: v }), [updateActivePlotTab]);
  const setLineStyles = useCallback((updater) => {
    updateActivePlotTab((pt) => ({
      ...pt,
      lineStyles: typeof updater === 'function' ? updater(pt.lineStyles || {}) : updater,
    }));
  }, [updateActivePlotTab]);
  const setDatatips = useCallback((updater) => {
    updateActivePlotTab((pt) => ({
      ...pt,
      datatips: typeof updater === 'function' ? updater(pt.datatips || []) : updater,
    }));
  }, [updateActivePlotTab]);

  const handleAddPlotTab = useCallback(() => {
    const nextIdx = plotTabs.length + 1;
    const newId = `plot_${Date.now().toString(36)}_${nextIdx}`;
    const seed = {};
    if (availableChannels[nextIdx - 1]) {
      seed[availableChannels[nextIdx - 1].id] = true;
    } else if (availableChannels[0]) {
      seed[availableChannels[0].id] = true;
    }
    const newTab = createDefaultPlotTab(newId, `Plot ${nextIdx}`, seed);
    setPlotTabs((prev) => [...prev, newTab]);
    setActivePlotTabId(newId);
    if (plotLayoutRows * plotLayoutCols < nextIdx) {
      if (nextIdx <= 2) { setPlotLayoutRows(1); setPlotLayoutCols(2); }
      else if (nextIdx <= 4) { setPlotLayoutRows(2); setPlotLayoutCols(2); }
      else { setPlotLayoutCols(Math.ceil(nextIdx / plotLayoutRows)); }
    }
    setEditingLineKey(null);
  }, [plotTabs.length, availableChannels, plotLayoutRows, plotLayoutCols]);

  const handleClosePlotTab = useCallback((e, ptId) => {
    e.stopPropagation();
    if (plotTabs.length <= 1) {
      const fresh = createDefaultPlotTab('plot_1', 'Plot 1', {});
      setPlotTabs([fresh]);
      setActivePlotTabId('plot_1');
      setEditingLineKey(null);
      return;
    }
    const idx = plotTabs.findIndex((p) => p.id === ptId);
    const rem = plotTabs.filter((p) => p.id !== ptId);
    setPlotTabs(rem);
    if (ptId === activePlotTabId) {
      const fallback = rem[Math.max(0, idx - 1)] || rem[0];
      setActivePlotTabId(fallback.id);
    }
    setEditingLineKey(null);
  }, [plotTabs, activePlotTabId]);

  const svgCanvasRef = useRef(null);
  const fileInputRef = useRef(null);
  const toastTimerRef = useRef(null);


  useEffect(() => {
    const updatedTabs = circuitTabs.map((t) =>
      t.id === activeTabId
        ? {
            ...t,
            title: circuitTitle,
            desc: circuitDesc,
            components,
            connections,
            view,
            simSettings,
            unitPreset,
            units,
            plotTabs,
            activePlotTabId,
            plotLayout,
            plotLayoutRows,
            plotLayoutCols,
          }
        : t
    );
    saveBrowserSavedState({
      circuitTabs: updatedTabs,
      activeTabId,
      components,
      connections,
      circuitTitle,
      circuitDesc,
      simSettings,
      unitPreset,
      units,
      plotTabs,
      activePlotTabId,
      plotLayout,
      plotLayoutRows,
      plotLayoutCols,
    });
  }, [
    circuitTabs, activeTabId, components, connections, circuitTitle, circuitDesc,
    view, simSettings, unitPreset, units, plotTabs, activePlotTabId, plotLayout, plotLayoutRows, plotLayoutCols,
  ]);

  const notify = useCallback((msg) => {
    setToast(msg);
    if (toastTimerRef.current) clearTimeout(toastTimerRef.current);
    toastTimerRef.current = setTimeout(() => setToast(null), 2600);
  }, []);

  const [portToNode, setPortToNode] = useState({});
  const topology = useMemo(() => ({ portToNode }), [portToNode]);
  const groupLayouts = useMemo(() => buildGroupLayouts(components, connections), [components, connections]);
  const [simState, setSimState] = useState(() => createEmptyClientState(simSettings.startTime));
  const [diagnostics, setDiagnostics] = useState([]);



  useEffect(() => {
    setPlotTabs((prevTabs) =>
      prevTabs.map((pt, tabIdx) => {
        const prev = pt.enabledChannels || {};
        const next = {};
        let any = false;
        for (const ch of availableChannels) {
          if (prev[ch.id]) { next[ch.id] = true; any = true; }
        }
        if (!any && availableChannels.length > 0) {
          const preferred = availableChannels.filter((c) => c.id.endsWith(':p') || c.id.endsWith(':pos') || c.id.endsWith(':rpm') || c.id.endsWith(':fill'));
          const pool = preferred.length > 0 ? preferred : availableChannels;
          if (tabIdx === 0) {
            for (const p of pool.slice(0, 3)) next[p.id] = true;
          } else {
            const pick = pool[tabIdx % pool.length] || availableChannels[tabIdx % availableChannels.length];
            if (pick) next[pick.id] = true;
          }
        }
        return { ...pt, enabledChannels: next };
      })
    );
  }, [availableChannels]);

  const simStateRef = useRef(simState);
  simStateRef.current = simState;
  const simSettingsRef = useRef(simSettings);
  simSettingsRef.current = simSettings;
  const componentsRef = useRef(components);
  componentsRef.current = components;
  const connectionsRef = useRef(connections);
  connectionsRef.current = connections;
  const topologyRef = useRef(topology);
  topologyRef.current = topology;
  const channelsRef = useRef(availableChannels);
  channelsRef.current = availableChannels;

  // Sync initial diagnostics & topology from backend when circuit changes while stopped
  useEffect(() => {
    if (simStatus !== 'stopped') return;
    let cancelled = false;
    fetch('/api/simulate', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ action: 'init', components, connections, simSettings: simSettingsRef.current, units }),
    })
      .then((r) => (r.ok ? r.json() : null))
      .then((data) => {
        if (!cancelled && data && data.state) {
          simStateRef.current = data.state;
          setSimState(data.state);
          setPortToNode(data.portToNode || {});
          setDiagnostics(data.diagnostics || []);
        }
      })
      .catch(() => {});
    return () => { cancelled = true; };
  }, [components, connections, simStatus, units]);

  // --- Undo / Redo Stack ---
  const undoStackRef = useRef(undoStack);
  undoStackRef.current = undoStack;
  const redoStackRef = useRef(redoStack);
  redoStackRef.current = redoStack;

  const pushUndo = useCallback((snapComps, snapConns) => {
    const entry = {
      components: structuredClone(snapComps ?? componentsRef.current),
      connections: structuredClone(snapConns ?? connectionsRef.current),
    };
    setUndoStack((prev) => [...prev.slice(-(MAX_UNDO_STEPS - 1)), entry]);
    setRedoStack([]);
  }, []);

  const handleUndo = useCallback(() => {
    const stack = undoStackRef.current;
    if (stack.length === 0) return;
    const last = stack[stack.length - 1];
    const currentSnap = { components: structuredClone(componentsRef.current), connections: structuredClone(connectionsRef.current) };
    setUndoStack(stack.slice(0, -1));
    setRedoStack((r) => [...r.slice(-(MAX_UNDO_STEPS - 1)), currentSnap]);
    setComponents(last.components);
    setConnections(last.connections);
    setSelectedIds([]);
    setSelectedConnId(null);
    notify('Undo');
  }, [notify]);

  const handleRedo = useCallback(() => {
    const stack = redoStackRef.current;
    if (stack.length === 0) return;
    const next = stack[stack.length - 1];
    const currentSnap = { components: structuredClone(componentsRef.current), connections: structuredClone(connectionsRef.current) };
    setRedoStack(stack.slice(0, -1));
    setUndoStack((u) => [...u.slice(-(MAX_UNDO_STEPS - 1)), currentSnap]);
    setComponents(next.components);
    setConnections(next.connections);
    setSelectedIds([]);
    setSelectedConnId(null);
    notify('Redo');
  }, [notify]);

  // --- Backend-Driven Simulation Loop (Zero physics in browser) ---
  useEffect(() => {
    if (simStatus !== 'running') return;
    let active = true;
    let timerId = null;

    const stepBackend = async () => {
      if (!active) return;
      const cfg = simSettingsRef.current;
      const tStart = Number(cfg.startTime) || 0;
      const tEnd = Number(cfg.endTime) || 0;
      const totalTime = tEnd > tStart ? (tEnd - tStart) : (tEnd === 0 ? 10 : Math.max(0.1, tEnd));
      const numSteps = Math.max(1, parseInt(cfg.numSteps, 10) || 200);
      const baseDt = totalTime / numSteps;
      let dt = baseDt * (cfg.simSpeed || 1.0);
      if (tEnd > 0 && simStateRef.current.time + dt > tEnd) {
        dt = Math.max(1e-6, tEnd - simStateRef.current.time);
      }
      try {
        const res = await fetch('/api/simulate', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            action: 'step',
            components: componentsRef.current,
            connections: connectionsRef.current,
            state: simStateRef.current,
            dt,
            simSettings: cfg,
            units,
          }),
        });
        if (!res.ok) throw new Error('Backend simulation error');
        const data = await res.json();
        if (!active) return;

        const nextState = data.state;
        simStateRef.current = nextState;
        setSimState(nextState);
        if (data.portToNode) setPortToNode(data.portToNode);
        if (data.diagnostics) setDiagnostics(data.diagnostics);

        const values = {};
        for (const ch of channelsRef.current) {
          if (ch.compId === '__sys__') {
            values[ch.id] = nextState[ch.metric] ?? 0;
          } else {
            values[ch.id] = nextState.compMetrics[ch.compId]?.[ch.metric] ?? 0;
          }
        }
        setHistory((prev) => {
          const next = prev.length >= MAX_HISTORY_POINTS ? prev.slice(prev.length - MAX_HISTORY_POINTS + 1) : prev;
          return [...next, { t: nextState.time, values }];
        });

        if (cfg.endTime > 0 && nextState.time >= cfg.endTime - 1e-9) {
          setSimStatus('paused');
          notify(`Reached configured end time (${cfg.endTime} s)`);
          return;
        }
      } catch (err) {
        if (active) {
          setSimStatus('paused');
          notify('Backend solver unreachable — check Vercel /api/simulate');
        }
        return;
      }
      const pollMs = Math.max(20, Math.min(120, Math.round(baseDt * 1000)));
      if (active) timerId = setTimeout(stepBackend, pollMs);
    };

    stepBackend();
    return () => { active = false; if (timerId) clearTimeout(timerId); };
  }, [simStatus, units, notify]);

  const handleRun = useCallback(() => {
    const errors = diagnostics.filter((d) => d.severity === 'error');
    if (errors.length > 0 && simStatus === 'stopped') {
      setRightTab('diagnostics');
      notify(`Cannot start: ${errors[0].title}`);
      return;
    }
    setSimStatus('running');
  }, [diagnostics, simStatus, notify]);

  const handlePause = useCallback(() => setSimStatus('paused'), []);

  const handleStopReset = useCallback(() => {
    setSimStatus('stopped');
    const fresh = createEmptyClientState(simSettingsRef.current.startTime);
    simStateRef.current = fresh;
    setSimState(fresh);
    setHistory([]);
  }, []);

  const loadExample = (key) => {
    const ex = EXAMPLE_CIRCUITS[key];
    if (!ex) return;
    pushUndo();
    setSimStatus('stopped');
    const newComps = structuredClone(ex.components);
    const newConns = structuredClone(ex.connections);
    setComponents(newComps);
    setConnections(newConns);
    setCircuitTitle(ex.name);
    setCircuitDesc(ex.description);
    const fresh = createEmptyClientState(simSettings.startTime);
    simStateRef.current = fresh;
    setSimState(fresh);
    setHistory([]);
    const exPlot = createDefaultPlotTab('plot_1', 'Plot 1', {});
    setPlotTabs([exPlot]);
    setActivePlotTabId('plot_1');
    setPlotLayout('single');
    setEditingLineKey(null);
    setSelectedIds(newComps[0] ? [newComps[0].id] : []);
    setSelectedConnId(null);
    setShowExamples(false);
    setView({ x: 24, y: 16, zoom: 1 });
    notify(`Loaded ${ex.name}`);
  };

  const saveCurrentToTabs = useCallback((overrideTitle, overrideDesc) => {
    setCircuitTabs((prev) =>
      prev.map((t) =>
        t.id === activeTabId
          ? {
              ...t,
              title: overrideTitle ?? circuitTitle,
              desc: overrideDesc ?? circuitDesc,
              components: structuredClone(componentsRef.current),
              connections: structuredClone(connectionsRef.current),
              history: structuredClone(history),
              simState: simStateRef.current,
              undoStack: structuredClone(undoStackRef.current),
              redoStack: structuredClone(redoStackRef.current),
              view: { ...view },
            }
          : t
      )
    );
  }, [activeTabId, circuitTitle, circuitDesc, history, view]);

  const handleSwitchCircuitTab = useCallback((targetTabId) => {
    if (targetTabId === activeTabId) return;
    setSimStatus('stopped');
    const currentSnap = {
      components: structuredClone(componentsRef.current),
      connections: structuredClone(connectionsRef.current),
      history: structuredClone(history),
      simState: simStateRef.current,
      undoStack: structuredClone(undoStackRef.current),
      redoStack: structuredClone(redoStackRef.current),
      view: { ...view },
      simSettings: { ...simSettingsRef.current },
      unitPreset,
      units: { ...units },
      plotTabs: structuredClone(plotTabs),
      activePlotTabId,
      plotLayout,
      plotLayoutRows,
      plotLayoutCols,
    };
    const nextTab = circuitTabs.find((t) => t.id === targetTabId);
    if (!nextTab) return;

    setCircuitTabs((prev) => prev.map((t) => (t.id === activeTabId ? { ...t, ...currentSnap, title: circuitTitle, desc: circuitDesc } : t)));
    setActiveTabId(nextTab.id);
    setComponents(structuredClone(nextTab.components || []));
    setConnections(structuredClone(nextTab.connections || []));
    setCircuitTitle(nextTab.title || 'Untitled Hydraulic Circuit');
    setCircuitDesc(nextTab.desc || '');
    setHistory(structuredClone(nextTab.history || []));
    setUndoStack(structuredClone(nextTab.undoStack || []));
    setRedoStack(structuredClone(nextTab.redoStack || []));
    setView(nextTab.view ? { ...nextTab.view } : { x: 24, y: 16, zoom: 1 });
    const nextSettings = nextTab.simSettings ? { ...DEFAULT_SIM_SETTINGS, ...nextTab.simSettings } : { ...DEFAULT_SIM_SETTINGS };
    setSimSettings(nextSettings);
    setUnitPreset(nextTab.unitPreset || 'metric');
    setUnits(nextTab.units ? { ...UNIT_PRESETS.metric, ...nextTab.units } : { ...UNIT_PRESETS.metric });
    const nextPlots = Array.isArray(nextTab.plotTabs) && nextTab.plotTabs.length > 0
      ? structuredClone(nextTab.plotTabs)
      : [createDefaultPlotTab('plot_1', 'Plot 1', {})];
    setPlotTabs(nextPlots);
    setActivePlotTabId(nextTab.activePlotTabId || nextPlots[0].id);
    setPlotLayout(nextTab.plotLayout || 'single');
    setPlotLayoutRows(nextTab.plotLayoutRows || 1);
    setPlotLayoutCols(nextTab.plotLayoutCols || 2);
    setEditingLineKey(null);
    setSelectedIds([]);
    setSelectedConnId(null);
    const restoredState = nextTab.simState || createEmptyClientState(nextSettings.startTime);
    simStateRef.current = restoredState;
    setSimState(restoredState);
  }, [activeTabId, circuitTabs, circuitTitle, circuitDesc, history, view, unitPreset, units, plotTabs, activePlotTabId, plotLayout, plotLayoutRows, plotLayoutCols]);

  const handleCloseCircuitTab = useCallback((e, targetTabId) => {
    e.stopPropagation();
    if (circuitTabs.length <= 1) {
      const freshId = `tab_${Date.now().toString(36)}_1`;
      const freshTitle = 'Circuit 1';
      const freshDesc = 'Drag components from the left library onto the canvas and click ports to connect hydraulic lines.';
      const freshPlot = createDefaultPlotTab('plot_1', 'Plot 1', {});
      const freshTab = {
        id: freshId,
        title: freshTitle,
        desc: freshDesc,
        components: [],
        connections: [],
        history: [],
        simState: null,
        undoStack: [],
        redoStack: [],
        view: { x: 24, y: 16, zoom: 1 },
        simSettings: { ...DEFAULT_SIM_SETTINGS },
        unitPreset: 'metric',
        units: { ...UNIT_PRESETS.metric },
        plotTabs: [freshPlot],
        activePlotTabId: 'plot_1',
        plotLayout: 'single',
      };
      setSimStatus('stopped');
      setCircuitTabs([freshTab]);
      setActiveTabId(freshId);
      setComponents([]);
      setConnections([]);
      setCircuitTitle(freshTitle);
      setCircuitDesc(freshDesc);
      setHistory([]);
      setUndoStack([]);
      setRedoStack([]);
      setView({ x: 24, y: 16, zoom: 1 });
      setSimSettings({ ...DEFAULT_SIM_SETTINGS });
      setUnitPreset('metric');
      setUnits({ ...UNIT_PRESETS.metric });
      setPlotTabs([freshPlot]);
      setActivePlotTabId('plot_1');
      setPlotLayout('single');
      setEditingLineKey(null);
      setSelectedIds([]);
      setSelectedConnId(null);
      const freshState = createEmptyClientState(DEFAULT_SIM_SETTINGS.startTime);
      simStateRef.current = freshState;
      setSimState(freshState);
      notify('Closed tab and opened fresh workspace');
      return;
    }
    const idx = circuitTabs.findIndex((t) => t.id === targetTabId);
    const remaining = circuitTabs.filter((t) => t.id !== targetTabId);
    setCircuitTabs(remaining);
    if (targetTabId === activeTabId) {
      const fallback = remaining[Math.max(0, idx - 1)] || remaining[0];
      setSimStatus('stopped');
      setActiveTabId(fallback.id);
      setComponents(structuredClone(fallback.components || []));
      setConnections(structuredClone(fallback.connections || []));
      setCircuitTitle(fallback.title || 'Untitled Hydraulic Circuit');
      setCircuitDesc(fallback.desc || '');
      setHistory(structuredClone(fallback.history || []));
      setUndoStack(structuredClone(fallback.undoStack || []));
      setRedoStack(structuredClone(fallback.redoStack || []));
      setView(fallback.view ? { ...fallback.view } : { x: 24, y: 16, zoom: 1 });
      const fbSettings = fallback.simSettings ? { ...DEFAULT_SIM_SETTINGS, ...fallback.simSettings } : { ...DEFAULT_SIM_SETTINGS };
      setSimSettings(fbSettings);
      setUnitPreset(fallback.unitPreset || 'metric');
      setUnits(fallback.units ? { ...UNIT_PRESETS.metric, ...fallback.units } : { ...UNIT_PRESETS.metric });
      const fbPlots = Array.isArray(fallback.plotTabs) && fallback.plotTabs.length > 0
        ? structuredClone(fallback.plotTabs)
        : [createDefaultPlotTab('plot_1', 'Plot 1', {})];
      setPlotTabs(fbPlots);
      setActivePlotTabId(fallback.activePlotTabId || fbPlots[0].id);
      setPlotLayout(fallback.plotLayout || 'single');
      setPlotLayoutRows(fallback.plotLayoutRows || 1);
      setPlotLayoutCols(fallback.plotLayoutCols || 2);
      setEditingLineKey(null);
      setSelectedIds([]);
      setSelectedConnId(null);
      const restoredState = fallback.simState || createEmptyClientState(fbSettings.startTime);
      simStateRef.current = restoredState;
      setSimState(restoredState);
    }
  }, [circuitTabs, activeTabId, notify]);

  const handleNewCircuit = () => {
    setSimStatus('stopped');
    const currentSnap = {
      components: structuredClone(componentsRef.current),
      connections: structuredClone(connectionsRef.current),
      history: structuredClone(history),
      simState: simStateRef.current,
      undoStack: structuredClone(undoStackRef.current),
      redoStack: structuredClone(redoStackRef.current),
      view: { ...view },
      simSettings: { ...simSettingsRef.current },
      unitPreset,
      units: { ...units },
      plotTabs: structuredClone(plotTabs),
      activePlotTabId,
      plotLayout,
      plotLayoutRows,
      plotLayoutCols,
    };
    const nextNum = circuitTabs.length + 1;
    const newTabId = `tab_${Date.now().toString(36)}_${nextNum}`;
    const newTitle = `Circuit ${nextNum}`;
    const newDesc = 'Drag components from the left library onto the canvas and click ports to connect hydraulic lines.';
    const freshPlot = createDefaultPlotTab('plot_1', 'Plot 1', {});
    const newTab = {
      id: newTabId,
      title: newTitle,
      desc: newDesc,
      components: [],
      connections: [],
      history: [],
      simState: null,
      undoStack: [],
      redoStack: [],
      view: { x: 24, y: 16, zoom: 1 },
      simSettings: { ...DEFAULT_SIM_SETTINGS },
      unitPreset: 'metric',
      units: { ...UNIT_PRESETS.metric },
      plotTabs: [freshPlot],
      activePlotTabId: 'plot_1',
      plotLayout: 'single',
    };

    setCircuitTabs((prev) => [
      ...prev.map((t) => (t.id === activeTabId ? { ...t, ...currentSnap, title: circuitTitle, desc: circuitDesc } : t)),
      newTab,
    ]);
    setActiveTabId(newTabId);
    setComponents([]);
    setConnections([]);
    setCircuitTitle(newTitle);
    setCircuitDesc(newDesc);
    setHistory([]);
    setUndoStack([]);
    setRedoStack([]);
    setView({ x: 24, y: 16, zoom: 1 });
    setSimSettings({ ...DEFAULT_SIM_SETTINGS });
    setUnitPreset('metric');
    setUnits({ ...UNIT_PRESETS.metric });
    setPlotTabs([freshPlot]);
    setActivePlotTabId('plot_1');
    setPlotLayout('single');
    setEditingLineKey(null);
    setSelectedIds([]);
    setSelectedConnId(null);
    const fresh = createEmptyClientState(DEFAULT_SIM_SETTINGS.startTime);
    simStateRef.current = fresh;
    setSimState(fresh);
    notify(`Opened "${newTitle}" in a new tab`);
  };

  const handleSaveJSON = () => {
    const payload = { app: 'HydroSim', version: '2.0', name: circuitTitle, components, connections, simSettings, units };
    const blob = new Blob([JSON.stringify(payload, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'hydrosim-circuit.json';
    a.click();
    URL.revokeObjectURL(url);
    notify('Saved circuit JSON');
  };

  const handleLoadJSON = (e) => {
    const file = e.target.files?.[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = (ev) => {
      try {
        const data = JSON.parse(ev.target.result);
        if (!Array.isArray(data.components) || !Array.isArray(data.connections)) throw new Error('Invalid HydroSim JSON format');
        pushUndo();
        setSimStatus('stopped');
        setComponents(data.components);
        setConnections(data.connections);
        setCircuitTitle(data.name || file.name);
        setCircuitDesc('Loaded from JSON file.');
        setHistory([]);
        setEnabledChannels({});
        setSelectedIds([]);
        setSelectedConnId(null);
        notify(`Loaded ${file.name}`);
      } catch (err) {
        notify(`Load error: ${err.message}`);
      }
    };
    reader.readAsText(file);
    e.target.value = '';
  };

  const handleExportCSV = () => {
    setShowExportMenu(false);
    if (history.length === 0) { notify('Run the simulation first to record CSV data'); return; }
    const headers = ['time_s', ...availableChannels.map((c) => `${c.label.replace(/\s+/g, '_')}_${c.unit}`)];
    const rows = history.map((pt) => [
      pt.t.toFixed(4),
      ...availableChannels.map((c) => convertToDisplay(pt.values[c.id] ?? 0, c.unitType, units).toFixed(3)),
    ].join(','));
    const blob = new Blob([[headers.join(','), ...rows].join('\n')], { type: 'text/csv' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'hydrosim-telemetry.csv';
    a.click();
    URL.revokeObjectURL(url);
    notify(`Exported ${history.length} samples to CSV`);
  };

  const buildExportSVGString = useCallback(() => {
    const svgEl = svgCanvasRef.current;
    if (!svgEl || components.length === 0) return null;
    let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
    for (const c of components) {
      const def = COMPONENT_CATALOG[c.type];
      const hw = (def?.width || 80) / 2 + 45;
      const hh = (def?.height || 60) / 2 + 55;
      minX = Math.min(minX, c.x - hw);
      minY = Math.min(minY, c.y - hh);
      maxX = Math.max(maxX, c.x + hw);
      maxY = Math.max(maxY, c.y + hh);
    }
    const pad = 40;
    const x0 = Math.floor(minX - pad);
    const y0 = Math.floor(minY - pad);
    const w = Math.max(600, Math.ceil(maxX - minX + pad * 2));
    const h = Math.max(400, Math.ceil(maxY - minY + pad * 2 + 48));
    const contentGroup = svgEl.querySelector('#hydrasim-scene-root');
    if (!contentGroup) return null;
    const dateStr = new Date().toLocaleDateString();
    return {
      width: w,
      height: h,
      svg: `<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}" viewBox="${x0} ${y0} ${w} ${h}">
  <defs><pattern id="export-grid" width="20" height="20" patternUnits="userSpaceOnUse"><path d="M 20 0 L 0 0 0 20" fill="none" stroke="#e2e8f0" stroke-width="0.8"/></pattern></defs>
  <rect x="${x0}" y="${y0}" width="${w}" height="${h}" fill="#f8fafc"/>
  <rect x="${x0}" y="${y0}" width="${w}" height="${h}" fill="url(#export-grid)"/>
  <g font-family="ui-sans-serif, system-ui, sans-serif">${contentGroup.innerHTML}</g>
  <g transform="translate(${x0 + w - 290}, ${y0 + h - 54})">
    <rect x="0" y="0" width="276" height="42" rx="4" fill="#ffffff" stroke="#94a3b8" stroke-width="1"/>
    <text x="10" y="17" font-size="11" font-weight="700" fill="#0f172a" font-family="sans-serif">${circuitTitle.replace(/[<>&]/g, '')}</text>
    <text x="10" y="33" font-size="9.5" fill="#64748b" font-family="monospace">HydroSim ISO 1219 · ${dateStr}</text>
  </g>
</svg>`,
    };
  }, [components, circuitTitle]);

  const handleExportSVG = () => {
    setShowExportMenu(false);
    const out = buildExportSVGString();
    if (!out) { notify('Add components before exporting SVG'); return; }
    const blob = new Blob([out.svg], { type: 'image/svg+xml;charset=utf-8' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'hydrosim-schematic.svg';
    a.click();
    URL.revokeObjectURL(url);
    notify('Exported schematic as SVG');
  };

  const handleExportPNG = () => {
    setShowExportMenu(false);
    const out = buildExportSVGString();
    if (!out) { notify('Add components before exporting PNG'); return; }
    const img = new window.Image();
    const blob = new Blob([out.svg], { type: 'image/svg+xml;charset=utf-8' });
    const url = URL.createObjectURL(blob);
    img.onload = () => {
      const canvas = document.createElement('canvas');
      canvas.width = out.width * 2;
      canvas.height = out.height * 2;
      const ctx = canvas.getContext('2d');
      ctx.scale(2, 2);
      ctx.fillStyle = '#f8fafc';
      ctx.fillRect(0, 0, out.width, out.height);
      ctx.drawImage(img, 0, 0);
      URL.revokeObjectURL(url);
      canvas.toBlob((pngBlob) => {
        if (!pngBlob) return;
        const pUrl = URL.createObjectURL(pngBlob);
        const a = document.createElement('a');
        a.href = pUrl;
        a.download = 'hydrosim-schematic.png';
        a.click();
        URL.revokeObjectURL(pUrl);
        notify('Exported schematic as high-res PNG');
      });
    };
    img.src = url;
  };

  const handleExportChartPNG = () => {
    setShowExportMenu(false);
    const plotBody = document.getElementById('hydrasim-plot-body');
    if (!plotBody || history.length < 2) {
      notify('Run the simulation first to export the Plot Window PNG');
      return;
    }
    const visibleTabs = plotLayout === 'sideBySide'
      ? plotTabs.slice(0, Math.max(1, plotLayoutRows * plotLayoutCols))
      : [activePlotTab];
    const bodyRect = plotBody.getBoundingClientRect();
    const totalW = Math.max(360, Math.round(bodyRect.width));
    const cols = plotLayout === 'sideBySide' && visibleTabs.length > 1 ? Math.max(1, plotLayoutCols) : 1;
    const rows = plotLayout === 'sideBySide' && visibleTabs.length > 1 ? Math.max(1, plotLayoutRows) : 1;
    const titleBarH = 26;

    const dashAttr = (d) =>
      d === 'dashed' ? ' stroke-dasharray="7 4"'
      : d === 'dotted' ? ' stroke-dasharray="2 4"'
      : d === 'dashdot' ? ' stroke-dasharray="8 3 2 3"'
      : '';

    const panesData = visibleTabs.map((pt, idx) => {
      const svgEl = document.getElementById(idx === 0 ? 'hydrasim-oscilloscope-svg' : `hydrasim-oscilloscope-svg-${pt.id}`);
      const r = svgEl ? svgEl.getBoundingClientRect() : { width: Math.floor(totalW / cols), height: 180 };
      const chartW = Math.max(240, Math.round(r.width));
      const chartH = Math.max(110, Math.round(r.height));
      const ptEnabled = pt.enabledChannels || {};
      const ptStyles = pt.lineStyles || {};
      const activeCh = availableChannels.filter((c) => ptEnabled[c.id]).map((ch) => ({
        ...ch,
        color: ptStyles[ch.id]?.color || ch.color,
        dash: ptStyles[ch.id]?.dash || 'solid',
      }));
      const legCols = Math.max(1, Math.floor((chartW - 24) / 185));
      const legRows = Math.max(1, Math.ceil(activeCh.length / legCols));
      const legH = 20 + legRows * 16;
      return { pt, idx, svgEl, chartW, chartH, activeCh, legCols, legH, paneH: legH + chartH };
    });

    const rowHeights = Array.from({ length: rows }, (_, rIdx) => {
      let maxH = 160;
      for (let cIdx = 0; cIdx < cols; cIdx++) {
        const p = panesData[rIdx * cols + cIdx];
        if (p && p.paneH > maxH) maxH = p.paneH;
      }
      return maxH;
    });
    const colWidth = Math.floor(totalW / cols);
    const totalH = titleBarH + rowHeights.reduce((a, b) => a + b, 0);

    const panesXml = panesData.map((pd) => {
      const rIdx = Math.floor(pd.idx / cols);
      const cIdx = pd.idx % cols;
      const ox = cIdx * colWidth;
      const oy = titleBarH + rowHeights.slice(0, rIdx).reduce((a, b) => a + b, 0);
      const pw = pd.chartW;
      const ph = pd.chartH;

      const legendItems = pd.activeCh.map((ch, i) => {
        const lx = 12 + (i % pd.legCols) * Math.floor((pw - 24) / pd.legCols);
        const ly = 28 + Math.floor(i / pd.legCols) * 16;
        return `<g transform="translate(${lx}, ${ly})"><line x1="0" y1="-3" x2="12" y2="-3" stroke="${ch.color}" stroke-width="2.2"${dashAttr(ch.dash)}/><text x="16" y="0" font-size="9.5" font-family="monospace, sans-serif" fill="#1e293b">${ch.label.replace(/[<>&]/g, '')} (${ch.unit})</text></g>`;
      }).join('');

      const rawT0 = history[0].t;
      const rawT1 = Math.max(rawT0 + 1e-6, history[history.length - 1].t);
      const t0 = (pd.pt.plotTimeMin !== '' && pd.pt.plotTimeMin !== undefined && Number.isFinite(parseFloat(pd.pt.plotTimeMin))) ? parseFloat(pd.pt.plotTimeMin) : rawT0;
      const t1 = Math.max(t0 + 1e-6, (pd.pt.plotTimeMax !== '' && pd.pt.plotTimeMax !== undefined && Number.isFinite(parseFloat(pd.pt.plotTimeMax))) ? parseFloat(pd.pt.plotTimeMax) : rawT1);
      const pLeft = 54, pRight = 18, pTop = 12, pBottom = 34;
      const innerW = Math.max(40, pw - pLeft - pRight);
      const innerH = Math.max(36, ph - pTop - pBottom);

      const tipSvgs = (pd.pt.datatips || []).map((tip) => {
        const tTarget = t0 + Math.max(0, Math.min(1, tip.fracT)) * (t1 - t0);
        let bestPt = history[0];
        let bestD = Math.abs(history[0].t - tTarget);
        for (const pt of history) {
          const d = Math.abs(pt.t - tTarget);
          if (d < bestD) { bestD = d; bestPt = pt; }
        }
        const xLine = pLeft + ((bestPt.t - t0) / (t1 - t0)) * innerW;
        const boxW = 192;
        const boxH = 22 + pd.activeCh.length * 14;
        const bx = Math.max(4, Math.min(pw - boxW - 4, tip.boxX ?? (xLine + 10)));
        const by = Math.max(4, Math.min(ph - boxH - 4, tip.boxY ?? 10));
        const rowsXml = pd.activeCh.map((ch, idx) => {
          const val = convertToDisplay(bestPt.values[ch.id] ?? 0, ch.unitType, units);
          const ry = by + 26 + idx * 14;
          return `<circle cx="${bx + 12}" cy="${ry - 3}" r="3.5" fill="${ch.color}"/><text x="${bx + 20}" y="${ry}" font-size="9" font-family="monospace, sans-serif" fill="#e2e8f0">${ch.label.replace(/[<>&]/g, '')}</text><text x="${bx + boxW - 8}" y="${ry}" text-anchor="end" font-size="9" font-weight="700" font-family="monospace, sans-serif" fill="#38bdf8">${val.toFixed(2)} ${ch.unit}</text>`;
        }).join('');
        return `<g><line x1="${xLine.toFixed(1)}" y1="${pTop}" x2="${xLine.toFixed(1)}" y2="${pTop + innerH}" stroke="#0284c7" stroke-width="1.4" stroke-dasharray="4 2"/><circle cx="${xLine.toFixed(1)}" cy="${pTop + 6}" r="3.5" fill="#0284c7"/><rect x="${bx.toFixed(1)}" y="${by.toFixed(1)}" width="${boxW}" height="${boxH}" rx="4" fill="#1c2736" fill-opacity="0.95" stroke="#384961" stroke-width="1"/><text x="${bx + 8}" y="${by + 13}" font-size="9" font-weight="700" font-family="monospace, sans-serif" fill="#cbd5e1">t = ${bestPt.t.toFixed(3)} s</text><line x1="${bx + 6}" y1="${by + 17}" x2="${bx + boxW - 6}" y2="${by + 17}" stroke="#334155" stroke-width="0.8"/>${rowsXml}</g>`;
      }).join('');

      return `<g transform="translate(${ox}, ${oy})">
        <rect x="0" y="0" width="${colWidth}" height="${rowHeights[rIdx]}" fill="#ffffff" stroke="#cbd5e1" stroke-width="1"/>
        <text x="12" y="14" font-size="10.5" font-weight="700" font-family="sans-serif" fill="#0369a1">${pd.pt.title.replace(/[<>&]/g, '')}</text>
        ${legendItems}
        <g transform="translate(0, ${pd.legH})">
          <svg width="${pw}" height="${ph}" viewBox="0 0 ${pw} ${ph}">${pd.svgEl ? pd.svgEl.innerHTML : ''}</svg>
          ${tipSvgs}
        </g>
      </g>`;
    }).join('');

    const svgStr = `<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="${totalW}" height="${totalH}" viewBox="0 0 ${totalW} ${totalH}">
  <rect width="${totalW}" height="${totalH}" fill="#ffffff"/>
  <text x="14" y="18" font-size="12" font-weight="700" font-family="sans-serif" fill="#0f172a">${circuitTitle.replace(/[<>&]/g, '')} — Plot Window (${visibleTabs.length} plot${visibleTabs.length > 1 ? 's' : ''})</text>
  ${panesXml}
</svg>`;
    const img = new window.Image();
    const blob = new Blob([svgStr], { type: 'image/svg+xml;charset=utf-8' });
    const url = URL.createObjectURL(blob);
    img.onload = () => {
      const canvas = document.createElement('canvas');
      canvas.width = totalW * 2;
      canvas.height = totalH * 2;
      const ctx = canvas.getContext('2d');
      ctx.scale(2, 2);
      ctx.fillStyle = '#ffffff';
      ctx.fillRect(0, 0, totalW, totalH);
      ctx.drawImage(img, 0, 0, totalW, totalH);
      URL.revokeObjectURL(url);
      canvas.toBlob((pngBlob) => {
        if (!pngBlob) return;
        const pUrl = URL.createObjectURL(pngBlob);
        const a = document.createElement('a');
        a.href = pUrl;
        a.download = 'hydrosim-plot-window.png';
        a.click();
        URL.revokeObjectURL(pUrl);
        notify(`Exported full Plot Window (${visibleTabs.length} plot${visibleTabs.length > 1 ? 's' : ''})`);
      });
    };
    img.src = url;
  };

  const handleExportPDFReport = () => {
    setShowExportMenu(false);
    const out = buildExportSVGString();
    const win = window.open('', '_blank', 'width=1020,height=820');
    if (!win) { notify('Allow pop-ups to generate the PDF Engineering Report'); return; }

    const escHtml = (s) => String(s ?? '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
    const projName = circuitTitle || 'Untitled Hydraulic Circuit';
    const projDesc = circuitDesc || 'ISO 1219 Hydraulic System Simulation & Analysis';
    const generatedAt = new Date().toLocaleString();

    const tStart = Number(simSettings.startTime) || 0;
    const tEnd = Number(simSettings.endTime) || 0;
    const totalTime = tEnd > tStart ? (tEnd - tStart) : (tEnd === 0 ? 10 : Math.max(0.1, tEnd));
    const numSteps = Math.max(1, parseInt(simSettings.numSteps, 10) || 200);
    const calcDt = totalTime / numSteps;

    const dashAttr = (d) =>
      d === 'dashed' ? ' stroke-dasharray="7 4"'
      : d === 'dotted' ? ' stroke-dasharray="2 4"'
      : d === 'dashdot' ? ' stroke-dasharray="8 3 2 3"'
      : '';

    // Render SVG snapshots for ALL plot windows/tabs defined for this circuit
    const renderPlotTabSvgHtml = (pt) => {
      const ptEnabled = pt.enabledChannels || {};
      const ptStyles = pt.lineStyles || {};
      const activeCh = availableChannels.filter((c) => ptEnabled[c.id]).map((ch) => ({
        ...ch,
        color: ptStyles[ch.id]?.color || ch.color,
        dash: ptStyles[ch.id]?.dash || 'solid',
      }));

      if (history.length < 2 || activeCh.length === 0) {
        return `<div class="empty-note">No recorded waveform samples for <strong>${escHtml(pt.title)}</strong> (${activeCh.length} curve(s) selected). Run simulation to capture results.</div>`;
      }

      const W = 820, H = 220;
      const pad = { top: 14, right: 20, bottom: 34, left: 56 };
      const plotW = W - pad.left - pad.right;
      const plotH = H - pad.top - pad.bottom;

      const hasCustomT0 = pt.plotTimeMin !== '' && pt.plotTimeMin !== undefined && Number.isFinite(parseFloat(pt.plotTimeMin));
      const hasCustomT1 = pt.plotTimeMax !== '' && pt.plotTimeMax !== undefined && Number.isFinite(parseFloat(pt.plotTimeMax));
      const t0 = hasCustomT0 ? parseFloat(pt.plotTimeMin) : history[0].t;
      const t1 = Math.max(t0 + 1e-6, hasCustomT1 ? parseFloat(pt.plotTimeMax) : history[history.length - 1].t);

      let minV = Infinity, maxV = -Infinity, anyInWin = false;
      for (const sample of history) {
        if (sample.t < t0 || sample.t > t1) continue;
        anyInWin = true;
        for (const ch of activeCh) {
          const v = convertToDisplay(sample.values[ch.id] ?? 0, ch.unitType, units);
          if (Number.isFinite(v)) {
            if (v < minV) minV = v;
            if (v > maxV) maxV = v;
          }
        }
      }
      if (!anyInWin || !Number.isFinite(minV) || !Number.isFinite(maxV)) {
        minV = 0; maxV = 10;
      }
      const span = maxV - minV;
      const padVal = span > 1e-6 ? span * 0.1 : Math.max(0.5, Math.abs(maxV) * 0.1);
      const hasCustomY0 = pt.plotYMin !== '' && pt.plotYMin !== undefined && Number.isFinite(parseFloat(pt.plotYMin));
      const hasCustomY1 = pt.plotYMax !== '' && pt.plotYMax !== undefined && Number.isFinite(parseFloat(pt.plotYMax));
      const y0 = hasCustomY0 ? parseFloat(pt.plotYMin) : (minV - padVal);
      const y1 = Math.max(y0 + 1e-6, hasCustomY1 ? parseFloat(pt.plotYMax) : (maxV + padVal));

      const toX = (t) => pad.left + ((t - t0) / Math.max(1e-6, t1 - t0)) * plotW;
      const toY = (v) => pad.top + plotH - ((v - y0) / Math.max(1e-6, y1 - y0)) * plotH;

      const yDivs = Math.max(2, parseInt(pt.plotGridRows, 10) || 4);
      const xDivs = Math.max(2, parseInt(pt.plotGridCols, 10) || 8);
      const gColor = pt.plotGridColor || '#e2e8f0';
      const gVis = pt.plotGridVisible ?? true;

      const yTicksXml = Array.from({ length: yDivs + 1 }, (_, i) => {
        const yv = y0 + (i / yDivs) * (y1 - y0);
        const yy = toY(yv).toFixed(1);
        const lbl = yv.toFixed(Math.abs(y1 - y0) < 2 ? 2 : Math.abs(y1 - y0) < 20 ? 1 : 0);
        return `${gVis ? `<line x1="${pad.left}" y1="${yy}" x2="${W - pad.right}" y2="${yy}" stroke="${gColor}" stroke-width="1"/>` : ''}<text x="${pad.left - 6}" y="${(Number(yy) + 3).toFixed(1)}" text-anchor="end" font-size="9.5" fill="#475569" font-family="monospace">${lbl}</text>`;
      }).join('');

      const xTicksXml = Array.from({ length: xDivs + 1 }, (_, i) => {
        const xv = t0 + (i / xDivs) * (t1 - t0);
        const xx = toX(xv).toFixed(1);
        return `${gVis ? `<line x1="${xx}" y1="${pad.top}" x2="${xx}" y2="${H - pad.bottom}" stroke="${gColor}" stroke-width="1"/>` : ''}<text x="${xx}" y="${H - 14}" text-anchor="middle" font-size="9.5" fill="#475569" font-family="monospace">${xv.toFixed(2)}s</text>`;
      }).join('');

      const clipId = `rep-clip-${pt.id.replace(/[^a-zA-Z0-9_-]/g, '_')}`;
      const curvesXml = activeCh.map((ch) => {
        const ptsStr = history.map((s) => `${toX(s.t).toFixed(1)},${toY(convertToDisplay(s.values[ch.id] ?? 0, ch.unitType, units)).toFixed(1)}`).join(' ');
        return `<polyline fill="none" stroke="${ch.color}" stroke-width="2"${dashAttr(ch.dash)} stroke-linejoin="round" points="${ptsStr}"/>`;
      }).join('');

      const tipsXml = (pt.datatips || []).map((tip) => {
        const tTarget = t0 + Math.max(0, Math.min(1, tip.fracT ?? 0.5)) * (t1 - t0);
        let bestPt = history[0];
        let bestD = Math.abs(history[0].t - tTarget);
        for (const s of history) {
          const d = Math.abs(s.t - tTarget);
          if (d < bestD) { bestD = d; bestPt = s; }
        }
        const xL = toX(bestPt.t);
        const boxW = 195;
        const boxH = 22 + activeCh.length * 14;
        const bx = Math.max(pad.left + 4, Math.min(W - pad.right - boxW - 4, tip.boxX ?? (xL + 8)));
        const by = Math.max(pad.top + 4, Math.min(H - pad.bottom - boxH - 4, tip.boxY ?? (pad.top + 8)));
        const rows = activeCh.map((ch, rI) => {
          const val = convertToDisplay(bestPt.values[ch.id] ?? 0, ch.unitType, units);
          const ry = by + 26 + rI * 14;
          return `<circle cx="${bx + 11}" cy="${ry - 3}" r="3.2" fill="${ch.color}"/><text x="${bx + 19}" y="${ry}" font-size="9" font-family="monospace" fill="#0f172a">${escHtml(ch.label)}</text><text x="${bx + boxW - 7}" y="${ry}" text-anchor="end" font-size="9" font-weight="700" font-family="monospace" fill="#0369a1">${val.toFixed(2)} ${escHtml(ch.unit)}</text>`;
        }).join('');
        return `<line x1="${xL.toFixed(1)}" y1="${pad.top}" x2="${xL.toFixed(1)}" y2="${H - pad.bottom}" stroke="#0284c7" stroke-width="1.3" stroke-dasharray="4 2"/><rect x="${bx.toFixed(1)}" y="${by.toFixed(1)}" width="${boxW}" height="${boxH}" rx="4" fill="#f1f5f9" fill-opacity="0.96" stroke="#94a3b8" stroke-width="1"/><text x="${bx + 7}" y="${by + 13}" font-size="9" font-weight="700" font-family="monospace" fill="#334155">t = ${bestPt.t.toFixed(3)} s</text>${rows}`;
      }).join('');

      const legendHtml = activeCh.map((ch) =>
        `<span class="leg-item"><span class="leg-swatch" style="border-top: 2.5px ${ch.dash === 'dashed' ? 'dashed' : ch.dash === 'dotted' ? 'dotted' : 'solid'} ${ch.color};"></span><strong>${escHtml(ch.label)}</strong> (${escHtml(ch.unit || '—')})</span>`
      ).join('');

      // Summary min/max/final stats table for curves in this plot
      const statsRows = activeCh.map((ch) => {
        let cMin = Infinity, cMax = -Infinity, cLast = 0;
        for (const s of history) {
          if (s.t < t0 || s.t > t1) continue;
          const v = convertToDisplay(s.values[ch.id] ?? 0, ch.unitType, units);
          if (v < cMin) cMin = v;
          if (v > cMax) cMax = v;
          cLast = v;
        }
        if (!Number.isFinite(cMin)) { cMin = 0; cMax = 0; }
        return `<tr><td><span style="display:inline-block;width:9px;height:9px;border-radius:2px;background:${ch.color};margin-right:6px;"></span>${escHtml(ch.label)}</td><td>${escHtml(ch.unit || '—')}</td><td class="num">${cMin.toFixed(3)}</td><td class="num">${cMax.toFixed(3)}</td><td class="num">${cLast.toFixed(3)}</td></tr>`;
      }).join('');

      return `
        <div class="plot-card">
          <div class="plot-card-hdr">
            <span>${escHtml(pt.title)}</span>
            <span class="plot-meta">Time: [${t0.toFixed(2)}s, ${t1.toFixed(2)}s] · Y-Axis: [${y0.toFixed(2)}, ${y1.toFixed(2)}]</span>
          </div>
          <div class="leg-bar">${legendHtml}</div>
          <svg viewBox="0 0 ${W} ${H}" style="width:100%;height:auto;background:#ffffff;display:block;">
            <defs><clipPath id="${clipId}"><rect x="${pad.left}" y="${pad.top}" width="${plotW}" height="${plotH}"/></clipPath></defs>
            ${yTicksXml}
            ${xTicksXml}
            <text x="${pad.left + plotW * 0.5}" y="${H - 2}" text-anchor="middle" font-size="10" font-weight="700" fill="#334155" font-family="sans-serif">time (sec)</text>
            <rect x="${pad.left}" y="${pad.top}" width="${plotW}" height="${plotH}" fill="none" stroke="#94a3b8" stroke-width="1"/>
            <g clip-path="url(#${clipId})">${curvesXml}</g>
            ${tipsXml}
          </svg>
          <table class="mini-tbl">
            <thead><tr><th>Plotted Curve</th><th>Unit</th><th class="num">Min</th><th class="num">Max</th><th class="num">Final</th></tr></thead>
            <tbody>${statsRows}</tbody>
          </table>
        </div>`;
    };

    const allPlotsHtml = plotTabs.map((pt) => renderPlotTabSvgHtml(pt)).join('');

    // Solver & Fluid Settings Table
    const solverRows = [
      ['Solver Method', simSettings.solverType === 'ode15s' ? 'ode15s (Stiff Multi-Step BDF)' : simSettings.solverType === 'ode23t' ? 'ode23t (Implicit Trapezoidal)' : 'Adaptive RK45 (Explicit)'],
      ['Solver Tolerance', String(simSettings.solverTolerance || 1e-4)],
      ['Start Time', `${tStart} s`],
      ['End Time / Total Time', `${tEnd === 0 ? 'Continuous (10 s window)' : `${tEnd} s`} (Total: ${totalTime.toFixed(3)} s)`],
      ['Number of Steps', `${numSteps}`],
      ['Calculated Time Step (Δt)', `${calcDt.toFixed(5)} s`],
      ['RK4 Substeps / Frame', `${simSettings.rk4Substeps || 30}`],
      ['Simulation Speed Multiplier', `${simSettings.simSpeed || 1.0}×`],
      ['Node Capacitance Volume', `${simSettings.nodeVolL || 1.5} L`],
      ['Initial Non-Tank Pressure', `${convertToDisplay(simSettings.initPressureBar || 0, 'pressure', units).toFixed(2)} ${units.pressure}`],
      ['Fluid Bulk Modulus', `${convertToDisplay(simSettings.bulkModulusBar || 10000, 'pressure', units).toFixed(0)} ${units.pressure}`],
      ['Fluid Density', `${simSettings.oilDensity || 870} kg/m³`],
      ['Kinematic Viscosity', `${simSettings.viscosityCst || 46} cSt`],
      ['Reference / Initial Oil Temp', `${convertToDisplay(simSettings.oilTempC ?? 45, 'tempC', units).toFixed(1)} ${units.temp}`],
      ['Engineering Unit System', units.label],
    ].map(([k, v]) => `<tr><td style="font-weight:600;width:42%">${escHtml(k)}</td><td class="mono">${escHtml(v)}</td></tr>`).join('');

    // Detailed Settings & Live/Final Telemetry of Each Used Component
    const componentChaptersHtml = components.length === 0
      ? '<p class="empty-note">No components placed in this circuit.</p>'
      : components.map((c, idx) => {
          const def = COMPONENT_CATALOG[c.type];
          const metaList = def?.paramMeta || [];
          const paramEntries = Object.entries(c.params || {});
          const paramRows = paramEntries.length === 0
            ? '<tr><td colspan="3" style="color:#64748b">Default boundary / no configurable parameters</td></tr>'
            : paramEntries.map(([k, rawVal]) => {
                const pm = metaList.find((m) => m.key === k);
                const label = pm ? pm.label : k;
                const uType = pm?.unit ? inferUnitType(pm.unit) : 'none';
                const dispUnit = pm?.unit ? getDisplayUnitLabel(uType, units, pm.unit) : '';
                let dispVal = rawVal;
                if (typeof rawVal === 'number' && uType !== 'none') {
                  dispVal = Number(convertToDisplay(rawVal, uType, units).toFixed(4));
                }
                if (pm?.options) {
                  const opt = pm.options.find((o) => String(o.value) === String(rawVal));
                  if (opt) dispVal = `${opt.label} (${rawVal})`;
                }
                return `<tr><td>${escHtml(label)}</td><td class="mono">${escHtml(dispVal === '' ? '—' : dispVal)}</td><td>${escHtml(dispUnit || '—')}</td></tr>`;
              }).join('');

          const m = simState.compMetrics?.[c.id];
          const metricEntries = m ? Object.entries(m).filter(([, v]) => v !== null && v !== undefined && typeof v !== 'boolean') : [];
          const telemetryHtml = metricEntries.length === 0
            ? ''
            : `<div class="sub-hdr">Final / Live Telemetry State</div>
               <table class="mini-tbl"><thead><tr><th>Output Quantity</th><th class="num">Value</th></tr></thead><tbody>
               ${metricEntries.map(([mk, mv]) => {
                 let disp = typeof mv === 'number' ? mv.toFixed(3) : String(mv);
                 if (mk.toLowerCase().includes('bar')) disp = `${convertToDisplay(mv, 'pressure', units).toFixed(2)} ${units.pressure}`;
                 else if (mk.toLowerCase().includes('lpm')) disp = `${convertToDisplay(mv, 'flow', units).toFixed(2)} ${units.flow}`;
                 else if (mk === 'posMm') disp = `${convertToDisplay(mv, 'lengthMm', units).toFixed(2)} ${units.length}`;
                 else if (mk === 'velMms') disp = `${convertToDisplay(mv, 'lengthMm', units).toFixed(2)} ${units.length}/s`;
                 else if (mk === 'forceKn') disp = `${convertToDisplay(mv, 'forceKn', units).toFixed(2)} ${units.force}`;
                 else if (mk.includes('Pct')) disp = `${mv.toFixed(1)} %`;
                 else if (mk.includes('Kw')) disp = `${mv.toFixed(3)} kW`;
                 else if (mk === 'tempC') disp = `${convertToDisplay(mv, 'tempC', units).toFixed(1)} ${units.temp}`;
                 return `<tr><td>${escHtml(mk)}</td><td class="num mono">${escHtml(disp)}</td></tr>`;
               }).join('')}
               </tbody></table>`;

          return `
            <div class="comp-block">
              <div class="comp-hdr">
                <span>4.${idx + 1} &nbsp; ${escHtml(c.name)} — ${escHtml(def?.name || c.type)}</span>
                <span class="comp-cat">${escHtml(def?.category || '')}</span>
              </div>
              <table class="mini-tbl">
                <thead><tr><th style="width:45%">Parameter</th><th>Configured Value</th><th style="width:18%">Unit</th></tr></thead>
                <tbody>${paramRows}</tbody>
              </table>
              ${telemetryHtml}
            </div>`;
        }).join('');

    // Connections table
    const connRows = connections.length === 0
      ? '<tr><td colspan="4" style="color:#64748b">No connections wired.</td></tr>'
      : connections.map((w, i) => {
          const c1 = components.find((c) => c.id === w.from.compId);
          const c2 = components.find((c) => c.id === w.to.compId);
          const qLpm = simState.connFlows?.[w.id] ?? 0;
          return `<tr><td class="mono">${i + 1}</td><td>${escHtml(c1?.name || w.from.compId)} : <strong>${escHtml(w.from.portId)}</strong></td><td>${escHtml(c2?.name || w.to.compId)} : <strong>${escHtml(w.to.portId)}</strong></td><td class="num mono">${convertToDisplay(qLpm, 'flow', units).toFixed(2)} ${escHtml(units.flow)}</td></tr>`;
        }).join('');

    const diagRows = diagnostics.length === 0
      ? '<tr><td colspan="3" style="color:#15803d;font-weight:600">No warnings or errors detected.</td></tr>'
      : diagnostics.map((d) => `<tr><td style="text-transform:uppercase;font-weight:700">${escHtml(d.severity)}</td><td>${escHtml(d.title)}</td><td>${escHtml(d.detail)}</td></tr>`).join('');

    const html = `<!DOCTYPE html><html><head><title>${escHtml(projName)} — HydroSim Engineering Report</title>
<style>
  * { box-sizing: border-box; }
  body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; color: #0f172a; margin: 0; padding: 24px 32px; font-size: 11.5px; line-height: 1.45; }
  .toolbar { position: sticky; top: 0; background: #0f172a; color: #fff; padding: 10px 18px; margin: -24px -32px 20px -32px; display: flex; justify-content: space-between; align-items: center; z-index: 100; }
  .toolbar button { padding: 7px 16px; background: #0284c7; color: #fff; border: none; border-radius: 4px; font-weight: 700; cursor: pointer; font-size: 12px; }
  .toolbar button:hover { background: #0369a1; }

  /* Cover / Title Page */
  .cover-page { border: 1.5px solid #cbd5e1; border-radius: 8px; padding: 36px 32px; background: linear-gradient(180deg, #f8fafc 0%, #ffffff 100%); margin-bottom: 24px; }
  .brand-tag { display: inline-block; background: #0284c7; color: #fff; font-weight: 800; font-size: 10px; letter-spacing: 0.08em; padding: 3px 9px; border-radius: 3px; text-transform: uppercase; margin-bottom: 12px; }
  .proj-title { font-size: 24px; font-weight: 800; color: #0f172a; margin: 0 0 8px 0; }
  .proj-desc { font-size: 12.5px; color: #475569; margin: 0 0 22px 0; }
  .kpi-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 10px; margin-top: 14px; }
  .kpi { border: 1px solid #cbd5e1; border-radius: 5px; padding: 9px 11px; background: #fff; }
  .kpi .lbl { font-size: 9.5px; color: #64748b; text-transform: uppercase; font-weight: 700; }
  .kpi .val { font-size: 15px; font-weight: 800; font-family: monospace; color: #0f172a; margin-top: 2px; }

  /* Index / Table of Contents Page */
  .toc-box { border: 1px solid #cbd5e1; border-radius: 6px; padding: 18px 22px; background: #ffffff; margin-bottom: 24px; }
  .toc-title { font-size: 15px; font-weight: 800; color: #0369a1; text-transform: uppercase; letter-spacing: 0.05em; border-bottom: 2px solid #0284c7; padding-bottom: 6px; margin: 0 0 12px 0; }
  .toc-list { list-style: none; padding: 0; margin: 0; }
  .toc-list li { display: flex; justify-content: space-between; padding: 6px 4px; border-bottom: 1px dashed #cbd5e1; font-size: 12px; }
  .toc-list li a { color: #0f172a; text-decoration: none; font-weight: 600; }
  .toc-list li a:hover { color: #0284c7; }
  .toc-sub { padding-left: 20px !important; font-size: 11px !important; color: #475569; }

  /* Chapters */
  .chapter { margin-top: 24px; }
  .chap-hdr { font-size: 14px; font-weight: 800; text-transform: uppercase; letter-spacing: 0.05em; color: #0369a1; border-bottom: 2px solid #cbd5e1; padding-bottom: 5px; margin: 0 0 12px 0; }
  .box { border: 1px solid #cbd5e1; border-radius: 6px; padding: 10px; background: #f8fafc; margin-bottom: 14px; }
  .box svg { width: 100%; height: auto; max-height: 400px; display: block; }
  .plot-card { border: 1px solid #cbd5e1; border-radius: 6px; padding: 10px 12px; background: #ffffff; margin-bottom: 14px; page-break-inside: avoid; }
  .plot-card-hdr { display: flex; justify-content: space-between; align-items: center; font-weight: 700; font-size: 12px; color: #0f172a; border-bottom: 1px solid #e2e8f0; padding-bottom: 5px; margin-bottom: 6px; }
  .plot-meta { font-family: monospace; font-size: 10px; color: #64748b; font-weight: 500; }
  .leg-bar { display: flex; flex-wrap: wrap; gap: 12px; padding: 4px 0 8px 0; font-size: 10.5px; color: #1e293b; }
  .leg-item { display: inline-flex; align-items: center; gap: 5px; }
  .leg-swatch { display: inline-block; width: 16px; height: 0; }

  .comp-block { border: 1px solid #cbd5e1; border-radius: 6px; padding: 9px 11px; margin-bottom: 10px; background: #ffffff; page-break-inside: avoid; }
  .comp-hdr { display: flex; justify-content: space-between; align-items: center; font-weight: 700; font-size: 12px; color: #0f172a; background: #f1f5f9; padding: 5px 8px; border-radius: 4px; margin-bottom: 6px; }
  .comp-cat { font-size: 10px; color: #475569; font-weight: 600; }
  .sub-hdr { font-size: 10px; font-weight: 700; text-transform: uppercase; color: #0369a1; margin: 7px 0 3px 0; }

  table { width: 100%; border-collapse: collapse; margin-top: 4px; font-size: 10.5px; }
  th, td { border: 1px solid #cbd5e1; padding: 4px 7px; text-align: left; }
  th { background: #f1f5f9; font-weight: 700; color: #1e293b; }
  .mono { font-family: monospace; }
  .num { text-align: right; font-family: monospace; }
  .empty-note { color: #64748b; font-style: italic; padding: 8px; background: #f8fafc; border: 1px dashed #cbd5e1; border-radius: 4px; }

  @media print {
    .no-print { display: none !important; }
    body { padding: 0; }
    .page-break { page-break-before: always; }
  }
</style></head><body>
  <div class="toolbar no-print">
    <span><strong>HydroSim Engineering Report Preview</strong> — ${escHtml(projName)}</span>
    <button onclick="window.print()">Save as PDF / Print</button>
  </div>

  <!-- PROJECT COVER SUMMARY -->
  <div class="cover-page">
    <div class="brand-tag">HydroSim ISO 1219 Simulation Report</div>
    <h1 class="proj-title">${escHtml(projName)}</h1>
    <p class="proj-desc">${escHtml(projDesc)}</p>
    <div style="font-size:11px;color:#64748b;font-family:monospace;">Generated: ${escHtml(generatedAt)} &nbsp;|&nbsp; Units: ${escHtml(units.label)} &nbsp;|&nbsp; Solver: ${escHtml(simSettings.solverType || 'rk45')}</div>
    <div class="kpi-grid">
      <div class="kpi"><div class="lbl">Simulated Time</div><div class="val">${simState.time.toFixed(2)} s</div></div>
      <div class="kpi"><div class="lbl">System Efficiency</div><div class="val">${(simState.sysEffPct || 0).toFixed(1)} %</div></div>
      <div class="kpi"><div class="lbl">Bulk Oil Temp</div><div class="val">${convertToDisplay(simState.oilTempC ?? simSettings.oilTempC, 'tempC', units).toFixed(1)} ${escHtml(units.temp)}</div></div>
      <div class="kpi"><div class="lbl">Components / Plots</div><div class="val">${components.length} / ${plotTabs.length}</div></div>
    </div>
  </div>

  <!-- INDEX / TABLE OF CONTENTS -->
  <div class="toc-box">
    <div class="toc-title">Index — Report Contents</div>
    <ul class="toc-list">
      <li><a href="#chap-1">Chapter 1. ISO 1219 Hydraulic Circuit Schematic &amp; Connections</a><span>Section 1</span></li>
      <li><a href="#chap-2">Chapter 2. Simulation Results — Plot Windows (${plotTabs.length})</a><span>Section 2</span></li>
      ${plotTabs.map((pt, i) => `<li class="toc-sub"><a href="#chap-2">2.${i + 1} ${escHtml(pt.title)}</a><span>Oscilloscope &amp; Statistics</span></li>`).join('')}
      <li><a href="#chap-3">Chapter 3. Solver &amp; Fluid Configuration Settings</a><span>Section 3</span></li>
      <li><a href="#chap-4">Chapter 4. Component-Wise Settings &amp; Telemetry (${components.length})</a><span>Section 4</span></li>
      ${components.map((c, i) => `<li class="toc-sub"><a href="#chap-4">4.${i + 1} ${escHtml(c.name)} (${escHtml(COMPONENT_CATALOG[c.type]?.shortName || c.type)})</a><span>Parameters</span></li>`).join('')}
      <li><a href="#chap-5">Chapter 5. Circuit Diagnostics &amp; Verification</a><span>Section 5</span></li>
    </ul>
  </div>

  <!-- CHAPTER 1: SCHEMATIC -->
  <div id="chap-1" class="chapter page-break">
    <h2 class="chap-hdr">Chapter 1. ISO 1219 Hydraulic Circuit Schematic &amp; Connections</h2>
    <div class="box">${out ? out.svg : '<p class="empty-note">Empty schematic.</p>'}</div>
    <table>
      <thead><tr><th style="width:40px">#</th><th>From Port</th><th>To Port</th><th class="num">Line Flow</th></tr></thead>
      <tbody>${connRows}</tbody>
    </table>
  </div>

  <!-- CHAPTER 2: ALL PLOT WINDOWS -->
  <div id="chap-2" class="chapter page-break">
    <h2 class="chap-hdr">Chapter 2. Simulation Results — All Plot Windows (${plotTabs.length})</h2>
    ${allPlotsHtml}
  </div>

  <!-- CHAPTER 3: SOLVER & FLUID SETTINGS -->
  <div id="chap-3" class="chapter page-break">
    <h2 class="chap-hdr">Chapter 3. Solver &amp; Fluid Configuration Settings</h2>
    <table>
      <thead><tr><th>Setting Parameter</th><th>Configured Value</th></tr></thead>
      <tbody>${solverRows}</tbody>
    </table>
  </div>

  <!-- CHAPTER 4: COMPONENT-WISE SETTINGS -->
  <div id="chap-4" class="chapter page-break">
    <h2 class="chap-hdr">Chapter 4. Component-Wise Settings &amp; Telemetry (${components.length} Components)</h2>
    ${componentChaptersHtml}
  </div>

  <!-- CHAPTER 5: DIAGNOSTICS -->
  <div id="chap-5" class="chapter">
    <h2 class="chap-hdr">Chapter 5. Circuit Diagnostics &amp; Verification</h2>
    <table>
      <thead><tr><th style="width:90px">Severity</th><th style="width:220px">Diagnostic</th><th>Details</th></tr></thead>
      <tbody>${diagRows}</tbody>
    </table>
  </div>
</body></html>`;
    win.document.open();
    win.document.write(html);
    win.document.close();
    notify('Opened structured PDF Engineering Report');
  };

  // --- Backend Storage Integration ---
  const [backendOnline, setBackendOnline] = useState(false);
  const [showCloudModal, setShowCloudModal] = useState(false);

  useEffect(() => {
    HydraAPI.checkHealth().then((h) => setBackendOnline(!!h.online));
  }, []);

  const handleSaveToBackend = async (name, description) => {
    const payload = { name, description, components, connections, simSettings, units };
    const res = await HydraAPI.saveCircuit(payload);
    setCircuitTitle(name);
    setCircuitDesc(description);
    notify(res.source === 'server' ? `Saved "${name}" to backend server` : `Saved "${name}" to local storage`);
  };

  const handleLoadFromBackend = async (id) => {
    try {
      const res = await HydraAPI.getCircuit(id);
      const data = res.circuit;
      pushUndo();
      setSimStatus('stopped');
      setComponents(structuredClone(data.components || []));
      setConnections(structuredClone(data.connections || []));
      setCircuitTitle(data.name || 'Saved Circuit');
      setCircuitDesc(data.description || '');
      if (data.simSettings) setSimSettings((s) => ({ ...s, ...data.simSettings }));
      if (data.units) setUnits((u) => ({ ...u, ...data.units }));
      setHistory([]);
      setEnabledChannels({});
      setSelectedIds([]);
      setSelectedConnId(null);
      setShowCloudModal(false);
      notify(`Loaded "${data.name}"`);
    } catch (err) {
      notify(`Load error: ${err.message}`);
    }
  };

  // --- Component Editing, Transform & Selection Actions ---
  const snapVal = useCallback((v) => (simSettings.snapToGrid ? Math.round(v / GRID_SIZE) * GRID_SIZE : Math.round(v)), [simSettings.snapToGrid]);

  const addComponentAt = useCallback((type, wx, wy) => {
    const def = COMPONENT_CATALOG[type];
    if (!def) return;
    pushUndo();
    const existingCount = componentsRef.current.filter((c) => c.type === type).length;
    const id = `${type}_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 5)}`;
    const newComp = {
      id,
      type,
      name: `${def.prefix}${existingCount + 1}`,
      x: snapVal(wx),
      y: snapVal(wy),
      rotation: 0,
      flipX: false,
      flipY: false,
      scale: 1,
      params: structuredClone(def.defaultParams),
    };
    setComponents((prev) => [...prev, newComp]);
    setSelectedIds([id]);
    setSelectedConnId(null);
    notify(`Added ${def.shortName} (${newComp.name})`);
  }, [pushUndo, snapVal, notify]);

  const handleDeleteSelected = useCallback(() => {
    if (selectedConnId) {
      pushUndo();
      setConnections((prev) => prev.filter((w) => w.id !== selectedConnId));
      setSelectedConnId(null);
      notify('Deleted hydraulic line');
      return;
    }
    if (selectedIds.length === 0) return;
    pushUndo();
    const delSet = new Set(selectedIds);
    setComponents((prev) => prev.filter((c) => !delSet.has(c.id)));
    setConnections((prev) => prev.filter((w) => !delSet.has(w.from.compId) && !delSet.has(w.to.compId)));
    setSelectedIds([]);
    notify(`Deleted ${delSet.size} component(s)`);
  }, [selectedIds, selectedConnId, pushUndo, notify]);

  const handleRotateSelected = useCallback((deltaDeg) => {
    if (selectedIds.length === 0) return;
    pushUndo();
    const selSet = new Set(selectedIds);
    setComponents((prev) =>
      prev.map((c) => (selSet.has(c.id) ? { ...c, rotation: ((c.rotation || 0) + deltaDeg + 360) % 360 } : c))
    );
  }, [selectedIds, pushUndo]);

  const handleFlipSelected = useCallback((axis) => {
    if (selectedIds.length === 0) return;
    pushUndo();
    const selSet = new Set(selectedIds);
    setComponents((prev) =>
      prev.map((c) => (selSet.has(c.id) ? { ...c, [axis]: !c[axis] } : c))
    );
  }, [selectedIds, pushUndo]);

  const handleCopy = useCallback(() => {
    if (selectedIds.length === 0) return;
    const selSet = new Set(selectedIds);
    const copiedComps = structuredClone(componentsRef.current.filter((c) => selSet.has(c.id)));
    const copiedConns = structuredClone(
      connectionsRef.current.filter((w) => selSet.has(w.from.compId) && selSet.has(w.to.compId))
    );
    setClipboard({ components: copiedComps, connections: copiedConns });
    notify(`Copied ${copiedComps.length} component(s)`);
  }, [selectedIds, notify]);

  const handlePaste = useCallback(() => {
    if (!clipboard || clipboard.components.length === 0) return;
    pushUndo();
    const idMap = {};
    const newComps = clipboard.components.map((c, idx) => {
      const newId = `${c.type}_${Date.now().toString(36)}_${idx}`;
      idMap[c.id] = newId;
      return { ...structuredClone(c), id: newId, name: `${c.name}_c`, x: c.x + 40, y: c.y + 40 };
    });
    const newConns = clipboard.connections.map((w, idx) => ({
      id: `w_${Date.now().toString(36)}_${idx}`,
      from: { compId: idMap[w.from.compId], portId: w.from.portId },
      to: { compId: idMap[w.to.compId], portId: w.to.portId },
    }));
    setComponents((prev) => [...prev, ...newComps]);
    setConnections((prev) => [...prev, ...newConns]);
    setSelectedIds(newComps.map((c) => c.id));
    notify(`Pasted ${newComps.length} component(s)`);
  }, [clipboard, pushUndo, notify]);

  const handleGroupSelected = useCallback(() => {
    if (selectedIds.length < 2) return;
    pushUndo();
    const gid = `grp_${Date.now().toString(36)}`;
    const existingGroups = new Set(componentsRef.current.map((c) => c.groupId).filter(Boolean));
    const gName = `Subsystem ${existingGroups.size + 1}`;
    const selSet = new Set(selectedIds);
    setComponents((prev) => prev.map((c) => (selSet.has(c.id) ? { ...c, groupId: gid, groupName: gName } : c)));
    notify(`Grouped ${selectedIds.length} components into ${gName}`);
  }, [selectedIds, pushUndo, notify]);

  const handleUngroupSelected = useCallback(() => {
    if (selectedIds.length === 0) return;
    pushUndo();
    const selSet = new Set(selectedIds);
    setComponents((prev) => prev.map((c) => (selSet.has(c.id) ? { ...c, groupId: undefined, groupName: undefined } : c)));
    notify('Ungrouped selection');
  }, [selectedIds, pushUndo, notify]);

  const handleUngroupById = useCallback((gid) => {
    pushUndo();
    setComponents((prev) => prev.map((c) => (c.groupId === gid ? { ...c, groupId: undefined, groupName: undefined } : c)));
    notify('Ungrouped subsystem');
  }, [pushUndo, notify]);

  const handleToggleSpool = useCallback((compId, newPos, paramKey = 'spoolPos') => {
    setComponents((prev) =>
      prev.map((c) => (c.id === compId ? { ...c, params: { ...c.params, [paramKey]: newPos } } : c))
    );
  }, []);

  const handleUpdateCompParam = useCallback((compId, key, val) => {
    setComponents((prev) =>
      prev.map((c) => (c.id === compId ? { ...c, params: { ...c.params, [key]: val } } : c))
    );
  }, []);

  const handleRenameComp = useCallback((compId, newName) => {
    setComponents((prev) => prev.map((c) => (c.id === compId ? { ...c, name: newName } : c)));
  }, []);

  // --- Fit View & Zoom ---
  const handleFitView = useCallback(() => {
    const svgEl = svgCanvasRef.current;
    if (!svgEl || componentsRef.current.length === 0) {
      setView({ x: 24, y: 16, zoom: 1 });
      return;
    }
    const rect = svgEl.getBoundingClientRect();
    let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
    for (const c of componentsRef.current) {
      minX = Math.min(minX, c.x - 80);
      minY = Math.min(minY, c.y - 60);
      maxX = Math.max(maxX, c.x + 80);
      maxY = Math.max(maxY, c.y + 60);
    }
    const bw = Math.max(200, maxX - minX);
    const bh = Math.max(200, maxY - minY);
    const zoom = Math.max(0.45, Math.min(1.5, Math.min((rect.width - 60) / bw, (rect.height - 60) / bh)));
    const cx = (minX + maxX) / 2;
    const cy = (minY + maxY) / 2;
    setView({ x: rect.width / 2 - cx * zoom, y: rect.height / 2 - cy * zoom, zoom });
  }, []);

  // --- Keyboard Shortcuts ---
  useEffect(() => {
    const onKeyDown = (e) => {
      const tag = e.target?.tagName;
      if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') return;
      if (e.code === 'Space') {
        e.preventDefault();
        if (simStatus === 'running') handlePause();
        else handleRun();
      } else if (e.key === 'Delete' || e.key === 'Backspace') {
        e.preventDefault();
        handleDeleteSelected();
      } else if (e.key === 'Escape') {
        setPendingPort(null);
        setShowExamples(false);
        setShowExportMenu(false);
      } else if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'z') {
        e.preventDefault();
        if (e.shiftKey) handleRedo();
        else handleUndo();
      } else if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'y') {
        e.preventDefault();
        handleRedo();
      } else if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'c') {
        e.preventDefault();
        handleCopy();
      } else if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'v') {
        e.preventDefault();
        handlePaste();
      } else if (e.key.toLowerCase() === 'r' && !e.ctrlKey && !e.metaKey) {
        handleRotateSelected(90);
      }
    };
    window.addEventListener('keydown', onKeyDown);
    return () => window.removeEventListener('keydown', onKeyDown);
  }, [simStatus, handleRun, handlePause, handleDeleteSelected, handleUndo, handleRedo, handleCopy, handlePaste, handleRotateSelected]);

  // --- SVG Canvas Pointer & Drag Handlers ---
  const screenToWorld = useCallback((clientX, clientY) => {
    const svgEl = svgCanvasRef.current;
    if (!svgEl) return { x: 0, y: 0 };
    const rect = svgEl.getBoundingClientRect();
    return {
      x: (clientX - rect.left - view.x) / view.zoom,
      y: (clientY - rect.top - view.y) / view.zoom,
    };
  }, [view]);

  const handleCanvasMouseDown = (e) => {
    if (e.button === 1 || (e.button === 0 && toolMode === 'pan')) {
      setDragState({ mode: 'pan', startClientX: e.clientX, startClientY: e.clientY, startViewX: view.x, startViewY: view.y });
      return;
    }
    if (e.button === 0) {
      if (pendingPort) {
        setPendingPort(null);
        return;
      }
      const pt = screenToWorld(e.clientX, e.clientY);
      setSelectedIds([]);
      setSelectedConnId(null);
      setMarquee({ x0: pt.x, y0: pt.y, x1: pt.x, y1: pt.y });
    }
  };

  const handleCanvasMouseMove = (e) => {
    const pt = screenToWorld(e.clientX, e.clientY);
    setMouseWorld(pt);

    if (dragState?.mode === 'pan') {
      setView((v) => ({
        ...v,
        x: dragState.startViewX + (e.clientX - dragState.startClientX),
        y: dragState.startViewY + (e.clientY - dragState.startClientY),
      }));
    } else if (dragState?.mode === 'move') {
      const dx = pt.x - dragState.startWorldX;
      const dy = pt.y - dragState.startWorldY;
      setComponents((prev) =>
        prev.map((c) => {
          const orig = dragState.origins[c.id];
          if (!orig) return c;
          return { ...c, x: snapVal(orig.x + dx), y: snapVal(orig.y + dy) };
        })
      );
    } else if (dragState?.mode === 'resize') {
      const dist = Math.max(12, Math.hypot(pt.x - dragState.cx, pt.y - dragState.cy));
      const nextScale = Math.max(0.55, Math.min(2.4, Number(((dist / dragState.startDist) * dragState.startScale).toFixed(2))));
      setComponents((prev) =>
        prev.map((c) => (c.id === dragState.compId ? { ...c, scale: nextScale } : c))
      );
    } else if (dragState?.mode === 'wire') {
      const delta = dragState.axis === 'x' ? (pt.x - dragState.startWorldX) : (pt.y - dragState.startWorldY);
      const nextOff = Math.round((dragState.origOffset + delta) / 5) * 5;
      setConnections((prev) =>
        prev.map((w) => (w.id === dragState.connId ? { ...w, midOffset: nextOff } : w))
      );
    } else if (dragState?.mode === 'label') {
      const dx = pt.x - dragState.startWorldX;
      const dy = pt.y - dragState.startWorldY;
      setComponents((prev) =>
        prev.map((c) => (c.id === dragState.compId ? { ...c, labelDx: Math.round(dragState.origDx + dx), labelDy: Math.round(dragState.origDy + dy) } : c))
      );
    } else if (dragState?.mode === 'badge') {
      const dx = pt.x - dragState.startWorldX;
      const dy = pt.y - dragState.startWorldY;
      setComponents((prev) =>
        prev.map((c) => (c.id === dragState.compId ? { ...c, badgeDx: Math.round(dragState.origDx + dx), badgeDy: Math.round(dragState.origDy + dy) } : c))
      );
    } else if (marquee) {
      setMarquee((m) => (m ? { ...m, x1: pt.x, y1: pt.y } : null));
    }
  };

  const handleCanvasMouseUp = () => {
    if (marquee) {
      const minX = Math.min(marquee.x0, marquee.x1);
      const maxX = Math.max(marquee.x0, marquee.x1);
      const minY = Math.min(marquee.y0, marquee.y1);
      const maxY = Math.max(marquee.y0, marquee.y1);
      if (maxX - minX > 6 || maxY - minY > 6) {
        const hit = components.filter((c) => c.x >= minX && c.x <= maxX && c.y >= minY && c.y <= maxY).map((c) => c.id);
        setSelectedIds(hit);
      }
      setMarquee(null);
    }
    setDragState(null);
  };

  const handleCanvasWheel = (e) => {
    e.preventDefault();
    const svgEl = svgCanvasRef.current;
    if (!svgEl) return;
    const rect = svgEl.getBoundingClientRect();
    const mx = e.clientX - rect.left;
    const my = e.clientY - rect.top;
    const factor = e.deltaY < 0 ? 1.1 : 0.91;
    setView((v) => {
      const nextZoom = Math.max(0.35, Math.min(2.5, v.zoom * factor));
      const scale = nextZoom / v.zoom;
      return { zoom: nextZoom, x: mx - (mx - v.x) * scale, y: my - (my - v.y) * scale };
    });
  };

  const handleCompMouseDown = (e, comp) => {
    e.stopPropagation();
    if (toolMode === 'pan') return;
    const pt = screenToWorld(e.clientX, e.clientY);
    let nextSelected = selectedIds;
    if (e.shiftKey) {
      nextSelected = selectedIds.includes(comp.id) ? selectedIds.filter((id) => id !== comp.id) : [...selectedIds, comp.id];
      setSelectedIds(nextSelected);
    } else if (!selectedIds.includes(comp.id)) {
      if (comp.groupId) {
        nextSelected = componentsRef.current.filter((c) => c.groupId === comp.groupId).map((c) => c.id);
      } else {
        nextSelected = [comp.id];
      }
      setSelectedIds(nextSelected);
    }
    setSelectedConnId(null);

    pushUndo();
    const origins = {};
    for (const c of componentsRef.current) {
      if (nextSelected.includes(c.id)) origins[c.id] = { x: c.x, y: c.y };
    }
    setDragState({ mode: 'move', startWorldX: pt.x, startWorldY: pt.y, origins });
  };

  const handleResizeMouseDown = (e, comp) => {
    e.stopPropagation();
    const pt = screenToWorld(e.clientX, e.clientY);
    const startDist = Math.max(12, Math.hypot(pt.x - comp.x, pt.y - comp.y));
    pushUndo();
    setDragState({
      mode: 'resize',
      compId: comp.id,
      cx: comp.x,
      cy: comp.y,
      startDist,
      startScale: comp.scale || 1,
    });
  };

  const handleGroupBoxMouseDown = (e, grp) => {
    e.stopPropagation();
    if (toolMode === 'pan') return;
    const pt = screenToWorld(e.clientX, e.clientY);
    setSelectedIds(grp.memberIds);
    setSelectedConnId(null);
    pushUndo();
    const origins = {};
    for (const c of componentsRef.current) {
      if (grp.memberIds.includes(c.id)) origins[c.id] = { x: c.x, y: c.y };
    }
    setDragState({ mode: 'move', startWorldX: pt.x, startWorldY: pt.y, origins });
  };

  const handleWireMouseDown = (e, w, axis) => {
    e.stopPropagation();
    if (toolMode === 'pan') return;
    const pt = screenToWorld(e.clientX, e.clientY);
    setSelectedConnId(w.id);
    setSelectedIds([]);
    pushUndo();
    setDragState({
      mode: 'wire',
      connId: w.id,
      axis,
      startWorldX: pt.x,
      startWorldY: pt.y,
      origOffset: w.midOffset || 0,
    });
  };

  const handleLabelMouseDown = (e, comp) => {
    e.stopPropagation();
    if (toolMode === 'pan') return;
    const pt = screenToWorld(e.clientX, e.clientY);
    pushUndo();
    setDragState({
      mode: 'label',
      compId: comp.id,
      startWorldX: pt.x,
      startWorldY: pt.y,
      origDx: comp.labelDx || 0,
      origDy: comp.labelDy || 0,
    });
  };

  const handleBadgeMouseDown = (e, comp) => {
    e.stopPropagation();
    if (toolMode === 'pan') return;
    const pt = screenToWorld(e.clientX, e.clientY);
    pushUndo();
    setDragState({
      mode: 'badge',
      compId: comp.id,
      startWorldX: pt.x,
      startWorldY: pt.y,
      origDx: comp.badgeDx || 0,
      origDy: comp.badgeDy || 0,
    });
  };

  const handlePortClick = (e, compId, portId) => {
    e.stopPropagation();
    if (!pendingPort) {
      setPendingPort({ compId, portId });
      return;
    }
    if (pendingPort.compId === compId && pendingPort.portId === portId) {
      setPendingPort(null);
      return;
    }
    const exists = connections.some(
      (w) =>
        (w.from.compId === pendingPort.compId && w.from.portId === pendingPort.portId && w.to.compId === compId && w.to.portId === portId) ||
        (w.to.compId === pendingPort.compId && w.to.portId === pendingPort.portId && w.from.compId === compId && w.from.portId === portId)
    );
    const cFrom = components.find((c) => c.id === pendingPort.compId);
    const cTo = components.find((c) => c.id === compId);
    const pFromDef = cFrom && COMPONENT_CATALOG[cFrom.type]?.ports?.find((p) => p.id === pendingPort.portId);
    const pToDef = cTo && COMPONENT_CATALOG[cTo.type]?.ports?.find((p) => p.id === portId);
    const fromNonHyd = !!(pFromDef?.isSignal || pFromDef?.isMech);
    const toNonHyd = !!(pToDef?.isSignal || pToDef?.isMech);
    if (fromNonHyd !== toNonHyd) {
      notify('Cannot connect hydraulic port directly to signal/mechanical port');
      setPendingPort(null);
      return;
    }
    if (!exists) {
      pushUndo();
      const newConn = {
        id: `w_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 5)}`,
        from: { compId: pendingPort.compId, portId: pendingPort.portId },
        to: { compId, portId },
      };
      setConnections((prev) => [...prev, newConn]);
      notify('Connected hydraulic line');
    }
    setPendingPort(null);
  };

  const handleDropOnCanvas = (e) => {
    e.preventDefault();
    const type = e.dataTransfer.getData('text/hydrasim-type');
    if (!type || !COMPONENT_CATALOG[type]) return;
    const pt = screenToWorld(e.clientX, e.clientY);
    addComponentAt(type, pt.x, pt.y);
  };

  // --- Oscilloscope Panel Vertical Resizer ---
  const startResizeBottom = (e) => {
    e.preventDefault();
    const startY = e.clientY;
    const startH = bottomHeight;
    const onMove = (ev) => {
      setBottomHeight(Math.max(120, Math.min(420, startH + (startY - ev.clientY))));
    };
    const onUp = () => {
      window.removeEventListener('mousemove', onMove);
      window.removeEventListener('mouseup', onUp);
    };
    window.addEventListener('mousemove', onMove);
    window.addEventListener('mouseup', onUp);
  };

  // --- Filtered Catalog & Selected Component ---
  const filteredCatalogByCat = useMemo(() => {
    const q = searchQuery.trim().toLowerCase();
    const map = {};
    for (const cat of CATEGORIES) map[cat] = [];
    for (const key of Object.keys(COMPONENT_CATALOG)) {
      const item = COMPONENT_CATALOG[key];
      if (!q || item.name.toLowerCase().includes(q) || item.shortName.toLowerCase().includes(q) || item.category.toLowerCase().includes(q)) {
        if (!map[item.category]) map[item.category] = [];
        map[item.category].push(item);
      }
    }
    return map;
  }, [searchQuery]);

  const selectedComp = selectedIds.length === 1 ? components.find((c) => c.id === selectedIds[0]) : null;
  const selectedDef = selectedComp ? COMPONENT_CATALOG[selectedComp.type] : null;
  const selectedMetrics = selectedComp ? simState.compMetrics[selectedComp.id] : null;
  const errorCount = diagnostics.filter((d) => d.severity === 'error').length;
  const warnCount = diagnostics.filter((d) => d.severity === 'warning').length;

  const handleUnitPresetChange = (presetKey) => {
    setUnitPreset(presetKey);
    if (UNIT_PRESETS[presetKey]) setUnits(UNIT_PRESETS[presetKey]);
  };

  const pendingPortWorld = useMemo(() => {
    if (!pendingPort) return null;
    const comp = components.find((c) => c.id === pendingPort.compId);
    return comp ? getDynamicRodPortWorldPos(comp, pendingPort.portId, simState.compMetrics[comp.id], groupLayouts) : null;
  }, [pendingPort, components, simState.compMetrics, groupLayouts]);

  return (
    <div className="h-full w-full flex flex-col bg-slate-100 text-slate-900 overflow-hidden font-sans">
      {/* ==================== TOP ENGINEERING TOOLBAR ==================== */}
      <header className="h-11 bg-slate-900 text-slate-100 border-b border-slate-800 px-2.5 flex items-center justify-between gap-2 shrink-0 z-30">
        {/* Left: Brand & File Actions */}
        <div className="flex items-center gap-1.5 min-w-0">
          <div className="flex items-center gap-1.5 pr-2 border-r border-slate-700">
            <div className="w-6 h-6 rounded bg-sky-500 flex items-center justify-center text-white font-black text-xs shadow">H</div>
            <span className="font-bold text-sm tracking-tight text-white">HydroSim</span>
            <span className="hidden xl:inline text-[10px] font-mono text-sky-400 bg-slate-800 px-1.5 py-0.5 rounded">ISO 1219</span>
          </div>

          <button onClick={handleNewCircuit} title="New Blank Circuit" className="p-1.5 hover:bg-slate-800 rounded text-slate-300 hover:text-white">
            <FilePlus size={15} />
          </button>
          <button onClick={() => fileInputRef.current?.click()} title="Open JSON File" className="p-1.5 hover:bg-slate-800 rounded text-slate-300 hover:text-white">
            <Upload size={15} />
          </button>
          <input ref={fileInputRef} type="file" accept=".json" onChange={handleLoadJSON} className="hidden" />
          <button onClick={handleSaveJSON} title="Download JSON" className="p-1.5 hover:bg-slate-800 rounded text-slate-300 hover:text-white">
            <Download size={15} />
          </button>



          {/* Examples Dropdown */}
          <div className="relative">
            <button
              onClick={() => { setShowExamples((v) => !v); setShowExportMenu(false); }}
              className="flex items-center gap-1 px-2 py-1 text-xs font-medium bg-slate-800 hover:bg-slate-700 text-slate-200 rounded border border-slate-700"
            >
              <BookOpen size={13} />
              <span className="hidden sm:inline">Examples</span>
              <ChevronDown size={12} />
            </button>
            {showExamples && (
              <div className="absolute left-0 top-9 w-80 bg-white text-slate-800 rounded-lg shadow-2xl border border-slate-200 py-1.5 z-50 max-h-[70vh] overflow-y-auto">
                <div className="px-3 py-1 text-[10px] font-bold uppercase tracking-wider text-slate-400">Validated Hydraulic Circuits</div>
                {Object.keys(EXAMPLE_CIRCUITS).map((key) => {
                  const ex = EXAMPLE_CIRCUITS[key];
                  return (
                    <button
                      key={key}
                      onClick={() => loadExample(key)}
                      className="w-full text-left px-3 py-2 hover:bg-sky-50 border-b border-slate-100 last:border-0"
                    >
                      <div className="text-xs font-semibold text-slate-900">{ex.name}</div>
                      <div className="text-[11px] text-slate-500 line-clamp-2">{ex.description}</div>
                    </button>
                  );
                })}
              </div>
            )}
          </div>
        </div>

        {/* Center: Simulation Transport Controls */}
        <div className="flex items-center gap-1 bg-slate-800/90 px-2 py-1 rounded-md border border-slate-700">
          {simStatus !== 'running' ? (
            <button onClick={handleRun} className="flex items-center gap-1 px-2.5 py-1 bg-emerald-600 hover:bg-emerald-500 text-white text-xs font-semibold rounded shadow-sm">
              <Play size={13} /> Run
            </button>
          ) : (
            <button onClick={handlePause} className="flex items-center gap-1 px-2.5 py-1 bg-amber-500 hover:bg-amber-400 text-slate-950 text-xs font-semibold rounded shadow-sm">
              <Pause size={13} /> Pause
            </button>
          )}
          <button onClick={handleStopReset} title="Stop & Reset (t = 0)" className="p-1.5 hover:bg-slate-700 text-slate-300 hover:text-white rounded">
            <Square size={13} />
          </button>

          <div className="h-4 w-px bg-slate-700 mx-1" />
          <div className="font-mono text-xs text-sky-300 px-1.5 min-w-[64px] text-center">
            t = {simState.time.toFixed(2)}s
          </div>
          <select
            value={simSettings.simSpeed}
            onChange={(e) => setSimSettings((s) => ({ ...s, simSpeed: parseFloat(e.target.value) }))}
            title="Simulation Speed"
            className="bg-slate-900 border border-slate-700 text-[11px] font-mono text-slate-200 rounded px-1.5 py-0.5"
          >
            <option value={0.25}>0.25×</option>
            <option value={0.5}>0.5×</option>
            <option value={1.0}>1.0×</option>
            <option value={2.0}>2.0×</option>
          </select>
          <div className="h-4 w-px bg-slate-700 mx-0.5" />
          <label className="flex items-center gap-1 text-[10.5px] text-slate-300" title="Define simulation run-time in seconds (0 = continuous)">
            <span className="hidden sm:inline font-semibold">Run</span>
            <input
              type="number"
              min={0}
              max={3600}
              step={1}
              value={simSettings.endTime}
              onChange={(e) => setSimSettings((s) => ({ ...s, endTime: Math.max(0, parseFloat(e.target.value) || 0) }))}
              className="w-12 bg-slate-900 border border-slate-700 text-[11px] font-mono text-sky-300 rounded px-1 py-0.5 text-center"
            />
            <span className="text-[10px] font-mono text-slate-400">s</span>
          </label>
        </div>

        {/* Right: Edit Tools, Units, Export, Settings */}
        <div className="flex items-center gap-1">
          <button onClick={handleUndo} disabled={undoStack.length === 0} title="Undo (Ctrl+Z)" className="p-1.5 hover:bg-slate-800 rounded text-slate-300 disabled:opacity-30">
            <Undo2 size={14} />
          </button>
          <button onClick={handleRedo} disabled={redoStack.length === 0} title="Redo (Ctrl+Y)" className="p-1.5 hover:bg-slate-800 rounded text-slate-300 disabled:opacity-30">
            <Redo2 size={14} />
          </button>

          <div className="h-4 w-px bg-slate-700 mx-0.5 hidden lg:block" />
          <div className="hidden lg:flex items-center gap-0.5">
            <button onClick={() => handleRotateSelected(-90)} disabled={selectedIds.length === 0} title="Rotate CCW" className="p-1.5 hover:bg-slate-800 rounded text-slate-300 disabled:opacity-30"><RotateCcw size={14} /></button>
            <button onClick={() => handleRotateSelected(90)} disabled={selectedIds.length === 0} title="Rotate CW (R)" className="p-1.5 hover:bg-slate-800 rounded text-slate-300 disabled:opacity-30"><RotateCw size={14} /></button>
            <button onClick={() => handleFlipSelected('flipX')} disabled={selectedIds.length === 0} title="Flip Horizontal" className="p-1.5 hover:bg-slate-800 rounded text-slate-300 disabled:opacity-30"><FlipHorizontal size={14} /></button>
            <button onClick={() => handleFlipSelected('flipY')} disabled={selectedIds.length === 0} title="Flip Vertical" className="p-1.5 hover:bg-slate-800 rounded text-slate-300 disabled:opacity-30"><FlipVertical size={14} /></button>
            <button onClick={handleCopy} disabled={selectedIds.length === 0} title="Copy (Ctrl+C)" className="p-1.5 hover:bg-slate-800 rounded text-slate-300 disabled:opacity-30"><Copy size={14} /></button>
            <button onClick={handlePaste} disabled={!clipboard} title="Paste (Ctrl+V)" className="p-1.5 hover:bg-slate-800 rounded text-slate-300 disabled:opacity-30"><Clipboard size={14} /></button>
            <button onClick={handleGroupSelected} disabled={selectedIds.length < 2} title="Group Selected Components" className="px-1.5 py-1 hover:bg-slate-800 rounded text-[10px] font-bold text-slate-300 disabled:opacity-30">GRP</button>
            <button onClick={handleUngroupSelected} disabled={selectedIds.length === 0} title="Ungroup Selected" className="px-1.5 py-1 hover:bg-slate-800 rounded text-[10px] font-bold text-slate-300 disabled:opacity-30">UNGRP</button>
            <button onClick={handleDeleteSelected} disabled={selectedIds.length === 0 && !selectedConnId} title="Delete (Del)" className="p-1.5 hover:bg-red-900/60 hover:text-red-300 rounded text-slate-300 disabled:opacity-30"><Trash2 size={14} /></button>
          </div>

          <div className="h-4 w-px bg-slate-700 mx-0.5" />
          <select
            value={unitPreset}
            onChange={(e) => handleUnitPresetChange(e.target.value)}
            className="hidden sm:block bg-slate-800 border border-slate-700 text-[11px] text-slate-200 rounded px-1.5 py-1"
            title="Engineering Unit Preset"
          >
            {Object.keys(UNIT_PRESETS).map((k) => (
              <option key={k} value={k}>{UNIT_PRESETS[k].short}</option>
            ))}
          </select>

          <div className="relative">
            <button
              onClick={() => { setShowExportMenu((v) => !v); setShowExamples(false); }}
              className="flex items-center gap-1 px-2 py-1 text-xs font-medium bg-slate-800 hover:bg-slate-700 text-slate-200 rounded border border-slate-700"
            >
              <FileSpreadsheet size={13} />
              <span className="hidden md:inline">Export</span>
            </button>
            {showExportMenu && (
              <div className="absolute right-0 top-9 w-48 bg-white text-slate-800 rounded-lg shadow-xl border border-slate-200 py-1 z-50 text-xs">
                <button onClick={handleExportCSV} className="w-full px-3 py-2 text-left hover:bg-sky-50 flex items-center gap-2"><FileSpreadsheet size={14} className="text-emerald-600" /> Telemetry CSV</button>
                <button onClick={handleExportSVG} className="w-full px-3 py-2 text-left hover:bg-sky-50 flex items-center gap-2"><FileCode size={14} className="text-sky-600" /> Schematic SVG</button>
                <button onClick={handleExportPNG} className="w-full px-3 py-2 text-left hover:bg-sky-50 flex items-center gap-2"><Image size={14} className="text-violet-600" /> Schematic PNG (2×)</button>
                <button onClick={handleExportChartPNG} className="w-full px-3 py-2 text-left hover:bg-sky-50 flex items-center gap-2"><Activity size={14} className="text-amber-600" /> Chart PNG (2×)</button>
                <button onClick={handleExportPDFReport} className="w-full px-3 py-2 text-left hover:bg-sky-50 flex items-center gap-2 border-t border-slate-100 font-semibold text-sky-700"><BookOpen size={14} className="text-sky-600" /> PDF Eng. Report</button>
              </div>
            )}
          </div>

          <button
            onClick={handleResetLayout}
            title="Reset Workspace Layout (Restore all docked windows)"
            className="px-2 py-1 text-[11px] font-semibold bg-slate-800 hover:bg-slate-700 text-slate-200 rounded border border-slate-700 whitespace-nowrap"
          >
            ↺ Layout
          </button>

          <button onClick={() => setShowSettingsModal(true)} title="Simulation & Workspace Settings" className="p-1.5 hover:bg-slate-800 rounded text-slate-300 hover:text-white">
            <Settings size={15} />
          </button>
        </div>
      </header>

      {/* ==================== MULTI-CIRCUIT TABS BAR ==================== */}
      <div className="h-8 bg-slate-800 border-b border-slate-700 px-2 flex items-center gap-1 overflow-x-auto shrink-0 z-20 text-xs">
        {circuitTabs.map((t) => {
          const isAct = t.id === activeTabId;
          const label = isAct ? circuitTitle : t.title;
          return (
            <div
              key={t.id}
              onClick={() => handleSwitchCircuitTab(t.id)}
              className={`group flex items-center gap-1.5 px-2.5 py-1 rounded-t border-t border-x cursor-pointer select-none shrink-0 transition-colors ${
                isAct
                  ? 'bg-slate-100 text-slate-900 border-slate-300 font-semibold'
                  : 'bg-slate-900/70 text-slate-300 border-slate-700 hover:bg-slate-700/70 hover:text-white'
              }`}
            >
              <span className="truncate max-w-[160px]">{label}</span>
              <button
                type="button"
                onClick={(e) => handleCloseCircuitTab(e, t.id)}
                title="Close tab"
                className={`ml-0.5 rounded px-1 leading-none text-[11px] ${
                  isAct ? 'text-slate-500 hover:bg-slate-300 hover:text-slate-900' : 'text-slate-400 hover:bg-slate-600 hover:text-white'
                }`}
              >
                ×
              </button>
            </div>
          );
        })}
        <button
          type="button"
          onClick={handleNewCircuit}
          title="New Circuit in New Tab"
          className="px-2 py-0.5 rounded bg-slate-700 hover:bg-sky-600 text-slate-200 hover:text-white font-bold text-xs leading-none shrink-0 cursor-pointer"
        >
          + New Tab
        </button>
      </div>

      {/* ==================== MAIN 3-COLUMN WORKSPACE ==================== */}
      <div className="flex-1 flex min-h-0 overflow-hidden">
        {/* LEFT SIDEBAR: 28-COMPONENT ISO 1219 LIBRARY */}
        <aside className="w-60 bg-white border-r border-slate-200 flex flex-col shrink-0 z-20">
          <div className="p-2 border-b border-slate-200 space-y-1.5">

            <div className="relative">
              <Search size={13} className="absolute left-2 top-2 text-slate-400" />
              <input
                type="text"
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                placeholder="Filter valves, pumps..."
                className="w-full pl-7 pr-2 py-1 text-xs bg-slate-50 border border-slate-200 rounded focus:outline-none focus:border-sky-500"
              />
            </div>
          </div>

          <div className="flex-1 overflow-y-auto p-1.5 space-y-1">
            {CATEGORIES.map((cat) => {
              const items = filteredCatalogByCat[cat] || [];
              if (items.length === 0) return null;
              const isCollapsed = collapsedCats[cat] && !searchQuery;
              return (
                <div key={cat} className="border border-slate-100 rounded overflow-hidden">
                  <button
                    onClick={() => setCollapsedCats((prev) => ({ ...prev, [cat]: !prev[cat] }))}
                    className="w-full flex items-center justify-between px-2 py-1.5 bg-slate-50 hover:bg-slate-100 text-[11px] font-semibold text-slate-700"
                  >
                    <span className="truncate">{cat}</span>
                    {isCollapsed ? <ChevronRight size={13} /> : <ChevronDown size={13} />}
                  </button>
                  {!isCollapsed && (
                    <div className="p-1 space-y-1 bg-white">
                      {items.map((item) => (
                        <div
                          key={item.type}
                          draggable
                          onDragStart={(e) => e.dataTransfer.setData('text/hydrasim-type', item.type)}
                          title={`Drag onto canvas or click + to add ${item.name}`}
                          className="flex items-center gap-1.5 p-1.5 rounded border border-slate-100 hover:border-sky-300 hover:bg-sky-50/70 cursor-grab active:cursor-grabbing transition-colors"
                        >
                          <button
                            type="button"
                            onClick={(e) => { e.stopPropagation(); addComponentAt(item.type, (360 - view.x) / view.zoom, (220 - view.y) / view.zoom); }}
                            title={`Add ${item.name} to circuit`}
                            className="w-5 h-5 shrink-0 rounded bg-sky-50 hover:bg-sky-600 text-sky-700 hover:text-white border border-sky-200 hover:border-sky-600 flex items-center justify-center font-bold text-xs leading-none transition-colors cursor-pointer"
                          >
                            +
                          </button>
                          <LibraryMiniIcon type={item.type} />
                          <div className="min-w-0">
                            <div className="text-[11px] font-semibold text-slate-800 truncate">{item.shortName}</div>
                            <div className="text-[9.5px] text-slate-400 truncate">{item.ports.length} port{item.ports.length > 1 ? 's' : ''}</div>
                          </div>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        </aside>

        {/* CENTER COLUMN: CIRCUIT WINDOW + PLOT WINDOW */}
        <div className="flex-1 flex flex-col min-w-0 overflow-hidden">
          {/* CIRCUIT WINDOW */}
          {!winState.circuit.min && (
          <div
            style={winState.circuit.floating ? { left: winState.circuit.x, top: winState.circuit.y, width: winState.circuit.w, height: winState.circuit.h } : undefined}
            className={`${winState.circuit.floating ? 'hs-panel-floating' : winState.circuit.max ? 'hs-panel-max' : 'flex-1 min-h-0'} flex flex-col bg-slate-50 overflow-hidden`}
          >
          {/* Circuit Window Header */}
          <div
            onMouseDown={(e) => startFloatDrag(e, 'circuit')}
            className={`h-8 bg-white border-b border-slate-200 px-3 flex items-center justify-between text-xs shrink-0 ${winState.circuit.floating ? 'cursor-move' : ''}`}
          >
            <div className="flex items-center gap-2 min-w-0">
              <span className="font-bold text-slate-800 truncate">{circuitTitle}</span>
              <span className="hidden lg:inline text-slate-400 truncate">— {circuitDesc}</span>
            </div>
            <div className="flex items-center gap-1 shrink-0">
              <button
                onClick={() => setToolMode('select')}
                title="Select / Wire Tool"
                className={`p-1 rounded ${toolMode === 'select' ? 'bg-sky-100 text-sky-700' : 'text-slate-500 hover:bg-slate-100'}`}
              >
                <MousePointer size={13} />
              </button>
              <button
                onClick={() => setToolMode('pan')}
                title="Pan Canvas Tool"
                className={`p-1 rounded ${toolMode === 'pan' ? 'bg-sky-100 text-sky-700' : 'text-slate-500 hover:bg-slate-100'}`}
              >
                <Hand size={13} />
              </button>
              <div className="w-px h-3.5 bg-slate-200 mx-0.5" />
              <button onClick={() => setView((v) => ({ ...v, zoom: Math.min(2.5, v.zoom * 1.15) }))} title="Zoom In" className="p-1 text-slate-500 hover:bg-slate-100 rounded"><ZoomIn size={13} /></button>
              <span className="font-mono text-[10px] text-slate-500 w-9 text-center">{Math.round(view.zoom * 100)}%</span>
              <button onClick={() => setView((v) => ({ ...v, zoom: Math.max(0.35, v.zoom * 0.87) }))} title="Zoom Out" className="p-1 text-slate-500 hover:bg-slate-100 rounded"><ZoomOut size={13} /></button>
              <button onClick={handleFitView} title="Fit Schematic to View" className="p-1 text-slate-500 hover:bg-slate-100 rounded"><Maximize2 size={13} /></button>
              <div className="w-px h-3.5 bg-slate-200 mx-0.5" />
              <button
                type="button"
                onClick={() => {
                  const nextVal = !simSettings.showLiveBadges;
                  setSimSettings((s) => ({ ...s, showLiveBadges: nextVal }));
                  setComponents((prev) => prev.map((c) => (c.showBadge !== undefined ? { ...c, showBadge: undefined } : c)));
                  notify(nextVal ? 'Showing all component readings' : 'Hidden all component readings');
                }}
                title={simSettings.showLiveBadges ? 'Hide all component readings/parameters on canvas' : 'Show all component readings/parameters on canvas'}
                className={`px-1.5 py-0.5 rounded text-[10.5px] font-semibold border transition-colors cursor-pointer ${
                  simSettings.showLiveBadges
                    ? 'bg-sky-50 text-sky-700 border-sky-200 hover:bg-sky-100'
                    : 'bg-slate-100 text-slate-500 border-slate-200 hover:bg-slate-200'
                }`}
              >
                {simSettings.showLiveBadges ? '👁 Readings' : '👁‍🗨 Hidden'}
              </button>
              <button
                type="button"
                onClick={() => {
                  const nextVal = !(simSettings.showComponentNames ?? true);
                  setSimSettings((s) => ({ ...s, showComponentNames: nextVal }));
                  setComponents((prev) => prev.map((c) => (c.showName !== undefined ? { ...c, showName: undefined } : c)));
                  notify(nextVal ? 'Showing all component names' : 'Hidden all component names');
                }}
                title={(simSettings.showComponentNames ?? true) ? 'Hide all component names/tags on canvas' : 'Show all component names/tags on canvas'}
                className={`px-1.5 py-0.5 rounded text-[10.5px] font-semibold border transition-colors cursor-pointer ${
                  (simSettings.showComponentNames ?? true)
                    ? 'bg-sky-50 text-sky-700 border-sky-200 hover:bg-sky-100'
                    : 'bg-slate-100 text-slate-500 border-slate-200 hover:bg-slate-200'
                }`}
              >
                {(simSettings.showComponentNames ?? true) ? '🏷 Names' : '🏷 Hidden'}
              </button>
              <WinControls panelKey="circuit" />
            </div>
          </div>

          {/* INTERACTIVE SVG SCHEMATIC CANVAS */}
          <div
            className={`flex-1 relative bg-slate-50 overflow-hidden ${toolMode === 'pan' ? 'cursor-grab active:cursor-grabbing' : 'cursor-default'}`}
            onDragOver={(e) => e.preventDefault()}
            onDrop={handleDropOnCanvas}
          >
            <svg
              ref={svgCanvasRef}
              className="w-full h-full block"
              onMouseDown={handleCanvasMouseDown}
              onMouseMove={handleCanvasMouseMove}
              onMouseUp={handleCanvasMouseUp}
              onWheel={handleCanvasWheel}
            >
              <defs>
                <pattern id="hydrasim-grid" width={GRID_SIZE * view.zoom} height={GRID_SIZE * view.zoom} patternUnits="userSpaceOnUse" x={view.x % (GRID_SIZE * view.zoom)} y={view.y % (GRID_SIZE * view.zoom)}>
                  <path d={`M ${GRID_SIZE * view.zoom} 0 L 0 0 0 ${GRID_SIZE * view.zoom}`} fill="none" stroke="#e2e8f0" strokeWidth={0.8} />
                </pattern>
              </defs>

              {simSettings.showGrid && <rect width="100%" height="100%" fill="url(#hydrasim-grid)" />}

              <g id="hydrasim-scene-root" transform={`translate(${view.x}, ${view.y}) scale(${view.zoom})`}>
                {/* Hydraulic Connections with Directional Flow Arrows & Non-Connecting Bridge Jumps */}
                {(() => {
                  const renderedHorizSegs = [];
                  return connections.map((w) => {
                  const c1 = components.find((c) => c.id === w.from.compId);
                  const c2 = components.find((c) => c.id === w.to.compId);
                  if (!c1 || !c2) return null;
                  if (c1.groupId && c1.groupId === c2.groupId && groupLayouts[c1.groupId]) return null;
                  const p1 = getDynamicRodPortWorldPos(c1, w.from.portId, simState.compMetrics[c1.id], groupLayouts);
                  const p2 = getDynamicRodPortWorldPos(c2, w.to.portId, simState.compMetrics[c2.id], groupLayouts);
                  const mOff = w.midOffset || 0;
                  const pathD = buildOrthogonalPathWithBridges(p1, p2, mOff, renderedHorizSegs);
                  for (const [sa, sb] of getOrthogonalSegments(p1, p2, mOff)) {
                    if (Math.abs(sa.y - sb.y) < 1.5 && Math.abs(sa.x - sb.x) > 4) {
                      renderedHorizSegs.push([sa, sb]);
                    }
                  }
                  const dragInfo = getWireDragInfo(p1, p2, mOff);
                  const nodeIdx = topology.portToNode[`${w.from.compId}:${w.from.portId}`];
                  const pBar = nodeIdx !== undefined ? (simState.pressures[nodeIdx] || 0) / PA_PER_BAR : 0;
                  const qLpm = simState.connFlows[w.id] || 0;
                  const isSel = selectedConnId === w.id;
                  const pt1Def = COMPONENT_CATALOG[c1.type]?.ports?.find((p) => p.id === w.from.portId);
                  const pt2Def = COMPONENT_CATALOG[c2.type]?.ports?.find((p) => p.id === w.to.portId);
                  const isSigWire = !!(pt1Def?.isSignal || pt2Def?.isSignal);
                  const isMechWire = !!(pt1Def?.isMech || pt2Def?.isMech);
                  const lineColor = isMechWire ? (isSel ? '#0ea5e9' : '#059669') : isSigWire ? (isSel ? '#0ea5e9' : '#7c3aed') : (isSel ? '#0ea5e9' : simState.time > 0 ? getSchematicPressureColor(pBar, simSettings.pressureColors) : 'var(--hs-wire, #64748b)');
                  const hasFlow = Math.abs(qLpm) >= 0.05;
                  const arrows = !isSigWire && !isMechWire && hasFlow ? getFlowArrowMarkers(p1, p2, qLpm < 0, mOff) : [];

                  return (
                    <g key={w.id} onMouseDown={(e) => handleWireMouseDown(e, w, dragInfo.axis)} onClick={(e) => { e.stopPropagation(); setSelectedConnId(w.id); setSelectedIds([]); }} className={dragInfo.axis === 'x' ? 'cursor-ew-resize' : 'cursor-ns-resize'}>
                      <path d={pathD} fill="none" stroke="transparent" strokeWidth={12} />
                      <path d={pathD} fill="none" stroke={lineColor} strokeWidth={isSel ? 3.5 : (isMechWire ? 3.0 : isSigWire ? 1.9 : 2.4)} strokeDasharray={isSigWire ? '5 3' : undefined} strokeLinejoin="round" />
                      {simStatus === 'running' && hasFlow && (
                        <path
                          d={pathD}
                          fill="none"
                          stroke="#ffffff"
                          strokeOpacity={0.75}
                          strokeWidth={1.6}
                          className={qLpm > 0 ? 'hydrasim-flow-fwd' : 'hydrasim-flow-rev'}
                        />
                      )}
                      {arrows.map((ar, idx) => (
                        <g key={idx} transform={`translate(${ar.x}, ${ar.y}) rotate(${ar.angleDeg})`} className="pointer-events-none">
                          <polygon points="7,0 -5,-4.5 -2.5,0 -5,4.5" fill={lineColor} stroke="#ffffff" strokeWidth={1.1} strokeLinejoin="round" />
                        </g>
                      ))}
                    </g>
                  );
                  });
                })()}

                {/* Pending Wire Preview */}
                {pendingPortWorld && (
                  <path
                    d={buildOrthogonalPath(pendingPortWorld, mouseWorld)}
                    fill="none"
                    stroke="#0284c7"
                    strokeWidth={2}
                    strokeDasharray="5 4"
                    className="pointer-events-none"
                  />
                )}

                {/* Ungrouped Hydraulic Components (Resizable) */}
                {components.map((comp) => {
                  if (comp.groupId && groupLayouts[comp.groupId]) return null;
                  const def = COMPONENT_CATALOG[comp.type];
                  if (!def) return null;
                  const isSelected = selectedIds.includes(comp.id);
                  const metrics = simState.compMetrics[comp.id];
                  const sc = comp.scale || 1;
                  const transformStr = `translate(${comp.x}, ${comp.y}) rotate(${comp.rotation || 0}) scale(${(comp.flipX ? -1 : 1) * sc}, ${(comp.flipY ? -1 : 1) * sc})`;
                  const boxHW = (def.width / 2 + 6) * sc;
                  const boxHH = (def.height / 2 + 6) * sc;

                  return (
                    <g key={comp.id} onMouseDown={(e) => handleCompMouseDown(e, comp)} className="cursor-move">
                      <g transform={transformStr}>
                        <HydraulicSymbol
                          comp={comp}
                          metrics={metrics}
                          isRunning={simStatus === 'running'}
                          onToggleSpool={handleToggleSpool}
                          onBadgeMouseDown={handleBadgeMouseDown}
                          units={units}
                          showBadges={comp.showBadge !== undefined ? comp.showBadge : simSettings.showLiveBadges}
                        />
                      </g>

                      {isSelected && (
                        <g>
                          <rect
                            x={comp.x - boxHW}
                            y={comp.y - boxHH}
                            width={boxHW * 2}
                            height={boxHH * 2}
                            rx={6}
                            fill="#0ea5e9"
                            fillOpacity={0.07}
                            stroke="#0284c7"
                            strokeWidth={1.5}
                            strokeDasharray="4 2"
                            className="pointer-events-none"
                          />
                          {selectedIds.length === 1 && (
                            <g
                              onMouseDown={(e) => handleResizeMouseDown(e, comp)}
                              className="cursor-nwse-resize"
                              title="Drag to resize component"
                            >
                              <rect
                                x={comp.x + boxHW - 5}
                                y={comp.y + boxHH - 5}
                                width={10}
                                height={10}
                                rx={2}
                                fill="#0284c7"
                                stroke="#ffffff"
                                strokeWidth={1.5}
                              />
                            </g>
                          )}
                        </g>
                      )}

                      {/* Movable Component Label */}
                      {(comp.showName !== undefined ? comp.showName : (simSettings.showComponentNames ?? true)) && (
                        <text
                          x={comp.x + (comp.labelDx || 0)}
                          y={comp.y + (def.height / 2) * sc + 16 + (comp.labelDy || 0)}
                          textAnchor="middle"
                          fontSize={10}
                          fontWeight="700"
                          fill={isSelected ? '#0ea5e9' : 'var(--hs-label, #64748b)'}
                          onMouseDown={(e) => handleLabelMouseDown(e, comp)}
                          className="cursor-move select-none"
                          title="Drag to move label"
                        >
                          {comp.name}
                        </text>
                      )}

                      {/* Interactive Ports */}
                      {def.ports.map((pt) => {
                        if (pt.isSignal && pt.id === 'S' && comp.type !== 'pump' && comp.type !== 'var_pump' && comp.type !== 'gear_pump' && comp.type !== 'vane_pump' && comp.type !== 'piston_pump' && comp.params?.controlMode !== 'signal') return null;
                        const wp = getDynamicRodPortWorldPos(comp, pt.id, metrics, null);
                        const isPending = pendingPort?.compId === comp.id && pendingPort?.portId === pt.id;
                        return (
                          <g key={pt.id} onMouseDown={(e) => e.stopPropagation()} onClick={(e) => handlePortClick(e, comp.id, pt.id)} className="cursor-crosshair">
                            <circle cx={wp.x} cy={wp.y} r={9} fill="transparent" />
                            <circle
                              cx={wp.x}
                              cy={wp.y}
                              r={isPending ? 5.5 : 4}
                              fill={isPending ? '#0284c7' : (pt.isMech ? '#d1fae5' : pt.isSignal ? '#ede9fe' : '#ffffff')}
                              stroke={isPending ? '#0369a1' : (pt.isMech ? '#059669' : pt.isSignal ? '#7c3aed' : '#0284c7')}
                              strokeWidth={1.8}
                            />
                            {simSettings.showPortLabels && (
                              <text x={wp.x + 7} y={wp.y - 5} fontSize={8.5} fontWeight="700" fill="#64748b" className="pointer-events-none">
                                {pt.label}
                              </text>
                            )}
                          </g>
                        );
                      })}
                    </g>
                  );
                })}

                {/* Grouped Subsystem Boxes (Dynamic Inlet & Outlet Ports) */}
                {Object.values(groupLayouts).map((grp) => {
                  const isSel = grp.memberIds.some((id) => selectedIds.includes(id));
                  const x0 = grp.cx - grp.width / 2;
                  const y0 = grp.cy - grp.height / 2;
                  const memberSummary = grp.members.map((m) => m.name).join(', ');
                  return (
                    <g key={grp.groupId} onMouseDown={(e) => handleGroupBoxMouseDown(e, grp)} className="cursor-move">
                      <rect
                        x={x0}
                        y={y0}
                        width={grp.width}
                        height={grp.height}
                        rx={8}
                        fill="var(--hs-fill, #ffffff)"
                        stroke={isSel ? '#0ea5e9' : 'var(--hs-stroke, #334155)'}
                        strokeWidth={isSel ? 2.4 : 1.8}
                      />
                      {/* Subsystem Header Bar */}
                      <path
                        d={`M ${x0} ${y0 + 22} L ${x0} ${y0 + 8} Q ${x0} ${y0} ${x0 + 8} ${y0} L ${x0 + grp.width - 8} ${y0} Q ${x0 + grp.width} ${y0} ${x0 + grp.width} ${y0 + 8} L ${x0 + grp.width} ${y0 + 22} Z`}
                        fill={isSel ? '#0284c7' : '#1e293b'}
                      />
                      <text x={x0 + 8} y={y0 + 14.5} fontSize={10} fontWeight="700" fill="#ffffff" className="pointer-events-none">
                        {grp.name} ({grp.members.length})
                      </text>
                      {/* Quick Ungroup Button on Box */}
                      <g
                        onMouseDown={(e) => e.stopPropagation()}
                        onClick={(e) => { e.stopPropagation(); handleUngroupById(grp.groupId); }}
                        className="cursor-pointer"
                        title="Ungroup subsystem"
                      >
                        <rect x={x0 + grp.width - 36} y={y0 + 4} width={30} height={14} rx={3} fill="#ffffff" fillOpacity={0.2} />
                        <text x={x0 + grp.width - 21} y={y0 + 13.5} textAnchor="middle" fontSize={7.5} fontWeight="700" fill="#ffffff" className="pointer-events-none">
                          SPLIT
                        </text>
                      </g>

                      {/* Internal member summary */}
                      <text x={grp.cx} y={y0 + grp.height - 8} textAnchor="middle" fontSize={8.5} fontFamily="monospace" fill="#64748b" className="pointer-events-none">
                        {memberSummary.length > 22 ? memberSummary.slice(0, 21) + '…' : memberSummary}
                      </text>

                      {/* Inlet Ports (Left Edge) */}
                      {grp.inlets.map((pt) => {
                        const isPending = pendingPort?.compId === pt.compId && pendingPort?.portId === pt.portId;
                        return (
                          <g key={pt.key} onMouseDown={(e) => e.stopPropagation()} onClick={(e) => handlePortClick(e, pt.compId, pt.portId)} className="cursor-crosshair">
                            <circle cx={pt.x} cy={pt.y} r={9} fill="transparent" />
                            <circle cx={pt.x} cy={pt.y} r={isPending ? 5.5 : 4.5} fill={isPending ? '#0284c7' : '#dcfce7'} stroke="#15803d" strokeWidth={1.8} />
                            <text x={pt.x + 8} y={pt.y + 3} fontSize={8.5} fontWeight="700" fill="#15803d" fontFamily="monospace" className="pointer-events-none">
                              IN·{pt.label}
                            </text>
                          </g>
                        );
                      })}

                      {/* Outlet Ports (Right Edge) */}
                      {grp.outlets.map((pt) => {
                        const isPending = pendingPort?.compId === pt.compId && pendingPort?.portId === pt.portId;
                        return (
                          <g key={pt.key} onMouseDown={(e) => e.stopPropagation()} onClick={(e) => handlePortClick(e, pt.compId, pt.portId)} className="cursor-crosshair">
                            <circle cx={pt.x} cy={pt.y} r={9} fill="transparent" />
                            <circle cx={pt.x} cy={pt.y} r={isPending ? 5.5 : 4.5} fill={isPending ? '#0284c7' : '#fef3c7'} stroke="#b45309" strokeWidth={1.8} />
                            <text x={pt.x - 8} y={pt.y + 3} textAnchor="end" fontSize={8.5} fontWeight="700" fill="#b45309" fontFamily="monospace" className="pointer-events-none">
                              {pt.label}·OUT
                            </text>
                          </g>
                        );
                      })}
                    </g>
                  );
                })}

                {/* Marquee Selection Box */}
                {marquee && (
                  <rect
                    x={Math.min(marquee.x0, marquee.x1)}
                    y={Math.min(marquee.y0, marquee.y1)}
                    width={Math.abs(marquee.x1 - marquee.x0)}
                    height={Math.abs(marquee.y1 - marquee.y0)}
                    fill="#0ea5e9"
                    fillOpacity={0.12}
                    stroke="#0284c7"
                    strokeWidth={1}
                    strokeDasharray="4 2"
                  />
                )}
              </g>
            </svg>

            {/* Editable Pressure Color Legend */}
            {(() => {
              const pc = { ...DEFAULT_PRESSURE_COLORS, ...(simSettings.pressureColors || {}) };
              const p1Disp = convertToDisplay(pc.lowMaxBar, 'pressure', units).toFixed(0);
              const p2Disp = convertToDisplay(pc.midMaxBar, 'pressure', units).toFixed(0);
              const p3Disp = convertToDisplay(pc.highMaxBar, 'pressure', units).toFixed(0);
              return (
                <button
                  type="button"
                  onClick={() => setShowSettingsModal(true)}
                  title="Click to customize hydraulic line pressure color coding"
                  className="absolute bottom-2.5 left-2.5 bg-white/90 hover:bg-white backdrop-blur-sm border border-slate-200 hover:border-sky-400 rounded px-2.5 py-1 flex items-center gap-3 text-[10px] font-mono text-slate-600 shadow-sm cursor-pointer"
                >
                  <span className="flex items-center gap-1"><span className="w-2.5 h-1.5 rounded-sm" style={{ backgroundColor: pc.lowColor }} /> &lt;{p1Disp}</span>
                  <span className="flex items-center gap-1"><span className="w-2.5 h-1.5 rounded-sm" style={{ backgroundColor: pc.midColor }} /> {p1Disp}–{p2Disp}</span>
                  <span className="flex items-center gap-1"><span className="w-2.5 h-1.5 rounded-sm" style={{ backgroundColor: pc.highColor }} /> {p2Disp}–{p3Disp}</span>
                  <span className="flex items-center gap-1"><span className="w-2.5 h-1.5 rounded-sm" style={{ backgroundColor: pc.peakColor }} /> &gt;{p3Disp} {units.pressure}</span>
                </button>
              );
            })()}

            {pendingPort && (
              <div className="absolute top-2.5 left-1/2 -translate-x-1/2 bg-sky-600 text-white text-xs px-3 py-1 rounded-full shadow-md font-medium">
                Click another port to connect hydraulic line · Esc to cancel
              </div>
            )}
          </div>

          </div>
          )}

          {/* PLOT WINDOW (OSCILLOSCOPE) */}
          {!winState.plot.min && (
          <div
            style={
              winState.plot.floating
                ? { left: winState.plot.x, top: winState.plot.y, width: winState.plot.w, height: winState.plot.h }
                : winState.plot.max || winState.circuit.min
                ? undefined
                : { height: bottomHeight }
            }
            className={`${winState.plot.floating ? 'hs-panel-floating' : winState.plot.max ? 'hs-panel-max' : (winState.circuit.min ? 'flex-1 min-h-0' : 'shrink-0')} bg-white border-t border-slate-300 flex flex-col overflow-hidden`}
          >
            {!winState.plot.floating && !winState.plot.max && !winState.plot.min && (
              <div
                onMouseDown={startResizeBottom}
                className="h-1.5 bg-slate-200 hover:bg-sky-400 cursor-ns-resize transition-colors"
                title="Drag to resize plot window"
              />
            )}
            {/* Plot Window Header + Plot Tabs + Single / Side-by-Side Layout Switcher */}
            <div
              onMouseDown={(e) => startFloatDrag(e, 'plot')}
              className={`px-2.5 py-1 bg-slate-100 border-b border-slate-200 flex items-center justify-between gap-2 flex-wrap shrink-0 relative z-30 ${winState.plot.floating ? 'cursor-move' : ''}`}
            >
              <div className="flex items-center gap-1.5 flex-wrap">
                <div className="flex items-center gap-1 mr-1">
                  <Activity size={13} className="text-sky-600" />
                  <span className="text-[11px] font-bold uppercase tracking-wider text-slate-700">Plots</span>
                </div>

                {/* Per-Circuit Plot Tabs (Inactive tabs stay minimized here in Single Tab mode) */}
                {plotTabs.map((pt) => {
                  const isActPt = pt.id === activePlotTab.id;
                  const activeCount = Object.values(pt.enabledChannels || {}).filter(Boolean).length;
                  return (
                    <div
                      key={pt.id}
                      onClick={() => { setActivePlotTabId(pt.id); }}
                      title={plotLayout === 'single' && !isActPt ? `Restore ${pt.title} (${activeCount} curves)` : pt.title}
                      className={`flex items-center gap-1 px-2 py-0.5 rounded text-[10.5px] border cursor-pointer select-none transition-colors ${
                        plotLayout === 'sideBySide'
                          ? (isActPt ? 'bg-sky-600 text-white border-sky-700 font-semibold' : 'bg-white text-slate-700 border-slate-300 hover:border-sky-400')
                          : (isActPt ? 'bg-slate-900 text-white border-slate-900 font-semibold' : 'bg-slate-200/80 text-slate-600 border-slate-300 hover:bg-white hover:text-slate-900')
                      }`}
                    >
                      <span>{pt.title}</span>
                      {plotLayout === 'single' && !isActPt && (
                        <span className="text-[9px] font-mono opacity-75">({activeCount})</span>
                      )}
                      <button
                        type="button"
                        onClick={(e) => handleClosePlotTab(e, pt.id)}
                        title="Close plot tab"
                        className="ml-0.5 px-0.5 rounded leading-none text-[10px] opacity-75 hover:opacity-100"
                      >
                        ×
                      </button>
                    </div>
                  );
                })}

                <button
                  type="button"
                  onClick={handleAddPlotTab}
                  title="Add another plot tab for this circuit"
                  className="px-2 py-0.5 rounded text-[10px] font-semibold bg-sky-600 hover:bg-sky-700 text-white cursor-pointer"
                >
                  + Plot Tab
                </button>
              </div>

              <div className="flex items-center gap-1.5 shrink-0">
                {plotTabs.length > 1 && (
                  <>
                    <div className="flex items-center rounded border border-slate-300 overflow-hidden text-[10px] font-semibold" title="Switch between single active plot tab (others minimized) and multi-plot grid view">
                      <button
                        type="button"
                        onClick={() => setPlotLayout('single')}
                        className={`px-2 py-0.5 cursor-pointer ${plotLayout === 'single' ? 'bg-slate-800 text-white' : 'bg-white text-slate-600 hover:bg-slate-50'}`}
                      >
                        Single Tab
                      </button>
                      <button
                        type="button"
                        onClick={() => setPlotLayout('sideBySide')}
                        className={`px-2 py-0.5 border-l border-slate-300 cursor-pointer ${plotLayout === 'sideBySide' ? 'bg-slate-800 text-white' : 'bg-white text-slate-600 hover:bg-slate-50'}`}
                      >
                        Grid View ({plotTabs.length})
                      </button>
                    </div>
                    {plotLayout === 'sideBySide' && (
                      <div className="flex items-center gap-1 text-[10px] font-mono text-slate-600 bg-white border border-slate-300 rounded px-1.5 py-0.5" title="Define number of plot rows × columns (e.g. 2 × 2 = 2 plots per row across 2 rows)">
                        <span>Rows</span>
                        <input
                          type="number"
                          min={1}
                          max={6}
                          value={plotLayoutRows}
                          onChange={(e) => setPlotLayoutRows(Math.max(1, Math.min(6, parseInt(e.target.value, 10) || 1)))}
                          className="w-8 px-0.5 py-0 text-center border border-slate-200 rounded bg-slate-50"
                        />
                        <span>×</span>
                        <span>Cols</span>
                        <input
                          type="number"
                          min={1}
                          max={6}
                          value={plotLayoutCols}
                          onChange={(e) => setPlotLayoutCols(Math.max(1, Math.min(6, parseInt(e.target.value, 10) || 1)))}
                          className="w-8 px-0.5 py-0 text-center border border-slate-200 rounded bg-slate-50"
                        />
                      </div>
                    )}
                  </>
                )}
                <WinControls panelKey="plot" />
              </div>
            </div>

            {/* Plot Panes Container (Single active tab OR configurable Rows × Cols grid) */}
            <div
              id="hydrasim-plot-body"
              className={`flex-1 min-h-0 ${plotLayout === 'sideBySide' && plotTabs.length > 1 ? 'grid gap-px bg-slate-300' : 'flex flex-col'}`}
              style={
                plotLayout === 'sideBySide' && plotTabs.length > 1
                  ? {
                      gridTemplateColumns: `repeat(${Math.max(1, plotLayoutCols)}, minmax(0, 1fr))`,
                      gridTemplateRows: `repeat(${Math.max(1, plotLayoutRows)}, minmax(0, 1fr))`,
                    }
                  : undefined
              }
            >
              {(plotLayout === 'sideBySide' ? plotTabs.slice(0, Math.max(1, plotLayoutRows * plotLayoutCols)) : [activePlotTab]).map((pt, paneIdx) => {
                const ptEnabled = pt.enabledChannels || {};
                const ptGridVis = pt.plotGridVisible ?? true;
                const ptGridCols = pt.plotGridCols ?? 8;
                const ptGridRows = pt.plotGridRows ?? 4;
                const ptGridColor = pt.plotGridColor || '#e2e8f0';
                const ptTMin = pt.plotTimeMin ?? '';
                const ptTMax = pt.plotTimeMax ?? '';
                const ptYMin = pt.plotYMin ?? '';
                const ptYMax = pt.plotYMax ?? '';
                const ptTipW = pt.datatipWidthPx ?? 208;
                const ptTipOp = pt.datatipOpacity ?? 0.94;
                const ptTipFs = pt.datatipFontSizePx ?? 11;
                const ptStyles = pt.lineStyles || {};
                const ptTips = pt.datatips || [];
                const activeChList = availableChannels.filter((c) => ptEnabled[c.id]);
                const isPlotCfgOpen = openChannelDropdownId === pt.id;

                return (
                  <div
                    key={pt.id}
                    onMouseDown={() => { if (activePlotTabId !== pt.id) setActivePlotTabId(pt.id); }}
                    className={`flex-1 min-w-0 min-h-0 bg-white flex flex-col overflow-hidden relative ${plotLayout === 'sideBySide' && pt.id === activePlotTab.id ? 'ring-1 ring-inset ring-sky-400/60' : ''}`}
                  >
                    {/* Minimal Single-Line Plot Header: Active Legend Summary + Small '+ Tip' & '⚙' Settings Button */}
                    <div className="h-6 px-2 bg-slate-50 border-b border-slate-200 flex items-center justify-between gap-2 shrink-0 relative z-20">
                      <div className="flex items-center gap-2 min-w-0 overflow-hidden text-[10px]">
                        {plotLayout === 'sideBySide' && (
                          <span className="font-bold text-sky-700 shrink-0">{pt.title}</span>
                        )}
                        <div className="flex items-center gap-2 min-w-0 overflow-hidden">
                          {activeChList.length === 0 ? (
                            <span className="text-slate-400 italic truncate">No curves selected (click ⚙)</span>
                          ) : (
                            activeChList.map((ch) => {
                              const st = ptStyles[ch.id] || { color: ch.color, dash: 'solid' };
                              return (
                                <span key={ch.id} className="inline-flex items-center gap-1 text-slate-700 font-medium truncate shrink-0">
                                  <svg width="12" height="6" className="shrink-0">
                                    <line
                                      x1="0" y1="3" x2="12" y2="3"
                                      stroke={st.color}
                                      strokeWidth="2"
                                      strokeDasharray={st.dash === 'dashed' ? '4 2' : st.dash === 'dotted' ? '1.5 2' : st.dash === 'dashdot' ? '5 1.5 1.5 1.5' : undefined}
                                    />
                                  </svg>
                                  <span className="truncate max-w-[110px]">{ch.label}</span>
                                </span>
                              );
                            })
                          )}
                        </div>
                      </div>

                      <div className="flex items-center gap-1 shrink-0" onMouseDown={(e) => e.stopPropagation()}>
                        <button
                          type="button"
                          onClick={() => {
                            const idx = ptTips.length + 1;
                            const frac = Math.min(0.9, Math.max(0.1, (idx * 0.22) % 0.85));
                            updatePlotTabById(pt.id, (cur) => ({
                              ...cur,
                              datatips: [...(cur.datatips || []), { id: `tip_${Date.now().toString(36)}`, fracT: frac, boxX: 60 + idx * 24, boxY: 14 + (idx % 3) * 18 }],
                            }));
                          }}
                          title="Add moveable datatip to this plot"
                          className="px-1.5 py-0.2 rounded text-[9.5px] font-semibold bg-sky-600 hover:bg-sky-700 text-white cursor-pointer"
                        >
                          + Tip
                        </button>

                        <div className="relative">
                          <button
                            type="button"
                            onClick={() => { if (!isPlotCfgOpen) { const vw = typeof window !== 'undefined' ? window.innerWidth : 1200; setPlotCfgPos((p) => ({ x: Math.min(p.x, Math.max(16, vw - 630)), y: Math.max(48, Math.min(p.y, 180)) })); } setOpenChannelDropdownId(isPlotCfgOpen ? null : pt.id); }}
                            title={`Configure ${pt.title} (Curves, Axes, Grid & Datatip Appearance)`}
                            className={`p-1 rounded border cursor-pointer flex items-center gap-0.5 text-[10px] ${
                              isPlotCfgOpen
                                ? 'bg-slate-900 text-white border-slate-900'
                                : 'bg-white text-slate-600 border-slate-300 hover:border-sky-400 hover:text-sky-700'
                            }`}
                          >
                            <Settings size={11} />
                          </button>

                          {isPlotCfgOpen && (
                            <div
                              style={{ left: `${plotCfgPos.x}px`, top: `${plotCfgPos.y}px` }}
                              onMouseDown={(e) => e.stopPropagation()}
                              onWheel={(e) => e.stopPropagation()}
                              className="fixed w-80 max-h-[75vh] overflow-y-auto pb-8 bg-white text-slate-800 border border-slate-300 rounded-lg shadow-2xl p-2.5 z-[6000] space-y-2.5 text-[10.5px]"
                            >
                              <div
                                onMouseDown={startPlotCfgDrag}
                                title="Drag to move settings popup anywhere"
                                className="flex items-center justify-between border-b border-slate-200 pb-1.5 -mx-2.5 -mt-2.5 px-2.5 pt-2 bg-slate-100 rounded-t-lg cursor-move select-none"
                              >
                                <span className="font-bold text-slate-800">⋮⋮ {pt.title} Settings</span>
                                <button
                                  type="button"
                                  onClick={() => setOpenChannelDropdownId(null)}
                                  className="text-slate-400 hover:text-slate-700 px-1 cursor-pointer"
                                >
                                  ✕
                                </button>
                              </div>

                              {/* 1. Curves Selection (Checkboxes + Color + Line Style) */}
                              <div className="space-y-1">
                                <div className="text-[9.5px] font-bold uppercase tracking-wider text-sky-700">1. Curves &amp; Line Styles</div>
                                <div className="max-h-32 overflow-y-auto border border-slate-200 rounded p-1 space-y-0.5 bg-slate-50/50">
                                  {availableChannels.length === 0 ? (
                                    <div className="py-2 text-center text-slate-400">Add components to plot curves</div>
                                  ) : (
                                    availableChannels.map((ch) => {
                                      const checked = !!ptEnabled[ch.id];
                                      const st = ptStyles[ch.id] || { color: ch.color, dash: 'solid' };
                                      return (
                                        <div key={ch.id} className={`flex items-center justify-between gap-1 px-1 py-0.5 rounded ${checked ? 'bg-sky-50' : 'hover:bg-white'}`}>
                                          <label className="flex items-center gap-1.5 min-w-0 flex-1 cursor-pointer select-none">
                                            <input
                                              type="checkbox"
                                              checked={checked}
                                              onChange={() =>
                                                updatePlotTabById(pt.id, (cur) => ({
                                                  ...cur,
                                                  enabledChannels: {
                                                    ...(cur.enabledChannels || {}),
                                                    [ch.id]: !(cur.enabledChannels || {})[ch.id],
                                                  },
                                                }))
                                              }
                                              className="rounded border-slate-300 text-sky-600 cursor-pointer shrink-0"
                                            />
                                            <span className="truncate font-medium text-slate-800">{ch.label}</span>
                                            {ch.unit && <span className="text-[9px] font-mono text-slate-400 shrink-0">({ch.unit})</span>}
                                          </label>
                                          <div className="flex items-center gap-1 shrink-0">
                                            <input
                                              type="color"
                                              value={st.color}
                                              onChange={(e) =>
                                                updatePlotTabById(pt.id, (cur) => ({
                                                  ...cur,
                                                  lineStyles: { ...(cur.lineStyles || {}), [ch.id]: { ...st, color: e.target.value } },
                                                }))
                                              }
                                              className="w-5 h-4 p-0 border border-slate-200 rounded cursor-pointer"
                                            />
                                            <select
                                              value={st.dash}
                                              onChange={(e) =>
                                                updatePlotTabById(pt.id, (cur) => ({
                                                  ...cur,
                                                  lineStyles: { ...(cur.lineStyles || {}), [ch.id]: { ...st, dash: e.target.value } },
                                                }))
                                              }
                                              className="px-1 py-0.2 bg-white border border-slate-200 rounded text-[9.5px]"
                                            >
                                              <option value="solid">───</option>
                                              <option value="dashed">╌╌</option>
                                              <option value="dotted">····</option>
                                              <option value="dashdot">─·─</option>
                                            </select>
                                          </div>
                                        </div>
                                      );
                                    })
                                  )}
                                </div>
                              </div>

                              {/* 2. X (Time) & Y Axis Range Limits */}
                              <div className="space-y-1">
                                <div className="flex items-center justify-between">
                                  <span className="text-[9.5px] font-bold uppercase tracking-wider text-sky-700">2. X &amp; Y Axis Limits</span>
                                  {(ptTMin !== '' || ptTMax !== '' || ptYMin !== '' || ptYMax !== '') && (
                                    <button
                                      type="button"
                                      onClick={() => updatePlotTabById(pt.id, { plotTimeMin: '', plotTimeMax: '', plotYMin: '', plotYMax: '' })}
                                      className="text-[9.5px] font-semibold text-sky-700 hover:underline cursor-pointer"
                                    >
                                      Reset Auto
                                    </button>
                                  )}
                                </div>
                                <div className="grid grid-cols-2 gap-1.5 font-mono">
                                  <label className="flex items-center justify-between bg-slate-50 border border-slate-200 rounded px-1.5 py-1">
                                    <span className="text-slate-500">t₀ (s)</span>
                                    <input
                                      type="number"
                                      step="any"
                                      placeholder="auto"
                                      value={ptTMin}
                                      onChange={(e) => updatePlotTabById(pt.id, { plotTimeMin: e.target.value })}
                                      className="w-14 px-1 py-0.2 bg-white border border-slate-200 rounded text-right"
                                    />
                                  </label>
                                  <label className="flex items-center justify-between bg-slate-50 border border-slate-200 rounded px-1.5 py-1">
                                    <span className="text-slate-500">t₁ (s)</span>
                                    <input
                                      type="number"
                                      step="any"
                                      placeholder="auto"
                                      value={ptTMax}
                                      onChange={(e) => updatePlotTabById(pt.id, { plotTimeMax: e.target.value })}
                                      className="w-14 px-1 py-0.2 bg-white border border-slate-200 rounded text-right"
                                    />
                                  </label>
                                  <label className="flex items-center justify-between bg-slate-50 border border-slate-200 rounded px-1.5 py-1">
                                    <span className="text-slate-500">y₀</span>
                                    <input
                                      type="number"
                                      step="any"
                                      placeholder="auto"
                                      value={ptYMin}
                                      onChange={(e) => updatePlotTabById(pt.id, { plotYMin: e.target.value })}
                                      className="w-14 px-1 py-0.2 bg-white border border-slate-200 rounded text-right"
                                    />
                                  </label>
                                  <label className="flex items-center justify-between bg-slate-50 border border-slate-200 rounded px-1.5 py-1">
                                    <span className="text-slate-500">y₁</span>
                                    <input
                                      type="number"
                                      step="any"
                                      placeholder="auto"
                                      value={ptYMax}
                                      onChange={(e) => updatePlotTabById(pt.id, { plotYMax: e.target.value })}
                                      className="w-14 px-1 py-0.2 bg-white border border-slate-200 rounded text-right"
                                    />
                                  </label>
                                </div>
                              </div>

                              {/* 3. Grid Lines */}
                              <div className="space-y-1">
                                <div className="flex items-center justify-between">
                                  <span className="text-[9.5px] font-bold uppercase tracking-wider text-sky-700">3. Grid Lines</span>
                                  <label className="flex items-center gap-1 cursor-pointer">
                                    <input
                                      type="checkbox"
                                      checked={ptGridVis}
                                      onChange={(e) => updatePlotTabById(pt.id, { plotGridVisible: e.target.checked })}
                                      className="rounded border-slate-300 text-sky-600"
                                    />
                                    <span>Visible</span>
                                  </label>
                                </div>
                                <div className="flex items-center justify-between gap-1.5 font-mono bg-slate-50 border border-slate-200 rounded px-1.5 py-1">
                                  <label className="flex items-center gap-1">
                                    <span className="text-slate-500">X</span>
                                    <input
                                      type="number"
                                      min={2}
                                      max={24}
                                      value={ptGridCols}
                                      onChange={(e) => updatePlotTabById(pt.id, { plotGridCols: Math.max(2, Math.min(24, parseInt(e.target.value, 10) || 8)) })}
                                      className="w-10 px-1 py-0.2 bg-white border border-slate-200 rounded text-center"
                                    />
                                  </label>
                                  <label className="flex items-center gap-1">
                                    <span className="text-slate-500">Y</span>
                                    <input
                                      type="number"
                                      min={2}
                                      max={20}
                                      value={ptGridRows}
                                      onChange={(e) => updatePlotTabById(pt.id, { plotGridRows: Math.max(2, Math.min(20, parseInt(e.target.value, 10) || 4)) })}
                                      className="w-10 px-1 py-0.2 bg-white border border-slate-200 rounded text-center"
                                    />
                                  </label>
                                  <label className="flex items-center gap-1">
                                    <span className="text-slate-500">Color</span>
                                    <input
                                      type="color"
                                      value={ptGridColor}
                                      onChange={(e) => updatePlotTabById(pt.id, { plotGridColor: e.target.value })}
                                      className="w-5 h-4 p-0 border border-slate-200 rounded cursor-pointer"
                                    />
                                  </label>
                                </div>
                              </div>

                              {/* 4. Datatip Box Size, Transparency & Text Size */}
                              <div className="space-y-1">
                                <div className="text-[9.5px] font-bold uppercase tracking-wider text-sky-700">4. Datatip Box Appearance</div>
                                <div className="space-y-1 bg-slate-50 border border-slate-200 rounded p-1.5 font-mono">
                                  <label className="flex items-center justify-between gap-2">
                                    <span className="text-slate-600">Box Width ({ptTipW}px)</span>
                                    <input
                                      type="range"
                                      min={150}
                                      max={380}
                                      step={4}
                                      value={ptTipW}
                                      onChange={(e) => {
                                        const wVal = Number(e.target.value);
                                        updatePlotTabById(pt.id, (cur) => ({
                                          ...cur,
                                          datatipWidthPx: wVal,
                                          datatips: (cur.datatips || []).map((t) => ({ ...t, boxW: wVal })),
                                        }));
                                      }}
                                      className="w-28 accent-sky-600 cursor-pointer"
                                    />
                                  </label>
                                  <label className="flex items-center justify-between gap-2">
                                    <span className="text-slate-600">Opacity ({Math.round(ptTipOp * 100)}%)</span>
                                    <input
                                      type="range"
                                      min={0.25}
                                      max={1}
                                      step={0.05}
                                      value={ptTipOp}
                                      onChange={(e) => updatePlotTabById(pt.id, { datatipOpacity: Number(e.target.value) })}
                                      className="w-28 accent-sky-600 cursor-pointer"
                                    />
                                  </label>
                                  <label className="flex items-center justify-between gap-2">
                                    <span className="text-slate-600">Text Size ({ptTipFs}px)</span>
                                    <input
                                      type="range"
                                      min={8}
                                      max={16}
                                      step={0.5}
                                      value={ptTipFs}
                                      onChange={(e) => updatePlotTabById(pt.id, { datatipFontSizePx: Number(e.target.value) })}
                                      className="w-28 accent-sky-600 cursor-pointer"
                                    />
                                  </label>
                                </div>
                              </div>
                            </div>
                          )}
                        </div>
                      </div>
                    </div>

                    <div className="flex-1 min-h-0">
                      <OscilloscopeChart
                        svgId={paneIdx === 0 ? 'hydrasim-oscilloscope-svg' : `hydrasim-oscilloscope-svg-${pt.id}`}
                        history={history}
                        channels={availableChannels}
                        enabledIds={ptEnabled}
                        lineStyles={ptStyles}
                        units={units}
                        plotGridVisible={ptGridVis}
                        plotGridCols={ptGridCols}
                        plotGridRows={ptGridRows}
                        plotGridColor={ptGridColor}
                        timeMin={ptTMin !== '' && Number.isFinite(parseFloat(ptTMin)) ? parseFloat(ptTMin) : null}
                        timeMax={ptTMax !== '' && Number.isFinite(parseFloat(ptTMax)) ? parseFloat(ptTMax) : null}
                        yMinLimit={ptYMin !== '' && Number.isFinite(parseFloat(ptYMin)) ? parseFloat(ptYMin) : null}
                        yMaxLimit={ptYMax !== '' && Number.isFinite(parseFloat(ptYMax)) ? parseFloat(ptYMax) : null}
                        datatipWidthPx={ptTipW}
                        datatipOpacity={ptTipOp}
                        datatipFontSizePx={ptTipFs}
                        datatips={ptTips}
                        onChangeDatatips={(updater) => updatePlotTabById(pt.id, (cur) => ({
                          ...cur,
                          datatips: typeof updater === 'function' ? updater(cur.datatips || []) : updater,
                        }))}
                        hoverTimeFrac={hoverTimeFrac}
                        onChangeHoverTimeFrac={setHoverTimeFrac}
                      />
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
          )}
        </div>

        {/* RIGHT INSPECTOR: PROPERTIES & DIAGNOSTICS WINDOW */}
        {!winState.props.min && (
        <aside
          style={
            winState.props.floating
              ? { left: winState.props.x, top: winState.props.y, width: winState.props.w, height: winState.props.h }
              : undefined
          }
          className={`${winState.props.floating ? 'hs-panel-floating' : winState.props.max ? 'hs-panel-max' : 'w-72 shrink-0'} bg-white border-l border-slate-200 flex flex-col z-20 overflow-hidden`}
        >
          <div
            onMouseDown={(e) => startFloatDrag(e, 'props')}
            className={`flex items-center border-b border-slate-200 bg-slate-50 text-xs font-semibold pr-1 ${winState.props.floating ? 'cursor-move' : ''}`}
          >
            <button
              onClick={() => setRightTab('properties')}
              className={`flex-1 py-2 flex items-center justify-center gap-1.5 border-b-2 ${
                rightTab === 'properties' ? 'border-sky-600 text-sky-700 bg-white' : 'border-transparent text-slate-500 hover:text-slate-700'
              }`}
            >
              <Sliders size={13} /> Properties
            </button>
            <button
              onClick={() => setRightTab('diagnostics')}
              className={`flex-1 py-2 flex items-center justify-center gap-1.5 border-b-2 ${
                rightTab === 'diagnostics' ? 'border-sky-600 text-sky-700 bg-white' : 'border-transparent text-slate-500 hover:text-slate-700'
              }`}
            >
              <Gauge size={13} /> Diagnostics
              {(errorCount > 0 || warnCount > 0) && (
                <span className={`text-[10px] px-1.5 py-0.2 rounded-full font-mono ${errorCount > 0 ? 'bg-red-100 text-red-700' : 'bg-amber-100 text-amber-700'}`}>
                  {errorCount + warnCount}
                </span>
              )}
            </button>
            <WinControls panelKey="props" />
          </div>

          <div className="flex-1 overflow-y-auto p-3 text-xs space-y-3">
            {rightTab === 'properties' ? (
              selectedComp && selectedDef ? (
                <>
                  <div className="space-y-1.5 pb-2.5 border-b border-slate-200">
                    <div className="text-[10px] font-bold uppercase tracking-wider text-sky-700">{selectedDef.category}</div>
                    <div className="font-bold text-sm text-slate-900">{selectedDef.name}</div>
                    <label className="block pt-1">
                      <span className="text-[11px] text-slate-500">Component Tag</span>
                      <input
                        type="text"
                        value={selectedComp.name}
                        onChange={(e) => handleRenameComp(selectedComp.id, e.target.value)}
                        className="mt-0.5 w-full px-2 py-1 font-mono bg-slate-50 border border-slate-200 rounded focus:outline-none focus:border-sky-500"
                      />
                    </label>
                    <label className="block pt-1.5">
                      <div className="flex justify-between text-[11px] text-slate-500">
                        <span>Component Size</span>
                        <span className="font-mono text-slate-700">{Math.round((selectedComp.scale || 1) * 100)}%</span>
                      </div>
                      <input
                        type="range"
                        min={55}
                        max={240}
                        step={5}
                        value={Math.round((selectedComp.scale || 1) * 100)}
                        onChange={(e) => {
                          const s = Number(e.target.value) / 100;
                          setComponents((prev) => prev.map((c) => (c.id === selectedComp.id ? { ...c, scale: s } : c)));
                        }}
                        className="w-full accent-sky-600 cursor-pointer"
                      />
                    </label>
                    <label className="flex items-center justify-between pt-1.5 cursor-pointer select-none">
                      <span className="text-[11px] text-slate-600 font-medium">Show On-Canvas Reading</span>
                      <input
                        type="checkbox"
                        checked={selectedComp.showBadge !== undefined ? selectedComp.showBadge : simSettings.showLiveBadges}
                        onChange={(e) => {
                          const checked = e.target.checked;
                          setComponents((prev) => prev.map((c) => (c.id === selectedComp.id ? { ...c, showBadge: checked } : c)));
                        }}
                        className="rounded border-slate-300 text-sky-600 cursor-pointer"
                      />
                    </label>
                    <label className="flex items-center justify-between pt-1 cursor-pointer select-none">
                      <span className="text-[11px] text-slate-600 font-medium">Show Component Name</span>
                      <input
                        type="checkbox"
                        checked={selectedComp.showName !== undefined ? selectedComp.showName : (simSettings.showComponentNames ?? true)}
                        onChange={(e) => {
                          const checked = e.target.checked;
                          setComponents((prev) => prev.map((c) => (c.id === selectedComp.id ? { ...c, showName: checked } : c)));
                        }}
                        className="rounded border-slate-300 text-sky-600 cursor-pointer"
                      />
                    </label>
                  </div>

                  {/* Live Telemetry Readouts */}
                  {selectedMetrics && (
                    <div className="bg-slate-900 text-slate-100 rounded-md p-2.5 space-y-1 font-mono text-[11px]">
                      <div className="text-[10px] uppercase tracking-wider text-sky-400 font-sans font-bold mb-1">Live Telemetry</div>
                      {Object.entries(selectedMetrics).map(([k, v]) => {
                        if (typeof v === 'boolean' || v === null) return null;
                        let disp = typeof v === 'number' ? v.toFixed(2) : String(v);
                        if (k.toLowerCase().includes('bar')) disp = `${convertToDisplay(v, 'pressure', units).toFixed(2)} ${units.pressure}`;
                        else if (k.toLowerCase().includes('lpm')) disp = `${convertToDisplay(v, 'flow', units).toFixed(2)} ${units.flow}`;
                        else if (k === 'posMm') disp = `${convertToDisplay(v, 'lengthMm', units).toFixed(1)} ${units.length}`;
                        else if (k === 'velMms') disp = `${convertToDisplay(v, 'lengthMm', units).toFixed(1)} ${units.length}/s`;
                        else if (k === 'forceKn') disp = `${convertToDisplay(v, 'forceKn', units).toFixed(2)} ${units.force}`;
                        else if (k.includes('Pct')) disp = `${v.toFixed(1)} %`;
                        else if (k.includes('Kw')) disp = `${v.toFixed(2)} kW`;
                        else if (k === 'tempC') disp = `${convertToDisplay(v, 'tempC', units).toFixed(1)} ${units.temp}`;
                        return (
                          <div key={k} className="flex justify-between">
                            <span className="text-slate-400">{k}</span>
                            <span className="text-emerald-300 font-semibold">{disp}</span>
                          </div>
                        );
                      })}
                    </div>
                  )}

                  {/* Parameter Editors */}
                  {selectedDef.paramMeta.length > 0 && (
                    <div className="space-y-2.5">
                      <div className="text-[10px] font-bold uppercase tracking-wider text-slate-500">Parameters</div>
                      {selectedDef.paramMeta.map((pm) => {
                        const rawVal = selectedComp.params[pm.key];
                        if (pm.type === 'profile') {
                          return (
                            <div key={pm.key} className="space-y-1" title={pm.tip}>
                              <div className="flex items-center justify-between">
                                <span className="text-slate-700 font-medium">{pm.label}</span>
                                <button
                                  type="button"
                                  onClick={() => setSignalModal({ compId: selectedComp.id, key: pm.key, title: `${selectedComp.name} — ${pm.label}`, unit: pm.unit || '', value: rawVal ?? '' })}
                                  className="px-2 py-0.5 bg-violet-600 hover:bg-violet-700 text-white font-semibold rounded text-[10px] cursor-pointer"
                                >
                                  📈 Table / Graph
                                </button>
                              </div>
                              <input
                                type="text"
                                value={rawVal ?? ''}
                                onChange={(e) => handleUpdateCompParam(selectedComp.id, pm.key, e.target.value)}
                                placeholder="Click Table / Graph to edit"
                                className="w-full px-2 py-1 font-mono text-[10.5px] bg-slate-50 border border-slate-200 rounded focus:outline-none focus:border-violet-500"
                              />
                            </div>
                          );
                        }
                        if (pm.type === 'text') {
                          return (
                            <label key={pm.key} className="block space-y-1" title={pm.tip}>
                              <span className="text-slate-700 font-medium block">{pm.label}</span>
                              <input
                                type="text"
                                value={rawVal ?? ''}
                                onChange={(e) => handleUpdateCompParam(selectedComp.id, pm.key, e.target.value)}
                                placeholder="e.g. 0:0, 5:100, 10:50"
                                className="w-full px-2 py-1 font-mono text-[11px] bg-slate-50 border border-slate-200 rounded focus:outline-none focus:border-sky-500"
                              />
                            </label>
                          );
                        }
                        if (pm.type === 'select' || pm.type === 'selectNum') {
                          return (
                            <label key={pm.key} className="block space-y-1" title={pm.tip}>
                              <span className="text-slate-700 font-medium block">{pm.label}</span>
                              <select
                                value={rawVal}
                                onChange={(e) => handleUpdateCompParam(selectedComp.id, pm.key, pm.type === 'selectNum' ? Number(e.target.value) : e.target.value)}
                                className="w-full px-2 py-1.5 bg-slate-50 border border-slate-200 rounded text-xs"
                              >
                                {pm.options.map((opt) => (
                                  <option key={opt.value} value={opt.value}>{opt.label}</option>
                                ))}
                              </select>
                            </label>
                          );
                        }
                        const uType = inferUnitType(pm.unit);
                        const dispUnit = getDisplayUnitLabel(uType, units, pm.unit);
                        const dispVal = convertToDisplay(rawVal, uType, units);
                        const draftKey = `${selectedComp.id}:${pm.key}`;
                        const shownVal = paramDrafts[draftKey] !== undefined ? paramDrafts[draftKey] : Number(dispVal.toFixed(3));

                        const outOfRange =
                          (pm.min !== undefined && rawVal < pm.min) ||
                          (pm.max !== undefined && rawVal > pm.max);
                        const minDisp = pm.min !== undefined ? convertToDisplay(pm.min, uType, units) : null;
                        const maxDisp = pm.max !== undefined ? convertToDisplay(pm.max, uType, units) : null;

                        return (
                          <label key={pm.key} className="block space-y-1" title={pm.tip}>
                            <div className="flex justify-between">
                              <span className="text-slate-700 font-medium">{pm.label}</span>
                              <span className="text-[10px] font-mono text-slate-400">{dispUnit}</span>
                            </div>
                            <input
                              type="number"
                              step="any"
                              value={shownVal}
                              onChange={(e) => {
                                const txt = e.target.value;
                                setParamDrafts((d) => ({ ...d, [draftKey]: txt }));
                                const num = parseFloat(txt);
                                if (!Number.isNaN(num)) {
                                  const siVal = convertFromDisplay(num, uType, units);
                                  handleUpdateCompParam(selectedComp.id, pm.key, siVal);
                                }
                              }}
                              onBlur={() => setParamDrafts((d) => { const n = { ...d }; delete n[draftKey]; return n; })}
                              className={`w-full px-2 py-1 font-mono rounded focus:outline-none border ${
                                outOfRange ? 'bg-red-50 border-red-400 text-red-900' : 'bg-slate-50 border-slate-200 focus:border-sky-500'
                              }`}
                            />
                            {outOfRange && (
                              <div className="text-[10px] text-red-600 font-medium">
                                Valid range: {minDisp !== null ? minDisp.toFixed(1) : '—'} to {maxDisp !== null ? maxDisp.toFixed(1) : '—'} {dispUnit}
                              </div>
                            )}
                          </label>
                        );
                      })}
                    </div>
                  )}


                </>
              ) : (
                <div className="text-center text-slate-400 py-10 space-y-2">
                  <Sliders size={24} className="mx-auto opacity-40" />
                  <p>Select a component on the schematic to edit parameters and inspect live telemetry.</p>
                </div>
              )
            ) : (
              <div className="space-y-2">
                {diagnostics.length === 0 ? (
                  <div className="p-3 rounded bg-emerald-50 border border-emerald-200 text-emerald-800 flex items-center gap-2">
                    <CheckCircle2 size={16} className="shrink-0" />
                    <span>Circuit topology verified — no warnings or errors detected.</span>
                  </div>
                ) : (
                  diagnostics.map((d, idx) => (
                    <div
                      key={idx}
                      className={`p-2.5 rounded border text-[11px] space-y-0.5 ${
                        d.severity === 'error'
                          ? 'bg-red-50 border-red-200 text-red-900'
                          : d.severity === 'warning'
                          ? 'bg-amber-50 border-amber-200 text-amber-900'
                          : 'bg-sky-50 border-sky-200 text-sky-900'
                      }`}
                    >
                      <div className="font-bold flex items-center gap-1.5">
                        {d.severity === 'error' ? <AlertCircle size={13} /> : d.severity === 'warning' ? <AlertTriangle size={13} /> : <Info size={13} />}
                        {d.title}
                      </div>
                      <div className="opacity-85 leading-snug">{d.detail}</div>
                    </div>
                  ))
                )}
              </div>
            )}
          </div>
        </aside>
        )}
      </div>

      {/* MINIMIZED WINDOWS TAB BAR */}
      {(winState.circuit.min || winState.plot.min || winState.props.min) && (
        <div className="h-7 bg-slate-900 border-t border-slate-700 px-2.5 flex items-center gap-1.5 shrink-0 z-30 text-xs">
          <span className="text-[10px] font-bold uppercase tracking-wider text-slate-400 mr-1">Minimized:</span>
          {winState.circuit.min && (
            <button
              type="button"
              onClick={() => toggleWinFlag('circuit', 'min')}
              className="px-2.5 py-0.5 rounded bg-slate-800 hover:bg-sky-600 text-sky-300 hover:text-white border border-slate-600 font-semibold text-[11px] transition-colors cursor-pointer"
            >
              📐 Circuit Window
            </button>
          )}
          {winState.plot.min && (
            <button
              type="button"
              onClick={() => toggleWinFlag('plot', 'min')}
              className="px-2.5 py-0.5 rounded bg-slate-800 hover:bg-sky-600 text-sky-300 hover:text-white border border-slate-600 font-semibold text-[11px] transition-colors cursor-pointer"
            >
              📈 Plot Window
            </button>
          )}
          {winState.props.min && (
            <button
              type="button"
              onClick={() => toggleWinFlag('props', 'min')}
              className="px-2.5 py-0.5 rounded bg-slate-800 hover:bg-sky-600 text-sky-300 hover:text-white border border-slate-600 font-semibold text-[11px] transition-colors cursor-pointer"
            >
              ⚙ Properties
            </button>
          )}
          <button
            type="button"
            onClick={handleResetLayout}
            className="ml-auto px-2 py-0.5 rounded bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-600 text-[10.5px] font-semibold cursor-pointer"
          >
            ↺ Restore All
          </button>
        </div>
      )}

      {/* ==================== MODALS & TOAST ==================== */}
      {signalModal && (
        <window.SignalBuilderModal
          title={signalModal.title}
          unit={signalModal.unit}
          initialProfile={signalModal.value}
          onApply={(nextStr) => handleUpdateCompParam(signalModal.compId, signalModal.key, nextStr)}
          onClose={() => setSignalModal(null)}
        />
      )}

      {showSettingsModal && (
        <SimulationSettingsModal
          settings={simSettings}
          units={units}
          onUpdateSettings={(patch) => setSimSettings((s) => ({ ...s, ...patch }))}
          onUpdateUnits={(patch) => setUnits((u) => ({ ...u, ...patch }))}
          onResetDefaults={() => { setSimSettings(DEFAULT_SIM_SETTINGS); setUnits(UNIT_PRESETS.metric); setUnitPreset('metric'); }}
          onClose={() => setShowSettingsModal(false)}
        />
      )}

      {showCloudModal && (
        <CloudCircuitsModal
          currentTitle={circuitTitle}
          currentDesc={circuitDesc}
          backendOnline={backendOnline}
          onSaveCurrent={handleSaveToBackend}
          onLoadCloud={handleLoadFromBackend}
          onClose={() => setShowCloudModal(false)}
        />
      )}

      {toast && (
        <div className="fixed bottom-4 right-4 bg-slate-900 text-white text-xs font-medium px-3.5 py-2 rounded-md shadow-xl border border-slate-700 z-50">
          {toast}
        </div>
      )}
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);

})();
