// valve-lib.jsx — tema del curso «Válvulas de Control».
// Acero claro con acento ámbar. Código de color fijo en todo el curso:
//   fluido de proceso = azul (ca) · aire e instrumentación = naranja (cc) · fuerza y mecánica = ámbar (sun).
// Se carga después de animations.jsx (useTime, Easing, clamp, Stage).
const SL = {
  bg: '#eef3f8', bg2: '#c9d8e8', paper: '#ffffff', paper2: '#f3f7fb',
  ink: '#10233a', mut: '#4a5f78', dim: '#8396ad',
  line: 'rgba(16,35,58,0.06)', lineS: 'rgba(16,35,58,0.16)',
  sun: '#c27803', sunD: '#9a5b00', cc: '#e8590c', ca: '#1c7ed6', ok: '#2b8a3e', bad: '#c92a2a',
  steel: '#a9b8c9', steelD: '#6b7f96',
  shadow: '0 14px 40px rgba(16,35,58,0.14)', shadowSm: '0 6px 16px rgba(16,35,58,0.10)',
  glowSun: 'rgba(255,214,140,0.45)', glowB: 'rgba(255,255,255,0.4)', vignette: 'rgba(16,35,58,0.08)',
};
const DISP = "'Space Grotesk', system-ui, sans-serif";
const MONO = "'IBM Plex Mono', ui-monospace, monospace";

function popS(t, appear, d = 0.55, rise = 18) {
  const lt = t - appear;
  if (lt < 0) return { op: 0, sc: 0.95, ty: rise };
  const e = Easing.easeOutCubic(clamp(lt / d, 0, 1));
  const eb = Easing.easeOutBack(clamp(lt / d, 0, 1));
  return { op: e, sc: 0.95 + 0.05 * eb, ty: (1 - e) * rise };
}
/** 0→1 entre a y a+d (con suavizado) */
const segS = (t, a, d = 0.8) => Easing.easeInOutCubic(clamp((t - a) / d, 0, 1));

// ── Fondo ────────────────────────────────────────────────────────────────────
function GlobalBGS() {
  const t = useTime();
  const sx = 82 + Math.sin(t * 0.05) * 4, sy = 12 + Math.cos(t * 0.04) * 3;
  const gridShift = (t * 3) % 60;
  return (
    <div style={{ position: 'absolute', inset: 0, overflow: 'hidden', background: `linear-gradient(165deg, ${SL.bg2}, ${SL.bg})` }}>
      <div style={{ position: 'absolute', inset: 0, background: `radial-gradient(circle 760px at ${sx}% ${sy}%, ${SL.glowSun}, transparent 62%)` }} />
      <div style={{ position: 'absolute', inset: 0, background: `radial-gradient(circle 700px at 12% 92%, ${SL.glowB}, transparent 60%)` }} />
      <div style={{ position: 'absolute', inset: 0, maskImage: 'radial-gradient(ellipse 85% 80% at 50% 50%, #000 40%, transparent 90%)', WebkitMaskImage: 'radial-gradient(ellipse 85% 80% at 50% 50%, #000 40%, transparent 90%)' }}>
        <div style={{ position: 'absolute', inset: '-60px', backgroundImage: `linear-gradient(${SL.line} 1px, transparent 1px), linear-gradient(90deg, ${SL.line} 1px, transparent 1px)`, backgroundSize: '60px 60px', transform: `translate(${-gridShift}px, 0)` }} />
      </div>
      <div style={{ position: 'absolute', inset: 0, background: `radial-gradient(ellipse 120% 120% at 50% 50%, transparent 52%, ${SL.vignette} 100%)` }} />
    </div>
  );
}

