// flujo-art.jsx — Dibujos en corte de medidores de flujo (Módulo 3 · Tecnologías de medición)
// Va después de m17-lib.jsx. Todo en coordenadas de pantalla (1920 × 1080).
// Cada <svg> que use estas piezas debe incluir <FlowDefs /> una vez.

const FA = {
  steel: '#d3dae2', steelD: '#9aa6b4', trim: '#eef2f6', trimD: '#a9b5c2',
  ink: '#0f2b4a', mut: '#5b7388', liq: '#b9d8f6', liqD: '#3f86d4',
  paint: '#4a6a90', paintD: '#2f4a6b', paintL: '#6d8db3',
  hi: '#df6f1f', lo: '#2f86e6', ok: '#2fae6a', bad: '#d7263d', dot: '#1f66bf',
};
const faSmooth = (e0, e1, x) => { const k = Math.max(0, Math.min(1, (x - e0) / (e1 - e0))); return k * k * (3 - 2 * k); };
const faLerp = (a, b, k) => a + (b - a) * k;
const faPoly = (pts) => 'M' + pts.map((p) => `${p[0].toFixed(1)} ${p[1].toFixed(1)}`).join(' L') + ' Z';

function FlowDefs() {
  return (
    <defs>
      <pattern id="faHatch" width="14" height="14" patternUnits="userSpaceOnUse" patternTransform="rotate(45)">
        <rect width="14" height="14" fill={FA.steel} /><line x1="0" y1="0" x2="0" y2="14" stroke={FA.steelD} strokeWidth="2.2" />
      </pattern>
      <pattern id="faHatchT" width="10" height="10" patternUnits="userSpaceOnUse" patternTransform="rotate(-45)">
        <rect width="10" height="10" fill={FA.trim} /><line x1="0" y1="0" x2="0" y2="10" stroke={FA.trimD} strokeWidth="1.8" />
      </pattern>
      <pattern id="faHatchP" width="12" height="12" patternUnits="userSpaceOnUse" patternTransform="rotate(45)">
        <rect width="12" height="12" fill={FA.paint} /><line x1="0" y1="0" x2="0" y2="12" stroke={FA.paintD} strokeWidth="2" />
      </pattern>
      <pattern id="faDirt" width="8" height="8" patternUnits="userSpaceOnUse" patternTransform="rotate(30)">
        <rect width="8" height="8" fill="#8a7a62" /><circle cx="3" cy="3" r="1.6" fill="#5e5140" />
      </pattern>
      <linearGradient id="faLiq" x1="0" x2="0" y1="0" y2="1">
        <stop offset="0" stopColor="#d3e7fb" /><stop offset="0.5" stopColor="#aed0f4" /><stop offset="1" stopColor="#d3e7fb" />
      </linearGradient>
      <marker id="faArr" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="5" markerHeight="5" orient="auto-start-reverse"><path d="M0 0 L10 5 L0 10 z" fill={FA.ink} /></marker>
      <marker id="faArrM" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse"><path d="M0 0 L10 5 L0 10 z" fill={FA.mut} /></marker>
      <marker id="faArrH" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="5" markerHeight="5" orient="auto-start-reverse"><path d="M0 0 L10 5 L0 10 z" fill={FA.hi} /></marker>
    </defs>
  );
}

// ── Partículas que siguen el paso del fluido ────────────────────────────────
// bounds(x) → [arriba, abajo] del paso. La velocidad es inversa al ancho del paso,
// así que las partículas aceleran en la restricción.
function faTable(x1, x2, bounds, N = 300) {
  const xs = [], tops = [], bots = [], cum = [0];
  for (let i = 0; i <= N; i++) {
    const x = x1 + (x2 - x1) * i / N;
    const [a, b] = bounds(x);
    xs.push(x); tops.push(a); bots.push(b);
    if (i) cum.push(cum[i - 1] + ((b - a) + (bots[i - 1] - tops[i - 1])) / 2 * (x2 - x1) / N);
  }
  return { xs, tops, bots, cum, N };
}
function faAt(T, p, f) {
  const target = p * T.cum[T.N];
  let lo = 0, hi = T.N;
  while (hi - lo > 1) { const m = (lo + hi) >> 1; if (T.cum[m] < target) lo = m; else hi = m; }
  const k = (target - T.cum[lo]) / Math.max(1e-9, T.cum[hi] - T.cum[lo]);
  const x = faLerp(T.xs[lo], T.xs[hi], k);
  return [x, faLerp(faLerp(T.tops[lo], T.tops[hi], k), faLerp(T.bots[lo], T.bots[hi], k), f)];
}
function FlowDots({ T, t, n = 40, speed = 0.08, r = 5, color = FA.dot, op = 0.85, seed = 0 }) {
  const els = [];
  for (let k = 0; k < n; k++) {
    const f = 0.1 + 0.8 * (((k + seed) * 0.6180339887) % 1);
    const p = (((t * speed + k / n) % 1) + 1) % 1;
    const [x, y] = faAt(T, p, f);
    const fade = Math.min(1, p * 14, (1 - p) * 14);
    els.push(<circle key={k} cx={x.toFixed(1)} cy={y.toFixed(1)} r={r} fill={color} opacity={(op * fade).toFixed(3)} />);
  }
  return <g>{els}</g>;
}

// ── Tubería, bridas y fluido ────────────────────────────────────────────────
function PipeRun({ x1, x2, yc, R, wall = 14, fill = 'url(#faLiq)' }) {
  return (
    <g>
      {fill && <rect x={x1} y={yc - R} width={x2 - x1} height={2 * R} fill={fill} />}
      <rect x={x1} y={yc - R - wall} width={x2 - x1} height={wall} fill="url(#faHatch)" stroke={FA.ink} strokeWidth="2.5" />
      <rect x={x1} y={yc + R} width={x2 - x1} height={wall} fill="url(#faHatch)" stroke={FA.ink} strokeWidth="2.5" />
    </g>
  );
}
// Fluido con perfil h(x) (mitad del alto del paso)
function FluidPoly({ x1, x2, yc, h, fill = 'url(#faLiq)', N = 80 }) {
  const top = [], bot = [];
  for (let i = 0; i <= N; i++) { const x = x1 + (x2 - x1) * i / N; top.push([x, yc - h(x)]); bot.push([x, yc + h(x)]); }
  return <path d={faPoly([...top, ...bot.reverse()])} fill={fill} />;
}
// Par de bridas con su junta en x (la placa va en medio)
function FlangePair({ x, yc, R, wall = 14, gap = 12, w = 26, h = 34 }) {
  const parts = [];
  for (const s of [-1, 1]) {
    for (const side of [-1, 1]) {
      const fx = side < 0 ? x - gap / 2 - w : x + gap / 2;
      const y0 = s < 0 ? yc - R - wall - h : yc + R;
      parts.push(<rect key={`f${s}${side}`} x={fx} y={y0} width={w} height={wall + h} fill="url(#faHatch)" stroke={FA.ink} strokeWidth="2.5" />);
    }
    const by = s < 0 ? yc - R - wall - h * 0.45 : yc + R + wall + h * 0.45;
    const xa = x - gap / 2 - w, xb = x + gap / 2 + w;
    parts.push(
      <g key={`b${s}`}>
        <line x1={xa - 6} y1={by} x2={xb + 6} y2={by} stroke={FA.ink} strokeWidth="4" />
        <rect x={xa - 12} y={by - 7} width="7" height="14" fill={FA.steelD} stroke={FA.ink} strokeWidth="1.5" />
        <rect x={xb + 5} y={by - 7} width="7" height="14" fill={FA.steelD} stroke={FA.ink} strokeWidth="1.5" />
      </g>
    );
  }
  return <g>{parts}</g>;
}

// ── Placa de orificio ───────────────────────────────────────────────────────
// flip: instalada al revés (bisel aguas arriba). worn: canto de entrada redondeado.
function OrificePlate({ x, yc, R, wall = 14, h = 34, beta = 0.6, th = 12, flip = false, worn = false }) {
  const r = beta * R, top = R + wall + h * 0.45 - 9;
  const e = th * 0.35, sg = flip ? -1 : 1;
  const xu = x - sg * th / 2, xd = x + sg * th / 2;
  const half = (s) => {
    const yo = yc + s * top, yb = yc + s * r, yv = yc + s * (r + (th - e));
    const d = worn
      ? `M${xu} ${yo} L${xd} ${yo} L${xd} ${yv} L${xu + sg * e} ${yb} L${xu + sg * 2} ${yb} Q${xu} ${yb} ${xu} ${yc + s * (r + 9)} Z`
      : `M${xu} ${yo} L${xd} ${yo} L${xd} ${yv} L${xu + sg * e} ${yb} L${xu} ${yb} Z`;
    return <path key={s} d={d} fill="url(#faHatchT)" stroke={FA.ink} strokeWidth="2.5" strokeLinejoin="round" />;
  };
  return <g>{half(-1)}{half(1)}</g>;
}
// Paso del chorro: se contrae hasta la vena contracta y se abre de nuevo
function orificeBounds(x0, yc, R, beta, cc = 0.78) {
  const r = beta * R, rc = r * cc;
  return (x) => {
    let h;
    if (x < x0 - 1.2 * R) h = R;
    else if (x < x0) h = faLerp(R, r, faSmooth(x0 - 1.2 * R, x0, x));
    else if (x < x0 + 0.7 * R) h = faLerp(r, rc, faSmooth(x0, x0 + 0.7 * R, x));
    else h = faLerp(rc, R, faSmooth(x0 + 0.7 * R, x0 + 5 * R, x));
    return [yc - h, yc + h];
  };
}
// Presión a lo largo del tubo (1 = aguas arriba, 0 = mínimo)
const orificeP = (x0, R, loss = 0.63) => (x) =>
  x < x0 + 0.7 * R ? faLerp(1, 0, faSmooth(x0 - 0.7 * R, x0 + 0.7 * R, x)) : faLerp(0, 1 - loss, faSmooth(x0 + 0.7 * R, x0 + 6 * R, x));
