// vc1c1.jsx — Válvulas de Control · M1 · Clase 1.1 «¿Qué es una válvula de control?»
// Después de valve-lib.jsx, pf-valves.jsx y vc-art.jsx (dibujos en corte). Exporta SCENES_VC1C1.

// ── El lazo de control ──────────────────────────────────────────────────────
function S_Loop({ start, dur }) {
  const t = useTime(); const s = start;
  const lt = Math.max(0, t - s);
  // la voz dice «cae la presión de entrada» a los 12,4 s; el controlador abre la válvula y la PV vuelve al SP
  const T0 = 12.6;
  const k = lt - T0;
  const dist = k > 0 ? 1 : 0;
  const pvDev = k > 0 ? -18 * Math.exp(-k / 2.6) * Math.cos(k * 0.9) : 0;
  const out = 50 + (k > 0 ? 22 * (1 - Math.exp(-k / 1.6)) : 0);
  const pv = 60 + pvDev;
  const ink = SL.ink, mono = MONO;
  const box = (x, y, tag, sub, col) => (
    <g>
      <circle cx={x} cy={y} r="46" fill={SL.paper} stroke={col} strokeWidth="3.5" />
      <line x1={x - 46} y1={y} x2={x + 46} y2={y} stroke={col} strokeWidth="2" />
      <text x={x} y={y - 10} fill={ink} fontFamily={mono} fontSize="20" fontWeight="700" textAnchor="middle">{tag}</text>
      <text x={x} y={y + 26} fill={SL.mut} fontFamily={mono} fontSize="16" textAnchor="middle">101</text>
      <text x={x} y={y + 76} fill={SL.mut} fontFamily={DISP} fontSize="20" textAnchor="middle">{sub}</text>
    </g>
  );
  // tendencia
  const TX = 1140, TY = 640, TW = 620, TH = 260;
  const hist = [];
  for (let i = 0; i <= 120; i++) {
    const tt = lt - 12 + (i / 120) * 12;
    const kk = tt - T0;
    const v = 60 + (kk > 0 ? -18 * Math.exp(-kk / 2.6) * Math.cos(kk * 0.9) : 0);
    hist.push(`${i ? 'L' : 'M'}${TX + (i / 120) * TW} ${TY + TH - ((v - 30) / 50) * TH}`);
  }
  const VX = 470, VY = 800, VS = 0.27; // válvula en corte sobre la tubería
  return (
    <SceneS start={start} dur={dur}>
      <HeadS s={s} dur={dur} kicker="El lazo de control" title={<>Medir, comparar y <span style={{ color: SL.sun }}>actuar</span>: la válvula es la que actúa.</>} />
      <svg style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', overflow: 'visible' }}>
        <ValveDefs />
        <g opacity={clamp((lt - 0.8) / 0.6, 0, 1)}>
          {/* tubería en corte y válvula */}
          <PipeCut x1={110} x2={VX - 400 * VS} y={VY} d={44} wall={9} t={t} speed={20 + out * 0.6} />
          <PipeCut x1={VX + 400 * VS} x2={1010} y={VY} d={44} wall={9} t={t} speed={20 + out * 0.6} />
          <g transform={`translate(${VX} ${VY}) scale(${VS})`}><GlobeAssembly open={0.15 + out / 100 * 0.8} air={out / 100} act="ATO" t={t} positioner posSignal={out / 100} /></g>
          {/* elemento primario: placa de orificio */}
          <rect x={826} y={VY - 34} width="8" height="68" fill={SL.ink} />
          {/* instrumentos */}
          {box(830, 520, 'FT', 'mide', SL.ca)}
          {box(640, 330, 'FIC', 'compara', SL.sun)}
          {box(220, 520, 'FV', 'actúa', SL.cc)}
          <path d={`M830 ${VY - 40} L830 566`} stroke={SL.ca} strokeWidth="2.5" strokeDasharray="8 6" />
          <path d="M784 490 L686 360" stroke={SL.ca} strokeWidth="2.5" strokeDasharray="8 6" />
          <path d="M594 360 L266 500" stroke={SL.cc} strokeWidth="2.5" strokeDasharray="8 6" />
          <path d={`M266 540 L${VX + 350 * VS} ${VY - 640 * VS}`} stroke={SL.cc} strokeWidth="2.5" strokeDasharray="8 6" />
          <text x={140} y={VY + 120} fill={SL.mut} fontFamily={mono} fontSize="18">salida del controlador: {Math.round(out)} %</text>
          {dist > 0 && lt < T0 + 5 && <text x={120} y={VY - 70} fill={SL.bad} fontFamily={DISP} fontSize="24" fontWeight="700">↓ baja la presión de entrada</text>}
          {/* tendencia */}
          <rect x={TX - 20} y={TY - 60} width={TW + 40} height={TH + 110} rx="16" fill={SL.paper} stroke={SL.lineS} />
          <text x={TX} y={TY - 24} fill={ink} fontFamily={DISP} fontSize="24" fontWeight="700">Caudal medido (PV)</text>
          <line x1={TX} y1={TY + TH - (30 / 50) * TH} x2={TX + TW} y2={TY + TH - (30 / 50) * TH} stroke={SL.sun} strokeWidth="2" strokeDasharray="8 6" />
          <text x={TX + TW} y={TY + TH - (30 / 50) * TH - 8} fill={SL.sun} fontFamily={mono} fontSize="16" textAnchor="end">SP</text>
          <path d={hist.join(' ')} fill="none" stroke={SL.ca} strokeWidth="4" />
          <text x={TX} y={TY + TH + 34} fill={SL.mut} fontFamily={mono} fontSize="17">PV = {pv.toFixed(1).replace('.', ',')} m³/h · SP = 60</text>
        </g>
      </svg>
    </SceneS>
  );
}