// ── Escena, textos ───────────────────────────────────────────────────────────
function SceneS({ start, dur, children, fade = 0.55 }) {
  const t = useTime();
  const end = start + dur;
  if (t < start - 0.02 || t > end + 0.02) return null;
  const lt = t - start;
  let op = 1;
  if (lt < fade) op = clamp(lt / fade, 0, 1);
  else if (t > end - fade) op = clamp((end - t) / fade, 0, 1);
  return <div style={{ position: 'absolute', inset: 0, opacity: op }}>{children}</div>;
}

function CapS({ start, dur = 3, children, x = '50%', y = '50%', size = 56, weight = 600, color = SL.ink, mono = false, align = 'center', width = 1500, lh = 1.12 }) {
  const t = useTime();
  const lt = t - start;
  if (lt < -0.02 || lt > dur + 0.02) return null;
  let op = 1, ty = 0;
  if (lt < 0.5) { const e = Easing.easeOutCubic(clamp(lt / 0.5, 0, 1)); op = e; ty = (1 - e) * 20; }
  else if (lt > dur - 0.4) { const e = Easing.easeInCubic(clamp((lt - (dur - 0.4)) / 0.4, 0, 1)); op = 1 - e; ty = -e * 10; }
  const tx = align === 'center' ? '-50%' : align === 'right' ? '-100%' : '0';
  return (
    <div style={{ position: 'absolute', left: x, top: y, transform: `translate(${tx}, calc(-50% + ${ty}px))`, opacity: op, width, textAlign: align, color, fontFamily: mono ? MONO : DISP, fontSize: size, fontWeight: weight, lineHeight: lh, letterSpacing: '-0.01em', textWrap: 'balance' }}>
      {children}
    </div>
  );
}

function KickerS({ start, dur = 3, text, x = '50%', y = '9%', color = SL.sun, align = 'center' }) {
  const t = useTime();
  const lt = t - start;
  if (lt < -0.02 || lt > dur + 0.02) return null;
  let op = 1;
  if (lt < 0.4) op = clamp(lt / 0.4, 0, 1);
  else if (lt > dur - 0.35) op = clamp((dur - lt) / 0.35, 0, 1);
  const tx = align === 'center' ? '-50%' : '0';
  return (
    <div style={{ position: 'absolute', left: x, top: y, transform: `translate(${tx},-50%)`, opacity: op, color, fontFamily: MONO, fontSize: 17, letterSpacing: '0.3em', fontWeight: 600, textTransform: 'uppercase', whiteSpace: 'nowrap', display: 'flex', alignItems: 'center', gap: 12 }}>
      <span style={{ width: 26, height: 2, background: color, opacity: 0.6 }} />{text}<span style={{ width: 26, height: 2, background: color, opacity: 0.6 }} />
    </div>
  );
}

/** Título de escena: kicker arriba y título grande que se queda */
function HeadS({ s, dur, kicker, title, color = SL.sun, y = '17%', size = 50 }) {
  return (
    <>
      <KickerS start={s + 0.2} dur={dur - 0.4} text={kicker} color={color} />
      {title && <CapS start={s + 0.5} dur={dur - 0.9} size={size} y={y} width={1600}>{title}</CapS>}
    </>
  );
}

function BracketsS({ color = SL.sun, size = 16, thick = 2, inset = 0 }) {
  const c = (pos) => {
    const base = { position: 'absolute', width: size, height: size, borderColor: color, borderStyle: 'solid', borderWidth: 0 };
    const m = inset;
    if (pos === 'tl') return { ...base, top: m, left: m, borderTopWidth: thick, borderLeftWidth: thick };
    if (pos === 'tr') return { ...base, top: m, right: m, borderTopWidth: thick, borderRightWidth: thick };
    if (pos === 'bl') return { ...base, bottom: m, left: m, borderBottomWidth: thick, borderLeftWidth: thick };
    return { ...base, bottom: m, right: m, borderBottomWidth: thick, borderRightWidth: thick };
  };
  return <>{['tl', 'tr', 'bl', 'br'].map(p => <div key={p} style={c(p)} />)}</>;
}

