// vc-art.jsx — Dibujos en corte para el curso «Válvulas de control».
// Carga después de valve-lib.jsx y de ../../premium/modulo-1-fundamentos/pf-valves.jsx.
// Aplica el código de color del curso a la biblioteca de dibujos:
//   fluido = azul · aire e instrumentación = naranja · fuerza y mecánica (piezas móviles) = ámbar.
// Y agrega piezas propias del curso (accesorios del montaje, tubería en corte).

Object.assign(VA, {
  air: '#ffb27a', airD: SL.cc,            // aire de instrumentos: naranja del curso
  move: '#e8a93a', moveD: SL.sunD,        // piezas móviles: ámbar del curso
  spring: SL.sunD,
});

// Tramo de tubería en corte (paredes rayadas y fluido) de x1 a x2, centrado en y, con diámetro interior d
function PipeCut({ x1, x2, y, d = 60, wall = 12, t = 0, speed = 40, flow = true }) {
  const w = x2 - x1, h = d / 2;
  return (
    <g>
      <rect x={x1} y={y - h - wall} width={w} height={wall} fill="url(#vaHatch)" stroke={VA.ink} strokeWidth="2.5" />
      <rect x={x1} y={y + h} width={w} height={wall} fill="url(#vaHatch)" stroke={VA.ink} strokeWidth="2.5" />
      <rect x={x1} y={y - h} width={w} height={d} fill="url(#vaLiq)" />
      {flow && <line x1={x1} y1={y} x2={x2} y2={y} stroke="#ffffff" strokeWidth="5" strokeDasharray="4 22" strokeLinecap="round" strokeDashoffset={-t * speed} opacity="0.85" />}
    </g>
  );
}

// Caja de accesorio con su tag (coordenadas de pantalla)
function AccBox({ x, y, w = 130, h = 70, tag, sub, color = SL.cc }) {
  return (
    <g>
      <rect x={x} y={y} width={w} height={h} rx="10" fill={SL.paper} stroke={color} strokeWidth="3" />
      <text x={x + w / 2} y={y + h / 2 + (sub ? -2 : 8)} fill={SL.ink} fontFamily={MONO} fontSize="22" fontWeight="700" textAnchor="middle">{tag}</text>
      {sub && <text x={x + w / 2} y={y + h / 2 + 22} fill={SL.mut} fontFamily={DISP} fontSize="15" textAnchor="middle">{sub}</text>}
    </g>
  );
}

// Solo las capas pedidas del ensamble de globo (para armarlo por partes)
const VC_PARTS = ['body', 'seat', 'cage', 'plug', 'stem', 'bonnet', 'yoke', 'actuator'];
const vcOnly = (keys) => Object.fromEntries(VC_PARTS.map((k) => [k, keys.includes(k)]));

// ── Piezas del Módulo 2 (desempeño) ─────────────────────────────────────────

// Contorno de una rueda dentada: dientes de rIn a rOut (si rOut < rIn, dientes hacia adentro)
function gearPts(rIn, rOut, n, frac, phase = 0) {
  const pts = [], step = 360 / n, half = frac * step / 2;
  const P = (r, a) => `${(r * Math.cos(a * Math.PI / 180)).toFixed(1)} ${(r * Math.sin(a * Math.PI / 180)).toFixed(1)}`;
  for (let i = 0; i < n; i++) {
    const c = phase + i * step;
    pts.push(P(rIn, c - half - 2), P(rOut, c - half), P(rOut, c + half), P(rIn, c + half + 2));
  }
  return 'M ' + pts.join(' L ') + ' Z';
}

// Acople estriado en corte: el eje del disco dentro del cubo de la palanca.
// hub y shaft: ángulos en grados. Con 10 estrías la holgura total es de unos 9°.
function SplineCoupling({ hub = 0, shaft = 0, worn = true }) {
  const frac = worn ? 0.36 : 0.47;
  return (
    <g>
      <g transform={`rotate(${hub})`}>
        <rect x="-26" y="-330" width="52" height="170" rx="10" fill="url(#vaHatchP)" stroke={VA.ink} strokeWidth="4" />
        <circle cx="0" cy="-310" r="13" fill={VA.ink} />
        <path d={`M 0 -178 A 178 178 0 1 1 -0.1 -178 Z ${gearPts(130, 100, 10, frac, 18)}`} fill="url(#vaHatchP)" fillRule="evenodd" stroke={VA.ink} strokeWidth="4" />
      </g>
      <g transform={`rotate(${shaft})`}>
        <path d={gearPts(94, 124, 10, frac, 0)} fill="url(#vaHatchM)" stroke={VA.ink} strokeWidth="4" />
        <circle cx="0" cy="0" r="58" fill="url(#vaHatchM)" stroke={VA.ink} strokeWidth="2" />
        <line x1="0" y1="-40" x2="0" y2="40" stroke={VA.ink} strokeWidth="6" />
        <circle cx="0" cy="-70" r="9" fill={VA.hot} />
      </g>
    </g>
  );
}