// ── Cómo regula: resistencia variable ──────────────────────────────────────
function S_Restriction({ start, dur }) {
  const t = useTime(); const s = start;
  const lt = Math.max(0, t - s);
  // abierta al inicio; cierra cuando la voz dice «al cerrar» (7,4 s) y luego respira
  const open = lt < 7 ? 0.85 : 0.5 + 0.35 * Math.cos((lt - 7) * 0.45);
  const X0 = 180, X1 = 1740;
  const p1 = 10, p2 = 10 - 4.5 * (1 - open) - 1.2, pvc = p2 - 2.2 * (1 - open) - 0.6;
  const PX = (x) => X0 + x * (X1 - X0), PY = (p) => 975 - ((p - 2.5) / 7.5) * 230;
  const prof = `M${PX(0)} ${PY(p1)} L${PX(0.45)} ${PY(p1 - 0.2)} Q${PX(0.49)} ${PY(pvc)} ${PX(0.52)} ${PY(pvc)} Q${PX(0.62)} ${PY(pvc)} ${PX(0.78)} ${PY(p2)} L${PX(1)} ${PY(p2 - 0.1)}`;
  const VX = 960, VY = 520, VS = 0.62;
  return (
    <SceneS start={start} dur={dur}>
      <HeadS s={s} dur={dur} kicker="Cómo regula" title={<>La válvula es una <span style={{ color: SL.sun }}>resistencia variable</span> al paso del fluido.</>} />
      <svg style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', overflow: 'visible' }}>
        <ValveDefs />
        <g opacity={clamp((lt - 0.8) / 0.6, 0, 1)}>
          <PipeCut x1={X0} x2={VX - 400 * VS} y={VY} d={160 * VS} wall={60 * VS} t={t} speed={30 + open * 80} />
          <PipeCut x1={VX + 400 * VS} x2={X1} y={VY} d={160 * VS} wall={60 * VS} t={t} speed={30 + open * 80} />
          <clipPath id="vcRestr"><rect x={VX - 460} y={VY - 260} width="920" height="440" /></clipPath>
          <g clipPath="url(#vcRestr)"><g transform={`translate(${VX} ${VY}) scale(${VS})`}>
            <GlobeAssembly open={open} air={open} t={t * (0.4 + open)} show={vcOnly(['body', 'seat', 'cage', 'plug', 'stem', 'bonnet'])} />
          </g></g>
          <text x={VX + 300} y={VY - 190} fill={SL.ink} fontFamily={MONO} fontSize="22" fontWeight="700">apertura {Math.round(open * 100)} %</text>
          <path d={prof} fill="none" stroke={SL.cc} strokeWidth="5" />
          <line x1={PX(0.52)} y1={VY + 170} x2={PX(0.52)} y2={PY(pvc) - 10} stroke={SL.mut} strokeWidth="2" strokeDasharray="4 6" />
          <text x={PX(0.02)} y={PY(p1) - 14} fill={SL.cc} fontFamily={MONO} fontSize="18">P1</text>
          <text x={PX(0.52)} y={PY(pvc) + 30} fill={SL.cc} fontFamily={MONO} fontSize="17" textAnchor="middle">vena contracta</text>
          <text x={PX(0.95)} y={PY(p2) - 14} fill={SL.cc} fontFamily={MONO} fontSize="18">P2</text>
          <text x={X1} y={PY(10) - 40} fill={SL.mut} fontFamily={MONO} fontSize="18" textAnchor="end">presión a lo largo de la tubería · ΔP = {(p1 - p2).toFixed(1).replace('.', ',')} bar</text>
        </g>
      </svg>
    </SceneS>
  );
}