/** Tarjeta con acento, título y texto; entra en `at` */
function CardS({ at, x, y, w = 420, h, accent = SL.sun, title, children, no, icon, style }) {
  const t = useTime();
  const p = popS(t, at);
  return (
    <div style={{ position: 'absolute', left: x, top: y, width: w, height: h, opacity: p.op, transform: `translateY(${p.ty}px) scale(${p.sc})`, borderRadius: 14, background: SL.paper, border: `1px solid ${SL.lineS}`, boxShadow: SL.shadow, padding: '24px 26px', display: 'flex', flexDirection: 'column', gap: 12, ...style }}>
      <div style={{ position: 'absolute', left: 0, top: 18, bottom: 18, width: 3, borderRadius: 2, background: accent }} />
      {(no || icon) && (
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          {icon}
          {no && <span style={{ fontFamily: MONO, fontSize: 15, color: accent, letterSpacing: '0.18em', fontWeight: 600 }}>{no}</span>}
        </div>
      )}
      {title && <div style={{ fontFamily: DISP, fontSize: 30, fontWeight: 700, color: SL.ink, lineHeight: 1.12 }}>{title}</div>}
      {children && <div style={{ fontFamily: DISP, fontSize: 21, color: SL.mut, lineHeight: 1.42 }}>{children}</div>}
    </div>
  );
}

/** Viñetas que entran una por una en los tiempos `items[i].at` */
function ListS({ x, y, w = 900, items, size = 30, accent = SL.sun, gap = 26 }) {
  const t = useTime();
  return (
    <div style={{ position: 'absolute', left: x, top: y, width: w, display: 'flex', flexDirection: 'column', gap }}>
      {items.map((it, i) => {
        const p = popS(t, it.at, 0.5, 14);
        return (
          <div key={i} style={{ opacity: p.op, transform: `translateY(${p.ty}px)`, display: 'flex', gap: 18, alignItems: 'baseline' }}>
            <span style={{ fontFamily: MONO, fontSize: size * 0.55, color: it.color || accent, fontWeight: 600, minWidth: 34 }}>{it.no || String(i + 1).padStart(2, '0')}</span>
            <div>
              <div style={{ fontFamily: DISP, fontSize: size, fontWeight: 600, color: SL.ink, lineHeight: 1.2 }}>{it.k}</div>
              {it.d && <div style={{ fontFamily: DISP, fontSize: size * 0.68, color: SL.mut, lineHeight: 1.4, marginTop: 6 }}>{it.d}</div>}
            </div>
          </div>
        );
      })}
    </div>
  );
}

/** Aviso de seguridad (el temario pide una nota en toda escena con equipos energizados) */
function SafetyS({ at, until, x = '50%', y = '88%', children, w = 1300 }) {
  const t = useTime();
  if (until != null && t > until + 0.02) return null;
  const p = popS(t, at, 0.5, 12);
  const out = until != null ? clamp((until - t) / 0.4, 0, 1) : 1;
  return (
    <div style={{ position: 'absolute', left: x, top: y, transform: `translate(-50%, calc(-50% + ${p.ty}px))`, opacity: p.op * out, maxWidth: w, display: 'flex', alignItems: 'stretch', borderRadius: 10, overflow: 'hidden', border: '1px solid rgba(251,191,36,0.45)', background: 'rgba(251,191,36,0.07)', boxShadow: SL.shadowSm }}>
      <div style={{ background: SL.sun, color: '#1a1205', fontFamily: MONO, fontSize: 14, fontWeight: 700, letterSpacing: '0.16em', padding: '14px 18px', display: 'flex', alignItems: 'center', gap: 8, whiteSpace: 'nowrap' }}>⚠ SEGURIDAD</div>
      <div style={{ color: SL.ink, fontFamily: DISP, fontSize: 23, padding: '12px 22px', display: 'flex', alignItems: 'center', lineHeight: 1.35 }}>{children}</div>
    </div>
  );
}