// Remolinos detrás de la placa
function Eddy({ cx, cy, rx, ry, t, cw = true, color = FA.mut }) {
  return <ellipse cx={cx} cy={cy} rx={rx} ry={ry} fill="none" stroke={color} strokeWidth="2.5" strokeDasharray="9 7" strokeDashoffset={(cw ? -1 : 1) * t * 30} opacity="0.75" />;
}
function OrificeEddies({ x0, yc, R, beta, t, s = 1 }) {
  const r = beta * R, cy = (R + r * 0.78) / 2;
  return <g>
    <Eddy cx={x0 + 1.1 * R} cy={yc - cy} rx={0.75 * R} ry={(R - r * 0.78) / 2 - 4} t={t} cw={false} />
    <Eddy cx={x0 + 1.1 * R} cy={yc + cy} rx={0.75 * R} ry={(R - r * 0.78) / 2 - 4} t={t} cw={true} />
  </g>;
}

// ── Venturi ─────────────────────────────────────────────────────────────────
function venturiGeo(x0, R, beta) {
  const r = beta * R;
  const a = x0, b = a + (R - r) / Math.tan(10.5 * Math.PI / 180), c = b + 1.4 * r, d = c + (R - r) / Math.tan(7.5 * Math.PI / 180);
  const h = (x) => x < a ? R : x < b ? faLerp(R, r, (x - a) / (b - a)) : x < c ? r : x < d ? faLerp(r, R, (x - c) / (d - c)) : R;
  return { r, a, b, c, d, h };
}
const venturiP = (g, R, loss = 0.1) => (x) => {
  const k = (R * R / (g.h(x) ** 2) - 1) / (R * R / (g.r * g.r) - 1);
  return 1 - k - loss * faSmooth(g.c, g.d, x);
};
function VenturiBody({ x0, yc, R, wall = 14, beta = 0.6, ext = 40, taps = true }) {
  const g = venturiGeo(x0, R, beta);
  const xs = [g.a - ext, g.a, g.b, g.c, g.d, g.d + ext];
  const walls = [-1, 1].map((s) => {
    const inner = xs.map((x) => [x, yc + s * g.h(x)]);
    const outer = xs.slice().reverse().map((x) => [x, yc + s * (g.h(x) + wall)]);
    return <path key={s} d={faPoly([...inner, ...outer])} fill="url(#faHatch)" stroke={FA.ink} strokeWidth="2.5" strokeLinejoin="round" />;
  });
  const ring = (xm) => {
    const hh = g.h(xm);
    return [-1, 1].map((s) => <g key={`${xm}${s}`}>
      <rect x={xm - 13} y={s < 0 ? yc - hh - wall - 13 : yc + hh + wall} width="26" height="13" rx="4" fill="#fff" stroke={FA.ink} strokeWidth="2" />
      <line x1={xm} y1={yc + s * hh} x2={xm} y2={yc + s * (hh + wall)} stroke={FA.ink} strokeWidth="2" />
    </g>);
  };
  return <g>{walls}{taps && ring(g.a - ext * 0.5)}{taps && ring((g.b + g.c) / 2)}</g>;
}

// ── Tobera (ISA 1932) ───────────────────────────────────────────────────────
function nozzleGeo(x0, R, beta) {
  const r = beta * R, x1 = x0 + 0.55 * R, x2 = x1 + 0.6 * r;
  const h = (x) => x < x0 ? R : x < x1 ? R - (R - r) * Math.sqrt(Math.max(0, 1 - ((x1 - x) / (x1 - x0)) ** 2)) : x <= x2 ? r : R;
  return { r, x1, x2, h };
}
function NozzleBody({ x0, yc, R, wall = 14, h = 34, beta = 0.6 }) {
  const g = nozzleGeo(x0, R, beta), top = R + wall + h * 0.45 - 9;
  return <g>{[-1, 1].map((s) => {
    const pts = [[x0, yc + s * top], [x0, yc + s * R]];
    for (let i = 1; i <= 16; i++) { const x = x0 + (g.x1 - x0) * i / 16; pts.push([x, yc + s * g.h(x)]); }
    pts.push([g.x2, yc + s * g.r], [g.x2 + 6, yc + s * (g.r + 6)], [g.x2 + 6, yc + s * top]);
    return <path key={s} d={faPoly(pts)} fill="url(#faHatchT)" stroke={FA.ink} strokeWidth="2.5" strokeLinejoin="round" />;
  })}</g>;
}
function nozzleBounds(x0, yc, R, beta) {
  const g = nozzleGeo(x0, R, beta);
  return (x) => {
    let h;
    if (x < x0 - 0.6 * R) h = R;
    else if (x < g.x1) h = Math.min(faLerp(R, g.r, faSmooth(x0 - 0.6 * R, g.x1, x)), g.h(x));
    else if (x < g.x2 + 0.3 * R) h = g.r * 0.98;
    else h = faLerp(g.r * 0.98, R, faSmooth(g.x2 + 0.3 * R, g.x2 + 4.5 * R, x));
    return [yc - h, yc + h];
  };
}

// ── Cono (V-Cone) ───────────────────────────────────────────────────────────
function coneGeo(xc, R, beta) {
  const rb = R * Math.sqrt(1 - beta * beta), xt = xc - 1.1 * R, xb = xc + 0.55 * R;
  const up = (x) => x < xt || x > xb ? 0 : x < xc ? rb * (x - xt) / (xc - xt) : rb * (1 - (x - xc) / (xb - xc));
  return { rb, xt, xb, up };
}
function ConeBody({ xc, yc, R, beta = 0.6 }) {
  const g = coneGeo(xc, R, beta);
  const ex = g.xb + 0.7 * R, w = Math.max(5, R * 0.13);
  return <g>
    <path d={faPoly([[g.xb - 4, yc - w], [ex + w, yc - w], [ex + w, yc + R], [ex - w, yc + R], [ex - w, yc + w], [g.xb - 4, yc + w]])} fill="url(#faHatch)" stroke={FA.ink} strokeWidth="2.5" strokeLinejoin="round" />
    <path d={faPoly([[g.xt, yc], [xc, yc - g.rb], [g.xb, yc], [xc, yc + g.rb]])} fill="url(#faHatchT)" stroke={FA.ink} strokeWidth="2.5" strokeLinejoin="round" />
  </g>;
}
const coneBoundsTop = (xc, yc, R, beta) => { const g = coneGeo(xc, R, beta); return (x) => [yc - R, yc - g.up(x)]; };
const coneBoundsBot = (xc, yc, R, beta) => { const g = coneGeo(xc, R, beta); return (x) => [yc + g.up(x), yc + R]; };

// ── Cuña ────────────────────────────────────────────────────────────────────
function wedgeGeo(xw, R, hw = 1.0, half = 0.55) {
  const H = hw * R, L = half * R;
  return { H, L, w: (x) => Math.max(0, H * (1 - Math.abs(x - xw) / L)) };
}
function WedgeBody({ xw, yc, R, hw = 1.0, half = 0.55 }) {
  const g = wedgeGeo(xw, R, hw, half);
  return <path d={faPoly([[xw - g.L, yc - R], [xw + g.L, yc - R], [xw, yc - R + g.H]])} fill="url(#faHatchT)" stroke={FA.ink} strokeWidth="2.5" strokeLinejoin="round" />;
}
const wedgeBounds = (xw, yc, R, hw = 1.0, half = 0.55) => { const g = wedgeGeo(xw, R, hw, half); return (x) => [yc - R + g.w(x), yc + R]; };

// ── Acondicionador de flujo (placa perforada) ───────────────────────────────
function Conditioner({ x, yc, R, wall = 14, h = 34, th = 12, holes = 5 }) {
  const top = R + wall + h * 0.45 - 9, hh = (2 * R) / (2 * holes + 1);
  return <g>
    <rect x={x - th / 2} y={yc - top} width={th} height={2 * top} fill="url(#faHatchT)" stroke={FA.ink} strokeWidth="2.5" />
    {Array.from({ length: holes }, (_, i) => <rect key={i} x={x - th / 2} y={yc - R + hh * (2 * i + 1)} width={th} height={hh} fill="#cfe4fa" stroke={FA.ink} strokeWidth="1.5" />)}
  </g>;
}