// ── El conjunto ────────────────────────────────────────────────────────────
function S_Assembly({ start, dur }) {
  const t = useTime(); const s = start;
  const lt = Math.max(0, t - s);
  // tiempos de la voz: cuerpo 4,4 · actuador 7,8 · posicionador 10,3 · accesorios 14,3
  const parts = [
    { k: 'Cuerpo', d: 'Contiene la presión y aloja el trim: asiento, obturador y guía.', at: 4.4 },
    { k: 'Actuador', d: 'Convierte energía neumática, eléctrica o hidráulica en fuerza y movimiento.', at: 7.8 },
    { k: 'Posicionador', d: 'Compara la señal del controlador con la carrera real y corrige.', at: 10.3 },
    { k: 'Accesorios', d: 'Solenoide, transmisor de posición, finales de carrera, booster, filtro regulador.', at: 14.3 },
  ];
  const X = 600, Y = 900, S = 0.5;
  const run = lt > 17;
  const open = run ? 0.5 - 0.4 * Math.cos((lt - 17) * 0.8) : 0.35;
  const L = (a, keys, extra = {}) => (
    <g opacity={segS(t, s + a, 0.7)} transform={`translate(0 ${(1 - segS(t, s + a, 0.7)) * -40})`}>
      <g transform={`translate(${X} ${Y}) scale(${S})`}><GlobeAssembly open={open} air={open} act="ATO" t={t} flow={run && keys.includes('body')} show={vcOnly(keys)} {...extra} /></g>
    </g>
  );
  const PX = X + 425 * S, PY = Y - 600 * S; // posicionador en pantalla
  return (
    <SceneS start={start} dur={dur}>
      <HeadS s={s} dur={dur} kicker="Una válvula de control es un conjunto" title={<>Cuerpo, actuador, posicionador y accesorios <span style={{ color: SL.sun }}>trabajan como uno</span>.</>} />
      <svg style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', overflow: 'visible' }}>
        <ValveDefs />
        {L(4.4, ['body', 'seat', 'cage', 'plug', 'bonnet'])}
        {L(7.8, ['stem', 'yoke', 'actuator'])}
        {L(10.3, [], { positioner: true, posSignal: open })}
        <g opacity={segS(t, s + 14.3, 0.7)}>
          <path d={`M${PX + 40} ${PY - 50} L${PX + 40} ${PY - 120}`} stroke={SL.cc} strokeWidth="4" />
          <AccBox x={PX - 30} y={PY - 200} w={140} h={78} tag="SOV" sub="solenoide" />
          <AccBox x={PX + 140} y={PY - 200} w={150} h={78} tag="ZSO · ZSC" sub="finales de carrera" color={SL.steelD} />
          <AccBox x={PX + 140} y={PY - 100} w={150} h={78} tag="ZT" sub="posición 4-20 mA" color={SL.steelD} />
          <AccBox x={PX + 140} y={PY} w={150} h={78} tag="FR" sub="filtro regulador" color={SL.steelD} />
          <AccBox x={PX + 140} y={PY + 100} w={150} h={78} tag="BOOSTER" sub="más caudal de aire" color={SL.steelD} />
        </g>
      </svg>
      <ListS x={1260} y={300} w={600} size={28} items={parts.map((p) => ({ k: p.k, d: p.d, at: s + p.at }))} />
    </SceneS>
  );
}