/** Ruta de energía animada: trazo que se dibuja y luego fluye (CC naranja, CA azul) */
function FlowS({ d, at, color = SL.cc, width = 5, dur = 0.9, speed = 60, len = 2000 }) {
  const t = useTime();
  const draw = clamp((t - at) / dur, 0, 1);
  if (draw <= 0) return null;
  const flow = -((t * speed) % 40);
  return (
    <g>
      <path d={d} fill="none" stroke={color} strokeOpacity="0.18" strokeWidth={width * 4} strokeLinecap="round" strokeLinejoin="round" strokeDasharray={len} strokeDashoffset={len * (1 - draw)} />
      <path d={d} fill="none" stroke={color} strokeWidth={width} strokeLinecap="round" strokeLinejoin="round" strokeDasharray={draw < 1 ? len : '16 24'} strokeDashoffset={draw < 1 ? len * (1 - draw) : flow} />
    </g>
  );
}

/** Foto real con pie (entra cuando la narración nombra el equipo) */
function PhotoS({ at, until, src, label, x, y, w, h, fit = 'contain' }) {
  const t = useTime();
  if (t < at - 0.02 || (until != null && t > until + 0.02)) return null;
  const p = popS(t, at, 0.7, 24);
  const out = until != null ? clamp((until - t) / 0.4, 0, 1) : 1;
  return (
    <div style={{ position: 'absolute', left: x, top: y, width: w, opacity: p.op * out, transform: `translateY(${p.ty}px) scale(${p.sc})`, zIndex: 5 }}>
      <div style={{ borderRadius: 14, padding: 8, background: SL.paper, border: `1px solid ${SL.lineS}`, boxShadow: SL.shadow }}>
        <div style={{ height: h, borderRadius: 9, overflow: 'hidden', background: fit === 'contain' ? '#f4f6f8' : SL.bg2 }}>
          <img src={src} alt={label} draggable={false} style={{ width: '100%', height: '100%', objectFit: fit, display: 'block' }} />
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 6px 4px' }}>
          <span style={{ fontFamily: MONO, fontSize: 13, letterSpacing: '0.2em', color: SL.sun, fontWeight: 600 }}>FOTO</span>
          <span style={{ width: 18, height: 1, background: SL.lineS }} />
          <span style={{ fontFamily: DISP, fontSize: 21, fontWeight: 600, color: SL.ink }}>{label}</span>
        </div>
      </div>
    </div>
  );
}

/** Fórmula destacada */
function FormulaS({ at, x = '50%', y = '50%', children, size = 54, color = SL.sun, sub }) {
  const t = useTime();
  const p = popS(t, at, 0.6, 16);
  return (
    <div style={{ position: 'absolute', left: x, top: y, transform: `translate(-50%, calc(-50% + ${p.ty}px)) scale(${p.sc})`, opacity: p.op, background: SL.paper, border: `1px solid ${SL.lineS}`, borderRadius: 14, boxShadow: SL.shadow, padding: '22px 40px', textAlign: 'center' }}>
      <div style={{ fontFamily: MONO, fontSize: size, fontWeight: 700, color, whiteSpace: 'nowrap' }}>{children}</div>
      {sub && <div style={{ fontFamily: DISP, fontSize: 21, color: SL.mut, marginTop: 10 }}>{sub}</div>}
    </div>
  );
}

