(() => {
const { useState, useEffect, useRef, useMemo, useCallback } = React;
const { Settings, X } = window.HydraIcons;

// ============================================================================
// 6. AUTHENTIC ISO 1219 SVG SYMBOLS FOR ALL 28 COMPONENTS
// ============================================================================

function HydraulicSymbol({ comp, metrics, isRunning, onToggleSpool, onBadgeMouseDown, units = UNIT_PRESETS.metric, showBadges = true }) {
  const bdx = comp.badgeDx || 0;
  const bdy = comp.badgeDy || 0;
  const BadgeWrap = ({ children }) => (
    <g
      transform={`translate(${bdx}, ${bdy})`}
      onMouseDown={(e) => { if (onBadgeMouseDown) { e.stopPropagation(); onBadgeMouseDown(e, comp); } }}
      className={onBadgeMouseDown ? 'cursor-move' : ''}
      title="Drag to move reading"
    >
      {children}
    </g>
  );
  const stroke = 'var(--hs-stroke, #1e293b)';
  const accent = '#0284c7';
  const p = comp.params;
  const pDisp = (bar) => convertToDisplay(bar, 'pressure', units);
  const qDisp = (lpm) => convertToDisplay(lpm, 'flow', units);
  const lDisp = (mm) => convertToDisplay(mm, 'lengthMm', units);
  const pUnitShort = units.pressure === 'bar' ? 'bar' : units.pressure;
  const qUnitShort = units.flow === 'L/min' ? 'lpm' : 'gpm';
  const lUnitShort = units.length;

  switch (comp.type) {
    case 'pump': {
      const over = metrics?.overpressure;
      const pBar = metrics?.pressureBar ?? 0;
      const qLpm = metrics?.flowLpm ?? 0;
      return (
        <g>
          <line x1={-34} y1={0} x2={-20} y2={0} stroke={stroke} strokeWidth={2} />
          <line x1={20} y1={0} x2={34} y2={0} stroke={stroke} strokeWidth={2} />
          <line x1={0} y1={20} x2={0} y2={30} stroke="#059669" strokeWidth={2.2} strokeDasharray="3 2" />
          <line x1={0} y1={20} x2={0} y2={30} stroke="#059669" strokeWidth={2.2} strokeDasharray="3 2" />
          <circle cx={0} cy={0} r={20} fill={over ? '#7f1d1d' : 'var(--hs-fill, #ffffff)'} stroke={over ? '#dc2626' : stroke} strokeWidth={2} />
          <polygon points="18,0 7,-7 7,7" fill={stroke} />
          <g className={isRunning ? 'hydrasim-spin' : ''}>
            <line x1={-11} y1={0} x2={1} y2={0} stroke={accent} strokeWidth={1.8} strokeLinecap="round" />
            <line x1={-5} y1={-6} x2={-5} y2={6} stroke={accent} strokeWidth={1.8} strokeLinecap="round" />
          </g>
          {showBadges && (
            <BadgeWrap>
              <rect x={-36} y={-38} width={72} height={14} rx={3} fill={over ? '#dc2626' : '#0f172a'} />
              <text x={0} y={-28} textAnchor="middle" fontSize={8.5} fontWeight="700" fill="#38bdf8" fontFamily="monospace">
                {pDisp(pBar).toFixed(units.pressure === 'MPa' ? 1 : 0)}{pUnitShort} · {qDisp(qLpm).toFixed(1)}{qUnitShort}
              </text>
            </BadgeWrap>
          )}
        </g>
      );
    }

    case 'var_pump': {
      const over = metrics?.overpressure;
      const strokePct = metrics?.strokePct ?? 100;
      const qLpm = metrics?.flowLpm ?? 0;
      return (
        <g>
          <line x1={-36} y1={0} x2={-20} y2={0} stroke={stroke} strokeWidth={2} />
          <line x1={20} y1={0} x2={36} y2={0} stroke={stroke} strokeWidth={2} />
          <circle cx={0} cy={0} r={20} fill={over ? '#7f1d1d' : 'var(--hs-fill, #ffffff)'} stroke={over ? '#dc2626' : stroke} strokeWidth={2} />
          <polygon points="18,0 7,-7 7,7" fill={stroke} />
          <line x1={-22} y1={22} x2={22} y2={-22} stroke={accent} strokeWidth={1.7} />
          <polygon points="22,-22 14,-20 19,-14" fill={accent} />
          {showBadges && (
            <BadgeWrap>
              <rect x={-38} y={-40} width={76} height={14} rx={3} fill="#0f172a" />
              <text x={0} y={-30} textAnchor="middle" fontSize={8.5} fontWeight="700" fill="#38bdf8" fontFamily="monospace">
                {strokePct.toFixed(0)}% · {qDisp(qLpm).toFixed(1)}{qUnitShort}
              </text>
            </BadgeWrap>
          )}
        </g>
      );
    }

    case 'electric_motor': {
      const overloaded = metrics?.overloaded;
      const rpm = metrics?.rpm ?? (p.syncRpm || 1500);
      const loadPct = metrics?.loadPct ?? 0;
      return (
        <g>
          <line x1={20} y1={-3} x2={36} y2={-3} stroke={stroke} strokeWidth={2} />
          <line x1={20} y1={3} x2={36} y2={3} stroke={stroke} strokeWidth={2} />
          <circle cx={0} cy={0} r={20} fill={overloaded ? '#fee2e2' : '#f0fdf4'} stroke={overloaded ? '#dc2626' : '#15803d'} strokeWidth={2} />
          <text x={0} y={5} textAnchor="middle" fontSize={14} fontWeight="800" fill={overloaded ? '#dc2626' : '#15803d'}>M</text>
          <text x={0} y={14} textAnchor="middle" fontSize={6.5} fontWeight="700" fill="#475569">3~</text>
          {showBadges && (
            <BadgeWrap>
              <rect x={-38} y={-38} width={76} height={14} rx={3} fill={overloaded ? '#dc2626' : '#0f172a'} />
              <text x={0} y={-28} textAnchor="middle" fontSize={8.5} fontWeight="700" fill={overloaded ? '#ffffff' : '#4ade80'} fontFamily="monospace">
                {rpm.toFixed(0)}rpm · {loadPct.toFixed(0)}%
              </text>
            </BadgeWrap>
          )}
        </g>
      );
    }

    case 'gear_pump': {
      const over = metrics?.overpressure;
      const pBar = metrics?.pressureBar ?? 0;
      const qLpm = metrics?.flowLpm ?? 0;
      return (
        <g>
          <line x1={-34} y1={0} x2={-20} y2={0} stroke={stroke} strokeWidth={2} />
          <line x1={20} y1={0} x2={34} y2={0} stroke={stroke} strokeWidth={2} />
          <circle cx={0} cy={0} r={20} fill={over ? '#7f1d1d' : 'var(--hs-fill, #ffffff)'} stroke={over ? '#dc2626' : stroke} strokeWidth={2} />
          <polygon points="18,0 8,-6.5 8,6.5" fill={stroke} />
          <g className={isRunning ? 'hydrasim-spin' : ''}>
            <circle cx={-5} cy={-5.5} r={5} fill="none" stroke={accent} strokeWidth={1.6} strokeDasharray="2.5 1.5" />
            <circle cx={-5} cy={5.5} r={5} fill="none" stroke={accent} strokeWidth={1.6} strokeDasharray="2.5 1.5" />
          </g>
          {showBadges && (
            <BadgeWrap>
              <rect x={-38} y={-38} width={76} height={14} rx={3} fill={over ? '#dc2626' : '#0f172a'} />
              <text x={0} y={-28} textAnchor="middle" fontSize={8.5} fontWeight="700" fill="#38bdf8" fontFamily="monospace">
                GP {pDisp(pBar).toFixed(0)}{pUnitShort} · {qDisp(qLpm).toFixed(1)}{qUnitShort}
              </text>
            </BadgeWrap>
          )}
        </g>
      );
    }

    case 'vane_pump': {
      const over = metrics?.overpressure;
      const pBar = metrics?.pressureBar ?? 0;
      const qLpm = metrics?.flowLpm ?? 0;
      return (
        <g>
          <line x1={-34} y1={0} x2={-20} y2={0} stroke={stroke} strokeWidth={2} />
          <line x1={20} y1={0} x2={34} y2={0} stroke={stroke} strokeWidth={2} />
          <circle cx={0} cy={0} r={20} fill={over ? '#7f1d1d' : 'var(--hs-fill, #ffffff)'} stroke={over ? '#dc2626' : stroke} strokeWidth={2} />
          <polygon points="18,0 8,-6.5 8,6.5" fill={stroke} />
          <g className={isRunning ? 'hydrasim-spin' : ''}>
            <circle cx={-5} cy={0} r={5.5} fill="#e0f2fe" stroke={accent} strokeWidth={1.5} />
            <line x1={-5} y1={-11} x2={-5} y2={11} stroke={accent} strokeWidth={1.4} />
            <line x1={-15} y1={0} x2={5} y2={0} stroke={accent} strokeWidth={1.4} />
          </g>
          {showBadges && (
            <BadgeWrap>
              <rect x={-38} y={-38} width={76} height={14} rx={3} fill={over ? '#dc2626' : '#0f172a'} />
              <text x={0} y={-28} textAnchor="middle" fontSize={8.5} fontWeight="700" fill="#38bdf8" fontFamily="monospace">
                VN {pDisp(pBar).toFixed(0)}{pUnitShort} · {qDisp(qLpm).toFixed(1)}{qUnitShort}
              </text>
            </BadgeWrap>
          )}
        </g>
      );
    }

    case 'piston_pump': {
      const over = metrics?.overpressure;
      const strokePct = metrics?.strokePct ?? (p.swashPct ?? 100);
      const qLpm = metrics?.flowLpm ?? 0;
      return (
        <g>
          <line x1={-36} y1={0} x2={-20} y2={0} stroke={stroke} strokeWidth={2} />
          <line x1={20} y1={0} x2={36} y2={0} stroke={stroke} strokeWidth={2} />
          <circle cx={0} cy={0} r={20} fill={over ? '#7f1d1d' : 'var(--hs-fill, #ffffff)'} stroke={over ? '#dc2626' : stroke} strokeWidth={2} />
          <polygon points="18,0 7,-7 7,7" fill={stroke} />
          <rect x={-11} y={-7} width={9} height={14} rx={1.5} fill="#e0f2fe" stroke={accent} strokeWidth={1.5} />
          <line x1={-22} y1={22} x2={22} y2={-22} stroke={accent} strokeWidth={1.7} />
          <polygon points="22,-22 14,-20 19,-14" fill={accent} />
          {showBadges && (
            <BadgeWrap>
              <rect x={-40} y={-40} width={80} height={14} rx={3} fill={over ? '#dc2626' : '#0f172a'} />
              <text x={0} y={-30} textAnchor="middle" fontSize={8.5} fontWeight="700" fill="#38bdf8" fontFamily="monospace">
                PP {strokePct.toFixed(0)}% · {qDisp(qLpm).toFixed(1)}{qUnitShort}
              </text>
            </BadgeWrap>
          )}
        </g>
      );
    }

    case 'tank': {
      const tBar = p.pressureBar ?? 0;
      return (
        <g>
          <line x1={0} y1={-22} x2={0} y2={4} stroke={stroke} strokeWidth={2} />
          <path d="M -22 -4 L -22 16 L 22 16 L 22 -4" fill="#e0f2fe" stroke={stroke} strokeWidth={2} />
          <line x1={-19} y1={4} x2={19} y2={4} stroke="#0284c7" strokeWidth={1.3} strokeDasharray="3 2" />
          {showBadges && Math.abs(tBar) > 0.001 && (
            <text x={0} y={13} textAnchor="middle" fontSize={7.5} fontWeight="700" fill="#0369a1" fontFamily="monospace">
              {pDisp(tBar).toFixed(1)}{pUnitShort}
            </text>
          )}
        </g>
      );
    }

    case 'dcv43': {
      const pos = metrics?.spoolPos ?? (p.spoolPos || 0);
      const leftType = p.leftType || 'parallel';
      const centerType = p.centerType || 'tandem';
      const rightType = p.rightType || 'crossed';
      const render4WayBox = (cfg, cx) => {
        const xA = cx - 10;
        const xB = cx + 10;
        switch (cfg) {
          case 'parallel':
            return (
              <g>
                <line x1={xA} y1={18} x2={xA} y2={-18} stroke={stroke} strokeWidth={1.6} />
                <polygon points={`${xA},-17 ${xA - 3},-10 ${xA + 3},-10`} fill={stroke} />
                <line x1={xB} y1={-18} x2={xB} y2={18} stroke={stroke} strokeWidth={1.6} />
                <polygon points={`${xB},17 ${xB - 3},10 ${xB + 3},10`} fill={stroke} />
              </g>
            );
          case 'crossed':
            return (
              <g>
                <line x1={xA} y1={18} x2={xB} y2={-18} stroke={stroke} strokeWidth={1.6} />
                <polygon points={`${xB},-17 ${xB - 6},-12 ${xB - 1},-9`} fill={stroke} />
                <line x1={xA} y1={-18} x2={xB} y2={18} stroke={stroke} strokeWidth={1.6} />
                <polygon points={`${xB},17 ${xB - 6},12 ${xB - 1},9`} fill={stroke} />
              </g>
            );
          case 'tandem':
            return (
              <g>
                <path d={`M ${xA} 18 L ${xA} 6 L ${xB} 6 L ${xB} 18`} fill="none" stroke={stroke} strokeWidth={1.6} />
                <line x1={xA} y1={-18} x2={xA} y2={-6} stroke={stroke} strokeWidth={1.6} />
                <line x1={xA - 4} y1={-6} x2={xA + 4} y2={-6} stroke={stroke} strokeWidth={1.8} />
                <line x1={xB} y1={-18} x2={xB} y2={-6} stroke={stroke} strokeWidth={1.6} />
                <line x1={xB - 4} y1={-6} x2={xB + 4} y2={-6} stroke={stroke} strokeWidth={1.8} />
              </g>
            );
          case 'closed':
            return (
              <g>
                {[xA, xB].map((x) => (
                  <g key={x}>
                    <line x1={x} y1={-18} x2={x} y2={-6} stroke={stroke} strokeWidth={1.6} />
                    <line x1={x - 4} y1={-6} x2={x + 4} y2={-6} stroke={stroke} strokeWidth={1.8} />
                    <line x1={x} y1={18} x2={x} y2={6} stroke={stroke} strokeWidth={1.6} />
                    <line x1={x - 4} y1={6} x2={x + 4} y2={6} stroke={stroke} strokeWidth={1.8} />
                  </g>
                ))}
              </g>
            );
          case 'open':
            return (
              <g>
                <line x1={xA} y1={-18} x2={xA} y2={18} stroke={stroke} strokeWidth={1.6} />
                <line x1={xB} y1={-18} x2={xB} y2={18} stroke={stroke} strokeWidth={1.6} />
                <line x1={xA} y1={0} x2={xB} y2={0} stroke={stroke} strokeWidth={1.6} />
              </g>
            );
          case 'float':
            return (
              <g>
                <path d={`M ${xA} -18 L ${xA} 0 L ${xB} 0 L ${xB} -18 M ${xB} 0 L ${xB} 18`} fill="none" stroke={stroke} strokeWidth={1.6} />
                <line x1={xA} y1={18} x2={xA} y2={6} stroke={stroke} strokeWidth={1.6} />
                <line x1={xA - 4} y1={6} x2={xA + 4} y2={6} stroke={stroke} strokeWidth={1.8} />
              </g>
            );
          case 'regen':
            return (
              <g>
                <path d={`M ${xA} -18 L ${xA} 0 L ${xB} 0 L ${xB} -18 M ${xA} 0 L ${xA} 18`} fill="none" stroke={stroke} strokeWidth={1.6} />
                <line x1={xB} y1={18} x2={xB} y2={6} stroke={stroke} strokeWidth={1.6} />
                <line x1={xB - 4} y1={6} x2={xB + 4} y2={6} stroke={stroke} strokeWidth={1.8} />
              </g>
            );
          case 'pa_b_blocked':
            return (
              <g>
                <line x1={xA} y1={18} x2={xA} y2={-18} stroke={stroke} strokeWidth={1.6} />
                <polygon points={`${xA},-17 ${xA - 3},-10 ${xA + 3},-10`} fill={stroke} />
                <line x1={xB} y1={-18} x2={xB} y2={-6} stroke={stroke} strokeWidth={1.6} />
                <line x1={xB - 4} y1={-6} x2={xB + 4} y2={-6} stroke={stroke} strokeWidth={1.8} />
                <line x1={xB} y1={18} x2={xB} y2={6} stroke={stroke} strokeWidth={1.6} />
                <line x1={xB - 4} y1={6} x2={xB + 4} y2={6} stroke={stroke} strokeWidth={1.8} />
              </g>
            );
          case 'pb_a_blocked':
            return (
              <g>
                <line x1={xA} y1={18} x2={xB} y2={-18} stroke={stroke} strokeWidth={1.6} />
                <polygon points={`${xB},-17 ${xB - 6},-12 ${xB - 1},-9`} fill={stroke} />
                <line x1={xA} y1={-18} x2={xA} y2={-6} stroke={stroke} strokeWidth={1.6} />
                <line x1={xA - 4} y1={-6} x2={xA + 4} y2={-6} stroke={stroke} strokeWidth={1.8} />
                <line x1={xB} y1={18} x2={xB} y2={6} stroke={stroke} strokeWidth={1.6} />
                <line x1={xB - 4} y1={6} x2={xB + 4} y2={6} stroke={stroke} strokeWidth={1.8} />
              </g>
            );
          case 'at_pb_blocked':
            return (
              <g>
                <line x1={xA} y1={-18} x2={xB} y2={18} stroke={stroke} strokeWidth={1.6} />
                <polygon points={`${xB},17 ${xB - 6},12 ${xB - 1},9`} fill={stroke} />
                <line x1={xA} y1={18} x2={xA} y2={6} stroke={stroke} strokeWidth={1.6} />
                <line x1={xA - 4} y1={6} x2={xA + 4} y2={6} stroke={stroke} strokeWidth={1.8} />
                <line x1={xB} y1={-18} x2={xB} y2={-6} stroke={stroke} strokeWidth={1.6} />
                <line x1={xB - 4} y1={-6} x2={xB + 4} y2={-6} stroke={stroke} strokeWidth={1.8} />
              </g>
            );
          case 'bt_pa_blocked':
            return (
              <g>
                <line x1={xB} y1={-18} x2={xB} y2={18} stroke={stroke} strokeWidth={1.6} />
                <polygon points={`${xB},17 ${xB - 3},10 ${xB + 3},10`} fill={stroke} />
                <line x1={xA} y1={-18} x2={xA} y2={-6} stroke={stroke} strokeWidth={1.6} />
                <line x1={xA - 4} y1={-6} x2={xA + 4} y2={-6} stroke={stroke} strokeWidth={1.8} />
                <line x1={xA} y1={18} x2={xA} y2={6} stroke={stroke} strokeWidth={1.6} />
                <line x1={xA - 4} y1={6} x2={xA + 4} y2={6} stroke={stroke} strokeWidth={1.8} />
              </g>
            );
          case 'pa_bt_p_t_loop':
            return (
              <g>
                <line x1={xA} y1={18} x2={xA} y2={-18} stroke={stroke} strokeWidth={1.6} />
                <polygon points={`${xA},-17 ${xA - 3},-10 ${xA + 3},-10`} fill={stroke} />
                <line x1={xA} y1={0} x2={xB} y2={0} stroke={stroke} strokeWidth={1.5} />
                <line x1={xB} y1={-18} x2={xB} y2={18} stroke={stroke} strokeWidth={1.6} />
                <polygon points={`${xB},17 ${xB - 3},10 ${xB + 3},10`} fill={stroke} />
              </g>
            );
          default:
            return null;
        }
      };
      return (
        <g>
          <line x1={-10} y1={-32} x2={-10} y2={-18} stroke={stroke} strokeWidth={2} />
          <line x1={10} y1={-32} x2={10} y2={-18} stroke={stroke} strokeWidth={2} />
          <line x1={-10} y1={18} x2={-10} y2={32} stroke={stroke} strokeWidth={2} />
          <line x1={10} y1={18} x2={10} y2={32} stroke={stroke} strokeWidth={2} />
          <g style={{ transition: 'transform 0.18s ease' }} transform={`translate(${-pos * 36}, 0)`}>
            <rect x={-54} y={-18} width={36} height={36} fill={pos <= -0.5 ? 'rgba(245,158,11,0.28)' : 'var(--hs-fill, #ffffff)'} stroke={stroke} strokeWidth={1.6} />
            <rect x={-18} y={-18} width={36} height={36} fill={Math.abs(pos) < 0.5 ? 'rgba(245,158,11,0.28)' : 'var(--hs-fill, #ffffff)'} stroke={stroke} strokeWidth={1.6} />
            <rect x={18} y={-18} width={36} height={36} fill={pos >= 0.5 ? 'rgba(245,158,11,0.28)' : 'var(--hs-fill, #ffffff)'} stroke={stroke} strokeWidth={1.6} />
            {render4WayBox(leftType, -36)}
            {render4WayBox(centerType, 0)}
            {render4WayBox(rightType, 36)}
            {p.controlMode === 'signal' ? (
              <g>
                <rect x={-66} y={-9} width={12} height={18} fill="#ede9fe" stroke="#7c3aed" strokeWidth={1.6} />
                <line x1={-63} y1={6} x2={-57} y2={-6} stroke="#7c3aed" strokeWidth={1.4} />
                <rect x={54} y={-9} width={12} height={18} fill="#ede9fe" stroke="#7c3aed" strokeWidth={1.6} />
                <line x1={57} y1={6} x2={63} y2={-6} stroke="#7c3aed" strokeWidth={1.4} />
              </g>
            ) : p.actuation === 'manual' ? (
              <g>
                <line x1={-54} y1={0} x2={-64} y2={0} stroke={stroke} strokeWidth={1.5} />
                <line x1={-64} y1={0} x2={-70} y2={-13} stroke={accent} strokeWidth={1.8} strokeLinecap="round" />
                <circle cx={-70} cy={-14} r={2.5} fill={accent} />
                <path d="M 54 -5 L 58 5 L 62 -5 L 66 5" fill="none" stroke={stroke} strokeWidth={1.3} />
              </g>
            ) : (
              <g>
                <rect x={-66} y={-8} width={12} height={16} fill={pos === -1 ? '#bae6fd' : '#f8fafc'} stroke={stroke} strokeWidth={1.3} />
                <line x1={-63} y1={6} x2={-57} y2={-6} stroke={stroke} strokeWidth={1.2} />
                <rect x={54} y={-8} width={12} height={16} fill={pos === 1 ? '#bae6fd' : '#f8fafc'} stroke={stroke} strokeWidth={1.3} />
                <line x1={57} y1={6} x2={63} y2={-6} stroke={stroke} strokeWidth={1.2} />
              </g>
            )}
          </g>
          {showBadges && p.controlMode === 'signal' && (
            <g>
              <rect x={-26} y={36} width={52} height={14} rx={3} fill="#7c3aed" />
              <text x={0} y={46} textAnchor="middle" fontSize={8} fontWeight="700" fill="#ffffff" fontFamily="monospace">
                SIG [{pos < -0.25 ? 'L' : pos > 0.25 ? 'R' : '0'}]
              </text>
            </g>
          )}
          {onToggleSpool && p.controlMode !== 'signal' && (
            <g onMouseDown={(e) => e.stopPropagation()}>
              {[
                { val: -1, label: 'L', x: -39 },
                { val: 0, label: '0', x: -12 },
                { val: 1, label: 'R', x: 15 },
              ].map((b) => (
                <g key={b.val} className="cursor-pointer" onClick={(e) => { e.stopPropagation(); onToggleSpool?.(comp.id, b.val); }}>
                  <rect x={b.x} y={36} width={24} height={15} rx={3} fill={pos === b.val ? '#0284c7' : '#e2e8f0'} />
                  <text x={b.x + 12} y={46.5} textAnchor="middle" fontSize={8.5} fontWeight="700" fill={pos === b.val ? '#ffffff' : '#475569'} className="pointer-events-none">
                    {b.label}
                  </text>
                </g>
              ))}
            </g>
          )}
        </g>
      );
    }

    case 'prop_dcv43': {
      const u = (metrics?.spoolPct ?? ((p.command || 0) * 100)) / 100;
      const slidePx = Math.max(-36, Math.min(36, -u * 36));
      const leftType = p.leftType || 'parallel';
      const centerType = p.centerType || 'closed';
      const rightType = p.rightType || 'crossed';
      const renderPropBox = (cfg, cx) => {
        const xA = cx - 10;
        const xB = cx + 10;
        if (cfg === 'parallel') {
          return (
            <g>
              <line x1={xA} y1={18} x2={xA} y2={-18} stroke={stroke} strokeWidth={1.6} />
              <polygon points={`${xA},-17 ${xA - 3},-10 ${xA + 3},-10`} fill={stroke} />
              <line x1={xB} y1={-18} x2={xB} y2={18} stroke={stroke} strokeWidth={1.6} />
              <polygon points={`${xB},17 ${xB - 3},10 ${xB + 3},10`} fill={stroke} />
            </g>
          );
        }
        if (cfg === 'crossed') {
          return (
            <g>
              <line x1={xA} y1={18} x2={xB} y2={-18} stroke={stroke} strokeWidth={1.6} />
              <polygon points={`${xB},-17 ${xB - 6},-12 ${xB - 1},-9`} fill={stroke} />
              <line x1={xA} y1={-18} x2={xB} y2={18} stroke={stroke} strokeWidth={1.6} />
              <polygon points={`${xB},17 ${xB - 6},12 ${xB - 1},9`} fill={stroke} />
            </g>
          );
        }
        if (cfg === 'tandem') {
          return (
            <g>
              <path d={`M ${xA} 18 L ${xA} 6 L ${xB} 6 L ${xB} 18`} fill="none" stroke={stroke} strokeWidth={1.6} />
              <line x1={xA} y1={-18} x2={xA} y2={-6} stroke={stroke} strokeWidth={1.6} />
              <line x1={xA - 4} y1={-6} x2={xA + 4} y2={-6} stroke={stroke} strokeWidth={1.8} />
              <line x1={xB} y1={-18} x2={xB} y2={-6} stroke={stroke} strokeWidth={1.6} />
              <line x1={xB - 4} y1={-6} x2={xB + 4} y2={-6} stroke={stroke} strokeWidth={1.8} />
            </g>
          );
        }
        if (cfg === 'open') {
          return (
            <g>
              <line x1={xA} y1={-18} x2={xA} y2={18} stroke={stroke} strokeWidth={1.6} />
              <line x1={xB} y1={-18} x2={xB} y2={18} stroke={stroke} strokeWidth={1.6} />
              <line x1={xA} y1={0} x2={xB} y2={0} stroke={stroke} strokeWidth={1.6} />
            </g>
          );
        }
        if (cfg === 'float') {
          return (
            <g>
              <path d={`M ${xA} -18 L ${xA} 0 L ${xB} 0 L ${xB} -18 M ${xB} 0 L ${xB} 18`} fill="none" stroke={stroke} strokeWidth={1.6} />
              <line x1={xA} y1={18} x2={xA} y2={6} stroke={stroke} strokeWidth={1.6} />
              <line x1={xA - 4} y1={6} x2={xA + 4} y2={6} stroke={stroke} strokeWidth={1.8} />
            </g>
          );
        }
        if (cfg === 'regen') {
          return (
            <g>
              <path d={`M ${xA} -18 L ${xA} 0 L ${xB} 0 L ${xB} -18 M ${xA} 0 L ${xA} 18`} fill="none" stroke={stroke} strokeWidth={1.6} />
              <line x1={xB} y1={18} x2={xB} y2={6} stroke={stroke} strokeWidth={1.6} />
              <line x1={xB - 4} y1={6} x2={xB + 4} y2={6} stroke={stroke} strokeWidth={1.8} />
            </g>
          );
        }
        return (
          <g>
            {[xA, xB].map((x) => (
              <g key={x}>
                <line x1={x} y1={-18} x2={x} y2={-6} stroke={stroke} strokeWidth={1.6} />
                <line x1={x - 4} y1={-6} x2={x + 4} y2={-6} stroke={stroke} strokeWidth={1.8} />
                <line x1={x} y1={18} x2={x} y2={6} stroke={stroke} strokeWidth={1.6} />
                <line x1={x - 4} y1={6} x2={x + 4} y2={6} stroke={stroke} strokeWidth={1.8} />
              </g>
            ))}
          </g>
        );
      };
      return (
        <g>
          <line x1={-10} y1={-32} x2={-10} y2={-18} stroke={stroke} strokeWidth={2} />
          <line x1={10} y1={-32} x2={10} y2={-18} stroke={stroke} strokeWidth={2} />
          <line x1={-10} y1={18} x2={-10} y2={32} stroke={stroke} strokeWidth={2} />
          <line x1={10} y1={18} x2={10} y2={32} stroke={stroke} strokeWidth={2} />
          <line x1={-54} y1={-22} x2={54} y2={-22} stroke={accent} strokeWidth={1.5} />
          <line x1={-54} y1={22} x2={54} y2={22} stroke={accent} strokeWidth={1.5} />
          <g transform={`translate(${slidePx.toFixed(1)}, 0)`}>
            <rect x={-54} y={-18} width={36} height={36} fill={u < -0.05 ? 'rgba(245,158,11,0.28)' : 'var(--hs-fill, #ffffff)'} stroke={stroke} strokeWidth={1.6} />
            <rect x={-18} y={-18} width={36} height={36} fill={Math.abs(u) <= 0.05 ? 'rgba(245,158,11,0.28)' : 'var(--hs-fill, #ffffff)'} stroke={stroke} strokeWidth={1.6} />
            <rect x={18} y={-18} width={36} height={36} fill={u > 0.05 ? 'rgba(245,158,11,0.28)' : 'var(--hs-fill, #ffffff)'} stroke={stroke} strokeWidth={1.6} />
            {renderPropBox(leftType, -36)}
            {renderPropBox(centerType, 0)}
            {renderPropBox(rightType, 36)}
            {p.controlMode === 'manual' ? (
              <g>
                <line x1={-54} y1={0} x2={-64} y2={0} stroke={stroke} strokeWidth={1.5} />
                <line x1={-64} y1={0} x2={-70} y2={-13} stroke={accent} strokeWidth={1.8} strokeLinecap="round" />
                <circle cx={-70} cy={-14} r={2.5} fill={accent} />
                <path d="M 54 -5 L 58 5 L 62 -5 L 66 5" fill="none" stroke={stroke} strokeWidth={1.3} />
              </g>
            ) : (
              <g>
                <rect x={-66} y={-9} width={12} height={18} fill="#ede9fe" stroke="#7c3aed" strokeWidth={1.6} />
                <line x1={-63} y1={6} x2={-57} y2={-6} stroke="#7c3aed" strokeWidth={1.4} />
                <rect x={54} y={-9} width={12} height={18} fill="#ede9fe" stroke="#7c3aed" strokeWidth={1.6} />
                <line x1={57} y1={6} x2={63} y2={-6} stroke="#7c3aed" strokeWidth={1.4} />
              </g>
            )}
          </g>
          {showBadges && (
            <BadgeWrap>
              <rect x={-32} y={36} width={64} height={14} rx={3} fill="#0f172a" />
              <text x={0} y={46} textAnchor="middle" fontSize={8.5} fontWeight="700" fill="#38bdf8" fontFamily="monospace">
                u {(u * 100).toFixed(0)}%
              </text>
            </BadgeWrap>
          )}
        </g>
      );
    }

    case 'pos_controller': {
      const tgt = metrics?.targetMm ?? 0;
      const act = metrics?.actualMm ?? 0;
      return (
        <g>
          <rect x={-40} y={-24} width={80} height={48} rx={6} fill="var(--hs-fill, #ffffff)" stroke="#7c3aed" strokeWidth={2} />
          <text x={0} y={-6} textAnchor="middle" fontSize={10} fontWeight="800" fill="#7c3aed">PID CTRL</text>
          <text x={0} y={8} textAnchor="middle" fontSize={8} fontWeight="700" fill="#64748b" fontFamily="monospace">
            Ref {lDisp(tgt).toFixed(0)}{lUnitShort}
          </text>
          <text x={0} y={19} textAnchor="middle" fontSize={8} fontWeight="700" fill="#059669" fontFamily="monospace">
            Act {lDisp(act).toFixed(0)}{lUnitShort}
          </text>
        </g>
      );
    }

    case 'dcv42': {
      const pos = metrics?.spoolPos ?? (p.spoolPos || 0);
      const posAType = p.posAType || 'parallel';
      const posBType = p.posBType || 'crossed';
      const render42Box = (cfg, cx) => {
        const xA = cx - 10;
        const xB = cx + 10;
        switch (cfg) {
          case 'parallel':
            return (
              <g>
                <line x1={xA} y1={18} x2={xA} y2={-18} stroke={stroke} strokeWidth={1.6} />
                <polygon points={`${xA},-17 ${xA - 3},-10 ${xA + 3},-10`} fill={stroke} />
                <line x1={xB} y1={-18} x2={xB} y2={18} stroke={stroke} strokeWidth={1.6} />
                <polygon points={`${xB},17 ${xB - 3},10 ${xB + 3},10`} fill={stroke} />
              </g>
            );
          case 'crossed':
            return (
              <g>
                <line x1={xA} y1={18} x2={xB} y2={-18} stroke={stroke} strokeWidth={1.6} />
                <polygon points={`${xB},-17 ${xB - 6},-12 ${xB - 1},-9`} fill={stroke} />
                <line x1={xA} y1={-18} x2={xB} y2={18} stroke={stroke} strokeWidth={1.6} />
                <polygon points={`${xB},17 ${xB - 6},12 ${xB - 1},9`} fill={stroke} />
              </g>
            );
          case 'tandem':
            return (
              <g>
                <path d={`M ${xA} 18 L ${xA} 6 L ${xB} 6 L ${xB} 18`} fill="none" stroke={stroke} strokeWidth={1.6} />
                <line x1={xA} y1={-18} x2={xA} y2={-6} stroke={stroke} strokeWidth={1.6} />
                <line x1={xA - 4} y1={-6} x2={xA + 4} y2={-6} stroke={stroke} strokeWidth={1.8} />
                <line x1={xB} y1={-18} x2={xB} y2={-6} stroke={stroke} strokeWidth={1.6} />
                <line x1={xB - 4} y1={-6} x2={xB + 4} y2={-6} stroke={stroke} strokeWidth={1.8} />
              </g>
            );
          case 'closed':
            return (
              <g>
                {[xA, xB].map((x) => (
                  <g key={x}>
                    <line x1={x} y1={-18} x2={x} y2={-6} stroke={stroke} strokeWidth={1.6} />
                    <line x1={x - 4} y1={-6} x2={x + 4} y2={-6} stroke={stroke} strokeWidth={1.8} />
                    <line x1={x} y1={18} x2={x} y2={6} stroke={stroke} strokeWidth={1.6} />
                    <line x1={x - 4} y1={6} x2={x + 4} y2={6} stroke={stroke} strokeWidth={1.8} />
                  </g>
                ))}
              </g>
            );
          case 'open':
            return (
              <g>
                <line x1={xA} y1={-18} x2={xA} y2={18} stroke={stroke} strokeWidth={1.6} />
                <line x1={xB} y1={-18} x2={xB} y2={18} stroke={stroke} strokeWidth={1.6} />
                <line x1={xA} y1={0} x2={xB} y2={0} stroke={stroke} strokeWidth={1.6} />
              </g>
            );
          case 'float':
            return (
              <g>
                <path d={`M ${xA} -18 L ${xA} 0 L ${xB} 0 L ${xB} -18 M ${xB} 0 L ${xB} 18`} fill="none" stroke={stroke} strokeWidth={1.6} />
                <line x1={xA} y1={18} x2={xA} y2={6} stroke={stroke} strokeWidth={1.6} />
                <line x1={xA - 4} y1={6} x2={xA + 4} y2={6} stroke={stroke} strokeWidth={1.8} />
              </g>
            );
          case 'regen':
            return (
              <g>
                <path d={`M ${xA} -18 L ${xA} 0 L ${xB} 0 L ${xB} -18 M ${xA} 0 L ${xA} 18`} fill="none" stroke={stroke} strokeWidth={1.6} />
                <line x1={xB} y1={18} x2={xB} y2={6} stroke={stroke} strokeWidth={1.6} />
                <line x1={xB - 4} y1={6} x2={xB + 4} y2={6} stroke={stroke} strokeWidth={1.8} />
              </g>
            );
          case 'pa_b_blocked':
            return (
              <g>
                <line x1={xA} y1={18} x2={xA} y2={-18} stroke={stroke} strokeWidth={1.6} />
                <polygon points={`${xA},-17 ${xA - 3},-10 ${xA + 3},-10`} fill={stroke} />
                <line x1={xB} y1={-18} x2={xB} y2={-6} stroke={stroke} strokeWidth={1.6} />
                <line x1={xB - 4} y1={-6} x2={xB + 4} y2={-6} stroke={stroke} strokeWidth={1.8} />
                <line x1={xB} y1={18} x2={xB} y2={6} stroke={stroke} strokeWidth={1.6} />
                <line x1={xB - 4} y1={6} x2={xB + 4} y2={6} stroke={stroke} strokeWidth={1.8} />
              </g>
            );
          case 'pb_a_blocked':
            return (
              <g>
                <line x1={xA} y1={18} x2={xB} y2={-18} stroke={stroke} strokeWidth={1.6} />
                <polygon points={`${xB},-17 ${xB - 6},-12 ${xB - 1},-9`} fill={stroke} />
                <line x1={xA} y1={-18} x2={xA} y2={-6} stroke={stroke} strokeWidth={1.6} />
                <line x1={xA - 4} y1={-6} x2={xA + 4} y2={-6} stroke={stroke} strokeWidth={1.8} />
                <line x1={xB} y1={18} x2={xB} y2={6} stroke={stroke} strokeWidth={1.6} />
                <line x1={xB - 4} y1={6} x2={xB + 4} y2={6} stroke={stroke} strokeWidth={1.8} />
              </g>
            );
          case 'at_pb_blocked':
            return (
              <g>
                <line x1={xA} y1={-18} x2={xB} y2={18} stroke={stroke} strokeWidth={1.6} />
                <polygon points={`${xB},17 ${xB - 6},12 ${xB - 1},9`} fill={stroke} />
                <line x1={xA} y1={18} x2={xA} y2={6} stroke={stroke} strokeWidth={1.6} />
                <line x1={xA - 4} y1={6} x2={xA + 4} y2={6} stroke={stroke} strokeWidth={1.8} />
                <line x1={xB} y1={-18} x2={xB} y2={-6} stroke={stroke} strokeWidth={1.6} />
                <line x1={xB - 4} y1={-6} x2={xB + 4} y2={-6} stroke={stroke} strokeWidth={1.8} />
              </g>
            );
          case 'bt_pa_blocked':
            return (
              <g>
                <line x1={xB} y1={-18} x2={xB} y2={18} stroke={stroke} strokeWidth={1.6} />
                <polygon points={`${xB},17 ${xB - 3},10 ${xB + 3},10`} fill={stroke} />
                <line x1={xA} y1={-18} x2={xA} y2={-6} stroke={stroke} strokeWidth={1.6} />
                <line x1={xA - 4} y1={-6} x2={xA + 4} y2={-6} stroke={stroke} strokeWidth={1.8} />
                <line x1={xA} y1={18} x2={xA} y2={6} stroke={stroke} strokeWidth={1.6} />
                <line x1={xA - 4} y1={6} x2={xA + 4} y2={6} stroke={stroke} strokeWidth={1.8} />
              </g>
            );
          default:
            return null;
        }
      };
      return (
        <g>
          <line x1={-10} y1={-32} x2={-10} y2={-18} stroke={stroke} strokeWidth={2} />
          <line x1={10} y1={-32} x2={10} y2={-18} stroke={stroke} strokeWidth={2} />
          <line x1={-10} y1={18} x2={-10} y2={32} stroke={stroke} strokeWidth={2} />
          <line x1={10} y1={18} x2={10} y2={32} stroke={stroke} strokeWidth={2} />
          <g style={{ transition: 'transform 0.08s linear' }} transform={`translate(${(18 - pos * 36).toFixed(1)}, 0)`}>
            <rect x={-36} y={-18} width={36} height={36} fill={pos < 0.5 ? 'rgba(245,158,11,0.28)' : 'var(--hs-fill, #ffffff)'} stroke={stroke} strokeWidth={1.7} />
            <rect x={0} y={-18} width={36} height={36} fill={pos >= 0.5 ? 'rgba(245,158,11,0.28)' : 'var(--hs-fill, #ffffff)'} stroke={stroke} strokeWidth={1.7} />
            {render42Box(posAType, -18)}
            {render42Box(posBType, 18)}
            {p.controlMode === 'signal' ? (
              <g><rect x={-48} y={-9} width={12} height={18} fill="#ede9fe" stroke="#7c3aed" strokeWidth={1.6} /><line x1={-45} y1={6} x2={-39} y2={-6} stroke="#7c3aed" strokeWidth={1.4} /></g>
            ) : p.actuation === 'manual' ? (
              <g><line x1={-36} y1={0} x2={-46} y2={0} stroke={stroke} strokeWidth={1.5} /><line x1={-46} y1={0} x2={-52} y2={-12} stroke={accent} strokeWidth={1.8} strokeLinecap="round" /><circle cx={-52} cy={-13} r={2.5} fill={accent} /></g>
            ) : (
              <g><rect x={-48} y={-8} width={12} height={16} fill="#f8fafc" stroke={stroke} strokeWidth={1.3} /><line x1={-45} y1={6} x2={-39} y2={-6} stroke={stroke} strokeWidth={1.2} /></g>
            )}
            <path d="M 36 -5 L 40 5 L 44 -5 L 48 5" fill="none" stroke={stroke} strokeWidth={1.3} />
          </g>
          {showBadges && p.controlMode === 'signal' && (
            <g>
              <rect x={-24} y={36} width={48} height={14} rx={3} fill="#7c3aed" />
              <text x={0} y={46} textAnchor="middle" fontSize={8} fontWeight="700" fill="#ffffff" fontFamily="monospace">SIG [{pos === 0 ? 'A' : 'B'}]</text>
            </g>
          )}
          {onToggleSpool && p.controlMode !== 'signal' && (
            <g onMouseDown={(e) => e.stopPropagation()}>
              <rect x={-28} y={36} width={26} height={15} rx={3} fill={pos === 0 ? '#0284c7' : '#e2e8f0'} className="cursor-pointer" onClick={(e) => { e.stopPropagation(); onToggleSpool?.(comp.id, 0); }} />
              <text x={-15} y={46.5} textAnchor="middle" fontSize={8.5} fontWeight="700" fill={pos === 0 ? '#ffffff' : '#475569'} className="pointer-events-none">A</text>
              <rect x={2} y={36} width={26} height={15} rx={3} fill={pos === 1 ? '#0284c7' : '#e2e8f0'} className="cursor-pointer" onClick={(e) => { e.stopPropagation(); onToggleSpool?.(comp.id, 1); }} />
              <text x={15} y={46.5} textAnchor="middle" fontSize={8.5} fontWeight="700" fill={pos === 1 ? '#ffffff' : '#475569'} className="pointer-events-none">B</text>
            </g>
          )}
        </g>
      );
    }

    case 'dcv32': {
      const pos = metrics?.spoolPos ?? (p.spoolPos || 0);
      const pos1Type = p.pos1Type || 'pa_t_blocked';
      const pos0Type = p.pos0Type || 'at_p_blocked';
      const render32Box = (cfg, cx) => {
        const xP = cx - 9;
        const xT = cx + 9;
        const xA = cx;
        switch (cfg) {
          case 'pa_t_blocked':
            return (
              <g>
                <line x1={xP} y1={18} x2={xA} y2={-18} stroke={stroke} strokeWidth={1.6} />
                <polygon points={`${xA},-17 ${xA - 4},-10 ${xA + 2},-9`} fill={stroke} />
                <line x1={xT} y1={18} x2={xT} y2={6} stroke={stroke} strokeWidth={1.6} />
                <line x1={xT - 4} y1={6} x2={xT + 4} y2={6} stroke={stroke} strokeWidth={1.8} />
              </g>
            );
          case 'at_p_blocked':
            return (
              <g>
                <line x1={xA} y1={-18} x2={xT} y2={18} stroke={stroke} strokeWidth={1.6} />
                <polygon points={`${xT},17 ${xT - 6},11 ${xT},9`} fill={stroke} />
                <line x1={xP} y1={18} x2={xP} y2={6} stroke={stroke} strokeWidth={1.6} />
                <line x1={xP - 4} y1={6} x2={xP + 4} y2={6} stroke={stroke} strokeWidth={1.8} />
              </g>
            );
          case 'pt_a_blocked':
            return (
              <g>
                <path d={`M ${xP} 18 L ${xP} 6 L ${xT} 6 L ${xT} 18`} fill="none" stroke={stroke} strokeWidth={1.6} />
                <line x1={xA} y1={-18} x2={xA} y2={-6} stroke={stroke} strokeWidth={1.6} />
                <line x1={xA - 4} y1={-6} x2={xA + 4} y2={-6} stroke={stroke} strokeWidth={1.8} />
              </g>
            );
          case 'all_open':
            return (
              <g>
                <line x1={xA} y1={-18} x2={xA} y2={0} stroke={stroke} strokeWidth={1.6} />
                <line x1={xP} y1={0} x2={xT} y2={0} stroke={stroke} strokeWidth={1.6} />
                <line x1={xP} y1={0} x2={xP} y2={18} stroke={stroke} strokeWidth={1.6} />
                <line x1={xT} y1={0} x2={xT} y2={18} stroke={stroke} strokeWidth={1.6} />
              </g>
            );
          case 'all_blocked':
          default:
            return (
              <g>
                <line x1={xA} y1={-18} x2={xA} y2={-6} stroke={stroke} strokeWidth={1.6} />
                <line x1={xA - 4} y1={-6} x2={xA + 4} y2={-6} stroke={stroke} strokeWidth={1.8} />
                <line x1={xP} y1={18} x2={xP} y2={6} stroke={stroke} strokeWidth={1.6} />
                <line x1={xP - 4} y1={6} x2={xP + 4} y2={6} stroke={stroke} strokeWidth={1.8} />
                <line x1={xT} y1={18} x2={xT} y2={6} stroke={stroke} strokeWidth={1.6} />
                <line x1={xT - 4} y1={6} x2={xT + 4} y2={6} stroke={stroke} strokeWidth={1.8} />
              </g>
            );
        }
      };
      return (
        <g>
          <line x1={-9} y1={18} x2={-9} y2={32} stroke={stroke} strokeWidth={2} />
          <line x1={9} y1={18} x2={9} y2={32} stroke={stroke} strokeWidth={2} />
          <line x1={0} y1={-32} x2={0} y2={-18} stroke={stroke} strokeWidth={2} />
          <g style={{ transition: 'transform 0.08s linear' }} transform={`translate(${(-17 + pos * 34).toFixed(1)}, 0)`}>
            <rect x={-34} y={-18} width={34} height={36} fill={pos >= 0.5 ? 'rgba(245,158,11,0.28)' : 'var(--hs-fill, #ffffff)'} stroke={stroke} strokeWidth={1.7} />
            <rect x={0} y={-18} width={34} height={36} fill={pos < 0.5 ? 'rgba(245,158,11,0.28)' : 'var(--hs-fill, #ffffff)'} stroke={stroke} strokeWidth={1.7} />
            {render32Box(pos1Type, -17)}
            {render32Box(pos0Type, 17)}
            {p.controlMode === 'signal' ? (
              <g><rect x={-46} y={-9} width={12} height={18} fill="#ede9fe" stroke="#7c3aed" strokeWidth={1.6} /><line x1={-43} y1={6} x2={-37} y2={-6} stroke="#7c3aed" strokeWidth={1.4} /></g>
            ) : p.actuation === 'manual' ? (
              <g><line x1={-34} y1={0} x2={-44} y2={0} stroke={stroke} strokeWidth={1.5} /><line x1={-44} y1={0} x2={-50} y2={-12} stroke={accent} strokeWidth={1.8} strokeLinecap="round" /><circle cx={-50} cy={-13} r={2.5} fill={accent} /></g>
            ) : (
              <g><rect x={-46} y={-8} width={12} height={16} fill="#f8fafc" stroke={stroke} strokeWidth={1.3} /><line x1={-43} y1={6} x2={-37} y2={-6} stroke={stroke} strokeWidth={1.2} /></g>
            )}
            <path d="M 34 -5 L 38 5 L 42 -5 L 46 5" fill="none" stroke={stroke} strokeWidth={1.3} />
          </g>
          {showBadges && p.controlMode === 'signal' && (
            <g>
              <rect x={-24} y={36} width={48} height={14} rx={3} fill="#7c3aed" />
              <text x={0} y={46} textAnchor="middle" fontSize={8} fontWeight="700" fill="#ffffff" fontFamily="monospace">SIG [{pos}]</text>
            </g>
          )}
          {onToggleSpool && p.controlMode !== 'signal' && (
            <g onMouseDown={(e) => e.stopPropagation()}>
              <rect x={-26} y={36} width={24} height={15} rx={3} fill={pos === 1 ? '#0284c7' : '#e2e8f0'} className="cursor-pointer" onClick={(e) => { e.stopPropagation(); onToggleSpool?.(comp.id, 1); }} />
              <text x={-14} y={46.5} textAnchor="middle" fontSize={8.5} fontWeight="700" fill={pos === 1 ? '#ffffff' : '#475569'} className="pointer-events-none">1</text>
              <rect x={2} y={36} width={24} height={15} rx={3} fill={pos === 0 ? '#0284c7' : '#e2e8f0'} className="cursor-pointer" onClick={(e) => { e.stopPropagation(); onToggleSpool?.(comp.id, 0); }} />
              <text x={14} y={46.5} textAnchor="middle" fontSize={8.5} fontWeight="700" fill={pos === 0 ? '#ffffff' : '#475569'} className="pointer-events-none">0</text>
            </g>
          )}
        </g>
      );
    }

    case 'dcv22': {
      const pos = metrics?.spoolPos ?? (p.spoolPos || 0);
      const defaultPos1 = p.normalState === 'no' ? 'blocked' : 'open_ab';
      const defaultPos0 = p.normalState === 'no' ? 'open_ab' : 'blocked';
      const pos1Type = p.pos1Type || defaultPos1;
      const pos0Type = p.pos0Type || defaultPos0;
      const activeCfg = pos >= 0.5 ? pos1Type : pos0Type;
      const isOpen = activeCfg !== 'blocked';
      const render22Box = (cfg, xL, xR) => {
        const xm = (xL + xR) * 0.5;
        if (cfg === 'open_ab') {
          return (
            <g>
              <line x1={xL + 4} y1={0} x2={xR - 4} y2={0} stroke={stroke} strokeWidth={1.6} />
              <polygon points={`${xR - 4},0 ${xR - 9},-3 ${xR - 9},3`} fill={stroke} />
              <polygon points={`${xL + 4},0 ${xL + 9},-3 ${xL + 9},3`} fill={stroke} />
            </g>
          );
        }
        if (cfg === 'open_a_to_b' || cfg === 'check_ab') {
          return (
            <g>
              <line x1={xL + 4} y1={0} x2={xR - 4} y2={0} stroke={stroke} strokeWidth={1.6} />
              <polygon points={`${xR - 4},0 ${xR - 10},-3.5 ${xR - 10},3.5`} fill={stroke} />
              {cfg === 'check_ab' && <circle cx={xm - 3} cy={0} r={2.5} fill="none" stroke={stroke} strokeWidth={1.3} />}
            </g>
          );
        }
        if (cfg === 'open_b_to_a' || cfg === 'check_ba') {
          return (
            <g>
              <line x1={xL + 4} y1={0} x2={xR - 4} y2={0} stroke={stroke} strokeWidth={1.6} />
              <polygon points={`${xL + 4},0 ${xL + 10},-3.5 ${xL + 10},3.5`} fill={stroke} />
              {cfg === 'check_ba' && <circle cx={xm + 3} cy={0} r={2.5} fill="none" stroke={stroke} strokeWidth={1.3} />}
            </g>
          );
        }
        return (
          <g>
            <line x1={xL + 4} y1={0} x2={xm - 4} y2={0} stroke={stroke} strokeWidth={1.5} />
            <line x1={xm - 4} y1={-6} x2={xm - 4} y2={6} stroke={stroke} strokeWidth={1.8} />
            <line x1={xm + 4} y1={-6} x2={xm + 4} y2={6} stroke={stroke} strokeWidth={1.8} />
            <line x1={xm + 4} y1={0} x2={xR - 4} y2={0} stroke={stroke} strokeWidth={1.5} />
          </g>
        );
      };
      return (
        <g>
          <g style={{ transition: 'transform 0.08s linear' }} transform={`translate(${(-14 + pos * 28).toFixed(1)}, 0)`}>
            <rect x={-28} y={-14} width={28} height={28} fill={pos >= 0.5 ? 'rgba(245,158,11,0.28)' : 'var(--hs-fill, #ffffff)'} stroke={stroke} strokeWidth={1.6} />
            <rect x={0} y={-14} width={28} height={28} fill={pos < 0.5 ? 'rgba(245,158,11,0.28)' : 'var(--hs-fill, #ffffff)'} stroke={stroke} strokeWidth={1.6} />
            {render22Box(pos1Type, -28, 0)}
            {render22Box(pos0Type, 0, 28)}
            {p.controlMode === 'signal' ? (
              <g><rect x={-38} y={-8} width={10} height={16} fill="#ede9fe" stroke="#7c3aed" strokeWidth={1.6} /><line x1={-36} y1={5} x2={-30} y2={-5} stroke="#7c3aed" strokeWidth={1.4} /></g>
            ) : p.actuation === 'manual' ? (
              <g><line x1={-28} y1={0} x2={-36} y2={0} stroke={stroke} strokeWidth={1.5} /><line x1={-36} y1={0} x2={-41} y2={-10} stroke={accent} strokeWidth={1.8} strokeLinecap="round" /><circle cx={-41} cy={-11} r={2.2} fill={accent} /></g>
            ) : (
              <g><rect x={-38} y={-7} width={10} height={14} fill="#f8fafc" stroke={stroke} strokeWidth={1.3} /><line x1={-36} y1={5} x2={-30} y2={-5} stroke={stroke} strokeWidth={1.2} /></g>
            )}
            <path d="M 28 -4 L 32 4 L 35 -4 L 38 4" fill="none" stroke={stroke} strokeWidth={1.3} />
          </g>
          {/* Port leads attach to the ACTIVE envelope (box centred between A and B) */}
          <line x1={-40} y1={0} x2={-14} y2={0} stroke={stroke} strokeWidth={2} />
          <line x1={14} y1={0} x2={40} y2={0} stroke={stroke} strokeWidth={2} />
          {p.controlMode === 'signal' ? (
            showBadges && (
              <g>
                <rect x={-28} y={18} width={56} height={14} rx={3} fill="#7c3aed" />
                <text x={0} y={28} textAnchor="middle" fontSize={8} fontWeight="700" fill="#ffffff" fontFamily="monospace">SIG·{isOpen ? 'OPEN' : 'SHUT'}</text>
              </g>
            )
          ) : onToggleSpool && (
            <g className="cursor-pointer" onMouseDown={(e) => e.stopPropagation()} onClick={(e) => { e.stopPropagation(); onToggleSpool?.(comp.id, pos === 0 ? 1 : 0); }}>
              <rect x={-26} y={18} width={52} height={15} rx={3} fill={isOpen ? '#0284c7' : '#334155'} />
              <text x={0} y={28.5} textAnchor="middle" fontSize={8.5} fontWeight="700" fill="var(--hs-fill, #ffffff)" fontFamily="monospace">{isOpen ? 'OPEN' : 'SHUT'} [{pos}]</text>
            </g>
          )}
        </g>
      );
    }

    case 'prv': {
      const active = metrics?.active;
      return (
        <g>
          <line x1={-34} y1={0} x2={-18} y2={0} stroke={stroke} strokeWidth={2} />
          <line x1={18} y1={0} x2={34} y2={0} stroke={stroke} strokeWidth={2} />
          <rect x={-18} y={-18} width={36} height={36} fill={active ? 'rgba(245,158,11,0.22)' : 'var(--hs-fill, #ffffff)'} stroke={stroke} strokeWidth={1.8} />
          <line x1={-10} y1={-6} x2={10} y2={-6} stroke={stroke} strokeWidth={1.6} />
          <polygon points="10,-6 4,-9.5 4,-2.5" fill={stroke} />
          <path d="M -28 0 L -28 -25 L 0 -25 L 0 -18" fill="none" stroke={stroke} strokeWidth={1.3} strokeDasharray="3 2" />
          <path d="M -6 18 L 6 22 L -6 26 L 6 30" fill="none" stroke={stroke} strokeWidth={1.4} />
          {showBadges && (
            <text x={0} y={-28} textAnchor="middle" fontSize={9} fontWeight="700" fill="#64748b" fontFamily="monospace">
              {pDisp(p.crackPressure).toFixed(units.pressure === 'MPa' ? 1 : 0)}{pUnitShort}
            </text>
          )}
        </g>
      );
    }

    case 'prv_reducing':
      return (
        <g>
          <line x1={-36} y1={0} x2={-18} y2={0} stroke={stroke} strokeWidth={2} />
          <line x1={18} y1={0} x2={36} y2={0} stroke={stroke} strokeWidth={2} />
          <line x1={0} y1={18} x2={0} y2={36} stroke={stroke} strokeWidth={1.6} strokeDasharray="3 2" />
          <rect x={-18} y={-18} width={36} height={36} fill="var(--hs-fill, #ffffff)" stroke={stroke} strokeWidth={1.8} />
          <line x1={-12} y1={0} x2={12} y2={0} stroke={stroke} strokeWidth={1.7} />
          <polygon points="12,0 6,-3.5 6,3.5" fill={stroke} />
          <path d="M 28 0 L 28 -24 L 0 -24 L 0 -18" fill="none" stroke={accent} strokeWidth={1.3} strokeDasharray="3 2" />
          <path d="M -14 20 L -6 23 L -14 26 L -6 29" fill="none" stroke={stroke} strokeWidth={1.3} />
          {showBadges && (
            <text x={0} y={-29} textAnchor="middle" fontSize={9} fontWeight="700" fill="#0369a1" fontFamily="monospace">
              RD {pDisp(p.setPressure).toFixed(units.pressure === 'MPa' ? 1 : 0)}{pUnitShort}
            </text>
          )}
        </g>
      );

    case 'seq_valve': {
      const active = metrics?.active;
      return (
        <g>
          <line x1={-36} y1={0} x2={-18} y2={0} stroke={stroke} strokeWidth={2} />
          <line x1={18} y1={0} x2={36} y2={0} stroke={stroke} strokeWidth={2} />
          <line x1={0} y1={18} x2={0} y2={36} stroke={stroke} strokeWidth={1.6} strokeDasharray="3 2" />
          <rect x={-18} y={-18} width={36} height={36} fill={active ? 'rgba(16,185,129,0.22)' : 'var(--hs-fill, #ffffff)'} stroke={stroke} strokeWidth={1.8} />
          <line x1={-10} y1={-6} x2={10} y2={-6} stroke={stroke} strokeWidth={1.6} />
          <polygon points="10,-6 4,-9.5 4,-2.5" fill={stroke} />
          <path d="M -28 0 L -28 -24 L 0 -24 L 0 -18" fill="none" stroke="#16a34a" strokeWidth={1.3} strokeDasharray="3 2" />
          <path d="M 6 20 L 14 23 L 6 26 L 14 29" fill="none" stroke={stroke} strokeWidth={1.3} />
          {showBadges && (
            <text x={0} y={-29} textAnchor="middle" fontSize={9} fontWeight="700" fill="#15803d" fontFamily="monospace">
              SQ {pDisp(p.seqPressure).toFixed(units.pressure === 'MPa' ? 1 : 0)}{pUnitShort}
            </text>
          )}
        </g>
      );
    }

    case 'cb_valve': {
      const active = metrics?.active;
      const openPct = metrics?.openPct ?? 0;
      return (
        <g>
          <line x1={-38} y1={0} x2={-18} y2={0} stroke={stroke} strokeWidth={2} />
          <line x1={18} y1={0} x2={38} y2={0} stroke={stroke} strokeWidth={2} />
          <line x1={0} y1={18} x2={0} y2={38} stroke={accent} strokeWidth={1.6} strokeDasharray="3 2" />
          <rect x={-18} y={-18} width={36} height={36} fill={active ? 'rgba(245,158,11,0.22)' : 'var(--hs-fill, #ffffff)'} stroke={stroke} strokeWidth={1.8} />
          <line x1={-10} y1={-5} x2={10} y2={-5} stroke={stroke} strokeWidth={1.6} />
          <polygon points="10,-5 4,-8.5 4,-1.5" fill={stroke} />
          <path d="M -26 0 L -26 -26 L 26 -26 L 26 0" fill="none" stroke={stroke} strokeWidth={1.3} />
          <circle cx={-3} cy={-26} r={3.5} fill="var(--hs-fill, #ffffff)" stroke={stroke} strokeWidth={1.3} />
          {showBadges && (
            <BadgeWrap>
              <rect x={-30} y={-48} width={60} height={14} rx={3} fill="#0f172a" />
              <text x={0} y={-38} textAnchor="middle" fontSize={8.5} fontWeight="700" fill={active ? '#fbbf24' : '#94a3b8'} fontFamily="monospace">
                CB {openPct.toFixed(0)}%
              </text>
            </BadgeWrap>
          )}
        </g>
      );
    }

    case 'unloading_valve': {
      const active = metrics?.unloading;
      const openPct = metrics?.openPct ?? 0;
      return (
        <g>
          <line x1={-36} y1={0} x2={-18} y2={0} stroke={stroke} strokeWidth={2} />
          <line x1={18} y1={0} x2={36} y2={0} stroke={stroke} strokeWidth={2} />
          <line x1={0} y1={18} x2={0} y2={36} stroke={accent} strokeWidth={1.6} strokeDasharray="3 2" />
          <rect x={-18} y={-18} width={36} height={36} fill={active ? 'rgba(245,158,11,0.22)' : 'var(--hs-fill, #ffffff)'} stroke={stroke} strokeWidth={1.8} />
          <line x1={-11} y1={-6} x2={11} y2={-6} stroke={stroke} strokeWidth={1.6} />
          <polygon points="11,-6 5,-9.5 5,-2.5" fill={stroke} />
          <path d="M -5 -26 L 5 -23 L -5 -20 L 5 -18" fill="none" stroke={stroke} strokeWidth={1.4} />
          <polygon points="0,18 -3.5,24 3.5,24" fill={accent} />
          {showBadges && (
            <BadgeWrap>
              <rect x={-34} y={-44} width={68} height={14} rx={3} fill={active ? '#b45309' : '#0f172a'} />
              <text x={0} y={-34} textAnchor="middle" fontSize={8.5} fontWeight="700" fill={active ? '#ffffff' : '#38bdf8'} fontFamily="monospace">
                UL {pDisp(p.unloadPressure).toFixed(0)}{pUnitShort} ({openPct.toFixed(0)}%)
              </text>
            </BadgeWrap>
          )}
        </g>
      );
    }

    case 'throttle':
      return (
        <g>
          <line x1={-38} y1={0} x2={38} y2={0} stroke={stroke} strokeWidth={2} />
          <path d="M -14 -12 Q 0 -2 14 -12" fill="none" stroke={stroke} strokeWidth={1.9} />
          <path d="M -14 12 Q 0 2 14 12" fill="none" stroke={stroke} strokeWidth={1.9} />
          <line x1={-12} y1={14} x2={12} y2={-14} stroke={accent} strokeWidth={1.6} />
          <polygon points="12,-14 6,-12 10,-7" fill={accent} />
          {showBadges && (
            <text x={0} y={-18} textAnchor="middle" fontSize={8.5} fontWeight="700" fill="#475569" fontFamily="monospace">
              {Math.round(p.openingPct ?? 45)}%
            </text>
          )}
        </g>
      );

    case 'orifice':
      return (
        <g>
          <line x1={-38} y1={0} x2={38} y2={0} stroke={stroke} strokeWidth={2} />
          <path d="M -14 -12 Q 0 -2 14 -12" fill="none" stroke={stroke} strokeWidth={2} />
          <path d="M -14 12 Q 0 2 14 12" fill="none" stroke={stroke} strokeWidth={2} />
          {showBadges && (
            <text x={0} y={-18} textAnchor="middle" fontSize={8.5} fontWeight="700" fill="#475569" fontFamily="monospace">
              Ø{(p.orificeDia || 3).toFixed(1)}mm
            </text>
          )}
        </g>
      );

    case 'ow_flow_ctrl':
      return (
        <g>
          <line x1={-41} y1={0} x2={41} y2={0} stroke={stroke} strokeWidth={2} />
          <path d="M -14 -10 Q 0 -1 14 -10" fill="none" stroke={stroke} strokeWidth={1.8} />
          <path d="M -14 10 Q 0 1 14 10" fill="none" stroke={stroke} strokeWidth={1.8} />
          <line x1={-10} y1={12} x2={10} y2={-12} stroke={accent} strokeWidth={1.4} />
          <path d="M -26 0 L -26 -20 L 26 -20 L 26 0" fill="none" stroke={stroke} strokeWidth={1.5} />
          <circle cx={-3} cy={-20} r={4} fill="var(--hs-fill, #ffffff)" stroke={stroke} strokeWidth={1.5} />
          <path d="M 3 -25 L -6 -20 L 3 -15" fill="none" stroke={stroke} strokeWidth={1.5} />
        </g>
      );

    case 'pc_flow_ctrl': {
      const qLpm = metrics?.flowLpm ?? 0;
      const reg = metrics?.regulated;
      return (
        <g>
          <line x1={-42} y1={0} x2={42} y2={0} stroke={stroke} strokeWidth={2} />
          <rect x={-26} y={-20} width={52} height={40} rx={3} fill="var(--hs-fill, #ffffff)" stroke={stroke} strokeWidth={1.5} strokeDasharray="4 2" />
          <path d="M -14 -11 Q 0 -2 14 -11" fill="none" stroke={stroke} strokeWidth={1.8} />
          <path d="M -14 11 Q 0 2 14 11" fill="none" stroke={stroke} strokeWidth={1.8} />
          <line x1={-12} y1={13} x2={12} y2={-13} stroke={accent} strokeWidth={1.5} />
          <polygon points="12,-13 6,-11 10,-7" fill={accent} />
          <line x1={-18} y1={-14} x2={-18} y2={14} stroke={stroke} strokeWidth={1.3} />
          <polygon points="-18,-14 -21,-9 -15,-9" fill={stroke} />
          {showBadges && (
            <BadgeWrap>
              <rect x={-38} y={-38} width={76} height={14} rx={3} fill={reg ? '#0369a1' : '#0f172a'} />
              <text x={0} y={-28} textAnchor="middle" fontSize={8.5} fontWeight="700" fill="var(--hs-fill, #ffffff)" fontFamily="monospace">
                PC {qDisp(qLpm).toFixed(1)}{qUnitShort}
              </text>
            </BadgeWrap>
          )}
        </g>
      );
    }

    case 'flow_divider': {
      const qA = metrics?.flowALpm ?? 0;
      const qB = metrics?.flowBLpm ?? 0;
      return (
        <g>
          <line x1={0} y1={18} x2={0} y2={34} stroke={stroke} strokeWidth={2} />
          <line x1={-24} y1={-34} x2={-24} y2={-18} stroke={stroke} strokeWidth={2} />
          <line x1={24} y1={-34} x2={24} y2={-18} stroke={stroke} strokeWidth={2} />
          <rect x={-36} y={-18} width={72} height={36} rx={3} fill="var(--hs-fill, #ffffff)" stroke={stroke} strokeWidth={1.8} />
          <path d="M 0 18 L 0 4 L -24 4 L -24 -18" fill="none" stroke={stroke} strokeWidth={1.6} />
          <path d="M 0 4 L 24 4 L 24 -18" fill="none" stroke={stroke} strokeWidth={1.6} />
          <circle cx={-24} cy={-7} r={3.5} fill="#e0f2fe" stroke={accent} strokeWidth={1.3} />
          <circle cx={24} cy={-7} r={3.5} fill="#e0f2fe" stroke={accent} strokeWidth={1.3} />
          <text x={0} y={-4} textAnchor="middle" fontSize={8.5} fontWeight="800" fill="#475569" fontFamily="monospace">
            {p.splitPct ?? 50}/{100 - (p.splitPct ?? 50)}
          </text>
          {showBadges && (
            <BadgeWrap>
              <rect x={-42} y={-48} width={84} height={14} rx={3} fill="#0f172a" />
              <text x={0} y={-38} textAnchor="middle" fontSize={8} fontWeight="700" fill="#38bdf8" fontFamily="monospace">
                {qDisp(qA).toFixed(1)} | {qDisp(qB).toFixed(1)}{qUnitShort}
              </text>
            </BadgeWrap>
          )}
        </g>
      );
    }

    case 'check':
      return (
        <g>
          <line x1={-34} y1={0} x2={-7} y2={0} stroke={stroke} strokeWidth={2} />
          <line x1={7} y1={0} x2={34} y2={0} stroke={stroke} strokeWidth={2} />
          <path d="M 3 -10 L -7 0 L 3 10" fill="none" stroke={stroke} strokeWidth={1.8} strokeLinejoin="round" />
          <circle cx={1.5} cy={0} r={5.2} fill="var(--hs-fill, #ffffff)" stroke={stroke} strokeWidth={1.8} />
        </g>
      );

    case 'po_check': {
      const open = metrics?.open;
      return (
        <g>
          <line x1={-37} y1={0} x2={-7} y2={0} stroke={stroke} strokeWidth={2} />
          <line x1={7} y1={0} x2={37} y2={0} stroke={stroke} strokeWidth={2} />
          <line x1={0} y1={8} x2={0} y2={32} stroke={accent} strokeWidth={1.6} strokeDasharray="3 2" />
          <path d="M 3 -10 L -7 0 L 3 10" fill="none" stroke={stroke} strokeWidth={1.8} strokeLinejoin="round" />
          <circle cx={1.5} cy={0} r={5.2} fill={open ? 'rgba(16,185,129,0.22)' : 'var(--hs-fill, #ffffff)'} stroke={stroke} strokeWidth={1.8} />
          {showBadges && (
            <BadgeWrap>
              <rect x={-26} y={-32} width={52} height={14} rx={3} fill={open ? '#14532d' : '#0f172a'} />
              <text x={0} y={-22} textAnchor="middle" fontSize={8.5} fontWeight="700" fill={open ? '#4ade80' : '#f87171'} fontFamily="monospace">
                {open ? 'OPEN' : 'LOCKED'}
              </text>
            </BadgeWrap>
          )}
        </g>
      );
    }

    case 'cylinder': {
      const strokeMm = p.stroke || 250;
      const posMm = metrics?.posMm ?? (p.initPos || 0);
      const frac = Math.max(0, Math.min(1, posMm / Math.max(1, strokeMm)));
      const pistonX = -44 + frac * 76;
      return (
        <g>
          <line x1={-48} y1={18} x2={-48} y2={29} stroke={stroke} strokeWidth={2} />
          <line x1={40} y1={18} x2={40} y2={29} stroke={stroke} strokeWidth={2} />
          <rect x={-56} y={-18} width={104} height={36} fill="var(--hs-fill, #ffffff)" stroke={stroke} strokeWidth={2} />
          <rect x={-54} y={-16} width={Math.max(0, pistonX + 54)} height={32} fill="#bae6fd" fillOpacity={0.55} />
          <rect x={pistonX - 4} y={-17} width={8} height={34} fill="#334155" />
          <rect x={pistonX + 4} y={-5} width={108} height={10} fill="#94a3b8" stroke={stroke} strokeWidth={1.5} />
          <rect x={pistonX + 112} y={-9} width={8} height={18} rx={2} fill="#475569" />
          {showBadges && (
            <BadgeWrap>
              <rect x={-36} y={-35} width={72} height={14} rx={3} fill="#0f172a" fillOpacity={0.85} />
              <text x={0} y={-25} textAnchor="middle" fontSize={9} fill="#38bdf8" fontWeight="700" fontFamily="monospace">
                {lDisp(posMm).toFixed(units.length === 'in' ? 1 : 0)}/{lDisp(strokeMm).toFixed(units.length === 'in' ? 1 : 0)}{lUnitShort}
              </text>
            </BadgeWrap>
          )}
        </g>
      );
    }

    case 'dr_cylinder': {
      const strokeMm = p.stroke || 250;
      const posMm = metrics?.posMm ?? (p.initPos ?? 125);
      const frac = Math.max(0, Math.min(1, posMm / Math.max(1, strokeMm)));
      const pistonX = -36 + frac * 72;
      return (
        <g>
          <line x1={-46} y1={18} x2={-46} y2={29} stroke={stroke} strokeWidth={2} />
          <line x1={46} y1={18} x2={46} y2={29} stroke={stroke} strokeWidth={2} />
          <rect x={-52} y={-18} width={104} height={36} fill="var(--hs-fill, #ffffff)" stroke={stroke} strokeWidth={2} />
          <rect x={-50} y={-16} width={Math.max(0, pistonX + 50)} height={32} fill="#bae6fd" fillOpacity={0.55} />
          <rect x={pistonX - 4} y={-17} width={8} height={34} fill="#334155" />
          {/* Left rod */}
          <rect x={pistonX - 104} y={-5} width={100} height={10} fill="#94a3b8" stroke={stroke} strokeWidth={1.5} />
          <rect x={pistonX - 110} y={-9} width={6} height={18} rx={1.5} fill="#475569" />
          {/* Right rod */}
          <rect x={pistonX + 4} y={-5} width={100} height={10} fill="#94a3b8" stroke={stroke} strokeWidth={1.5} />
          <rect x={pistonX + 104} y={-9} width={6} height={18} rx={1.5} fill="#475569" />
          {showBadges && (
            <BadgeWrap>
              <rect x={-36} y={-35} width={72} height={14} rx={3} fill="#0f172a" fillOpacity={0.85} />
              <text x={0} y={-25} textAnchor="middle" fontSize={9} fill="#38bdf8" fontWeight="700" fontFamily="monospace">
                {lDisp(posMm).toFixed(units.length === 'in' ? 1 : 0)}/{lDisp(strokeMm).toFixed(units.length === 'in' ? 1 : 0)}{lUnitShort}
              </text>
            </BadgeWrap>
          )}
        </g>
      );
    }

    case 'sa_cylinder': {
      const strokeMm = p.stroke || 200;
      const posMm = metrics?.posMm ?? (p.initPos || 0);
      const frac = Math.max(0, Math.min(1, posMm / Math.max(1, strokeMm)));
      const pistonX = -44 + frac * 76;
      const springX0 = pistonX + 6;
      const springX1 = 46;
      const springSegs = 6;
      const dx = Math.max(2, (springX1 - springX0) / springSegs);
      let springPath = `M ${springX0} 0`;
      for (let i = 1; i <= springSegs; i++) {
        springPath += ` L ${springX0 + (i - 0.5) * dx} ${i % 2 === 0 ? -10 : 10}`;
      }
      springPath += ` L ${springX1} 0`;
      return (
        <g>
          <line x1={-48} y1={18} x2={-48} y2={29} stroke={stroke} strokeWidth={2} />
          <rect x={-56} y={-18} width={104} height={36} fill="var(--hs-fill, #ffffff)" stroke={stroke} strokeWidth={2} />
          <rect x={-54} y={-16} width={Math.max(0, pistonX + 54)} height={32} fill="#bae6fd" fillOpacity={0.55} />
          <path d={springPath} fill="none" stroke="#64748b" strokeWidth={1.5} />
          <rect x={pistonX - 4} y={-17} width={8} height={34} fill="#334155" />
          <rect x={pistonX + 4} y={-5} width={108} height={10} fill="#94a3b8" stroke={stroke} strokeWidth={1.5} />
          <rect x={pistonX + 112} y={-9} width={8} height={18} rx={2} fill="#475569" />
          {showBadges && (
            <BadgeWrap>
              <rect x={-36} y={-35} width={72} height={14} rx={3} fill="#0f172a" fillOpacity={0.85} />
              <text x={0} y={-25} textAnchor="middle" fontSize={9} fill="#38bdf8" fontWeight="700" fontFamily="monospace">
                {lDisp(posMm).toFixed(units.length === 'in' ? 1 : 0)}/{lDisp(strokeMm).toFixed(units.length === 'in' ? 1 : 0)}{lUnitShort}
              </text>
            </BadgeWrap>
          )}
        </g>
      );
    }

    case 'motor': {
      const rpm = metrics?.rpm ?? 0;
      const angle = metrics?.angleDeg ?? 0;
      return (
        <g>
          <line x1={-34} y1={0} x2={-20} y2={0} stroke={stroke} strokeWidth={2} />
          <line x1={20} y1={0} x2={34} y2={0} stroke={stroke} strokeWidth={2} />
          <circle cx={0} cy={0} r={20} fill="var(--hs-fill, #ffffff)" stroke={stroke} strokeWidth={2} />
          <polygon points="-18,0 -9,-6 -9,6" fill={stroke} />
          <polygon points="18,0 9,-6 9,6" fill={stroke} />
          <g transform={`rotate(${angle})`}>
            <line x1={-8} y1={0} x2={8} y2={0} stroke={accent} strokeWidth={2.2} strokeLinecap="round" />
            <line x1={0} y1={-8} x2={0} y2={8} stroke={accent} strokeWidth={2.2} strokeLinecap="round" />
            <circle cx={0} cy={0} r={3} fill={accent} />
          </g>
          {showBadges && (
            <BadgeWrap>
              <rect x={-30} y={26} width={60} height={15} rx={3} fill="#0f172a" />
              <text x={0} y={36.5} textAnchor="middle" fontSize={9} fontWeight="700" fill="#38bdf8" fontFamily="monospace">
                {rpm.toFixed(0)} RPM
              </text>
            </BadgeWrap>
          )}
        </g>
      );
    }

    case 'accumulator': {
      const fillPct = metrics?.fillPct ?? 0;
      const gasBar = metrics?.pressureBar ?? (p.prechargeBar || 45);
      const fillH = Math.max(0, Math.min(54, (fillPct / 100) * 54));
      return (
        <g>
          <line x1={0} y1={28} x2={0} y2={42} stroke={stroke} strokeWidth={2} />
          <rect x={-18} y={-32} width={36} height={60} rx={16} fill="var(--hs-fill, #ffffff)" stroke={stroke} strokeWidth={2} />
          {fillH > 0 && (
            <rect x={-16} y={26 - fillH} width={32} height={fillH} rx={8} fill="#38bdf8" fillOpacity={0.65} />
          )}
          <polygon points="0,-29 -5,-21 5,-21" fill="none" stroke="#475569" strokeWidth={1.3} />
          <text x={0} y={-11} textAnchor="middle" fontSize={8} fontWeight="700" fill="#475569">N₂</text>
          {showBadges && (
            <BadgeWrap>
              <rect x={-38} y={-52} width={76} height={15} rx={3} fill="#0f172a" />
              <text x={0} y={-41.5} textAnchor="middle" fontSize={8.5} fontWeight="700" fill="#38bdf8" fontFamily="monospace">
                {fillPct.toFixed(0)}% · {pDisp(gasBar).toFixed(units.pressure === 'MPa' ? 1 : 0)}{pUnitShort}
              </text>
            </BadgeWrap>
          )}
        </g>
      );
    }

    case 'filter': {
      const byp = metrics?.bypassActive;
      const dPBar = metrics?.dPBar ?? 0;
      return (
        <g>
          <line x1={-39} y1={0} x2={-20} y2={0} stroke={stroke} strokeWidth={2} />
          <line x1={20} y1={0} x2={39} y2={0} stroke={stroke} strokeWidth={2} />
          <polygon points="0,-20 20,0 0,20 -20,0" fill={byp ? 'rgba(245,158,11,0.22)' : 'var(--hs-fill, #ffffff)'} stroke={byp ? '#d97706' : stroke} strokeWidth={1.8} />
          <line x1={0} y1={-16} x2={0} y2={16} stroke={stroke} strokeWidth={1.6} strokeDasharray="3 2" />
          {showBadges && (
            <BadgeWrap>
              <rect x={-36} y={-38} width={72} height={14} rx={3} fill={byp ? '#b45309' : '#0f172a'} />
              <text x={0} y={-28} textAnchor="middle" fontSize={8.5} fontWeight="700" fill={byp ? '#ffffff' : '#38bdf8'} fontFamily="monospace">
                {byp ? 'BYPASS!' : `ΔP ${pDisp(dPBar).toFixed(2)}${pUnitShort}`}
              </text>
            </BadgeWrap>
          )}
        </g>
      );
    }

    case 'cooler': {
      const kw = metrics?.heatRejectKw ?? 0;
      return (
        <g>
          <line x1={-42} y1={0} x2={-22} y2={0} stroke={stroke} strokeWidth={2} />
          <line x1={22} y1={0} x2={42} y2={0} stroke={stroke} strokeWidth={2} />
          <polygon points="0,-22 22,0 0,22 -22,0" fill="#f0f9ff" stroke={stroke} strokeWidth={1.8} />
          <polygon points="0,-16 -4,-9 4,-9" fill={accent} />
          <polygon points="0,16 -4,9 4,9" fill={accent} />
          <line x1={-16} y1={0} x2={16} y2={0} stroke={stroke} strokeWidth={1.4} strokeDasharray="3 2" />
          {showBadges && (
            <BadgeWrap>
              <rect x={-34} y={-40} width={68} height={14} rx={3} fill="#0f172a" />
              <text x={0} y={-30} textAnchor="middle" fontSize={8.5} fontWeight="700" fill="#38bdf8" fontFamily="monospace">
                -{kw.toFixed(2)} kW
              </text>
            </BadgeWrap>
          )}
        </g>
      );
    }

    case 'pipe': {
      const dPBar = metrics?.dPBar ?? 0;
      const velMs = metrics?.velMs ?? 0;
      const highVel = velMs > 6.0;
      return (
        <g>
          <line x1={-48} y1={0} x2={-34} y2={0} stroke={stroke} strokeWidth={2} />
          <line x1={34} y1={0} x2={48} y2={0} stroke={stroke} strokeWidth={2} />
          <rect x={-34} y={-8} width={68} height={16} rx={2} fill={highVel ? '#fef3c7' : '#f1f5f9'} stroke={highVel ? '#d97706' : stroke} strokeWidth={1.7} />
          <line x1={-30} y1={-3} x2={30} y2={-3} stroke="#cbd5e1" strokeWidth={1.5} />
          <text x={0} y={3.5} textAnchor="middle" fontSize={8} fontWeight="700" fill="#334155" fontFamily="monospace">
            {(p.lengthM || 5).toFixed(1)}m · Ø{p.innerDiaMm || 12}
          </text>
          {showBadges && (
            <BadgeWrap>
              <rect x={-42} y={-28} width={84} height={14} rx={3} fill={highVel ? '#b45309' : '#0f172a'} />
              <text x={0} y={-18} textAnchor="middle" fontSize={8} fontWeight="700" fill={highVel ? '#ffffff' : '#38bdf8'} fontFamily="monospace">
                ΔP {pDisp(Math.abs(dPBar)).toFixed(2)}{pUnitShort} · {velMs.toFixed(1)}m/s
              </text>
            </BadgeWrap>
          )}
        </g>
      );
    }

    case 'sensor': {
      const pBar = metrics?.pressureBar ?? 0;
      const qLpm = metrics?.flowLpm ?? 0;
      return (
        <g>
          <line x1={-42} y1={0} x2={42} y2={0} stroke={stroke} strokeWidth={2} />
          <circle cx={0} cy={0} r={16} fill="var(--hs-fill, #ffffff)" stroke={accent} strokeWidth={2} />
          <text x={0} y={3.5} textAnchor="middle" fontSize={9.5} fontWeight="800" fill={accent}>P/Q</text>
          {showBadges && (
            <BadgeWrap>
              <rect x={-44} y={-35} width={88} height={16} rx={3} fill="#0f172a" />
              <text x={0} y={-24} textAnchor="middle" fontSize={8.5} fontWeight="700" fill="#34d399" fontFamily="monospace">
                {pDisp(pBar).toFixed(1)}{pUnitShort} · {qDisp(qLpm).toFixed(1)}{qUnitShort}
              </text>
            </BadgeWrap>
          )}
        </g>
      );
    }

    case 'gauge': {
      const pBar = metrics?.pressureBar ?? 0;
      const maxS = Math.max(10, p.maxScale || 250);
      const frac = Math.max(0, Math.min(1.08, pBar / maxS));
      const needleDeg = -135 + frac * 270;
      const over = pBar > maxS;
      return (
        <g>
          <line x1={0} y1={18} x2={0} y2={32} stroke={stroke} strokeWidth={2} />
          <circle cx={0} cy={-2} r={20} fill="var(--hs-fill, #ffffff)" stroke={over ? '#dc2626' : stroke} strokeWidth={2} />
          <path d="M -11 9 A 14 14 0 1 1 11 9" fill="none" stroke="#cbd5e1" strokeWidth={2.5} strokeLinecap="round" />
          <g transform={`translate(0, -2) rotate(${needleDeg})`}>
            <line x1={0} y1={3} x2={0} y2={-14} stroke={over ? '#dc2626' : '#0284c7'} strokeWidth={2} strokeLinecap="round" />
            <circle cx={0} cy={0} r={2.8} fill="#1e293b" />
          </g>
          {showBadges && (
            <BadgeWrap>
              <rect x={-30} y={-40} width={60} height={14} rx={3} fill={over ? '#dc2626' : '#0f172a'} />
              <text x={0} y={-30} textAnchor="middle" fontSize={8.5} fontWeight="700" fill="var(--hs-fill, #ffffff)" fontFamily="monospace">
                {pDisp(pBar).toFixed(units.pressure === 'MPa' ? 1 : 0)} {units.pressure}
              </text>
            </BadgeWrap>
          )}
        </g>
      );
    }

    case 'motion_sensor': {
      const posMm = metrics?.posMm ?? 0;
      const velMms = metrics?.velMms ?? 0;
      return (
        <g>
          <rect x={-36} y={-24} width={72} height={48} rx={6} fill="var(--hs-fill, #ffffff)" stroke="#059669" strokeWidth={2} />
          <text x={0} y={-8} textAnchor="middle" fontSize={9} fontWeight="800" fill="#059669">MOTION</text>
          <text x={0} y={6} textAnchor="middle" fontSize={8.5} fontWeight="700" fill="#38bdf8" fontFamily="monospace">
            x {lDisp(posMm).toFixed(1)}{lUnitShort}
          </text>
          <text x={0} y={18} textAnchor="middle" fontSize={8} fontWeight="700" fill="#94a3b8" fontFamily="monospace">
            v {lDisp(velMms).toFixed(0)}{lUnitShort}/s
          </text>
        </g>
      );
    }

    case 'signal_source': {
      const val = metrics?.value ?? 0;
      const lblMap = { valve: 'VALVE', position: 'POS', force: 'FORCE', velocity: 'SPEED', flow: 'FLOW' };
      const unitMap = { valve: '', position: lUnitShort, force: units.force, velocity: 'rpm', flow: qUnitShort };
      const stype = p.signalType || 'valve';
      return (
        <g>
          <rect x={-40} y={-24} width={80} height={48} rx={6} fill="var(--hs-fill, #ffffff)" stroke="#7c3aed" strokeWidth={2} />
          <path d="M -28 8 L -16 8 L -8 -8 L 8 -8 L 16 8 L 28 8" fill="none" stroke="#a78bfa" strokeWidth={1.6} />
          <text x={0} y={-11} textAnchor="middle" fontSize={8.5} fontWeight="800" fill="#7c3aed">
            SIG · {lblMap[stype] || 'SIG'}
          </text>
          <text x={0} y={20} textAnchor="middle" fontSize={8.5} fontWeight="700" fill="#38bdf8" fontFamily="monospace">
            {val.toFixed(2)} {unitMap[stype] || ''}
          </text>
        </g>
      );
    }

    case 'temp_sensor': {
      const tC = metrics?.tempC ?? 45;
      const tDisp = convertToDisplay(tC, 'tempC', units);
      const over = metrics?.overTemp;
      return (
        <g>
          <line x1={-36} y1={0} x2={36} y2={0} stroke={stroke} strokeWidth={2} />
          <circle cx={0} cy={0} r={16} fill={over ? '#7f1d1d' : 'var(--hs-fill, #ffffff)'} stroke={over ? '#dc2626' : '#ea580c'} strokeWidth={2} />
          <line x1={0} y1={-8} x2={0} y2={4} stroke={over ? '#dc2626' : '#ea580c'} strokeWidth={2.2} strokeLinecap="round" />
          <circle cx={0} cy={6} r={3.5} fill={over ? '#dc2626' : '#ea580c'} />
          {showBadges && (
            <BadgeWrap>
              <rect x={-32} y={-36} width={64} height={15} rx={3} fill={over ? '#dc2626' : '#0f172a'} />
              <text x={0} y={-25.5} textAnchor="middle" fontSize={8.5} fontWeight="700" fill={over ? '#ffffff' : '#fb923c'} fontFamily="monospace">
                {tDisp.toFixed(1)} {units.temp}
              </text>
            </BadgeWrap>
          )}
        </g>
      );
    }

    case 'tee_fitting':
      return (
        <g>
          <line x1={-32} y1={0} x2={32} y2={0} stroke={stroke} strokeWidth={2.5} />
          <line x1={0} y1={0} x2={0} y2={27} stroke={stroke} strokeWidth={2.5} />
          <circle cx={0} cy={0} r={5} fill="#0284c7" stroke={stroke} strokeWidth={1.5} />
        </g>
      );

    case 'elbow_fitting':
      return (
        <g>
          <path d="M -30 0 L -8 0 Q 0 0 0 8 L 0 30" fill="none" stroke={stroke} strokeWidth={2.5} strokeLinecap="round" />
          <circle cx={-3} cy={3} r={3.2} fill="#e0f2fe" stroke="#0284c7" strokeWidth={1.3} />
        </g>
      );

    case 'manifold': {
      const pBar = metrics?.pressureBar ?? 0;
      return (
        <g>
          <line x1={-48} y1={0} x2={-36} y2={0} stroke={stroke} strokeWidth={2.2} />
          <line x1={-24} y1={-27} x2={-24} y2={-14} stroke={stroke} strokeWidth={2} />
          <line x1={0} y1={-27} x2={0} y2={-14} stroke={stroke} strokeWidth={2} />
          <line x1={24} y1={-27} x2={24} y2={-14} stroke={stroke} strokeWidth={2} />
          <rect x={-36} y={-14} width={72} height={28} rx={3} fill="#f1f5f9" stroke={stroke} strokeWidth={1.8} />
          <line x1={-32} y1={0} x2={28} y2={0} stroke="#0284c7" strokeWidth={2} />
          <circle cx={-24} cy={0} r={2.8} fill="#0284c7" />
          <circle cx={0} cy={0} r={2.8} fill="#0284c7" />
          <circle cx={24} cy={0} r={2.8} fill="#0284c7" />
          <line x1={-24} y1={0} x2={-24} y2={-14} stroke="#0284c7" strokeWidth={1.6} />
          <line x1={0} y1={0} x2={0} y2={-14} stroke="#0284c7" strokeWidth={1.6} />
          <line x1={24} y1={0} x2={24} y2={-14} stroke="#0284c7" strokeWidth={1.6} />
          {showBadges && (
            <BadgeWrap>
              <rect x={-32} y={18} width={64} height={14} rx={3} fill="#0f172a" />
              <text x={0} y={28} textAnchor="middle" fontSize={8} fontWeight="700" fill="#38bdf8" fontFamily="monospace">
                {pDisp(pBar).toFixed(0)}{pUnitShort}
              </text>
            </BadgeWrap>
          )}
        </g>
      );
    }

    case 'mech_load': {
      const fKn = metrics?.forceKn ?? (p.forceKn || 12);
      const fDisp = convertToDisplay(fKn, 'forceKn', units);
      return (
        <g>
          <line x1={-40} y1={0} x2={-22} y2={0} stroke={stroke} strokeWidth={2.5} />
          <rect x={-22} y={-18} width={48} height={36} rx={3} fill="#fef3c7" stroke="#b45309" strokeWidth={2} />
          <line x1={-22} y1={-6} x2={-10} y2={-18} stroke="#d97706" strokeWidth={1.2} />
          <line x1={-22} y1={10} x2={6} y2={-18} stroke="#d97706" strokeWidth={1.2} />
          <line x1={-10} y1={18} x2={22} y2={-14} stroke="#d97706" strokeWidth={1.2} />
          <text x={2} y={4} textAnchor="middle" fontSize={9.5} fontWeight="800" fill="#78350f">
            {p.massKg || 150}kg
          </text>
          {showBadges && (
            <BadgeWrap>
              <rect x={-34} y={-36} width={72} height={14} rx={3} fill="#78350f" />
              <text x={2} y={-26} textAnchor="middle" fontSize={8.5} fontWeight="700" fill="#fef3c7" fontFamily="monospace">
                {fDisp.toFixed(1)} {units.force}
              </text>
            </BadgeWrap>
          )}
        </g>
      );
    }

    case 'rotary_load': {
      const tNm = metrics?.torqueNm ?? (p.brakeTorqueNm || 45);
      const kw = metrics?.powerKw ?? 0;
      return (
        <g>
          <line x1={-36} y1={-3} x2={-20} y2={-3} stroke={stroke} strokeWidth={2} />
          <line x1={-36} y1={3} x2={-20} y2={3} stroke={stroke} strokeWidth={2} />
          <circle cx={0} cy={0} r={20} fill="#fef3c7" stroke="#b45309" strokeWidth={2.2} />
          <circle cx={0} cy={0} r={12} fill="none" stroke="#d97706" strokeWidth={1.4} strokeDasharray="4 2" />
          <text x={0} y={4} textAnchor="middle" fontSize={9} fontWeight="800" fill="#78350f">J/T</text>
          {showBadges && (
            <BadgeWrap>
              <rect x={-38} y={-38} width={76} height={14} rx={3} fill="#78350f" />
              <text x={0} y={-28} textAnchor="middle" fontSize={8.5} fontWeight="700" fill="#fef3c7" fontFamily="monospace">
                {tNm.toFixed(0)}Nm · {kw.toFixed(1)}kW
              </text>
            </BadgeWrap>
          )}
        </g>
      );
    }

    case 'shutoff_valve': {
      const open = (p.isOpen ?? 1) === 1;
      return (
        <g>
          <line x1={-34} y1={0} x2={-14} y2={0} stroke={stroke} strokeWidth={2} />
          <line x1={14} y1={0} x2={34} y2={0} stroke={stroke} strokeWidth={2} />
          <polygon points="-14,-10 0,0 -14,10" fill={open ? '#e0f2fe' : '#fee2e2'} stroke={stroke} strokeWidth={1.6} />
          <polygon points="14,-10 0,0 14,10" fill={open ? '#e0f2fe' : '#fee2e2'} stroke={stroke} strokeWidth={1.6} />
          <circle cx={0} cy={0} r={4} fill={open ? '#0284c7' : '#dc2626'} />
          <line x1={0} y1={-4} x2={0} y2={-15} stroke={stroke} strokeWidth={1.6} />
          <line x1={-7} y1={-15} x2={7} y2={-15} stroke={stroke} strokeWidth={2} strokeLinecap="round" />
          {onToggleSpool && (
            <g className="cursor-pointer" onMouseDown={(e) => e.stopPropagation()} onClick={(e) => { e.stopPropagation(); onToggleSpool?.(comp.id, open ? 0 : 1, 'isOpen'); }}>
              <rect x={-22} y={14} width={44} height={14} rx={3} fill={open ? '#0284c7' : '#dc2626'} />
              <text x={0} y={24} textAnchor="middle" fontSize={8} fontWeight="700" fill="var(--hs-fill, #ffffff)" fontFamily="monospace">{open ? 'OPEN' : 'SHUT'}</text>
            </g>
          )}
        </g>
      );
    }

    case 'quick_coupling': {
      const coupled = (p.coupled ?? 1) === 1;
      return (
        <g>
          <line x1={-36} y1={0} x2={-14} y2={0} stroke={stroke} strokeWidth={2} />
          <line x1={14} y1={0} x2={36} y2={0} stroke={stroke} strokeWidth={2} />
          <path d="M -14 -8 L -4 0 L -14 8" fill="none" stroke={stroke} strokeWidth={1.8} />
          <path d="M 14 -8 L 4 0 L 14 8" fill="none" stroke={stroke} strokeWidth={1.8} />
          <circle cx={-7} cy={0} r={2.5} fill={coupled ? '#0284c7' : '#dc2626'} />
          <circle cx={7} cy={0} r={2.5} fill={coupled ? '#0284c7' : '#dc2626'} />
          {!coupled && <line x1={0} y1={-11} x2={0} y2={11} stroke="#dc2626" strokeWidth={1.8} strokeDasharray="2 2" />}
          {onToggleSpool && (
            <g className="cursor-pointer" onMouseDown={(e) => e.stopPropagation()} onClick={(e) => { e.stopPropagation(); onToggleSpool?.(comp.id, coupled ? 0 : 1, 'coupled'); }}>
              <rect x={-24} y={13} width={48} height={14} rx={3} fill={coupled ? '#0f172a' : '#dc2626'} />
              <text x={0} y={23} textAnchor="middle" fontSize={7.8} fontWeight="700" fill="var(--hs-fill, #ffffff)" fontFamily="monospace">{coupled ? 'COUPLED' : 'OPEN'}</text>
            </g>
          )}
        </g>
      );
    }

    default:
      return <rect x={-20} y={-20} width={40} height={40} fill="var(--hs-fill, #ffffff)" stroke={stroke} />;
  }
}

function LibraryMiniIcon({ type }) {
  const dummy = { type, params: COMPONENT_CATALOG[type].defaultParams };
  return (
    <svg width={44} height={32} viewBox="-68 -42 136 84" className="shrink-0">
      <HydraulicSymbol comp={dummy} metrics={null} isRunning={false} showBadges={false} />
    </svg>
  );
}

// ============================================================================
// 7. MULTI-CHANNEL REAL-TIME SVG OSCILLOSCOPE
// ============================================================================

const SIGNAL_COLORS = ['#dc2626', '#059669', '#7c3aed', '#0284c7', '#d97706', '#db2777', '#0d9488', '#4f46e5'];

function buildAvailableChannels(components, units = UNIT_PRESETS.metric) {
  const channels = [];
  let colorIdx = 0;
  const nextColor = () => SIGNAL_COLORS[colorIdx++ % SIGNAL_COLORS.length];

  for (const c of components) {
    if (c.type === 'pump' || c.type === 'gear_pump' || c.type === 'vane_pump') {
      channels.push({ id: `${c.id}:p`, compId: c.id, metric: 'pressureBar', unitType: 'pressure', label: `${c.name} Pressure`, unit: units.pressure, color: nextColor() });
      channels.push({ id: `${c.id}:q`, compId: c.id, metric: 'flowLpm', unitType: 'flow', label: `${c.name} Flow`, unit: units.flow, color: nextColor() });
      channels.push({ id: `${c.id}:kw`, compId: c.id, metric: 'powerKw', unitType: 'none', label: `${c.name} Power`, unit: 'kW', color: nextColor() });
    } else if (c.type === 'piston_pump') {
      channels.push({ id: `${c.id}:p`, compId: c.id, metric: 'pressureBar', unitType: 'pressure', label: `${c.name} Pressure`, unit: units.pressure, color: nextColor() });
      channels.push({ id: `${c.id}:stroke`, compId: c.id, metric: 'strokePct', unitType: 'none', label: `${c.name} Stroke`, unit: '%', color: nextColor() });
      channels.push({ id: `${c.id}:q`, compId: c.id, metric: 'flowLpm', unitType: 'flow', label: `${c.name} Flow`, unit: units.flow, color: nextColor() });
    } else if (c.type === 'electric_motor') {
      channels.push({ id: `${c.id}:kw`, compId: c.id, metric: 'elecKw', unitType: 'none', label: `${c.name} Power`, unit: 'kW', color: nextColor() });
      channels.push({ id: `${c.id}:load`, compId: c.id, metric: 'loadPct', unitType: 'none', label: `${c.name} Load`, unit: '%', color: nextColor() });
    } else if (false) {
      channels.push({ id: `${c.id}:p`, compId: c.id, metric: 'pressureBar', unitType: 'pressure', label: `${c.name} Pressure`, unit: units.pressure, color: nextColor() });
      channels.push({ id: `${c.id}:q`, compId: c.id, metric: 'flowLpm', unitType: 'flow', label: `${c.name} Flow`, unit: units.flow, color: nextColor() });
    } else if (c.type === 'var_pump') {
      channels.push({ id: `${c.id}:p`, compId: c.id, metric: 'pressureBar', unitType: 'pressure', label: `${c.name} Pressure`, unit: units.pressure, color: nextColor() });
      channels.push({ id: `${c.id}:stroke`, compId: c.id, metric: 'strokePct', unitType: 'none', label: `${c.name} Stroke`, unit: '%', color: nextColor() });
      channels.push({ id: `${c.id}:q`, compId: c.id, metric: 'flowLpm', unitType: 'flow', label: `${c.name} Flow`, unit: units.flow, color: nextColor() });
      channels.push({ id: `${c.id}:kw`, compId: c.id, metric: 'powerKw', unitType: 'none', label: `${c.name} Power`, unit: 'kW', color: nextColor() });
    } else if (c.type === 'prop_dcv43') {
      channels.push({ id: `${c.id}:spool`, compId: c.id, metric: 'spoolPct', unitType: 'none', label: `${c.name} Spool`, unit: '%', color: nextColor() });
    } else if (c.type === 'pos_controller') {
      channels.push({ id: `${c.id}:tgt`, compId: c.id, metric: 'targetMm', unitType: 'lengthMm', label: `${c.name} Target`, unit: units.length, color: nextColor() });
      channels.push({ id: `${c.id}:err`, compId: c.id, metric: 'errMm', unitType: 'lengthMm', label: `${c.name} Error`, unit: units.length, color: nextColor() });
    } else if (c.type === 'sensor') {
      channels.push({ id: `${c.id}:p`, compId: c.id, metric: 'pressureBar', unitType: 'pressure', label: `${c.name} Pressure`, unit: units.pressure, color: nextColor() });
      channels.push({ id: `${c.id}:q`, compId: c.id, metric: 'flowLpm', unitType: 'flow', label: `${c.name} Flow`, unit: units.flow, color: nextColor() });
    } else if (c.type === 'cylinder' || c.type === 'sa_cylinder' || c.type === 'dr_cylinder') {
      channels.push({ id: `${c.id}:pos`, compId: c.id, metric: 'posMm', unitType: 'lengthMm', label: `${c.name} Disp.`, unit: units.length, color: nextColor() });
      channels.push({ id: `${c.id}:vel`, compId: c.id, metric: 'velMms', unitType: 'lengthMm', label: `${c.name} Vel.`, unit: `${units.length}/s`, color: nextColor() });
      channels.push({ id: `${c.id}:f`, compId: c.id, metric: 'forceKn', unitType: 'forceKn', label: `${c.name} Force`, unit: units.force, color: nextColor() });
    } else if (c.type === 'motor') {
      channels.push({ id: `${c.id}:rpm`, compId: c.id, metric: 'rpm', unitType: 'none', label: `${c.name} Speed`, unit: 'RPM', color: nextColor() });
    } else if (c.type === 'accumulator') {
      channels.push({ id: `${c.id}:fill`, compId: c.id, metric: 'fillPct', unitType: 'none', label: `${c.name} Fill`, unit: '%', color: nextColor() });
      channels.push({ id: `${c.id}:p`, compId: c.id, metric: 'pressureBar', unitType: 'pressure', label: `${c.name} Gas P`, unit: units.pressure, color: nextColor() });
    } else if (c.type === 'prv_reducing' || c.type === 'seq_valve') {
      channels.push({ id: `${c.id}:p`, compId: c.id, metric: 'pressureBar', unitType: 'pressure', label: `${c.name} Pressure`, unit: units.pressure, color: nextColor() });
    } else if (c.type === 'cb_valve') {
      channels.push({ id: `${c.id}:open`, compId: c.id, metric: 'openPct', unitType: 'none', label: `${c.name} Open`, unit: '%', color: nextColor() });
    } else if (c.type === 'filter') {
      channels.push({ id: `${c.id}:dp`, compId: c.id, metric: 'dPBar', unitType: 'pressure', label: `${c.name} ΔP`, unit: units.pressure, color: nextColor() });
    } else if (c.type === 'pc_flow_ctrl') {
      channels.push({ id: `${c.id}:q`, compId: c.id, metric: 'flowLpm', unitType: 'flow', label: `${c.name} Flow`, unit: units.flow, color: nextColor() });
    } else if (c.type === 'unloading_valve') {
      channels.push({ id: `${c.id}:open`, compId: c.id, metric: 'openPct', unitType: 'none', label: `${c.name} Unload`, unit: '%', color: nextColor() });
    } else if (c.type === 'cooler') {
      channels.push({ id: `${c.id}:kw`, compId: c.id, metric: 'heatRejectKw', unitType: 'none', label: `${c.name} Heat Rej.`, unit: 'kW', color: nextColor() });
    } else if (c.type === 'pipe') {
      channels.push({ id: `${c.id}:dp`, compId: c.id, metric: 'dPBar', unitType: 'pressure', label: `${c.name} ΔP`, unit: units.pressure, color: nextColor() });
      channels.push({ id: `${c.id}:vel`, compId: c.id, metric: 'velMs', unitType: 'none', label: `${c.name} Vel.`, unit: 'm/s', color: nextColor() });
    } else if (c.type === 'flow_divider') {
      channels.push({ id: `${c.id}:qa`, compId: c.id, metric: 'flowALpm', unitType: 'flow', label: `${c.name} Flow A`, unit: units.flow, color: nextColor() });
      channels.push({ id: `${c.id}:qb`, compId: c.id, metric: 'flowBLpm', unitType: 'flow', label: `${c.name} Flow B`, unit: units.flow, color: nextColor() });
    } else if (c.type === 'gauge') {
      channels.push({ id: `${c.id}:p`, compId: c.id, metric: 'pressureBar', unitType: 'pressure', label: `${c.name} Gauge`, unit: units.pressure, color: nextColor() });
    } else if (c.type === 'motion_sensor') {
      channels.push({ id: `${c.id}:pos`, compId: c.id, metric: 'posMm', unitType: 'lengthMm', label: `${c.name} Pos`, unit: units.length, color: nextColor() });
      channels.push({ id: `${c.id}:vel`, compId: c.id, metric: 'velMms', unitType: 'lengthMm', label: `${c.name} Vel`, unit: `${units.length}/s`, color: nextColor() });
    } else if (c.type === 'signal_source') {
      channels.push({ id: `${c.id}:val`, compId: c.id, metric: 'value', unitType: 'none', label: `${c.name} Signal`, unit: '', color: nextColor() });
    } else if (c.type === 'temp_sensor') {
      channels.push({ id: `${c.id}:temp`, compId: c.id, metric: 'tempC', unitType: 'tempC', label: `${c.name} Temp`, unit: units.temp, color: nextColor() });
    } else if (c.type === 'mech_load') {
      channels.push({ id: `${c.id}:kw`, compId: c.id, metric: 'powerKw', unitType: 'none', label: `${c.name} Power`, unit: 'kW', color: nextColor() });
    } else if (c.type === 'rotary_load') {
      channels.push({ id: `${c.id}:kw`, compId: c.id, metric: 'powerKw', unitType: 'none', label: `${c.name} Brake`, unit: 'kW', color: nextColor() });
    } else if (c.type === 'orifice') {
      channels.push({ id: `${c.id}:dp`, compId: c.id, metric: 'dPBar', unitType: 'pressure', label: `${c.name} ΔP`, unit: units.pressure, color: nextColor() });
    }
  }
  if (components.length > 0) {
    channels.push({ id: 'sys:eff', compId: '__sys__', metric: 'sysEffPct', unitType: 'none', label: 'System Efficiency', unit: '%', color: nextColor() });
    channels.push({ id: 'sys:temp', compId: '__sys__', metric: 'oilTempC', unitType: 'tempC', label: 'Bulk Oil Temp', unit: units.temp, color: nextColor() });
  }
  return channels;
}

function OscilloscopeChart({
  svgId = 'hydrasim-oscilloscope-svg',
  history,
  channels,
  enabledIds,
  lineStyles = {},
  units,
  plotGridVisible = true,
  plotGridCols = 8,
  plotGridRows = 4,
  plotGridColor = '#e2e8f0',
  timeMin = null,
  timeMax = null,
  yMinLimit = null,
  yMaxLimit = null,
  datatipWidthPx = 208,
  datatipOpacity = 0.94,
  datatipFontSizePx = 11,
  datatips = [],
  onChangeDatatips,
  hoverTimeFrac = null,
  onChangeHoverTimeFrac,
}) {
  const wrapRef = useRef(null);
  const svgRef = useRef(null);
  const [boxSize, setBoxSize] = useState({ w: 820, h: 170 });
  const [dragTip, setDragTip] = useState(null);

  useEffect(() => {
    const el = wrapRef.current;
    if (!el) return;
    const measure = () => {
      const r = el.getBoundingClientRect();
      if (r.width > 40 && r.height > 40) {
        setBoxSize({ w: Math.round(r.width), h: Math.round(r.height) });
      }
    };
    measure();
    let ro = null;
    if (typeof ResizeObserver !== 'undefined') {
      ro = new ResizeObserver(measure);
      ro.observe(el);
    }
    window.addEventListener('resize', measure);
    return () => {
      if (ro) ro.disconnect();
      window.removeEventListener('resize', measure);
    };
  }, []);

  const width = Math.max(240, boxSize.w);
  const height = Math.max(110, boxSize.h);
  const pad = { top: 12, right: 18, bottom: 34, left: 54 };
  const plotW = Math.max(40, width - pad.left - pad.right);
  const plotH = Math.max(36, height - pad.top - pad.bottom);

  const activeChannels = useMemo(
    () => channels.filter((ch) => enabledIds[ch.id]).map((ch) => ({
      ...ch,
      color: lineStyles[ch.id]?.color || ch.color,
      dash: lineStyles[ch.id]?.dash || 'solid',
    })),
    [channels, enabledIds, lineStyles]
  );

  const getVal = useCallback((pt, ch) => convertToDisplay(pt.values[ch.id] ?? 0, ch.unitType, units), [units]);

  const { tMin, tMax, yMin, yMax } = useMemo(() => {
    const hasCustomT0 = timeMin !== null && Number.isFinite(timeMin);
    const hasCustomT1 = timeMax !== null && Number.isFinite(timeMax);
    const hasCustomY0 = yMinLimit !== null && Number.isFinite(yMinLimit);
    const hasCustomY1 = yMaxLimit !== null && Number.isFinite(yMaxLimit);
    if (history.length < 2 || activeChannels.length === 0) {
      const t0Def = hasCustomT0 ? timeMin : 0;
      const t1Def = Math.max(t0Def + 1e-6, hasCustomT1 ? timeMax : 10);
      const y0Def = hasCustomY0 ? yMinLimit : 0;
      const y1Def = Math.max(y0Def + 1e-6, hasCustomY1 ? yMaxLimit : 150);
      return { tMin: t0Def, tMax: t1Def, yMin: y0Def, yMax: y1Def };
    }
    const t0 = hasCustomT0 ? timeMin : history[0].t;
    const t1 = Math.max(t0 + 1e-6, hasCustomT1 ? timeMax : history[history.length - 1].t);
    let minV = Infinity;
    let maxV = -Infinity;
    let anyInWindow = false;
    for (const pt of history) {
      if (pt.t < t0 || pt.t > t1) continue;
      anyInWindow = true;
      for (const ch of activeChannels) {
        const v = getVal(pt, ch);
        if (Number.isFinite(v)) {
          if (v < minV) minV = v;
          if (v > maxV) maxV = v;
        }
      }
    }
    if (!anyInWindow || !Number.isFinite(minV) || !Number.isFinite(maxV)) {
      minV = Infinity;
      maxV = -Infinity;
      for (const pt of history) {
        for (const ch of activeChannels) {
          const v = getVal(pt, ch);
          if (Number.isFinite(v)) {
            if (v < minV) minV = v;
            if (v > maxV) maxV = v;
          }
        }
      }
    }
    if (!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 autoY0 = minV - padVal;
    const autoY1 = maxV + padVal;
    const finalY0 = hasCustomY0 ? yMinLimit : autoY0;
    const finalY1 = Math.max(finalY0 + 1e-6, hasCustomY1 ? yMaxLimit : autoY1);
    return { tMin: t0, tMax: t1, yMin: finalY0, yMax: finalY1 };
  }, [history, activeChannels, getVal, timeMin, timeMax, yMinLimit, yMaxLimit]);

  const toX = useCallback((t) => pad.left + ((t - tMin) / Math.max(1e-6, tMax - tMin)) * plotW, [tMin, tMax, plotW, pad.left]);
  const toY = useCallback((v) => pad.top + plotH - ((v - yMin) / Math.max(1e-6, yMax - yMin)) * plotH, [yMin, yMax, plotH, pad.top]);

  const nearestSampleAtFrac = useCallback((frac) => {
    if (!history || history.length === 0) return null;
    const clamped = Math.max(0, Math.min(1, frac ?? 0));
    const targetT = tMin + clamped * (tMax - tMin);
    let best = history[0];
    let bestD = Math.abs(history[0].t - targetT);
    for (let i = 1; i < history.length; i++) {
      const d = Math.abs(history[i].t - targetT);
      if (d < bestD) { bestD = d; best = history[i]; }
    }
    return best;
  }, [history, tMin, tMax]);

  const handleMouseMove = (e) => {
    if (!wrapRef.current) return;
    const rect = wrapRef.current.getBoundingClientRect();
    const px = e.clientX - rect.left;
    const py = e.clientY - rect.top;

    if (dragTip && onChangeDatatips) {
      if (dragTip.mode === 'move') {
        const nx = Math.max(4, Math.min(width - 205, dragTip.origBoxX + (px - dragTip.startX)));
        const ny = Math.max(4, Math.min(height - 54, dragTip.origBoxY + (py - dragTip.startY)));
        onChangeDatatips((prev) => prev.map((t) => (t.id === dragTip.id ? { ...t, boxX: nx, boxY: ny } : t)));
      } else if (dragTip.mode === 'scrub') {
        const frac = Math.max(0, Math.min(1, (px - pad.left) / Math.max(1, plotW)));
        onChangeDatatips((prev) => prev.map((t) => (t.id === dragTip.id ? { ...t, fracT: frac } : t)));
      } else if (dragTip.mode === 'resize') {
        const nw = Math.max(150, Math.min(420, dragTip.origW + (px - dragTip.startX)));
        const nh = Math.max(48, Math.min(320, dragTip.origH + (py - dragTip.startY)));
        onChangeDatatips((prev) => prev.map((t) => (t.id === dragTip.id ? { ...t, boxW: Math.round(nw), boxH: Math.round(nh) } : t)));
      }
      return;
    }

    if (history.length >= 2 && onChangeHoverTimeFrac) {
      const frac = Math.max(0, Math.min(1, (px - pad.left) / Math.max(1, plotW)));
      onChangeHoverTimeFrac(frac);
    }
  };

  const handleMouseUp = () => {
    if (dragTip) setDragTip(null);
  };

  const handleMouseLeave = () => {
    setDragTip(null);
    if (onChangeHoverTimeFrac) onChangeHoverTimeFrac(null);
  };

  const yDivs = Math.max(2, parseInt(plotGridRows, 10) || 4);
  const xDivs = Math.max(2, parseInt(plotGridCols, 10) || 8);
  const yTicks = Array.from({ length: yDivs + 1 }, (_, i) => yMin + (i / yDivs) * (yMax - yMin));
  const xTicks = Array.from({ length: xDivs + 1 }, (_, i) => tMin + (i / xDivs) * (tMax - tMin));

  const dashArrayFor = (d) => {
    if (d === 'dashed') return '7 4';
    if (d === 'dotted') return '2 4';
    if (d === 'dashdot') return '8 3 2 3';
    return undefined;
  };

  const hoverSample = hoverTimeFrac !== null && history.length >= 2 ? nearestSampleAtFrac(hoverTimeFrac) : null;

  return (
    <div
      ref={wrapRef}
      className="relative w-full h-full select-none overflow-hidden"
      onMouseMove={handleMouseMove}
      onMouseUp={handleMouseUp}
      onMouseLeave={handleMouseLeave}
    >
      <svg
        id={svgId}
        ref={svgRef}
        width={width}
        height={height}
        viewBox={`0 0 ${width} ${height}`}
        className="w-full h-full bg-white block"
      >
        {yTicks.map((yv, i) => (
          <g key={`y${i}`}>
            {plotGridVisible && (
              <line x1={pad.left} y1={toY(yv)} x2={width - pad.right} y2={toY(yv)} stroke={plotGridColor} strokeWidth={1} />
            )}
            <text x={pad.left - 6} y={toY(yv) + 3} textAnchor="end" fontSize={9.5} fill="#64748b" fontFamily="monospace">
              {yv.toFixed(Math.abs(yMax - yMin) < 2 ? 2 : Math.abs(yMax - yMin) < 20 ? 1 : 0)}
            </text>
          </g>
        ))}
        {xTicks.map((xv, i) => (
          <g key={`x${i}`}>
            {plotGridVisible && (
              <line x1={toX(xv)} y1={pad.top} x2={toX(xv)} y2={height - pad.bottom} stroke={plotGridColor} strokeWidth={1} />
            )}
            <text x={toX(xv)} y={height - 15} textAnchor="middle" fontSize={9.5} fill="#64748b" fontFamily="monospace">
              {xv.toFixed(1)}s
            </text>
          </g>
        ))}

        <text x={pad.left + plotW * 0.5} y={height - 3} textAnchor="middle" fontSize={10} fontWeight="700" fill="#475569" fontFamily="sans-serif">
          time (sec)
        </text>

        <defs>
          <clipPath id={`${svgId}-clip`}>
            <rect x={pad.left} y={pad.top} width={plotW} height={plotH} />
          </clipPath>
        </defs>

        <rect x={pad.left} y={pad.top} width={plotW} height={plotH} fill="none" stroke="#94a3b8" strokeWidth={1} />

        <g clipPath={`url(#${svgId}-clip)`}>
          {history.length >= 2 &&
            activeChannels.map((ch) => {
              const pts = history.map((pt) => `${toX(pt.t).toFixed(1)},${toY(getVal(pt, ch)).toFixed(1)}`).join(' ');
              return (
                <polyline
                  key={ch.id}
                  fill="none"
                  stroke={ch.color}
                  strokeWidth={2}
                  strokeDasharray={dashArrayFor(ch.dash)}
                  strokeLinejoin="round"
                  points={pts}
                />
              );
            })}
        </g>

        {hoverSample && (
          <line
            x1={toX(hoverSample.t)}
            y1={pad.top}
            x2={toX(hoverSample.t)}
            y2={pad.top + plotH}
            stroke="#64748b"
            strokeWidth={1}
            strokeDasharray="3 2"
          />
        )}

        {history.length >= 2 && datatips.map((tip) => {
          const sample = nearestSampleAtFrac(tip.fracT);
          if (!sample) return null;
          const xLine = toX(sample.t);
          return (
            <g key={`marker_${tip.id}`}>
              <line
                x1={xLine}
                y1={pad.top}
                x2={xLine}
                y2={pad.top + plotH}
                stroke="#0284c7"
                strokeWidth={1.4}
                strokeDasharray="4 2"
              />
              {activeChannels.map((ch) => (
                <circle
                  key={`${tip.id}_${ch.id}`}
                  cx={xLine}
                  cy={toY(getVal(sample, ch))}
                  r={3.5}
                  fill={ch.color}
                  stroke="#ffffff"
                  strokeWidth={1.2}
                />
              ))}
            </g>
          );
        })}
      </svg>

      {history.length < 2 && (
        <div className="absolute inset-0 flex items-center justify-center pointer-events-none">
          <span className="text-xs text-slate-500 bg-white/90 px-3 py-1 rounded border border-slate-200 shadow-sm">
            Press <strong>Run</strong> (or Space) to stream real-time SI-unit simulation waveforms
          </span>
        </div>
      )}

      {history.length >= 2 && activeChannels.length > 0 && datatips.map((tip) => {
        const sample = nearestSampleAtFrac(tip.fracT);
        if (!sample) return null;
        const markerPx = toX(sample.t);
        const tipW = Math.max(150, Math.min(420, tip.boxW ?? datatipWidthPx ?? 208));
        const tipOp = Math.max(0.2, Math.min(1, datatipOpacity ?? 0.94));
        const tipFs = Math.max(8, Math.min(18, datatipFontSizePx ?? 11));
        const bx = Math.max(4, Math.min(width - tipW - 4, tip.boxX ?? (markerPx + 10)));
        const by = Math.max(4, Math.min(height - 54, tip.boxY ?? 10));
        return (
          <div
            key={tip.id}
            style={{
              left: `${bx}px`,
              top: `${by}px`,
              width: `${tipW}px`,
              '--hs-dt-alpha': String(tipOp),
              fontSize: `${tipFs}px`,
              minHeight: tip.boxH ? `${tip.boxH}px` : undefined,
            }}
            onMouseDown={(e) => {
              if (e.target.closest('button, input, .hs-dt-resize')) return;
              e.stopPropagation();
              const r = wrapRef.current?.getBoundingClientRect();
              setDragTip({ id: tip.id, mode: 'move', startX: e.clientX - (r?.left || 0), startY: e.clientY - (r?.top || 0), origBoxX: bx, origBoxY: by });
            }}
            className="hs-datatip-box absolute z-20 px-2.5 py-1.5 rounded font-mono space-y-0.5 cursor-move"
          >
            <div className="hs-dt-hdr flex items-center justify-between pb-0.5 mb-0.5 gap-1">
              <span>t = {sample.t.toFixed(3)} s</span>
              <div className="flex items-center gap-1">
                <button
                  type="button"
                  onMouseDown={(e) => {
                    e.stopPropagation();
                    const r = wrapRef.current?.getBoundingClientRect();
                    setDragTip({ id: tip.id, mode: 'scrub', startX: e.clientX - (r?.left || 0), startY: e.clientY - (r?.top || 0), origFracT: tip.fracT });
                  }}
                  title="Drag horizontally to scrub time point"
                  className="px-1 py-0.2 bg-sky-600 hover:bg-sky-500 text-white rounded text-[9px] cursor-ew-resize"
                >
                  ↔ t
                </button>
                {onChangeDatatips && (
                  <button
                    type="button"
                    onClick={(e) => { e.stopPropagation(); onChangeDatatips((prev) => prev.filter((d) => d.id !== tip.id)); }}
                    title="Delete datatip"
                    className="hover:text-red-500 text-[10px] px-0.5 cursor-pointer opacity-75 hover:opacity-100"
                  >
                    ✕
                  </button>
                )}
              </div>
            </div>
            <input
              type="range"
              min={0}
              max={1}
              step={0.005}
              value={tip.fracT ?? 0.5}
              onChange={(e) => {
                const v = parseFloat(e.target.value);
                if (onChangeDatatips) onChangeDatatips((prev) => prev.map((d) => (d.id === tip.id ? { ...d, fracT: v } : d)));
              }}
              title="Scrub time along simulation run"
              className="w-full h-1 accent-sky-400 cursor-pointer my-0.5"
            />
            <div className="flex flex-wrap items-center gap-x-3 gap-y-1 pt-0.5">
              {activeChannels.map((ch) => (
                <span key={ch.id} className="inline-flex items-center gap-1 shrink-0">
                  <span className="w-2.5 h-2.5 rounded-full shrink-0" style={{ backgroundColor: ch.color }} />
                  <span className="hs-dt-val font-semibold">
                    {getVal(sample, ch).toFixed(2)} {ch.unit}
                  </span>
                </span>
              ))}
            </div>
            <div
              onMouseDown={(e) => {
                e.stopPropagation();
                const r = wrapRef.current?.getBoundingClientRect();
                const card = e.currentTarget.parentElement?.getBoundingClientRect();
                setDragTip({
                  id: tip.id,
                  mode: 'resize',
                  startX: e.clientX - (r?.left || 0),
                  startY: e.clientY - (r?.top || 0),
                  origW: card ? card.width : tipW,
                  origH: card ? card.height : 70,
                });
              }}
              title="Drag corner to resize datatip box"
              className="hs-dt-resize absolute bottom-0.5 right-0.5 w-2.5 h-2.5 cursor-nwse-resize opacity-60 hover:opacity-100"
              style={{ borderRight: '2px solid currentColor', borderBottom: '2px solid currentColor' }}
            />
          </div>
        );
      })}

      {hoverSample && activeChannels.length > 0 && !dragTip && (
        <div className="hs-datatip-box pointer-events-none absolute top-2 right-3 z-10 text-[10.5px] px-2.5 py-1.5 rounded font-mono space-y-0.5">
          <div className="hs-dt-hdr hs-dt-val pb-0.5 mb-0.5">Hover · t = {hoverSample.t.toFixed(3)} s</div>
          <div className="flex flex-wrap items-center gap-x-3 gap-y-1">
            {activeChannels.map((ch) => (
              <span key={ch.id} className="inline-flex items-center gap-1 shrink-0">
                <span className="w-2.5 h-2.5 rounded-full" style={{ backgroundColor: ch.color }} />
                <span className="hs-dt-val font-semibold">
                  {getVal(hoverSample, ch).toFixed(2)} {ch.unit}
                </span>
              </span>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

// ============================================================================
// 8. SIMULATION SETTINGS MODAL
// ============================================================================

function SimulationSettingsModal({ settings, units, onUpdateSettings, onUpdateUnits, onResetDefaults, onClose }) {
  const bulkDisp = convertToDisplay(settings.bulkModulusBar, 'pressure', units);
  const tempDisp = convertToDisplay(settings.oilTempC, 'tempC', units);

  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-2xl overflow-hidden flex flex-col max-h-[88vh]"
        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">
            <Settings size={16} className="text-sky-600" />
            <h2 className="text-sm font-bold text-slate-900">Simulation & Workspace Settings</h2>
          </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>

        <div className="p-4 overflow-y-auto space-y-5 text-xs">
          {/* 1. Time & RK4 Solver */}
          <section className="space-y-2.5">
            <div className="text-[11px] font-bold uppercase tracking-wider text-sky-700 border-b border-slate-200 pb-1">
              1. Time & Numerical RK4 Solver
            </div>
            {(() => {
              const tStart = Number(settings.startTime) || 0;
              const tEnd = Number(settings.endTime) || 0;
              const totalT = tEnd > tStart ? (tEnd - tStart) : (tEnd === 0 ? 10 : Math.max(0.1, tEnd));
              const nSteps = Math.max(1, parseInt(settings.numSteps, 10) || 200);
              const calcDt = totalT / nSteps;
              return (
                <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
                  <label className="space-y-1">
                    <span className="text-slate-600 font-medium block">Start Time (s)</span>
                    <input type="number" min={0} max={1000} step={0.5} value={settings.startTime} onChange={(e) => onUpdateSettings({ startTime: Math.max(0, parseFloat(e.target.value) || 0) })} className="w-full px-2 py-1.5 font-mono bg-slate-50 border border-slate-200 rounded" />
                  </label>
                  <label className="space-y-1">
                    <span className="text-slate-600 font-medium block">End Time (s, 0 = ∞)</span>
                    <input type="number" min={0} max={3600} step={1} value={settings.endTime} onChange={(e) => onUpdateSettings({ endTime: Math.max(0, parseFloat(e.target.value) || 0) })} className="w-full px-2 py-1.5 font-mono bg-slate-50 border border-slate-200 rounded" />
                  </label>
                  <label className="space-y-1">
                    <span className="text-slate-600 font-medium block">Number of Steps</span>
                    <input type="number" min={5} max={10000} step={10} value={settings.numSteps ?? 200} onChange={(e) => onUpdateSettings({ numSteps: Math.max(5, Math.min(10000, parseInt(e.target.value, 10) || 200)) })} className="w-full px-2 py-1.5 font-mono bg-slate-50 border border-slate-200 rounded" />
                  </label>
                  <div className="space-y-1">
                    <span className="text-slate-600 font-medium block">Time Step Δt (Calc.)</span>
                    <div className="w-full px-2 py-1.5 font-mono bg-sky-50 border border-sky-200 text-sky-800 font-semibold rounded" title="Computed as (Total Time) / (Number of Steps)">
                      {calcDt.toFixed(4)} s
                    </div>
                  </div>
                </div>
              );
            })()}
            <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
              <label className="space-y-1">
                <span className="text-slate-600 font-medium block">RK4 Substeps / Frame</span>
                <input type="number" min={10} max={80} step={5} value={settings.rk4Substeps} onChange={(e) => onUpdateSettings({ rk4Substeps: Math.max(10, Math.min(80, parseInt(e.target.value, 10) || 30)) })} className="w-full px-2 py-1.5 font-mono bg-slate-50 border border-slate-200 rounded" />
              </label>
              <label className="space-y-1">
                <span className="text-slate-600 font-medium block">Node Capacitance (L)</span>
                <input type="number" min={0.5} max={10} step={0.1} value={settings.nodeVolL} onChange={(e) => onUpdateSettings({ nodeVolL: Math.max(0.5, Math.min(10, parseFloat(e.target.value) || 1.5)) })} className="w-full px-2 py-1.5 font-mono bg-slate-50 border border-slate-200 rounded" />
              </label>
              <label className="space-y-1">
                <span className="text-slate-600 font-medium block">Initial Pressure ({units.pressure})</span>
                <input
                  type="number"
                  min={0}
                  step={units.pressure === 'MPa' ? 0.5 : 5}
                  value={Number(convertToDisplay(settings.initPressureBar || 0, 'pressure', units).toFixed(1))}
                  onChange={(e) => {
                    const v = parseFloat(e.target.value);
                    if (!Number.isNaN(v)) onUpdateSettings({ initPressureBar: Math.max(0, Math.min(250, convertFromDisplay(v, 'pressure', units))) });
                  }}
                  className="w-full px-2 py-1.5 font-mono bg-slate-50 border border-slate-200 rounded"
                />
              </label>
              <label className="space-y-1">
                <span className="text-slate-600 font-medium block">Solver Method</span>
                <select value={settings.solverType || 'rk45'} onChange={(e) => onUpdateSettings({ solverType: e.target.value })} className="w-full px-2 py-1.5 font-mono bg-slate-50 border border-slate-200 rounded">
                  <option value="rk45">Adaptive RK45 (Explicit)</option>
                  <option value="ode23t">ode23t (Implicit Trapezoidal)</option>
                  <option value="ode15s">ode15s (Stiff Multi-Step BDF)</option>
                </select>
              </label>
              <label className="space-y-1">
                <span className="text-slate-600 font-medium block">Solver Tolerance</span>
                <select value={settings.solverTolerance || 1e-4} onChange={(e) => onUpdateSettings({ solverTolerance: Number(e.target.value) })} className="w-full px-2 py-1.5 font-mono bg-slate-50 border border-slate-200 rounded">
                  <option value={1e-3}>1e-3 (Fast)</option>
                  <option value={1e-4}>1e-4 (Standard)</option>
                  <option value={1e-5}>1e-5 (High Precision)</option>
                  <option value={1e-6}>1e-6 (Strict)</option>
                </select>
              </label>
            </div>
          </section>

          {/* 2. Fluid Properties */}
          <section className="space-y-2.5">
            <div className="text-[11px] font-bold uppercase tracking-wider text-sky-700 border-b border-slate-200 pb-1">
              2. Hydraulic Fluid Properties (ISO VG 46 Default)
            </div>
            <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
              <label className="space-y-1">
                <span className="text-slate-600 font-medium block">Bulk Modulus ({units.pressure})</span>
                <input
                  type="number"
                  value={Number(bulkDisp.toFixed(0))}
                  onChange={(e) => {
                    const v = parseFloat(e.target.value);
                    if (!Number.isNaN(v)) onUpdateSettings({ bulkModulusBar: Math.max(2000, Math.min(20000, convertFromDisplay(v, 'pressure', units))) });
                  }}
                  className="w-full px-2 py-1.5 font-mono bg-slate-50 border border-slate-200 rounded"
                />
              </label>
              <label className="space-y-1">
                <span className="text-slate-600 font-medium block">Density (kg/m³)</span>
                <input type="number" min={700} max={1100} value={settings.oilDensity} onChange={(e) => onUpdateSettings({ oilDensity: Math.max(700, Math.min(1100, parseFloat(e.target.value) || 870)) })} className="w-full px-2 py-1.5 font-mono bg-slate-50 border border-slate-200 rounded" />
              </label>
              <label className="space-y-1">
                <span className="text-slate-600 font-medium block">Viscosity (cSt)</span>
                <input type="number" min={10} max={220} value={settings.viscosityCst} onChange={(e) => onUpdateSettings({ viscosityCst: Math.max(10, Math.min(220, parseFloat(e.target.value) || 46)) })} className="w-full px-2 py-1.5 font-mono bg-slate-50 border border-slate-200 rounded" />
              </label>
              <label className="space-y-1">
                <span className="text-slate-600 font-medium block">Oil Temp ({units.temp})</span>
                <input
                  type="number"
                  value={Number(tempDisp.toFixed(1))}
                  onChange={(e) => {
                    const v = parseFloat(e.target.value);
                    if (!Number.isNaN(v)) onUpdateSettings({ oilTempC: Math.max(5, Math.min(110, convertFromDisplay(v, 'tempC', units))) });
                  }}
                  className="w-full px-2 py-1.5 font-mono bg-slate-50 border border-slate-200 rounded"
                />
              </label>
            </div>
          </section>

          {/* 3. Custom Unit Overrides */}
          <section className="space-y-2.5">
            <div className="text-[11px] font-bold uppercase tracking-wider text-sky-700 border-b border-slate-200 pb-1">
              3. Engineering Display Units (SI Internal)
            </div>
            <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
              <label className="space-y-1">
                <span className="text-slate-600 font-medium block">Pressure</span>
                <select value={units.pressure} onChange={(e) => onUpdateUnits({ pressure: e.target.value })} className="w-full px-2 py-1.5 bg-slate-50 border border-slate-200 rounded">
                  <option value="bar">bar</option>
                  <option value="MPa">MPa</option>
                  <option value="psi">psi</option>
                </select>
              </label>
              <label className="space-y-1">
                <span className="text-slate-600 font-medium block">Flow Rate</span>
                <select value={units.flow} onChange={(e) => onUpdateUnits({ flow: e.target.value })} className="w-full px-2 py-1.5 bg-slate-50 border border-slate-200 rounded">
                  <option value="L/min">L/min</option>
                  <option value="GPM">GPM</option>
                </select>
              </label>
              <label className="space-y-1">
                <span className="text-slate-600 font-medium block">Force</span>
                <select value={units.force} onChange={(e) => onUpdateUnits({ force: e.target.value })} className="w-full px-2 py-1.5 bg-slate-50 border border-slate-200 rounded">
                  <option value="kN">kN</option>
                  <option value="N">N</option>
                  <option value="lbf">lbf</option>
                </select>
              </label>
              <label className="space-y-1">
                <span className="text-slate-600 font-medium block">Length</span>
                <select value={units.length} onChange={(e) => onUpdateUnits({ length: e.target.value })} className="w-full px-2 py-1.5 bg-slate-50 border border-slate-200 rounded">
                  <option value="mm">mm</option>
                  <option value="in">in</option>
                </select>
              </label>
            </div>
          </section>

          {/* 4. Workspace Display */}
          <section className="space-y-2">
            <div className="text-[11px] font-bold uppercase tracking-wider text-sky-700 border-b border-slate-200 pb-1">
              4. Workspace & Schematic Display
            </div>
            <div className="grid grid-cols-2 gap-2.5 pt-1">
              {[
                { key: 'showGrid', label: 'Show Engineering Grid' },
                { key: 'snapToGrid', label: 'Snap Components to Grid (20 px)' },
                { key: 'showPortLabels', label: 'Show Port Identifiers (P, T, A, B, X)' },
                { key: 'showLiveBadges', label: 'Show Live Pressure / Flow Badges' },
                { key: 'showComponentNames', label: 'Show Component Names / Tags' },
              ].map((opt) => (
                <label key={opt.key} className="flex items-center gap-2 cursor-pointer p-1.5 rounded hover:bg-slate-50">
                  <input type="checkbox" checked={settings[opt.key]} onChange={(e) => onUpdateSettings({ [opt.key]: e.target.checked })} className="rounded border-slate-300 text-sky-600" />
                  <span className="text-slate-700 font-medium">{opt.label}</span>
                </label>
              ))}
            </div>
          </section>

          {/* 5. Hydraulic Line Pressure Color Coding */}
          <section className="space-y-2.5">
            <div className="flex items-center justify-between border-b border-slate-200 pb-1">
              <span className="text-[11px] font-bold uppercase tracking-wider text-sky-700">
                5. Hydraulic Line Pressure Color Coding
              </span>
              <button
                type="button"
                onClick={() => onUpdateSettings({ pressureColors: { lowMaxBar: 5, midMaxBar: 55, highMaxBar: 120, lowColor: '#3b82f6', midColor: '#10b981', highColor: '#d97706', peakColor: '#dc2626' } })}
                className="text-[10px] font-semibold text-sky-700 hover:underline"
              >
                Reset Colors
              </button>
            </div>
            {(() => {
              const pc = { lowMaxBar: 5, midMaxBar: 55, highMaxBar: 120, lowColor: '#3b82f6', midColor: '#10b981', highColor: '#d97706', peakColor: '#dc2626', ...(settings.pressureColors || {}) };
              const updatePc = (patch) => onUpdateSettings({ pressureColors: { ...pc, ...patch } });
              return (
                <div className="grid grid-cols-2 sm:grid-cols-4 gap-2.5 pt-1">
                  <div className="p-2 rounded border border-slate-200 bg-slate-50 space-y-1">
                    <div className="flex items-center justify-between">
                      <span className="font-semibold text-slate-700">Low (&lt; T1)</span>
                      <input type="color" value={pc.lowColor} onChange={(e) => updatePc({ lowColor: e.target.value })} className="w-6 h-5 p-0 border border-slate-300 rounded cursor-pointer" />
                    </div>
                    <label className="block">
                      <span className="text-[10px] text-slate-500">T1 Max ({units.pressure})</span>
                      <input
                        type="number"
                        step="any"
                        value={Number(convertToDisplay(pc.lowMaxBar, 'pressure', units).toFixed(1))}
                        onChange={(e) => {
                          const v = parseFloat(e.target.value);
                          if (!Number.isNaN(v)) updatePc({ lowMaxBar: Math.max(0.1, convertFromDisplay(v, 'pressure', units)) });
                        }}
                        className="w-full px-1.5 py-1 font-mono bg-white border border-slate-200 rounded mt-0.5"
                      />
                    </label>
                  </div>
                  <div className="p-2 rounded border border-slate-200 bg-slate-50 space-y-1">
                    <div className="flex items-center justify-between">
                      <span className="font-semibold text-slate-700">Medium (T1–T2)</span>
                      <input type="color" value={pc.midColor} onChange={(e) => updatePc({ midColor: e.target.value })} className="w-6 h-5 p-0 border border-slate-300 rounded cursor-pointer" />
                    </div>
                    <label className="block">
                      <span className="text-[10px] text-slate-500">T2 Max ({units.pressure})</span>
                      <input
                        type="number"
                        step="any"
                        value={Number(convertToDisplay(pc.midMaxBar, 'pressure', units).toFixed(1))}
                        onChange={(e) => {
                          const v = parseFloat(e.target.value);
                          if (!Number.isNaN(v)) updatePc({ midMaxBar: Math.max(1, convertFromDisplay(v, 'pressure', units)) });
                        }}
                        className="w-full px-1.5 py-1 font-mono bg-white border border-slate-200 rounded mt-0.5"
                      />
                    </label>
                  </div>
                  <div className="p-2 rounded border border-slate-200 bg-slate-50 space-y-1">
                    <div className="flex items-center justify-between">
                      <span className="font-semibold text-slate-700">High (T2–T3)</span>
                      <input type="color" value={pc.highColor} onChange={(e) => updatePc({ highColor: e.target.value })} className="w-6 h-5 p-0 border border-slate-300 rounded cursor-pointer" />
                    </div>
                    <label className="block">
                      <span className="text-[10px] text-slate-500">T3 Max ({units.pressure})</span>
                      <input
                        type="number"
                        step="any"
                        value={Number(convertToDisplay(pc.highMaxBar, 'pressure', units).toFixed(1))}
                        onChange={(e) => {
                          const v = parseFloat(e.target.value);
                          if (!Number.isNaN(v)) updatePc({ highMaxBar: Math.max(5, convertFromDisplay(v, 'pressure', units)) });
                        }}
                        className="w-full px-1.5 py-1 font-mono bg-white border border-slate-200 rounded mt-0.5"
                      />
                    </label>
                  </div>
                  <div className="p-2 rounded border border-slate-200 bg-slate-50 space-y-1">
                    <div className="flex items-center justify-between">
                      <span className="font-semibold text-slate-700">Peak (&gt; T3)</span>
                      <input type="color" value={pc.peakColor} onChange={(e) => updatePc({ peakColor: e.target.value })} className="w-6 h-5 p-0 border border-slate-300 rounded cursor-pointer" />
                    </div>
                    <div className="text-[10px] text-slate-500 pt-2">
                      Above {convertToDisplay(pc.highMaxBar, 'pressure', units).toFixed(1)} {units.pressure}
                    </div>
                  </div>
                </div>
              );
            })()}
          </section>
        </div>

        <div className="px-4 py-3 bg-slate-50 border-t border-slate-200 flex items-center justify-between">
          <button onClick={onResetDefaults} className="px-3 py-1.5 text-xs font-medium text-slate-600 hover:bg-slate-200/70 rounded border border-slate-300">
            Reset to Defaults
          </button>
          <button onClick={onClose} className="px-4 py-1.5 text-xs font-semibold text-white bg-sky-600 hover:bg-sky-700 rounded shadow-sm">
            Apply & Close
          </button>
        </div>
      </div>
    </div>
  );
}


window.HydraulicSymbol = HydraulicSymbol;
window.LibraryMiniIcon = LibraryMiniIcon;
window.buildAvailableChannels = buildAvailableChannels;
window.OscilloscopeChart = OscilloscopeChart;

// ============================================================================
// 8B. INTERACTIVE SIGNAL BUILDER MODAL (TABLE + DRAGGABLE GRAPHICAL EDITOR)
// ============================================================================

function parseProfilePoints(str) {
  if (!str || typeof str !== 'string') return [{ t: 0, v: 0 }, { t: 5, v: 0 }, { t: 10, v: 0 }];
  const pts = [];
  for (const seg of str.split(',')) {
    const parts = seg.split(':');
    if (parts.length === 2) {
      const t = parseFloat(parts[0]);
      const v = parseFloat(parts[1]);
      if (Number.isFinite(t) && Number.isFinite(v)) pts.push({ t, v });
    }
  }
  return pts.length > 0 ? pts.sort((a, b) => a.t - b.t) : [{ t: 0, v: 0 }, { t: 5, v: 0 }, { t: 10, v: 0 }];
}

function serializeProfilePoints(pts) {
  return [...pts]
    .sort((a, b) => a.t - b.t)
    .map((p) => `${Number(p.t.toFixed(3))}:${Number(p.v.toFixed(3))}`)
    .join(', ');
}

function SignalBuilderModal({ title, unit, initialProfile, onApply, onClose }) {
  const [points, setPoints] = useState(() => parseProfilePoints(initialProfile));
  const [dragIdx, setDragIdx] = useState(null);
  const svgRef = useRef(null);

  const W = 560, H = 210;
  const pad = { top: 18, right: 22, bottom: 30, left: 52 };
  const plotW = W - pad.left - pad.right;
  const plotH = H - pad.top - pad.bottom;

  const { tMax, yMin, yMax } = useMemo(() => {
    const maxT = Math.max(10, ...points.map((p) => p.t));
    const minV = Math.min(0, ...points.map((p) => p.v));
    const maxV = Math.max(1, ...points.map((p) => p.v));
    const span = Math.max(1, maxV - minV);
    return { tMax: Math.ceil(maxT), yMin: minV - span * 0.12, yMax: maxV + span * 0.15 };
  }, [points]);

  const toX = (t) => pad.left + (Math.max(0, Math.min(tMax, t)) / Math.max(1e-6, tMax)) * plotW;
  const toY = (v) => pad.top + plotH - ((v - yMin) / Math.max(1e-6, yMax - yMin)) * plotH;

  const clientToData = (clientX, clientY) => {
    const rect = svgRef.current.getBoundingClientRect();
    const sx = ((clientX - rect.left) / rect.width) * W;
    const sy = ((clientY - rect.top) / rect.height) * H;
    const t = Math.max(0, ((sx - pad.left) / plotW) * tMax);
    const v = yMin + ((pad.top + plotH - sy) / plotH) * (yMax - yMin);
    return { t: Number(t.toFixed(2)), v: Number(v.toFixed(2)) };
  };

  const handleSvgMouseMove = (e) => {
    if (dragIdx === null || !svgRef.current) return;
    const d = clientToData(e.clientX, e.clientY);
    setPoints((prev) => prev.map((pt, i) => (i === dragIdx ? d : pt)));
  };

  const handleSvgDoubleClick = (e) => {
    if (!svgRef.current) return;
    const d = clientToData(e.clientX, e.clientY);
    setPoints((prev) => [...prev, d].sort((a, b) => a.t - b.t));
  };

  const applyPreset = (kind) => {
    if (kind === 'step') setPoints([{ t: 0, v: 0 }, { t: 1, v: 0 }, { t: 1.05, v: 1 }, { t: 10, v: 1 }]);
    else if (kind === 'ramp') setPoints([{ t: 0, v: 0 }, { t: 1, v: 0 }, { t: 4, v: 100 }, { t: 7, v: 100 }, { t: 10, v: 0 }]);
    else if (kind === 'pulse') setPoints([{ t: 0, v: 0 }, { t: 1, v: 0 }, { t: 1.1, v: -1 }, { t: 4, v: -1 }, { t: 4.1, v: 0 }, { t: 5.5, v: 0 }, { t: 5.6, v: 1 }, { t: 8.5, v: 1 }, { t: 8.6, v: 0 }, { t: 10, v: 0 }]);
    else if (kind === 'sine') {
      const s = [];
      for (let i = 0; i <= 20; i++) {
        const t = Number((i * 0.5).toFixed(2));
        s.push({ t, v: Number((Math.sin((t / 10) * 2 * Math.PI)).toFixed(3)) });
      }
      setPoints(s);
    }
  };

  const sortedPts = useMemo(() => [...points].sort((a, b) => a.t - b.t), [points]);
  const polyStr = sortedPts.map((p) => `${toX(p.t).toFixed(1)},${toY(p.v).toFixed(1)}`).join(' ');
  const yTicks = [0, 0.25, 0.5, 0.75, 1].map((f) => yMin + f * (yMax - yMin));
  const xTicks = [0, 0.2, 0.4, 0.6, 0.8, 1].map((f) => f * tMax);

  return (
    <div className="fixed inset-0 bg-slate-900/50 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-2xl overflow-hidden flex flex-col max-h-[90vh]" onMouseDown={(e) => e.stopPropagation()}>
        <div className="px-4 py-2.5 bg-slate-50 border-b border-slate-200 flex items-center justify-between">
          <div className="flex items-center gap-2">
            <span className="text-violet-600 font-bold">📈</span>
            <h2 className="text-sm font-bold text-slate-900">Signal Builder — {title} {unit ? `(${unit})` : ''}</h2>
          </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>

        <div className="p-4 overflow-y-auto space-y-3 text-xs">
          {/* Quick Presets */}
          <div className="flex items-center justify-between flex-wrap gap-2">
            <div className="flex items-center gap-1.5">
              <span className="text-[11px] font-semibold text-slate-500">Presets:</span>
              <button type="button" onClick={() => applyPreset('step')} className="px-2 py-0.5 bg-slate-100 hover:bg-violet-100 text-slate-700 rounded border border-slate-200">Step</button>
              <button type="button" onClick={() => applyPreset('ramp')} className="px-2 py-0.5 bg-slate-100 hover:bg-violet-100 text-slate-700 rounded border border-slate-200">Ramp</button>
              <button type="button" onClick={() => applyPreset('pulse')} className="px-2 py-0.5 bg-slate-100 hover:bg-violet-100 text-slate-700 rounded border border-slate-200">Bi-Dir Pulse</button>
              <button type="button" onClick={() => applyPreset('sine')} className="px-2 py-0.5 bg-slate-100 hover:bg-violet-100 text-slate-700 rounded border border-slate-200">Sine</button>
            </div>
            <span className="text-[10.5px] text-slate-400">Drag dots to edit · Double-click graph to add point</span>
          </div>

          {/* Interactive Graphical Editor */}
          <div className="border border-slate-200 rounded-md overflow-hidden bg-slate-50">
            <svg
              ref={svgRef}
              viewBox={`0 0 ${W} ${H}`}
              className="w-full h-52 select-none cursor-crosshair bg-white"
              onMouseMove={handleSvgMouseMove}
              onMouseUp={() => setDragIdx(null)}
              onMouseLeave={() => setDragIdx(null)}
              onDoubleClick={handleSvgDoubleClick}
            >
              {yTicks.map((yv, i) => (
                <g key={`gy${i}`}>
                  <line x1={pad.left} y1={toY(yv)} x2={W - pad.right} y2={toY(yv)} stroke="#e2e8f0" strokeWidth={1} />
                  <text x={pad.left - 6} y={toY(yv) + 3} textAnchor="end" fontSize={9.5} fill="#64748b" fontFamily="monospace">{yv.toFixed(1)}</text>
                </g>
              ))}
              {xTicks.map((xv, i) => (
                <g key={`gx${i}`}>
                  <line x1={toX(xv)} y1={pad.top} x2={toX(xv)} y2={H - pad.bottom} stroke="#e2e8f0" strokeWidth={1} />
                  <text x={toX(xv)} y={H - 10} textAnchor="middle" fontSize={9.5} fill="#64748b" fontFamily="monospace">{xv.toFixed(1)}s</text>
                </g>
              ))}
              <rect x={pad.left} y={pad.top} width={plotW} height={plotH} fill="none" stroke="#94a3b8" strokeWidth={1} />
              {sortedPts.length >= 2 && (
                <polyline fill="none" stroke="#7c3aed" strokeWidth={2.2} strokeLinejoin="round" points={polyStr} />
              )}
              {points.map((pt, idx) => (
                <g key={idx} onMouseDown={(e) => { e.stopPropagation(); setDragIdx(idx); }} className="cursor-grab active:cursor-grabbing">
                  <circle cx={toX(pt.t)} cy={toY(pt.v)} r={10} fill="transparent" />
                  <circle cx={toX(pt.t)} cy={toY(pt.v)} r={dragIdx === idx ? 6 : 4.5} fill={dragIdx === idx ? '#dc2626' : '#7c3aed'} stroke="#ffffff" strokeWidth={1.6} />
                </g>
              ))}
            </svg>
          </div>

          {/* Table Editor */}
          <div className="space-y-1.5">
            <div className="flex items-center justify-between">
              <span className="text-[11px] font-bold uppercase tracking-wider text-slate-600">Data Points Table ({points.length})</span>
              <div className="flex items-center gap-1.5">
                <button
                  type="button"
                  onClick={() => setPoints((prev) => [...prev].sort((a, b) => a.t - b.t))}
                  className="px-2 py-0.5 bg-slate-100 hover:bg-slate-200 text-slate-700 rounded border border-slate-200 text-[11px]"
                >
                  Sort by Time
                </button>
                <button
                  type="button"
                  onClick={() => {
                    const last = sortedPts[sortedPts.length - 1] || { t: 0, v: 0 };
                    setPoints((prev) => [...prev, { t: Number((last.t + 1).toFixed(2)), v: last.v }]);
                  }}
                  className="px-2.5 py-0.5 bg-violet-600 hover:bg-violet-700 text-white font-semibold rounded text-[11px]"
                >
                  + Add Row
                </button>
              </div>
            </div>
            <div className="max-h-44 overflow-y-auto border border-slate-200 rounded">
              <table className="w-full text-left border-collapse font-mono text-[11px]">
                <thead className="bg-slate-50 sticky top-0 border-b border-slate-200">
                  <tr>
                    <th className="px-2.5 py-1.5 text-slate-500">#</th>
                    <th className="px-2.5 py-1.5 text-slate-600">Time (s)</th>
                    <th className="px-2.5 py-1.5 text-slate-600">Value {unit ? `(${unit})` : ''}</th>
                    <th className="px-2.5 py-1.5 text-right text-slate-500">Action</th>
                  </tr>
                </thead>
                <tbody>
                  {points.map((pt, idx) => (
                    <tr key={idx} className="border-b border-slate-100 last:border-0">
                      <td className="px-2.5 py-1 text-slate-400">{idx + 1}</td>
                      <td className="px-2 py-1">
                        <input
                          type="number"
                          step="any"
                          min={0}
                          value={pt.t}
                          onChange={(e) => {
                            const v = parseFloat(e.target.value);
                            setPoints((prev) => prev.map((p, i) => (i === idx ? { ...p, t: Number.isNaN(v) ? 0 : Math.max(0, v) } : p)));
                          }}
                          className="w-24 px-1.5 py-0.5 bg-slate-50 border border-slate-200 rounded"
                        />
                      </td>
                      <td className="px-2 py-1">
                        <input
                          type="number"
                          step="any"
                          value={pt.v}
                          onChange={(e) => {
                            const v = parseFloat(e.target.value);
                            setPoints((prev) => prev.map((p, i) => (i === idx ? { ...p, v: Number.isNaN(v) ? 0 : v } : p)));
                          }}
                          className="w-28 px-1.5 py-0.5 bg-slate-50 border border-slate-200 rounded"
                        />
                      </td>
                      <td className="px-2.5 py-1 text-right">
                        <button
                          type="button"
                          disabled={points.length <= 2}
                          onClick={() => setPoints((prev) => prev.filter((_, i) => i !== idx))}
                          className="px-1.5 py-0.5 text-red-600 hover:bg-red-50 rounded disabled:opacity-30"
                        >
                          ✕
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        </div>

        <div className="px-4 py-2.5 bg-slate-50 border-t border-slate-200 flex items-center justify-between">
          <button type="button" onClick={onClose} className="px-3 py-1.5 text-xs font-medium text-slate-600 hover:bg-slate-200/70 rounded border border-slate-300">Cancel</button>
          <button
            type="button"
            onClick={() => { onApply(serializeProfilePoints(points)); onClose(); }}
            className="px-4 py-1.5 text-xs font-semibold text-white bg-violet-600 hover:bg-violet-700 rounded shadow-sm"
          >
            Apply Signal Profile
          </button>
        </div>
      </div>
    </div>
  );
}

window.SimulationSettingsModal = SimulationSettingsModal;
window.SignalBuilderModal = SignalBuilderModal;

})();