// ── Codo en corte: baja por x0 y sale horizontal en yc hacia la derecha ─────
function ElbowCut({ x0, yTop, yc, R, wall = 14, Rb }) {
  const cx = x0 + Rb, cy = yc - Rb;
  const arc = (rad, a0, a1, N = 28) => Array.from({ length: N + 1 }, (_, i) => { const a = (a0 + (a1 - a0) * i / N) * Math.PI / 180; return [cx + rad * Math.cos(a), cy + rad * Math.sin(a)]; });
  const band = (r1, r2, withStraight) => {
    const A = arc(r1, 180, 90), B = arc(r2, 90, 180);
    return withStraight ? [[cx - r1, yTop], ...A, ...B, [cx - r2, yTop]] : [...A, ...B];
  };
  return <g>
    <path d={faPoly(band(Rb + R, Rb - R, true))} fill="url(#faLiq)" />
    <path d={faPoly(band(Rb + R + wall, Rb + R, true))} fill="url(#faHatch)" stroke={FA.ink} strokeWidth="2.5" strokeLinejoin="round" />
    <path d={faPoly(band(Rb - R, Rb - R - wall, true))} fill="url(#faHatch)" stroke={FA.ink} strokeWidth="2.5" strokeLinejoin="round" />
  </g>;
}

// ── Perfil de velocidad (flechas) ───────────────────────────────────────────
function VelProfile({ x, yc, R, L = 80, skew = 0, n = 9, color = FA.ink, op = 1 }) {
  const tips = [], ar = [];
  for (let i = 0; i < n; i++) {
    const u = -0.86 + 1.72 * i / (n - 1);
    const len = Math.max(12, L * Math.pow(Math.max(0, 1 - Math.abs(u)), 1 / 7) * (1 + skew * u));
    const y = yc + u * R;
    tips.push([x + len, y]);
    ar.push(<line key={i} x1={x} y1={y} x2={x + len - 4} y2={y} stroke={color} strokeWidth="3" markerEnd="url(#faArr)" />);
  }
  return <g opacity={op}>
    <line x1={x} y1={yc - R * 0.92} x2={x} y2={yc + R * 0.92} stroke={color} strokeWidth="2.5" />
    {ar}
    <path d={'M' + tips.map((p) => `${p[0].toFixed(1)} ${p[1].toFixed(1)}`).join(' L')} fill="none" stroke={FA.hi} strokeWidth="2.5" strokeDasharray="5 4" />
  </g>;
}

// ── Transmisor de presión diferencial (bridas H y L a los lados) ────────────
// (x, y) = centro de la cápsula. Puertos en (x ± 72, y).
function DPCell({ x, y, val = '', tag = 'FT', unit = '', alarm = false }) {
  return (
    <g>
      <rect x={x - 72} y={y - 48} width="27" height="96" rx="4" fill="url(#faHatch)" stroke={FA.ink} strokeWidth="2.5" />
      <rect x={x + 45} y={y - 48} width="27" height="96" rx="4" fill="url(#faHatch)" stroke={FA.ink} strokeWidth="2.5" />
      <rect x={x - 45} y={y - 38} width="90" height="76" rx="8" fill="url(#faHatchP)" stroke={FA.ink} strokeWidth="2.5" />
      <path d={`M${x} ${y - 30} Q${x + 6} ${y - 15} ${x} ${y} Q${x - 6} ${y + 15} ${x} ${y + 30}`} fill="none" stroke="#fff" strokeWidth="3" />
      <rect x={x - 12} y={y - 58} width="24" height="20" fill={FA.steelD} stroke={FA.ink} strokeWidth="2" />
      <rect x={x - 70} y={y - 142} width="140" height="86" rx="14" fill={FA.paintL} stroke={FA.ink} strokeWidth="2.5" />
      <rect x={x - 56} y={y - 132} width="112" height="46" rx="6" fill={alarm ? '#fde3e3' : '#f7fbff'} stroke={FA.ink} strokeWidth="2" />
      <text x={x} y={y - 100} fill={alarm ? FA.bad : FA.ink} fontFamily={MONO4} fontSize="21" fontWeight="700" textAnchor="middle">{val}</text>
      <text x={x} y={y - 66} fill="#fff" fontFamily={MONO4} fontSize="13" fontWeight="600" textAnchor="middle" letterSpacing="0.12em">{tag}{unit ? ` · ${unit}` : ''}</text>
      <text x={x - 58} y={y + 70} fill={FA.hi} fontFamily={MONO4} fontSize="18" fontWeight="700" textAnchor="middle">H</text>
      <text x={x + 58} y={y + 70} fill={FA.lo} fontFamily={MONO4} fontSize="18" fontWeight="700" textAnchor="middle">L</text>
    </g>
  );
}
// Válvula (símbolo de corbatín). state: 'open' | 'closed' | 'bad'
function BowTie({ x, y, vertical = false, state = 'open', s = 14 }) {
  const fill = state === 'open' ? FA.ok : state === 'bad' ? FA.bad : '#fff';
  const d = vertical
    ? `M${x - s} ${y - s} L${x + s} ${y - s} L${x - s} ${y + s} L${x + s} ${y + s} Z`
    : `M${x - s} ${y - s} L${x - s} ${y + s} L${x + s} ${y - s} L${x + s} ${y + s} Z`;
  return <path d={d} fill={fill} stroke={FA.ink} strokeWidth="2.5" strokeLinejoin="round" />;
}
// Línea de impulso (tubing)
function Tube({ d, color = FA.steelD, w = 7 }) {
  return <g>
    <path d={d} fill="none" stroke={FA.ink} strokeWidth={w + 4} strokeLinejoin="round" strokeLinecap="round" />
    <path d={d} fill="none" stroke={color} strokeWidth={w} strokeLinejoin="round" strokeLinecap="round" />
  </g>;
}

// ── Curvas y cotas ──────────────────────────────────────────────────────────
function ProfilePlot({ fn, x1, x2, y0, h, prog = 1, color = FA.hi, w = 5, dash }) {
  const xe = x1 + (x2 - x1) * Math.max(0, Math.min(1, prog));
  if (xe <= x1 + 1) return null;
  const pts = [];
  for (let i = 0; i <= 160; i++) { const x = x1 + (xe - x1) * i / 160; pts.push(`${x.toFixed(1)} ${(y0 - fn(x) * h).toFixed(1)}`); }
  return <path d={'M' + pts.join(' L')} fill="none" stroke={color} strokeWidth={w} strokeLinejoin="round" strokeLinecap="round" strokeDasharray={dash} />;
}
function DimLine({ x1, x2, y, label, color = FA.mut, op = 1, size = 18 }) {
  return <g opacity={op}>
    <line x1={x1} y1={y - 10} x2={x1} y2={y + 10} stroke={color} strokeWidth="2" />
    <line x1={x2} y1={y - 10} x2={x2} y2={y + 10} stroke={color} strokeWidth="2" />
    <line x1={x1 + 3} y1={y} x2={x2 - 3} y2={y} stroke={color} strokeWidth="2" markerStart="url(#faArrM)" markerEnd="url(#faArrM)" />
    <text x={(x1 + x2) / 2} y={y - 12} fill={color} fontFamily={MONO4} fontSize={size} fontWeight="600" textAnchor="middle">{label}</text>
  </g>;
}
function VDim({ x, y1, y2, label, color = FA.mut, op = 1, size = 18, side = -1 }) {
  return <g opacity={op}>
    <line x1={x + 3} y1={y1 + 3} x2={x + 3} y2={y2 - 3} stroke={color} strokeWidth="2" markerStart="url(#faArrM)" markerEnd="url(#faArrM)" transform={`translate(-3 0)`} />
    <text x={x + side * 12} y={(y1 + y2) / 2 + 6} fill={color} fontFamily={MONO4} fontSize={size} fontWeight="700" textAnchor={side < 0 ? 'end' : 'start'}>{label}</text>
  </g>;
}
function FaText({ x, y, children, size = 18, color = FA.ink, anchor = 'start', weight = 600, mono = false, op = 1 }) {
  return <text x={x} y={y} fill={color} fontFamily={mono ? MONO4 : DISP4} fontSize={size} fontWeight={weight} textAnchor={anchor} opacity={op}>{children}</text>;
}

Object.assign(window, {
  FA, faSmooth, faLerp, faPoly, FlowDefs, faTable, faAt, FlowDots, PipeRun, FluidPoly, FlangePair,
  OrificePlate, orificeBounds, orificeP, Eddy, OrificeEddies, venturiGeo, venturiP, VenturiBody,
  nozzleGeo, NozzleBody, nozzleBounds, coneGeo, ConeBody, coneBoundsTop, coneBoundsBot,
  wedgeGeo, WedgeBody, wedgeBounds, Conditioner, ElbowCut, VelProfile, DPCell, BowTie, Tube,
  ProfilePlot, DimLine, VDim, FaText,
});

// ═══ Sondas de inserción (Clase 3.3) ═══════════════════════════════════════