// ── Símbolo de corriente continua (la fuente no trae ⎓): línea llena sobre línea de trazos
function DcG({ x, y, w = 44, color = SL.cc, sw = 4 }) {
  return (
    <g transform={`translate(${x} ${y})`}>
      <line x1={-w / 2} y1={-sw * 1.2} x2={w / 2} y2={-sw * 1.2} stroke={color} strokeWidth={sw} strokeLinecap="round" />
      {[0, 1, 2].map(i => <line key={i} x1={-w / 2 + i * (w / 3) + 1} y1={sw * 1.2} x2={-w / 2 + (i + 1) * (w / 3) - w / 12} y2={sw * 1.2} stroke={color} strokeWidth={sw} strokeLinecap="round" />)}
    </g>
  );
}
function DcI({ size = 28, color = SL.cc }) {
  const w = size * 1.4, h = size * 0.8;
  return (
    <svg width={w} height={h} viewBox={`${-w / 2 - 3} ${-h / 2} ${w + 6} ${h}`} style={{ display: 'inline-block', verticalAlign: 'middle' }} aria-label="corriente continua">
      <DcG x={0} y={0} w={w} color={color} sw={Math.max(2.5, size / 8)} />
    </svg>
  );
}

// ── Equipos (dibujos SVG; se colocan con transform en un <svg> de 1920×1080) ──
function SunG({ x, y, r = 46, t = 0 }) {
  return (
    <g transform={`translate(${x} ${y})`}>
      <circle r={r * 1.9} fill={SL.sun} opacity={0.08 + 0.03 * Math.sin(t * 2)} />
      {[...Array(12)].map((_, i) => {
        const a = (i * Math.PI) / 6 + t * 0.2;
        return <line key={i} x1={Math.cos(a) * r * 1.25} y1={Math.sin(a) * r * 1.25} x2={Math.cos(a) * r * 1.6} y2={Math.sin(a) * r * 1.6} stroke={SL.sun} strokeWidth="4" strokeLinecap="round" />;
      })}
      <circle r={r} fill={SL.sun} />
    </g>
  );
}
/** Módulo FV visto de frente: rejilla de células */
function PanelG({ x, y, w = 120, h = 190, cols = 6, rows = 10, glow = 0 }) {
  const cw = w / cols, ch = h / rows;
  return (
    <g transform={`translate(${x} ${y})`}>
      {glow > 0 && <rect x={-6} y={-6} width={w + 12} height={h + 12} rx="8" fill={SL.sun} opacity={0.18 * glow} />}
      <rect width={w} height={h} rx="4" fill="#0d2a52" stroke="#9fb3cc" strokeWidth="3" />
      {[...Array(cols - 1)].map((_, i) => <line key={'c' + i} x1={(i + 1) * cw} y1={2} x2={(i + 1) * cw} y2={h - 2} stroke="#3b5f8f" strokeWidth="1.2" />)}
      {[...Array(rows - 1)].map((_, i) => <line key={'r' + i} x1={2} y1={(i + 1) * ch} x2={w - 2} y2={(i + 1) * ch} stroke="#3b5f8f" strokeWidth="1.2" />)}
      <path d={`M${w * 0.1} ${h * 0.05} L${w * 0.45} ${h * 0.05} L${w * 0.1} ${h * 0.4} Z`} fill="#fff" opacity="0.06" />
    </g>
  );
}
/** Caja con icono y rótulo para diagramas de bloques (en coordenadas SVG) */
function BlockG({ x, y, w = 220, h = 120, label, sub, color = SL.ink, op = 1, icon }) {
  return (
    <g transform={`translate(${x} ${y})`} opacity={op}>
      <rect width={w} height={h} rx="14" fill={SL.paper} stroke={color} strokeWidth="2.5" />
      {icon && <g transform={`translate(${w / 2} ${h * 0.4})`}>{icon}</g>}
      <text x={w / 2} y={icon ? h - 22 : h / 2 + 4} textAnchor="middle" fill={SL.ink} fontFamily={DISP} fontSize="21" fontWeight="700">{label}</text>
      {sub && <text x={w / 2} y={h + 26} textAnchor="middle" fill={SL.mut} fontFamily={MONO} fontSize="15">{sub}</text>}
    </g>
  );
}
// Iconos simples centrados en (0,0), ~60 px
const IcoPanel = ({ c = SL.ca }) => (<g><path d="M-30 18 L-18 -18 H30 L18 18 Z" fill="#0d2a52" stroke={c} strokeWidth="2.5" /><path d="M-24 0 H24 M-6 -18 L-12 18 M12 -18 L6 18" stroke={c} strokeWidth="1.4" opacity="0.7" /></g>);
const IcoInverter = ({ c = SL.ink }) => (<g><rect x="-26" y="-24" width="52" height="48" rx="6" fill="none" stroke={c} strokeWidth="2.5" /><line x1="-26" y1="24" x2="26" y2="-24" stroke={c} strokeWidth="1.5" /><path d="M-18 -12 H-4 M-18 -7 H-4" stroke={SL.cc} strokeWidth="2.5" /><path d="M4 12 q4 -7 8 0 t8 0" fill="none" stroke={SL.ca} strokeWidth="2.5" /></g>);
const IcoBox = ({ c = SL.cc }) => (<g><rect x="-24" y="-24" width="48" height="48" rx="5" fill="none" stroke={c} strokeWidth="2.5" /><path d="M-12 -10 v20 M0 -10 v20 M12 -10 v20" stroke={c} strokeWidth="3" /></g>);
const IcoBoard = ({ c = SL.ca }) => (<g><rect x="-22" y="-26" width="44" height="52" rx="4" fill="none" stroke={c} strokeWidth="2.5" />{[-14, -2, 10].map(yy => <rect key={yy} x="-12" y={yy} width="24" height="7" rx="1.5" fill={c} opacity="0.7" />)}</g>);
const IcoMeter = ({ c = SL.ca }) => (<g><circle r="25" fill="none" stroke={c} strokeWidth="2.5" /><text y="7" textAnchor="middle" fill={c} fontFamily={MONO} fontSize="17" fontWeight="700">kWh</text></g>);
const IcoGrid = ({ c = SL.ca }) => (<g><path d="M-16 28 L0 -28 L16 28 M-10 6 H10 M-13 16 H13 M-24 -14 H24" fill="none" stroke={c} strokeWidth="2.5" strokeLinejoin="round" /></g>);
const IcoTrafo = ({ c = SL.ca }) => (<g><circle cx="-10" r="17" fill="none" stroke={c} strokeWidth="2.5" /><circle cx="10" r="17" fill="none" stroke={c} strokeWidth="2.5" /></g>);
const IcoBattery = ({ c = SL.ok }) => (<g><rect x="-26" y="-16" width="48" height="32" rx="4" fill="none" stroke={c} strokeWidth="2.5" /><rect x="22" y="-7" width="6" height="14" fill={c} /><rect x="-20" y="-10" width="26" height="20" fill={c} opacity="0.6" /></g>);
const IcoBuilding = ({ c = SL.ink }) => (<g><path d="M-28 26 V-8 L-10 -20 V-8 L8 -20 V-8 L26 -20 V26 Z" fill="none" stroke={c} strokeWidth="2.5" strokeLinejoin="round" /><rect x="-6" y="8" width="12" height="18" fill={c} opacity="0.5" /></g>);
const IcoGen = ({ c = SL.mut }) => (<g><circle r="24" fill="none" stroke={c} strokeWidth="2.5" /><text y="8" textAnchor="middle" fill={c} fontFamily={DISP} fontSize="22" fontWeight="700">G</text></g>);