// ── Dos familias ───────────────────────────────────────────────────────────
function S_Families({ start, dur }) {
  const t = useTime(); const s = start;
  const lt = Math.max(0, t - s);
  const u = 0.5 + 0.42 * Math.sin(lt * 0.9);
  // la voz nombra la bola segmentada (14,4 s), la mariposa y el tapón excéntrico
  const rot = lt < 15.6 ? 'bola' : lt < 17 ? 'mariposa' : 'excentrico';
  return (
    <SceneS start={start} dur={dur}>
      <HeadS s={s} dur={dur} kicker="Dos grandes familias" title={<>El obturador se mueve <span style={{ color: SL.sun }}>en línea recta</span> o <span style={{ color: SL.sun }}>girando</span>.</>} />
      <svg style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', overflow: 'visible' }}>
        <ValveDefs />
        <g opacity={segS(t, s + 4.4)}>
          <rect x={160} y={290} width={760} height={600} rx="18" fill={SL.paper} stroke={SL.lineS} />
          <clipPath id="vcFamA"><rect x={170} y={300} width={740} height={460} rx="14" /></clipPath>
          <g clipPath="url(#vcFamA)"><g transform="translate(540 640) scale(0.62)">
            <GlobeAssembly open={u} air={u} t={t} show={vcOnly(['body', 'seat', 'cage', 'plug', 'stem', 'bonnet'])} />
          </g></g>
          <path d="M540 330 l-16 28 h32 Z M540 470 l-16 -28 h32 Z" fill={SL.cc} opacity="0.9" />
          <text x={540} y={810} fill={SL.ink} fontFamily={DISP} fontSize="34" fontWeight="700" textAnchor="middle">Vástago deslizante</text>
          <text x={540} y={850} fill={SL.mut} fontFamily={DISP} fontSize="22" textAnchor="middle">globo · ángulo · tres vías</text>
        </g>
        <g opacity={segS(t, s + 11.7)}>
          <rect x={1000} y={290} width={760} height={600} rx="18" fill={SL.paper} stroke={SL.lineS} />
          <g transform="translate(1380 540) scale(0.95)">
            {rot === 'bola' && <VBallArt angle={u * 90} t={t} />}
            {rot === 'mariposa' && <ButterflyArt angle={u * 90} t={t} />}
            {rot === 'excentrico' && <EccPlugArt angle={u * 60} t={t} />}
          </g>
          <path d="M1335 340 A50 50 0 0 1 1425 340" fill="none" stroke={SL.cc} strokeWidth="6" />
          <path d="M1425 340 l-4 -18 l18 10 Z" fill={SL.cc} />
          <text x={1380} y={810} fill={SL.ink} fontFamily={DISP} fontSize="34" fontWeight="700" textAnchor="middle">Rotativas</text>
          <text x={1380} y={850} fill={SL.mut} fontFamily={DISP} fontSize="22" textAnchor="middle">
            <tspan fill={rot === 'bola' ? SL.sunD : SL.mut} fontWeight={rot === 'bola' ? 700 : 400}>bola segmentada</tspan> · <tspan fill={rot === 'mariposa' ? SL.sunD : SL.mut} fontWeight={rot === 'mariposa' ? 700 : 400}>mariposa</tspan> · <tspan fill={rot === 'excentrico' ? SL.sunD : SL.mut} fontWeight={rot === 'excentrico' ? 700 : 400}>tapón excéntrico</tspan>
          </text>
        </g>
      </svg>
    </SceneS>
  );
}