// Tubo Pitot estático (Prandtl): punta en (xt, yc) mirando aguas arriba, vástago en xs hasta top.
// El conducto central (rojo/naranja) lleva la presión de impacto; el anular (azul), la estática.
function PitotStatic({ xt, yc, xs, top, d = 24, holes = true }) {
  const p = `M${xt} ${yc} L${xs} ${yc} L${xs} ${top}`;
  const hx = xt + 3.2 * d;
  return (
    <g>
      <path d={p} fill="none" stroke={FA.ink} strokeWidth={d} strokeLinejoin="round" />
      <path d={p} fill="none" stroke={FA.steel} strokeWidth={d - 5} strokeLinejoin="round" />
      <path d={p} fill="none" stroke="#bfe0ff" strokeWidth={d - 9} strokeLinejoin="round" />
      <path d={p} fill="none" stroke={FA.steelD} strokeWidth={d - 13} strokeLinejoin="round" />
      <path d={p} fill="none" stroke={FA.hi} strokeWidth={Math.max(3, d - 17)} strokeLinejoin="round" />
      <ellipse cx={xt} cy={yc} rx="3" ry={d / 2} fill={FA.ink} />
      {holes && [-1, 1].map((s) => <rect key={s} x={hx - 3} y={s < 0 ? yc - d / 2 - 1 : yc + d / 2 - 5} width="6" height="6" fill={FA.lo} />)}
    </g>
  );
}
// Líneas de corriente que se abren alrededor de la punta (punto de estancamiento)
function StagnationLines({ xt, yc, d = 24, len = 160, color = FA.mut, t = 0 }) {
  const ls = [-2.2, -1.2, 1.2, 2.2].map((k) => {
    const y0 = yc + k * d * 0.45, y1 = yc + k * d * 0.45 + Math.sign(k) * d * 0.9;
    return <path key={k} d={`M${xt - len} ${y0} C${xt - 40} ${y0} ${xt - 20} ${y1} ${xt + 40} ${y1} L${xt + 140} ${y1}`} fill="none" stroke={color} strokeWidth="2.5" strokeDasharray="10 8" strokeDashoffset={-t * 40} />;
  });
  return <g>{ls}<path d={`M${xt - len} ${yc} L${xt - 6} ${yc}`} stroke={FA.hi} strokeWidth="2.5" strokeDasharray="10 8" strokeDashoffset={-t * 40} /><circle cx={xt - 4} cy={yc} r="6" fill={FA.hi} /></g>;
}

// Sonda promediadora (vista lateral, el flujo va a la derecha). Cruza el tubo en xa.
// Orificios de frente (alta, naranja) y atrás (baja, azul) en anillos de igual área.
function AvgProbe({ xa, yc, R, top, w = 30, fill = 1 }) {
  const ports = [-0.866, -0.5, 0.5, 0.866].map((u) => yc + u * R);
  const yb = yc + R + 4;
  return (
    <g>
      <rect x={xa - w / 2} y={top} width={w} height={yb - top} rx="4" fill={FA.ink} />
      <rect x={xa - w / 2 + 3} y={top + 3} width={w / 2 - 4} height={yb - top - 6} fill={FA.hi} opacity={0.35 + 0.65 * fill} />
      <rect x={xa + 1} y={top + 3} width={w / 2 - 4} height={yb - top - 6} fill={FA.lo} opacity={0.35 + 0.65 * fill} />
      {ports.map((y, i) => <g key={i}>
        <rect x={xa - w / 2 - 1} y={y - 4} width="6" height="8" fill="#fff" stroke={FA.hi} strokeWidth="1.5" />
        <rect x={xa + w / 2 - 5} y={y - 4} width="6" height="8" fill="#fff" stroke={FA.lo} strokeWidth="1.5" />
      </g>)}
    </g>
  );
}
// Corte transversal de la barra: 'round' | 'diamond' | 'tee' (el flujo viene de la izquierda)
function ProbeSection({ x, y, kind, s = 34, t = 0 }) {
  const shape = kind === 'round' ? <circle cx={x} cy={y} r={s * 0.5} />
    : kind === 'diamond' ? <path d={`M${x - s * 0.55} ${y} L${x} ${y - s * 0.5} L${x + s * 0.55} ${y} L${x} ${y + s * 0.5} Z`} />
    : <path d={`M${x - s * 0.5} ${y - s * 0.55} H${x - s * 0.2} V${y - s * 0.12} H${x + s * 0.6} V${y + s * 0.12} H${x - s * 0.2} V${y + s * 0.55} H${x - s * 0.5} Z`} />;
  const sep = kind === 'round' ? [x + s * 0.05 + 6 * Math.sin(t * 3), y] : kind === 'diamond' ? [x, y] : [x - s * 0.2, y];
  return <g>
    <g fill="url(#faHatch)" stroke={FA.ink} strokeWidth="2.5">{shape}</g>
    {[-1, 1].map((k) => <circle key={k} cx={sep[0]} cy={y + k * s * (kind === 'tee' ? 0.55 : 0.5)} r="5" fill={kind === 'round' ? FA.bad : FA.ok} />)}
  </g>;
}

// Disco de un ducto con puntos de barrido en anillos de igual área
function TraverseDisk({ cx, cy, Rr, n = 5, t = 0, prog = 1 }) {
  const rings = Array.from({ length: n - 1 }, (_, k) => Rr * Math.sqrt((k + 1) / n));
  const pts = [];
  for (const dir of [[1, 0], [0, 1]]) for (const sg of [-1, 1]) for (let i = n; i >= 1; i--) {
    const r = Rr * Math.sqrt((2 * i - 1) / (2 * n));
    pts.push([cx + sg * dir[0] * r, cy + sg * dir[1] * r]);
  }
  const shown = Math.floor(pts.length * Math.max(0, Math.min(1, prog)));
  return <g>
    <circle cx={cx} cy={cy} r={Rr + 12} fill="url(#faHatch)" stroke={FA.ink} strokeWidth="2.5" />
    <circle cx={cx} cy={cy} r={Rr} fill="url(#faLiq)" stroke={FA.ink} strokeWidth="2" />
    {rings.map((r, k) => <circle key={k} cx={cx} cy={cy} r={r} fill="none" stroke={FA.mut} strokeWidth="1.5" strokeDasharray="6 5" />)}
    <line x1={cx - Rr} y1={cy} x2={cx + Rr} y2={cy} stroke={FA.mut} strokeWidth="1.5" />
    <line x1={cx} y1={cy - Rr} x2={cx} y2={cy + Rr} stroke={FA.mut} strokeWidth="1.5" />
    {pts.map((p, k) => <circle key={k} cx={p[0]} cy={p[1]} r={k < shown ? 8 : 5} fill={k < shown ? FA.hi : '#fff'} stroke={FA.ink} strokeWidth="1.5" />)}
  </g>;
}

// Ensamble de inserción en caliente sobre la tubería: boquilla, válvula de bola,
// prensaestopas y varillas roscadas. ins: 0 (retraída) a 1 (insertada).
function HotTap({ x, yPipe, R, ins = 1, w = 26, valveOpen = true }) {
  const yN = yPipe - R - 14;                 // cara exterior de la tubería
  const nz = yN - 36, vb = nz - 60, pk = vb - 36;
  const tipIns = yPipe + R + 4, headIns = pk - 24, Lp = tipIns - headIns;
  const tipRet = nz - 90, headRet = tipRet - Lp, plate = headRet - 18;
  const tip = tipRet + (tipIns - tipRet) * ins, head = tip - Lp;
  return <g>
    <rect x={x - 26} y={nz} width="52" height={yN - nz + 2} fill="url(#faHatch)" stroke={FA.ink} strokeWidth="2.5" />
    <rect x={x - 42} y={vb} width="84" height="60" rx="8" fill="url(#faHatchP)" stroke={FA.ink} strokeWidth="2.5" />
    <circle cx={x} cy={vb + 30} r="22" fill={FA.steel} stroke={FA.ink} strokeWidth="2" />
    {valveOpen ? <rect x={x - 15} y={vb + 18} width="30" height="24" fill="#fff" stroke={FA.ink} strokeWidth="1.5" /> : <rect x={x - 22} y={vb + 26} width="44" height="8" fill={FA.ink} />}
    <rect x={x + 42} y={vb + 22} width="56" height="14" rx="4" fill={FA.paintD} stroke={FA.ink} strokeWidth="2" />
    <rect x={x - 24} y={pk} width="48" height="36" fill="url(#faHatch)" stroke={FA.ink} strokeWidth="2.5" />
    <rect x={x - 16} y={pk + 6} width="32" height="12" fill="#8a7a62" />
    {[-1, 1].map((sg) => <line key={sg} x1={x + sg * 64} y1={plate} x2={x + sg * 64} y2={vb} stroke={FA.ink} strokeWidth="6" strokeDasharray="3 3" />)}
    <rect x={x - 78} y={vb - 6} width="156" height="10" fill={FA.steelD} stroke={FA.ink} strokeWidth="2" />
    <rect x={x - 78} y={plate - 4} width="156" height="10" fill={FA.steelD} stroke={FA.ink} strokeWidth="2" />
    <rect x={x - 78} y={head} width="156" height="12" fill={FA.steelD} stroke={FA.ink} strokeWidth="2" />
    <rect x={x - w / 2} y={head + 12} width={w} height={tip - head - 12} fill={FA.ink} />
    <rect x={x - w / 2 + 3} y={head + 12} width={w / 2 - 4} height={tip - head - 12} fill={FA.hi} opacity="0.75" />
    <rect x={x + 1} y={head + 12} width={w / 2 - 4} height={tip - head - 12} fill={FA.lo} opacity="0.75" />
    <rect x={x - 38} y={head - 58} width="76" height="56" rx="10" fill={FA.paintL} stroke={FA.ink} strokeWidth="2.5" />
    <rect x={x - 27} y={head - 50} width="54" height="26" rx="4" fill="#f7fbff" stroke={FA.ink} strokeWidth="1.5" />
    <text x={x} y={head - 32} fill={FA.ink} fontFamily={MONO4} fontSize="14" fontWeight="700" textAnchor="middle">FT</text>
  </g>;
}
const hotTapTop = (yPipe, R) => yPipe - 3 * R - 14 - 36 - 90 - (2 * R + 14 + 36 + 60 + 36 + 24 + 4 - R) - 18 - 58;