// Silueta de válvula de globo con actuador (decorativa, para portadas)
function ValveGlyph({ x, y, s = 1, t = 0, open = null }) {
  const o = open == null ? 0.5 + 0.4 * Math.sin(t * 0.8) : open;
  return (
    <g transform={`translate(${x} ${y}) scale(${s})`} opacity="0.9">
      <path d="M-70 -120 Q0 -170 70 -120 L70 -100 L-70 -100 Z" fill={SL.paper} stroke={SL.steelD} strokeWidth="3" />
      <line x1="0" y1="-100" x2="0" y2={-10 - o * 18} stroke={SL.steelD} strokeWidth="5" />
      <path d="M-36 -100 L-36 -40 M36 -100 L36 -40" stroke={SL.steelD} strokeWidth="3" />
      <path d="M-60 -40 L60 -40 L44 40 L-44 40 Z" fill={SL.paper} stroke={SL.steelD} strokeWidth="3" />
      <path d={`M-18 ${12 - o * 18} L18 ${12 - o * 18} L10 ${-6 - o * 18} L-10 ${-6 - o * 18} Z`} fill={SL.sun} />
      <path d="M-150 0 L-60 0 M60 0 L150 0" stroke={SL.ca} strokeWidth="14" strokeLinecap="round" opacity="0.35" />
    </g>
  );
}