// Actuador de pistón de doble efecto sobre el yugo de GlobeAssembly (mismas coordenadas locales).
// L: carrera en unidades locales (0 a LIFT). airTop y airBot: presión en cada cámara (0 a 1).
function PistonTop({ L = 55, airTop = 0.5, airBot = 0.5 }) {
  const py = -1000 - L;
  return (
    <g>
      <rect x="-15" y={py} width="30" height={350} fill="url(#vaShaft)" stroke={VA.ink} strokeWidth="3" />
      <rect x="-180" y="-1170" width="360" height="380" rx="8" fill="url(#vaHatchP)" stroke={VA.ink} strokeWidth="4" />
      <rect x="-150" y="-1140" width="300" height={py - 20 - (-1140)} fill={VA.air} opacity={0.12 + 0.78 * airTop} />
      <rect x="-150" y={py + 22} width="300" height={-820 - (py + 22)} fill={VA.air} opacity={0.12 + 0.78 * airBot} />
      <rect x="-150" y={py - 20} width="300" height="42" rx="5" fill="url(#vaHatchM)" stroke={VA.ink} strokeWidth="4" />
      <rect x="-150" y={py - 6} width="300" height="8" fill={VA.gasket} />
      {[[-1120, airTop], [-850, airBot]].map(([y, a]) => <rect key={y} x="180" y={y} width="60" height="18" fill="#7b8794" stroke={VA.ink} strokeWidth="2" />)}
    </g>
  );
}

// Booster de volumen en corte (coordenadas locales: x de -230 a 230, y de -230 a 230).
// sig y out: presión de la señal y de la salida (0 a 1); flow: de -1 (escape) a 1 (alimentación).
function BoosterArt({ sig = 0.5, out = 0.5, flow = 0, t = 0, bypass = 0.3 }) {
  const dy = 14 * clampV(flow, -1, 1); // el diafragma baja al llenar y sube al escapar
  const supply = flow > 0.05, exhaust = flow < -0.05;
  return (
    <g>
      <rect x="-170" y="-220" width="340" height="440" rx="16" fill="url(#vaHatch)" stroke={VA.ink} strokeWidth="5" />
      {/* cámara de señal */}
      <rect x="-130" y="-190" width="260" height={70 + dy} fill={VA.air} opacity={0.12 + 0.8 * sig} />
      <path d={`M -130 ${-120 + dy} Q 0 ${-108 + dy} 130 ${-120 + dy}`} stroke={VA.gasket} strokeWidth="7" fill="none" />
      {/* cámara de salida */}
      <rect x="-130" y={-104 + dy} width="260" height={120 - dy} fill={VA.air} opacity={0.12 + 0.8 * out} />
      {/* cámara de alimentación */}
      <rect x="-130" y="40" width="260" height="90" fill={VA.air} opacity="0.85" />
      {/* asiento y válvula de alimentación (poppet) */}
      <rect x="-130" y="18" width="95" height="22" fill="url(#vaHatchT)" stroke={VA.ink} strokeWidth="2" />
      <rect x="35" y="18" width="95" height="22" fill="url(#vaHatchT)" stroke={VA.ink} strokeWidth="2" />
      <path d={`M -34 ${42 + Math.max(0, dy) * 1.4} L 34 ${42 + Math.max(0, dy) * 1.4} L 20 ${70 + Math.max(0, dy) * 1.4} L -20 ${70 + Math.max(0, dy) * 1.4} Z`} fill="url(#vaHatchM)" stroke={VA.ink} strokeWidth="3" />
      <rect x="-9" y={-104 + dy} width="18" height={148 - dy + Math.max(0, dy) * 1.4} fill="url(#vaShaft)" stroke={VA.ink} strokeWidth="2" />
      {/* puertos */}
      <rect x="-26" y="-250" width="52" height="60" fill="#7b8794" stroke={VA.ink} strokeWidth="2" />
      <rect x="-230" y="60" width="100" height="40" fill="#7b8794" stroke={VA.ink} strokeWidth="2" />
      <rect x="130" y="-70" width="100" height="44" fill="#7b8794" stroke={VA.ink} strokeWidth="2" />
      <rect x="-22" y="130" width="44" height="100" fill="#7b8794" stroke={VA.ink} strokeWidth="2" />
      {/* derivación con aguja ajustable (de la señal a la salida) */}
      <path d="M 120 -160 L 150 -160 L 150 -100 L 120 -100" fill="none" stroke={VA.airD} strokeWidth="6" />
      <rect x="146" y="-150" width="40" height={14 + 30 * (1 - bypass)} fill="#9aa6b4" stroke={VA.ink} strokeWidth="2" />
      <circle cx="196" cy="-143" r="12" fill={VA.moveD} stroke={VA.ink} strokeWidth="2" />
      {supply && <Particles pts={[[-230, 80], [-60, 80], [0, 60], [0, -20], [90, -48], [230, -48]]} t={t} speed={0.5 * flow} n={10} r={6} color={VA.airD} op={0.95} />}
      {exhaust && <Particles pts={[[230, -48], [60, -48], [0, -60], [0, 120], [0, 230]]} t={t} speed={-0.5 * flow} n={9} r={6} color={VA.airD} op={0.95} />}
    </g>
  );
}