// Medidor de blanco: disco en el centro, barra que atraviesa un sello flexible hasta la galga
function TargetMeter({ xd, yc, R, wall = 14, rd = 0.42, force = 1, t = 0 }) {
  const h = rd * R, top = yc - R - wall;
  return <g>
    <rect x={xd - 5} y={top - 70} width="10" height={yc - h - top + 70} fill={FA.steelD} stroke={FA.ink} strokeWidth="2" />
    <rect x={xd - 9} y={yc - h} width="18" height={2 * h} rx="3" fill="url(#faHatchT)" stroke={FA.ink} strokeWidth="2.5" />
    <path d={`M${xd - 22} ${top - 6} Q${xd} ${top - 22} ${xd + 22} ${top - 6}`} fill="none" stroke={FA.ink} strokeWidth="5" />
    <rect x={xd - 60} y={top - 150} width="120" height="80" rx="12" fill={FA.paintL} stroke={FA.ink} strokeWidth="2.5" />
    <path d={`M${xd - 26} ${top - 104} l8 -10 l8 20 l8 -20 l8 20 l8 -20 l8 10`} fill="none" stroke={FA.hi} strokeWidth="3" />
    <text x={xd} y={top - 80} fill="#fff" fontFamily={MONO4} fontSize="12" fontWeight="700" textAnchor="middle">GALGA</text>
    <line x1={xd - 70 - 40 * force} y1={yc} x2={xd - 14} y2={yc} stroke={FA.hi} strokeWidth="6" markerEnd="url(#faArrH)" opacity={force > 0 ? 1 : 0} />
  </g>;
}
const targetBoundsTop = (xd, yc, R, rd = 0.42) => (x) => { const k = Math.exp(-(((x - xd) / (0.9 * R)) ** 2)); return [yc - R, yc - rd * R * k - 2]; };
const targetBoundsBot = (xd, yc, R, rd = 0.42) => (x) => { const k = Math.exp(-(((x - xd) / (0.9 * R)) ** 2)); return [yc + rd * R * k + 2, yc + R]; };

Object.assign(window, { hotTapTop, PitotStatic, StagnationLines, AvgProbe, ProbeSection, TraverseDisk, HotTap, TargetMeter, targetBoundsTop, targetBoundsBot });

// ═══ Medidores másicos (Clase 3.4) ═════════════════════════════════════════

// Coriolis de tubo recto en corte. El tubo vibra en su primer modo; con flujo, la fuerza de
// Coriolis agrega el segundo modo (torsión): la entrada se atrasa y la salida se adelanta.
// ph: fase de la vibración (rad); twist: 0 sin flujo … 1 con flujo.
function coriolisY(u, ph, A, twist) {
  return A * Math.sin(ph) * Math.sin(Math.PI * u) + A * 0.45 * twist * Math.cos(ph) * Math.sin(2 * Math.PI * u);
}
function CoriolisMeter({ x1, x2, yc, ph = 0, A = 26, twist = 0, r = 22, showCase = true, glow = 0 }) {
  const L = x2 - x1, N = 60;
  const pts = Array.from({ length: N + 1 }, (_, i) => { const u = i / N; return [x1 + L * u, yc + coriolisY(u, ph, A, twist)]; });
  const d = 'M' + pts.map((p) => `${p[0].toFixed(1)} ${p[1].toFixed(1)}`).join(' L');
  const pk = (u) => [x1 + L * u, yc + coriolisY(u, ph, A, twist)];
  const [ax, ay] = pk(0.25), [bx, by] = pk(0.75), [cx, cy] = pk(0.5);
  return (
    <g>
      {showCase && <rect x={x1 - 20} y={yc - 120} width={L + 40} height="240" rx="26" fill="#f4f7fb" stroke={FA.ink} strokeWidth="3" strokeDasharray="10 6" />}
      <rect x={x1 - 70} y={yc - r - 30} width="54" height={2 * r + 60} fill="url(#faHatch)" stroke={FA.ink} strokeWidth="2.5" />
      <rect x={x2 + 16} y={yc - r - 30} width="54" height={2 * r + 60} fill="url(#faHatch)" stroke={FA.ink} strokeWidth="2.5" />
      <path d={d} fill="none" stroke={FA.ink} strokeWidth={2 * r + 6} strokeLinecap="butt" />
      <path d={d} fill="none" stroke={FA.steel} strokeWidth={2 * r} strokeLinecap="butt" />
      <path d={d} fill="none" stroke="#aed0f4" strokeWidth={2 * r - 10} strokeLinecap="butt" />
      {/* bobina impulsora al centro y sensores en ¼ y ¾ */}
      <rect x={cx - 22} y={yc + 70} width="44" height="34" rx="5" fill={FA.paintD} stroke={FA.ink} strokeWidth="2" />
      <line x1={cx} y1={cy + r} x2={cx} y2={yc + 70} stroke={FA.ink} strokeWidth="5" />
      {[[ax, ay, FA.hi], [bx, by, FA.lo]].map(([x, y, c], k) => <g key={k}>
        <rect x={x - 20} y={yc + 70} width="40" height="34" rx="5" fill={c} stroke={FA.ink} strokeWidth="2" />
        <line x1={x} y1={y + r} x2={x} y2={yc + 70} stroke={FA.ink} strokeWidth="4" strokeDasharray="4 3" />
      </g>)}
    </g>
  );
}
// Osciloscopio con las señales de los dos sensores (entrada naranja, salida azul)
function ScopeTraces({ x, y, w = 520, h = 170, ph = 0, lag = 0, label = true }) {
  const tr = (off, c) => {
    const pts = Array.from({ length: 121 }, (_, i) => { const u = i / 120; return `${(x + w * u).toFixed(1)} ${(y + h / 2 - (h * 0.38) * Math.sin(u * 4 * Math.PI - ph + off)).toFixed(1)}`; });
    return <path d={'M' + pts.join(' L')} fill="none" stroke={c} strokeWidth="4" />;
  };
  const z = (k) => x + w * ((((ph + lag / 2) / (4 * Math.PI)) % 0.5 + 0.5) % 0.5 + k * 0.5); // cruce por cero aprox.
  return <g>
    <rect x={x - 12} y={y - 12} width={w + 24} height={h + 24} rx="12" fill={FA.ink} />
    {[0.25, 0.5, 0.75].map((k) => <line key={k} x1={x} y1={y + h * k} x2={x + w} y2={y + h * k} stroke="#24476e" strokeWidth="1" />)}
    {tr(lag / 2, FA.hi)}{tr(-lag / 2, '#6fb4ff')}
    {label && <text x={x + 8} y={y + 18} fill="#9fc2e8" fontFamily={MONO4} fontSize="14">entrada · salida</text>}
  </g>;
}

// Sonda térmica en un tubo de gas: sensor de referencia (azul) y sensor calentado (rojo).
// heat: 0..1 potencia; t para las estelas de calor.
function ThermalProbe({ xs, yc, R, top, t = 0, flow = 1, heat = 1 }) {
  const yTip = yc + 10, gap = 34;
  const plume = Array.from({ length: 10 }, (_, k) => {
    const ph = ((t * 0.6 * (0.4 + flow) + k / 10) % 1);
    return <circle key={k} cx={xs + gap / 2 + 14 + ph * 260 * (0.3 + flow)} cy={yTip + 40 + Math.sin(k * 1.7) * 10} r={6 - 4 * ph} fill={FA.bad} opacity={(1 - ph) * 0.55 * heat} />;
  });
  return <g>
    <rect x={xs - 22} y={top} width="44" height={yc - top - 40} fill="url(#faHatch)" stroke={FA.ink} strokeWidth="2.5" />
    <rect x={xs - 22} y={yc - 40} width="44" height="14" fill={FA.steelD} stroke={FA.ink} strokeWidth="2" />
    {plume}
    <rect x={xs - gap / 2 - 5} y={yc - 26} width="10" height="76" rx="5" fill={FA.lo} stroke={FA.ink} strokeWidth="2" />
    <rect x={xs + gap / 2 - 5} y={yc - 26} width="10" height="76" rx="5" fill={FA.bad} stroke={FA.ink} strokeWidth="2" opacity={0.5 + 0.5 * heat} />
  </g>;
}