// ── Apertura, cierre y armazón de la clase ───────────────────────────────────
function classDurS(total) { return total ? `${Math.max(1, Math.round(total / 60))} min` : ''; }

function TitleCardS({ start, dur, total, moduleNo, claseNo, title, objetivo }) {
  const t = useTime();
  const s = start, end = start + dur;
  if (t < s - 0.02 || t > end + 0.02) return null;
  const lt = t - s;
  let op = 1;
  if (lt < 0.6) op = clamp(lt / 0.6, 0, 1);
  else if (t > end - 0.6) op = clamp((end - t) / 0.6, 0, 1);
  const ti = popS(t, s + 0.8, 0.7, 20);
  const ob = popS(t, s + 1.8, 0.7, 16);
  return (
    <div style={{ position: 'absolute', inset: 0, opacity: op }}>
      <svg style={{ position: 'absolute', inset: 0, width: '100%', height: '100%' }}><ValveGlyph x={1500} y={600} s={1.9} t={t} /></svg>
      <div style={{ position: 'absolute', left: '9%', top: '50%', transform: 'translateY(-50%)', width: 1150 }}>
        <KickerS start={s + 0.3} dur={dur - 0.6} text={`Módulo ${moduleNo} · Clase ${moduleNo}.${claseNo}`} x="0" y="-120px" align="left" />
        <div style={{ opacity: ti.op, transform: `translateY(${ti.ty}px)`, fontFamily: DISP, fontSize: 84, fontWeight: 700, color: SL.ink, lineHeight: 1.03, letterSpacing: '-0.02em', textWrap: 'balance' }}>{title}</div>
        <div style={{ marginTop: 30, opacity: ob.op, transform: `translateY(${ob.ty}px)`, display: 'flex', flexDirection: 'column', gap: 18, maxWidth: 1000 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
            <span style={{ width: 44, height: 2, background: SL.sun }} />
            <span style={{ fontFamily: MONO, fontSize: 16, letterSpacing: '0.22em', color: SL.sun, textTransform: 'uppercase', fontWeight: 600 }}>Duración {classDurS(total)}</span>
          </div>
          <div style={{ fontFamily: DISP, fontSize: 30, color: SL.mut, lineHeight: 1.4 }}>{objetivo}</div>
        </div>
      </div>
    </div>
  );
}

/** Cierre: idea clave + pregunta de recuperación (el temario pide cerrar con una) */
function ClosingS({ start, dur, line, question }) {
  const t = useTime();
  const s = start, end = s + dur;
  if (t < s - 0.02 || t > end + 0.02) return null;
  const lt = t - s;
  let op = 1;
  if (lt < 0.6) op = clamp(lt / 0.6, 0, 1);
  else if (t > end - 0.6) op = clamp((end - t) / 0.6, 0, 1);
  const a = popS(t, s + 3.0, 0.6, 18);
  return (
    <div style={{ position: 'absolute', inset: 0, opacity: op, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 44, padding: '0 8%' }}>
      <div style={{ fontFamily: DISP, fontSize: 58, fontWeight: 600, color: SL.ink, textAlign: 'center', lineHeight: 1.14, maxWidth: 1500, textWrap: 'balance' }}>{line}</div>
      {question && (
        <div style={{ opacity: a.op, transform: `translateY(${a.ty}px)`, display: 'flex', alignItems: 'stretch', borderRadius: 10, overflow: 'hidden', border: `1px solid ${SL.lineS}`, boxShadow: SL.shadowSm, maxWidth: 1350, background: SL.paper }}>
          <div style={{ background: SL.sun, color: '#1a1205', fontFamily: MONO, fontSize: 15, fontWeight: 700, letterSpacing: '0.16em', padding: '20px 24px', display: 'flex', alignItems: 'center', textTransform: 'uppercase', whiteSpace: 'nowrap' }}>Pregunta para ti</div>
          <div style={{ color: SL.ink, fontFamily: DISP, fontSize: 25, padding: '18px 28px', display: 'flex', alignItems: 'center', lineHeight: 1.35 }}>{question}</div>
        </div>
      )}
    </div>
  );
}

function ClassShellS({ scenes, moduleNo, claseNo, claseName }) {
  let acc = 0;
  const timed = scenes.map(sc => { const o = { ...sc, start: acc }; acc += sc.dur; return o; });
  const total = acc;
  return (
    <Stage width={1920} height={1080} duration={total} background={SL.bg} persistKey={`vc${moduleNo}c${claseNo}`}>
      <div id="video-root" data-screen-label={`Valvulas M${moduleNo} Clase ${claseNo}`} style={{ position: 'absolute', inset: 0 }}>
        <GlobalBGS />
        {timed.map((sc, i) => <sc.C key={i} start={sc.start} dur={sc.dur} total={total} />)}
        <ChromeS timed={timed} moduleNo={moduleNo} claseNo={claseNo} claseName={claseName} />
        <ProgressS timed={timed} />
      </div>
    </Stage>
  );
}
function ChromeS({ timed, moduleNo, claseNo, claseName }) {
  const t = useTime();
  let label = '';
  for (const sc of timed) if (t >= sc.start - 0.0001) label = sc.label || '';
  return (
    <div style={{ position: 'absolute', left: 54, bottom: 44, zIndex: 40, fontFamily: MONO, fontSize: 13, letterSpacing: '0.2em', color: SL.mut, display: 'flex', alignItems: 'center', gap: 14, textTransform: 'uppercase' }}>
      <span style={{ color: SL.sun, fontWeight: 600 }}>VC · M{moduleNo} · CLASE {moduleNo}.{claseNo}</span>
      <span style={{ width: 30, height: 1, background: SL.lineS }} />
      <span>{claseName}</span>
      {label && <><span style={{ width: 30, height: 1, background: SL.lineS }} /><span style={{ color: SL.dim }}>{label}</span></>}
    </div>
  );
}
function ProgressS({ timed }) {
  const t = useTime();
  return (
    <div style={{ position: 'absolute', top: 40, right: 54, zIndex: 40, display: 'flex', gap: 6, alignItems: 'center' }}>
      {timed.map((sc, i) => {
        const active = t >= sc.start && t < sc.start + sc.dur;
        const done = t >= sc.start + sc.dur;
        return <div key={i} style={{ width: active ? 30 : 16, height: 3, borderRadius: 2, background: active ? SL.sun : (done ? SL.sunD : 'rgba(148,163,184,0.2)') }} />;
      })}
    </div>
  );
}

Object.assign(window, {
  SL, DISP, MONO, popS, segS, GlobalBGS, SceneS, CapS, KickerS, HeadS, BracketsS, CardS, ListS, SafetyS, FlowS, PhotoS, FormulaS,
  DcG, DcI, SunG, PanelG, BlockG, IcoPanel, IcoInverter, IcoBox, IcoBoard, IcoMeter, IcoGrid, IcoTrafo, IcoBattery, IcoBuilding, IcoGen,
  TitleCardS, ClosingS, ClassShellS, ValveGlyph,
});