// ── En el P&ID ─────────────────────────────────────────────────────────────
function S_Symbol({ start, dur }) {
  const t = useTime(); const s = start;
  const lt = Math.max(0, t - s);
  const step = (a) => segS(t, s + a, 0.6);
  const cx = 640, cy = 640, ink = SL.ink;
  return (
    <SceneS start={start} dur={dur}>
      <HeadS s={s} dur={dur} kicker="Cómo se dibuja en el P&ID" title={<>Un símbolo resume <span style={{ color: SL.sun }}>tipo, actuador, falla y señales</span>.</>} />
      <svg style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', overflow: 'visible' }}>
        <g opacity={step(1)}>
          <line x1={cx - 420} y1={cy} x2={cx + 420} y2={cy} stroke={ink} strokeWidth="4" />
          <path d={`M${cx - 60} ${cy - 40} L${cx - 60} ${cy + 40} L${cx} ${cy} Z M${cx + 60} ${cy - 40} L${cx + 60} ${cy + 40} L${cx} ${cy} Z`} fill={SL.paper} stroke={ink} strokeWidth="3.5" />
        </g>
        <g opacity={step(3)}>
          <line x1={cx} y1={cy} x2={cx} y2={cy - 90} stroke={ink} strokeWidth="3.5" />
          <path d={`M${cx - 50} ${cy - 90} Q${cx} ${cy - 150} ${cx + 50} ${cy - 90} Z`} fill={SL.paper} stroke={ink} strokeWidth="3.5" />
        </g>
        <g opacity={step(5)}>
          <text x={cx + 30} y={cy + 76} fill={SL.cc} fontFamily={MONO} fontSize="26" fontWeight="700">FC</text>
          <path d={`M${cx} ${cy + 20} L${cx} ${cy + 60}`} stroke={SL.cc} strokeWidth="3" />
          <path d={`M${cx - 10} ${cy + 46} L${cx} ${cy + 62} L${cx + 10} ${cy + 46}`} fill="none" stroke={SL.cc} strokeWidth="3" />
        </g>
        <g opacity={step(7)}>
          <circle cx={cx} cy={cy - 290} r="52" fill={SL.paper} stroke={ink} strokeWidth="3" />
          <line x1={cx - 52} y1={cy - 290} x2={cx + 52} y2={cy - 290} stroke={ink} strokeWidth="2" />
          <text x={cx} y={cy - 300} fill={ink} fontFamily={MONO} fontSize="22" fontWeight="700" textAnchor="middle">FIC</text>
          <text x={cx} y={cy - 262} fill={SL.mut} fontFamily={MONO} fontSize="18" textAnchor="middle">101</text>
          <path d={`M${cx} ${cy - 238} L${cx} ${cy - 150}`} stroke={ink} strokeWidth="2.5" strokeDasharray="10 8" />
          <text x={cx + 14} y={cy - 190} fill={SL.mut} fontFamily={MONO} fontSize="16">señal eléctrica</text>
        </g>
        <g opacity={step(9)}>
          <path d={`M${cx + 260} ${cy - 120} L${cx + 50} ${cy - 120}`} stroke={ink} strokeWidth="2.5" />
          {[0, 1, 2, 3, 4].map((i) => <line key={i} x1={cx + 230 - i * 40} y1={cy - 130} x2={cx + 222 - i * 40} y2={cy - 110} stroke={ink} strokeWidth="2.5" />)}
          <text x={cx + 270} y={cy - 114} fill={SL.mut} fontFamily={MONO} fontSize="16">aire de instrumentos</text>
          <text x={cx - 160} y={cy - 110} fill={ink} fontFamily={MONO} fontSize="24" fontWeight="700" textAnchor="end">FV-101</text>
        </g>
      </svg>
      <ListS x={1180} y={320} w={640} size={28} items={[
        { k: 'Cuerpo', d: 'Dos triángulos opuestos: válvula de globo genérica.', at: s + 1 },
        { k: 'Actuador', d: 'La cúpula indica diafragma con resorte.', at: s + 3 },
        { k: 'Posición de falla', d: 'FC, FO o FL, o una flecha bajo el cuerpo.', at: s + 5 },
        { k: 'Tag y señales', d: 'FV-101 recibe la salida de FIC-101; la línea con trazos cruzados es aire.', at: s + 7 },
      ]} />
    </SceneS>
  );
}