Object.assign(window, { coriolisY, CoriolisMeter, ScopeTraces, ThermalProbe });

// ═══ Magnético y ultrasónico (Clase 3.5) ═══════════════════════════════════

// Vista de frente del magnético: bobinas arriba y abajo (campo vertical), electrodos a los lados.
// El flujo entra a la pantalla (⊗). Las cargas se separan hacia los electrodos.
function MagEndView({ cx, cy, r = 200, t = 0, B = 1, sep = 1, liner = '#3a3f47' }) {
  const k = r / 200, cw = 1.2 * r, chh = 0.35 * r;
  const ch = Array.from({ length: 16 }, (_, i) => {
    const pos = i % 2 ? 1 : -1;            // + a la derecha, − a la izquierda
    const y0 = cy + (((i * 0.37) % 1) - 0.5) * r * 1.3;
    const drift = sep * (0.25 + 0.7 * (((t * 0.35 + i * 0.13) % 1)));
    const x = cx + pos * drift * r * 0.8 * Math.sqrt(Math.max(0, 1 - ((y0 - cy) / r) ** 2));
    return <g key={i}><circle cx={x} cy={y0} r={11 * k} fill={pos > 0 ? FA.hi : FA.lo} opacity="0.85" />{k > 0.6 && <text x={x} y={y0 + 5} fill="#fff" fontFamily={MONO4} fontSize="15" fontWeight="700" textAnchor="middle">{pos > 0 ? '+' : '−'}</text>}</g>;
  });
  return <g>
    {[-1, 1].map((sg) => { const y0 = sg < 0 ? cy - r - 0.55 * r : cy + r + 0.2 * r; return <g key={sg}>
      <rect x={cx - cw / 2} y={y0} width={cw} height={chh} rx={10 * k} fill={FA.paintD} stroke={FA.ink} strokeWidth="2.5" />
      {Array.from({ length: 9 }, (_, i) => <line key={i} x1={cx - cw / 2 + cw * (i + 0.8) / 9.6} y1={y0 + 6 * k} x2={cx - cw / 2 + cw * (i + 0.8) / 9.6} y2={y0 + chh - 6 * k} stroke="#c9631c" strokeWidth={Math.max(2, 5 * k)} />)}
    </g>; })}
    <circle cx={cx} cy={cy} r={r + 26 * k} fill="url(#faHatch)" stroke={FA.ink} strokeWidth="3" />
    <circle cx={cx} cy={cy} r={r + 6 * k} fill={liner} />
    <circle cx={cx} cy={cy} r={r} fill="url(#faLiq)" stroke={FA.ink} strokeWidth="2" />
    <g opacity={B}>{[-0.6, -0.3, 0, 0.3, 0.6].map((u) => <line key={u} x1={cx + u * r} y1={cy - r * Math.sqrt(1 - u * u) - 20 * k} x2={cx + u * r} y2={cy + r * Math.sqrt(1 - u * u) + 20 * k} stroke={FA.paintD} strokeWidth="2.5" strokeDasharray="10 8" strokeDashoffset={-t * 20} markerEnd={k > 0.6 ? 'url(#faArr)' : undefined} />)}</g>
    {[[-0.55, -0.45], [0.5, 0.5], [-0.15, 0.62], [0.2, -0.6]].map(([u, v], i) => <g key={i} opacity="0.55"><circle cx={cx + u * r} cy={cy + v * r} r={13 * k} fill="none" stroke={FA.ink} strokeWidth="2" /><path d={`M${cx + u * r - 8 * k} ${cy + v * r - 8 * k} l${16 * k} ${16 * k} M${cx + u * r + 8 * k} ${cy + v * r - 8 * k} l${-16 * k} ${16 * k}`} stroke={FA.ink} strokeWidth="2" /></g>)}
    {ch}
    {[-1, 1].map((sg) => <rect key={sg} x={sg < 0 ? cx - r - 26 * k : cx + r - 10 * k} y={cy - 9 * k} width={36 * k} height={18 * k} fill={FA.steelD} stroke={FA.ink} strokeWidth="2" />)}
  </g>;
}
// Magnético de lado, entre bridas, con revestimiento, bobinas, electrodo y anillos de tierra
function MagSideView({ x0, yc, R, L = 300, t = 0, rings = true, tx = true }) {
  const x1 = x0 - L / 2, x2 = x0 + L / 2;
  return <g>
    <rect x={x1} y={yc - R - 60} width={L} height={2 * R + 120} rx="18" fill={FA.paintL} stroke={FA.ink} strokeWidth="2.5" />
    {[-1, 1].map((s) => <rect key={s} x={x0 - 80} y={s < 0 ? yc - R - 52 : yc + R + 16} width="160" height="36" rx="6" fill={FA.paintD} stroke={FA.ink} strokeWidth="2" />)}
    <rect x={x1} y={yc - R - 12} width={L} height="12" fill="#3a3f47" />
    <rect x={x1} y={yc + R} width={L} height="12" fill="#3a3f47" />
    <rect x={x1} y={yc - R} width={L} height={2 * R} fill="url(#faLiq)" />
    <circle cx={x0} cy={yc} r="12" fill={FA.steelD} stroke={FA.ink} strokeWidth="2" />
    {rings && [x1 - 6, x2].map((x) => <rect key={x} x={x} y={yc - R - 30} width="6" height={2 * R + 60} fill={FA.ok} stroke={FA.ink} strokeWidth="1.5" />)}
    {tx && <g><rect x={x0 - 16} y={yc - R - 92} width="32" height="32" fill={FA.steelD} stroke={FA.ink} strokeWidth="2" />
      <rect x={x0 - 70} y={yc - R - 176} width="140" height="86" rx="14" fill={FA.paintL} stroke={FA.ink} strokeWidth="2.5" />
      <rect x={x0 - 56} y={yc - R - 164} width="112" height="40" rx="5" fill="#f7fbff" stroke={FA.ink} strokeWidth="1.5" />
      <text x={x0} y={yc - R - 137} fill={FA.ink} fontFamily={MONO4} fontSize="17" fontWeight="700" textAnchor="middle">FT</text></g>}
  </g>;
}

// Ultrasónico de tiempo de tránsito: transductores en (xa, arriba) y (xb, abajo).
// Dos pulsos: uno a favor (naranja) y otro en contra (azul).
function TransitPath({ xa, xb, yc, R, wall = 14, t = 0, period = 2.2, clamp = false }) {
  const ya = yc - R, yb = yc + R;
  const k = ((t / period) % 1);
  const pa = [xa + (xb - xa) * k, ya + (yb - ya) * k], pb = [xb + (xa - xb) * Math.min(1, k * 1.04), yb + (ya - yb) * Math.min(1, k * 1.04)];
  const tr = (x, y, s) => clamp
    ? <g><rect x={x - 26} y={s < 0 ? y - wall - 38 : y + wall} width="52" height="38" rx="6" fill={FA.paintD} stroke={FA.ink} strokeWidth="2" /></g>
    : <g transform={`rotate(${s < 0 ? -40 : 140} ${x} ${y})`}><rect x={x - 18} y={y - 52} width="36" height="56" rx="5" fill={FA.paintD} stroke={FA.ink} strokeWidth="2" /><rect x={x - 18} y={y - 4} width="36" height="8" fill={FA.hi} /></g>;
  return <g>
    <line x1={xa} y1={ya} x2={xb} y2={yb} stroke={FA.mut} strokeWidth="2" strokeDasharray="8 6" />
    <circle cx={pa[0]} cy={pa[1]} r="10" fill={FA.hi} opacity={k < 0.98 ? 0.95 : 0} />
    <circle cx={pb[0]} cy={pb[1]} r="10" fill={FA.lo} opacity={k < 0.94 ? 0.95 : 0} />
    {tr(xa, ya, -1)}{tr(xb, yb, 1)}
  </g>;
}
// Corte transversal con n cuerdas de medición
function ChordDisk({ cx, cy, r = 110, n = 4, t = 0 }) {
  const ys = n === 1 ? [0] : n === 2 ? [-0.5, 0.5] : [-0.81, -0.31, 0.31, 0.81];
  return <g>
    <circle cx={cx} cy={cy} r={r + 12} fill="url(#faHatch)" stroke={FA.ink} strokeWidth="2.5" />
    <circle cx={cx} cy={cy} r={r} fill="url(#faLiq)" stroke={FA.ink} strokeWidth="2" />
    {ys.map((u) => { const w = r * Math.sqrt(1 - u * u); const y = cy + u * r; return <g key={u}>
      <line x1={cx - w} y1={y} x2={cx + w} y2={y} stroke={FA.hi} strokeWidth="3" strokeDasharray="8 5" strokeDashoffset={-t * 30} />
      <rect x={cx - w - 14} y={y - 8} width="14" height="16" fill={FA.paintD} /><rect x={cx + w} y={y - 8} width="14" height="16" fill={FA.paintD} />
    </g>; })}
  </g>;
}
// Doppler: un transductor emite y recibe; el eco de las partículas regresa con otra frecuencia
function DopplerView({ x, yc, R, wall = 14, t = 0 }) {
  const y0 = yc - R - wall;
  const arcs = Array.from({ length: 5 }, (_, k) => { const ph = ((t * 0.7 + k / 5) % 1); const rr = 20 + ph * 170; return <path key={k} d={`M${x - rr * 0.5} ${y0 + rr * 0.6} A${rr} ${rr} 0 0 0 ${x + rr * 0.75} ${y0 + rr * 0.45}`} fill="none" stroke={FA.hi} strokeWidth="2.5" opacity={1 - ph} />; });
  const back = Array.from({ length: 4 }, (_, k) => { const ph = ((t * 0.7 + k / 4 + 0.1) % 1); const rr = 150 - ph * 130; return <path key={k} d={`M${x - rr * 0.4} ${y0 + rr * 0.7} A${rr} ${rr} 0 0 1 ${x + rr * 0.6} ${y0 + rr * 0.55}`} fill="none" stroke={FA.lo} strokeWidth="2" strokeDasharray="4 4" opacity={0.3 + 0.7 * (1 - ph)} />; });
  return <g>{arcs}{back}
    <g transform={`rotate(-30 ${x} ${y0})`}><rect x={x - 24} y={y0 - 48} width="48" height="50" rx="6" fill={FA.paintD} stroke={FA.ink} strokeWidth="2" /></g>
  </g>;
}