// Firma de la válvula: presión en el actuador contra carrera (lazo de histéresis).
// x, y: esquina inferior izquierda; prog: cuánto del lazo dibujar (0 a 1).
function SignaturePlot({ x, y, w = 420, h = 260, prog = 1, fric = 0.12 }) {
  const X = (v) => x + v * w, Y = (v) => y - v * h;
  const up = [], dn = [];
  for (let i = 0; i <= 40; i++) { const tr = i / 40; up.push([0.2 + 0.6 * tr + fric / 2, tr]); dn.push([0.2 + 0.6 * tr - fric / 2, tr]); }
  const loop = [[0.08, 0], ...up, [0.95, 1], ...dn.slice().reverse(), [0.08, 0]];
  const n = Math.max(2, Math.round(loop.length * clampV(prog, 0, 1)));
  const d = loop.slice(0, n).map(([p, tr], i) => `${i ? 'L' : 'M'}${X(p).toFixed(1)} ${Y(tr * 0.9 + 0.05).toFixed(1)}`).join(' ');
  return (
    <g>
      <rect x={x - 70} y={y - h - 40} width={w + 100} height={h + 100} rx="14" fill={SL.paper} stroke={SL.lineS} />
      <line x1={x} y1={y} x2={x + w} y2={y} stroke={SL.dim} strokeWidth="2" />
      <line x1={x} y1={y} x2={x} y2={y - h} stroke={SL.dim} strokeWidth="2" />
      <text x={x + w / 2} y={y + 36} fill={SL.ink} fontFamily={MONO} fontSize="16" textAnchor="middle">presión en el actuador</text>
      <text transform={`translate(${x - 26} ${y - h / 2}) rotate(-90)`} fill={SL.ink} fontFamily={MONO} fontSize="16" textAnchor="middle">carrera</text>
      <path d={d} fill="none" stroke={SL.cc} strokeWidth="4" strokeLinejoin="round" />
      {prog > 0.95 && <g>
        <line x1={X(0.5 - fric / 2)} y1={Y(0.5)} x2={X(0.5 + fric / 2)} y2={Y(0.5)} stroke={SL.bad} strokeWidth="4" />
        <text x={X(0.5 + fric / 2) + 10} y={Y(0.5) + 6} fill={SL.bad} fontFamily={MONO} fontSize="15">fricción</text>
        <text x={X(0.1)} y={Y(0.05) - 12} fill={SL.mut} fontFamily={MONO} fontSize="14" textAnchor="middle">asiento</text>
      </g>}
    </g>
  );
}

Object.assign(window, { PipeCut, AccBox, VC_PARTS, vcOnly, gearPts, SplineCoupling, PistonTop, BoosterArt, SignaturePlot });