// ── Por qué importa ────────────────────────────────────────────────────────
function S_Matters({ start, dur }) {
  const t = useTime(); const s = start;
  const lt = Math.max(0, t - s);
  const X0 = 200, Y0 = 760, W = 820, H = 300;
  const good = (x) => 50 + 1.2 * Math.sin(x * 9) + 0.8 * Math.sin(x * 23);
  const bad = (x) => 50 + 9 * Math.sign(Math.sin(x * 4.2)) * (0.6 + 0.4 * Math.sin(x * 1.3)) + 1.5 * Math.sin(x * 21);
  const tr = (f) => { let d = ''; for (let i = 0; i <= 200; i++) { const x = i / 200; d += `${i ? 'L' : 'M'}${X0 + x * W} ${Y0 - ((f(x + lt * 0.03) - 30) / 40) * H} `; } return d; };
  return (
    <SceneS start={start} dur={dur}>
      <HeadS s={s} dur={dur} kicker="Por qué importa" title={<>Un lazo nunca es mejor que <span style={{ color: SL.sun }}>su válvula</span>.</>} />
      <svg style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', overflow: 'visible' }}>
        <g opacity={segS(t, s + 1.2)}>
          <rect x={X0 - 30} y={Y0 - H - 70} width={W + 60} height={H + 130} rx="16" fill={SL.paper} stroke={SL.lineS} />
          <path d={tr(bad)} fill="none" stroke={SL.bad} strokeWidth="3.5" opacity="0.8" />
          <path d={tr(good)} fill="none" stroke={SL.ok} strokeWidth="4" />
          <text x={X0} y={Y0 - H - 30} fill={SL.ink} fontFamily={DISP} fontSize="26" fontWeight="700">Misma sintonía, dos válvulas</text>
          <text x={X0} y={Y0 + 40} fill={SL.ok} fontFamily={MONO} fontSize="18">válvula sana: variación pequeña</text>
          <text x={X0 + 440} y={Y0 + 40} fill={SL.bad} fontFamily={MONO} fontSize="18">válvula con fricción: ciclo límite</text>
        </g>
      </svg>
      <ListS x={1120} y={320} w={700} size={28} items={[
        { k: 'Banda muerta y fricción', d: 'La válvula no responde a cambios pequeños y el lazo oscila.', at: s + 3 },
        { k: 'Mal dimensionada', d: 'Muy grande trabaja casi cerrada; muy pequeña no alcanza el caudal.', at: s + 6 },
        { k: 'Característica inadecuada', d: 'La ganancia cambia con la carga y la sintonía deja de servir.', at: s + 9 },
      ]} />
    </SceneS>
  );
}

const SCENES_VC1C1 = [
  { C: (p) => <TitleCardS {...p} moduleNo={1} claseNo={1} title="¿Qué es una válvula de control?" objetivo="Su papel en el lazo, cómo regula, el conjunto que la forma, sus dos familias, cómo se dibuja y por qué decide la calidad del control." />, dur: 11, label: 'Apertura' },
  { C: S_Loop, dur: 24, label: 'El lazo' },
  { C: S_Restriction, dur: 25, label: 'Resistencia variable' },
  { C: S_Assembly, dur: 24, label: 'El conjunto' },
  { C: S_Families, dur: 19, label: 'Dos familias' },
  { C: S_Symbol, dur: 27, label: 'En el P&ID' },
  { C: S_Matters, dur: 22, label: 'Por qué importa' },
  { C: (p) => <ClosingS {...p} line="La válvula es la mano del lazo: si ella falla, ninguna sintonía lo compensa." question="En un lazo de tu planta, ¿qué tipo de válvula hay, qué actuador y cuál es su posición de falla? ¿Por qué crees que se eligió así?" />, dur: 15, label: 'Cierre' },
];

window.SCENES_VC1C1 = SCENES_VC1C1;