Object.assign(window, { MagEndView, MagSideView, TransitPath, ChordDisk, DopplerView });

// ═══ Vortex, turbina y desplazamiento positivo (Clase 3.6) ═════════════════

// Vista superior: cuerpo generador (trapecio) y calle de remolinos alternados
function VortexStreet({ xb, yc, R, t = 0, v = 1, d = 34, n = 7, op = 1, xmax = 1e9 }) {
  const lam = 4.4 * d, speed = 60 * v;
  const ed = [];
  for (let k = 0; k < n; k++) {
    for (const side of [-1, 1]) {
      const x = xb + d + ((t * speed + k * lam + (side > 0 ? lam / 2 : 0)) % (n * lam));
      if (x > xb + d + n * lam - 30 || x > xmax) continue;
      const grow = Math.min(1, (x - xb - d) / (lam * 0.6));
      const rr = 10 + 18 * grow;
      ed.push(<g key={`${k}${side}`} opacity={op * (1 - (x - xb) / (n * lam + 60)) }>
        <circle cx={x} cy={yc + side * d * 0.55} r={rr} fill="none" stroke={side < 0 ? FA.hi : FA.lo} strokeWidth="3" strokeDasharray="12 6" strokeDashoffset={side * t * 60} />
        <circle cx={x} cy={yc + side * d * 0.55} r="3" fill={side < 0 ? FA.hi : FA.lo} />
      </g>);
    }
  }
  return <g>
    {ed}
    <path d={`M${xb - d * 0.4} ${yc - d * 0.8} L${xb + d * 0.6} ${yc - d * 0.55} L${xb + d * 0.6} ${yc + d * 0.55} L${xb - d * 0.4} ${yc + d * 0.8} Z`} fill="url(#faHatchT)" stroke={FA.ink} strokeWidth="2.5" strokeLinejoin="round" />
  </g>;
}

// Turbina en corte: cubo con rotor helicoidal, enderezadores y captador magnético arriba
function TurbineMeter({ x0, yc, R, t = 0, rps = 1, N = 6 }) {
  const ph = t * rps * 2 * Math.PI;
  const hub = R * 0.32, bw = R * 0.5;
  const blades = Array.from({ length: N }, (_, k) => {
    const a = ph + k * 2 * Math.PI / N, sy = Math.sin(a), front = Math.cos(a) > 0;
    const yTip = yc - (hub + (R * 0.92 - hub)) * sy, yRoot = yc - hub * sy;
    const sk = 0.35 * bw;
    return { front, el: <path key={k} d={`M${x0 - bw / 2} ${yRoot} L${x0 + bw / 2} ${yRoot} L${x0 + bw / 2 - sk} ${yTip} L${x0 - bw / 2 - sk} ${yTip} Z`} fill={front ? FA.steel : '#c3ccd6'} stroke={FA.ink} strokeWidth="2" opacity={front ? 1 : 0.6} /> };
  });
  const vanes = (x) => [-1, 1].map((s) => <rect key={`${x}${s}`} x={x - 30} y={s < 0 ? yc - R : yc + hub} width="60" height={R - hub} fill="url(#faHatchT)" stroke={FA.ink} strokeWidth="1.5" opacity="0.9" />);
  return <g>
    {blades.filter((b) => !b.front).map((b) => b.el)}
    {vanes(x0 - R * 1.25)}{vanes(x0 + R * 1.25)}
    <rect x={x0 - R * 1.6} y={yc - hub} width={R * 3.2} height={2 * hub} rx={hub} fill="url(#faHatch)" stroke={FA.ink} strokeWidth="2.5" />
    {blades.filter((b) => b.front).map((b) => b.el)}
    <rect x={x0 - 16} y={yc - R - 70} width="32" height="56" fill={FA.paintD} stroke={FA.ink} strokeWidth="2" />
    {Array.from({ length: 5 }, (_, i) => <line key={i} x1={x0 - 16} y1={yc - R - 64 + i * 10} x2={x0 + 16} y2={yc - R - 64 + i * 10} stroke="#c9631c" strokeWidth="3" />)}
  </g>;
}
// Tren de pulsos (pickup)
function PulseTrain({ x, y, w = 420, h = 70, t = 0, f = 3, color = FA.hi }) {
  const pts = [];
  const per = w / (f * 2);
  for (let i = 0; i <= 2 * f * 2; i++) {
    const xs = x + i * per / 2 - ((t * 80) % per);
    const hi = Math.floor(i / 1) % 2 === 0;
    pts.push([xs, hi ? y : y + h]);
  }
  let d = `M${x} ${y + h}`;
  for (let k = 0; k < 40; k++) {
    const x0 = x + k * per - ((t * 80) % (2 * per));
    if (x0 > x + w) break;
    const xa = Math.max(x, x0), xb = Math.min(x + w, x0 + per);
    if (xb <= x) continue;
    d += k % 2 === 0 ? ` L${xa} ${y + h} L${xa} ${y} L${xb} ${y} L${xb} ${y + h}` : ` L${xb} ${y + h}`;
  }
  return <g><rect x={x - 10} y={y - 14} width={w + 20} height={h + 28} rx="10" fill={FA.ink} /><path d={d} fill="none" stroke={color} strokeWidth="3.5" /></g>;
}

// Engranes ovalados en su cámara. Giran y atrapan volúmenes fijos.
function OvalGears({ cx, cy, a = 90, b = 56, t = 0, speed = 0.5 }) {
  const th = t * speed * 2 * Math.PI;
  const sp = a + b, xa = cx - sp / 2, xb = cx + sp / 2;
  // ángulo del engrane B para que los dos óvalos sigan en contacto sobre la línea de centros
  const rr = (u) => a * b / Math.sqrt((b * Math.cos(u)) ** 2 + (a * Math.sin(u)) ** 2);
  const uu = ((th % Math.PI) + Math.PI) % Math.PI;
  const rB = sp - rr(uu), cc = Math.sqrt(Math.max(0, Math.min(1, (a * a * b * b / (rB * rB) - a * a) / (b * b - a * a))));
  const phB = uu < Math.PI / 2 ? Math.acos(cc) : -Math.acos(cc);
  const teeth = (gx, ang) => Array.from({ length: 20 }, (_, k) => { const u = k / 20 * 2 * Math.PI; const px = a * Math.cos(u), py = b * Math.sin(u); const c = Math.cos(ang), s = Math.sin(ang); return <circle key={k} cx={gx + px * c - py * s} cy={cy + px * s + py * c} r="5" fill={FA.steelD} />; });
  const gear = (gx, ang, fill) => <g>
    {teeth(gx, ang)}
    <ellipse cx={gx} cy={cy} rx={a} ry={b} transform={`rotate(${ang * 180 / Math.PI} ${gx} ${cy})`} fill={fill} stroke={FA.ink} strokeWidth="2.5" />
    <circle cx={gx} cy={cy} r="9" fill={FA.ink} />
  </g>;
  return <g>
    <path d={`M${xa} ${cy - a - 14} A${a + 14} ${a + 14} 0 0 0 ${xa} ${cy + a + 14} L${xb} ${cy + a + 14} A${a + 14} ${a + 14} 0 0 0 ${xb} ${cy - a - 14} Z`} fill="url(#faHatch)" stroke={FA.ink} strokeWidth="2.5" />
    <path d={`M${xa} ${cy - a - 2} A${a + 2} ${a + 2} 0 0 0 ${xa} ${cy + a + 2} L${xb} ${cy + a + 2} A${a + 2} ${a + 2} 0 0 0 ${xb} ${cy - a - 2} Z`} fill="#e9c98a" />
    {gear(xa, th, 'url(#faHatchT)')}
    {gear(xb, phB, 'url(#faHatchT)')}
  </g>;
}

// Rotámetro: tubo cónico de vidrio con flotador
function Rotameter({ x, yTop, h = 420, pos = 0.5, wTop = 70, wBot = 34 }) {
  const yb = yTop + h, yf = yb - 20 - pos * (h - 60);
  const wAt = (y) => wBot + (wTop - wBot) * (yb - y) / h;
  return <g>
    <rect x={x - wTop / 2 - 28} y={yTop - 30} width={wTop + 56} height="30" fill="url(#faHatch)" stroke={FA.ink} strokeWidth="2.5" />
    <rect x={x - wTop / 2 - 28} y={yb} width={wTop + 56} height="30" fill="url(#faHatch)" stroke={FA.ink} strokeWidth="2.5" />
    <path d={`M${x - wTop / 2} ${yTop} L${x + wTop / 2} ${yTop} L${x + wBot / 2} ${yb} L${x - wBot / 2} ${yb} Z`} fill="#eaf5ff" stroke={FA.ink} strokeWidth="2.5" />
    {Array.from({ length: 11 }, (_, i) => { const y = yb - 20 - i * (h - 60) / 10; return <g key={i}><line x1={x + wAt(y) / 2 + 4} y1={y} x2={x + wAt(y) / 2 + (i % 5 === 0 ? 22 : 12)} y2={y} stroke={FA.ink} strokeWidth="2" />{i % 5 === 0 && <text x={x + wAt(y) / 2 + 28} y={y + 6} fill={FA.mut} fontFamily={MONO4} fontSize="15">{i * 10}</text>}</g>; })}
    <path d={`M${x - wAt(yf) / 2 + 3} ${yf} L${x + wAt(yf) / 2 - 3} ${yf} L${x + 8} ${yf + 30} L${x - 8} ${yf + 30} Z`} fill={FA.hi} stroke={FA.ink} strokeWidth="2" />
    <line x1={x - wAt(yf) / 2 - 10} y1={yf} x2={x + wAt(yf) / 2 + 10} y2={yf} stroke={FA.bad} strokeWidth="2" strokeDasharray="4 3" />
  </g>;
}

Object.assign(window, { VortexStreet, TurbineMeter, PulseTrain, OvalGears, Rotameter });

// ═══ Canal abierto y medición fiscal (Clase 3.7) ═══════════════════════════

// Vertedero en corte lateral: el agua sube aguas arriba de la placa y cae en lámina.
// (xw, yb) = pie de la placa; P = altura de la cresta; h = carga sobre la cresta.
function WeirSide({ xw, yb, P = 150, h = 90, x1, x2, t = 0 }) {
  const yCrest = yb - P, yS = yCrest - h;
  const nappe = `M${xw} ${yS + h * 0.15} Q${xw + h * 1.1} ${yS + h * 0.2} ${xw + h * 1.4} ${yb - 10} L${xw + h * 0.9} ${yb - 10} Q${xw + h * 0.6} ${yCrest + 6} ${xw + 4} ${yCrest + 2} Z`;
  const ripples = Array.from({ length: 6 }, (_, k) => { const p = ((t * 0.25 + k / 6) % 1); return <line key={k} x1={x1 + 20 + p * (xw - x1 - 60)} y1={yS + 8} x2={x1 + 50 + p * (xw - x1 - 60)} y2={yS + 8} stroke="#fff" strokeWidth="3" opacity={0.7 * (1 - p)} />; });
  return <g>
    <rect x={x1} y={yS} width={xw - x1} height={yb - yS} fill="url(#faLiq)" />
    <rect x={xw + 6} y={yb - 22} width={x2 - xw - 6} height="22" fill="url(#faLiq)" />
    <path d={nappe} fill="#aed0f4" opacity="0.95" />
    {ripples}
    <rect x={x1} y={yb} width={x2 - x1} height="20" fill="url(#faHatch)" stroke={FA.ink} strokeWidth="2.5" />
    <rect x={xw - 6} y={yCrest} width="12" height={P} fill="url(#faHatchT)" stroke={FA.ink} strokeWidth="2.5" />
  </g>;
}
// Vertedero en V visto de frente
function VNotchFront({ cx, yCrest, h = 70, w = 300, H = 160, fill = true }) {
  return <g>
    {fill && <path d={`M${cx - h} ${yCrest - h} L${cx} ${yCrest} L${cx + h} ${yCrest - h} Z`} fill="url(#faLiq)" />}
    <path d={`M${cx - w / 2} ${yCrest - h - 40} L${cx - h - 40} ${yCrest - h - 40} L${cx} ${yCrest} L${cx + h + 40} ${yCrest - h - 40} L${cx + w / 2} ${yCrest - h - 40} L${cx + w / 2} ${yCrest + H} L${cx - w / 2} ${yCrest + H} Z`} fill="url(#faHatchT)" stroke={FA.ink} strokeWidth="2.5" strokeLinejoin="round" />
  </g>;
}
// Canal Parshall en planta
function ParshallPlan({ x, y, s = 1, t = 0 }) {
  const W = 60 * s, B = 180 * s, L1 = 260 * s, Lt = 90 * s, L2 = 200 * s, D = 130 * s;
  const pts = [[x, y - B / 2], [x + L1, y - W / 2], [x + L1 + Lt, y - W / 2], [x + L1 + Lt + L2, y - D / 2], [x + L1 + Lt + L2, y + D / 2], [x + L1 + Lt, y + W / 2], [x + L1, y + W / 2], [x, y + B / 2]];
  const dots = Array.from({ length: 14 }, (_, k) => { const p = ((t * 0.2 + k / 14) % 1); const xx = x + p * (L1 + Lt + L2); const half = xx < x + L1 ? faLerp(B / 2, W / 2, (xx - x) / L1) : xx < x + L1 + Lt ? W / 2 : faLerp(W / 2, D / 2, (xx - x - L1 - Lt) / L2); return <circle key={k} cx={xx} cy={y + (((k * 0.618) % 1) - 0.5) * 1.6 * half} r={4} fill={FA.dot} opacity="0.8" />; });
  return <g>
    <path d={faPoly(pts)} fill="url(#faLiq)" stroke={FA.ink} strokeWidth="5" strokeLinejoin="round" />
    {dots}
    <circle cx={x + L1 * 0.67} cy={y - faLerp(B / 2, W / 2, 0.67) - 26} r="14" fill="#fff" stroke={FA.ink} strokeWidth="2.5" />
    <line x1={x + L1 * 0.67} y1={y - faLerp(B / 2, W / 2, 0.67) - 12} x2={x + L1 * 0.67} y2={y - faLerp(B / 2, W / 2, 0.67)} stroke={FA.ink} strokeWidth="2.5" />
  </g>;
}
// Sensor de nivel sin contacto (radar o ultrasonido) con su haz
function LevelSensor({ x, yTop, ySurf, t = 0 }) {
  const arcs = Array.from({ length: 4 }, (_, k) => { const p = ((t * 0.8 + k / 4) % 1); const yy = yTop + 40 + p * (ySurf - yTop - 40); const w = 14 + p * 40; return <path key={k} d={`M${x - w} ${yy} Q${x} ${yy + 12} ${x + w} ${yy}`} fill="none" stroke={FA.hi} strokeWidth="2.5" opacity={1 - p} />; });
  return <g>{arcs}
    <rect x={x - 30} y={yTop} width="60" height="40" rx="8" fill={FA.paintL} stroke={FA.ink} strokeWidth="2.5" />
    <path d={`M${x - 18} ${yTop + 40} L${x + 18} ${yTop + 40} L${x + 26} ${yTop + 58} L${x - 26} ${yTop + 58} Z`} fill={FA.steelD} stroke={FA.ink} strokeWidth="2" />
  </g>;
}

// Probador de esfera (bidireccional) visto en planta: la esfera recorre un volumen
// calibrado entre dos detectores. k: 0..1 posición de la esfera.
function BallProver({ x1, x2, y, R = 26, k = 0.5 }) {
  const loopH = 150, xa = x1 + 140, xb = x2 - 140;
  const path = `M${x1} ${y} H${xa} V${y - loopH} H${xb} V${y} H${x2}`;
  const L = (xb - xa) + 2 * loopH, d = k * L;
  const pos = d < loopH ? [xa, y - d] : d < loopH + (xb - xa) ? [xa + d - loopH, y - loopH] : [xb, y - loopH + (d - loopH - (xb - xa))];
  const det = (px, py) => <g><rect x={px - 10} y={py - R - 30} width="20" height="30" fill={FA.bad} stroke={FA.ink} strokeWidth="2" /></g>;
  return <g>
    <path d={path} fill="none" stroke={FA.ink} strokeWidth={2 * R + 8} strokeLinejoin="round" />
    <path d={path} fill="none" stroke="#e9c98a" strokeWidth={2 * R - 2} strokeLinejoin="round" />
    {det(xa + 90, y - loopH)}{det(xb - 90, y - loopH)}
    <circle cx={pos[0]} cy={pos[1]} r={R - 4} fill={FA.paintD} stroke={FA.ink} strokeWidth="2" />
  </g>;
}

Object.assign(window, { WeirSide, VNotchFront, ParshallPlan, LevelSensor, BallProver });
