// dc1c2.jsx — Diseño de Ingeniería I&C · Clase 1.2 «Los entregables de instrumentación».
// Después de di-lib.jsx, temp-art.jsx y di-art.jsx. Exporta SCENES_DC1C2.
const TIEMPOS_DC1C2 = [[0.6], [0.6, 4.67, 6.7, 11.3, 13.92, 18.94, 22.53, 30.72], [0.6, 4.82, 8.05, 12.21, 16.64, 19.35, 25.15], [0.6], [0.6, 4.41, 7.27, 10.86, 17.85, 24.88, 32.96], [0.6, 4.43, 10.05, 13.84], [0.6, 4.89, 11.99, 15.81, 18.26, 20.09, 22.7, 24.69, 26.86], [0.6], [0.6, 5.79, 11.68, 14.99, 20.34, 23.4], [0.6, 4.06, 7.46, 10.12, 12.94, 16.97, 22.92, 26.38], [0.6, 4.44, 10.53, 20.4], [0.6, 6.55], [0.6, 6.97]]; // auto
const fr = (i, k) => (TIEMPOS_DC1C2[i] || [])[k] ?? 0.6 + k * 4;

function S_Families({ start, dur }) {
  const t = useTime(); const s = start; const I = 1;
  const fam = [
    ['Qué se hace', ['P&ID', 'Filosofía de control', 'Índice de instrumentos'], TL4.blue, 1, 'pid'],
    ['Cómo es cada equipo', ['Hojas de datos', 'Cálculos', 'Requisiciones de compra'], TL4.orange, 3, 'table'],
    ['Cómo se instala y se conecta', ['Diagramas de lazo e interconexión', 'Típicos de montaje', 'Planos de ubicación', 'Listas de materiales'], TL4.blueD, 5, 'logic'],
  ];
  return (
    <SceneM4 start={start} dur={dur}>
      <HeadM14 s={s} dur={dur} kicker="Los entregables">Tres familias <span style={{ color: TL4.orangeD }}>de documentos</span>.</HeadM14>
      {fam.map((f, i) => { const p = pop4(t, s + fr(I, f[3])); return (
        <div key={i} style={{ position: 'absolute', left: 170 + i * 540, top: 300, width: 500, height: 470, opacity: p.op, transform: `translateY(${p.ty}px)`, background: TL4.paper, borderRadius: 16, boxShadow: TL4.shadow, borderTop: `7px solid ${f[2]}`, padding: '26px 30px', fontFamily: DISP4 }}>
          <div style={{ fontFamily: MONO4, fontSize: 16, color: TL4.mut, letterSpacing: '0.14em' }}>FAMILIA {i + 1}</div>
          <div style={{ fontSize: 32, fontWeight: 700, color: f[2], marginTop: 6 }}>{f[0]}</div>
          {f[1].map((d, j) => <div key={j} style={{ marginTop: 14, fontSize: 24, opacity: pop4(t, s + fr(I, f[3] + 1) + j * 0.5).op }}>· {d}</div>)}
        </div>); })}
      <div style={{ position: 'absolute', left: 170, top: 820, width: 1580, opacity: pop4(t, s + fr(I, 7)).op }}>
        <NoteT bg={TL4.orangeWash} size={24}>Cuando recibas un documento, pregúntate primero <b>a qué familia pertenece</b>: así sabes para qué sirve y quién lo usa.</NoteT>
      </div>
    </SceneM4>
  );
}

function S_Index({ start, dur }) {
  const t = useTime(); const s = start; const I = 2;
  const cols = [
    ['TAG', 2], ['Servicio', 2], ['P&ID', 3], ['Línea / equipo', 3], ['Tipo', 4], ['Rango', 4], ['Señal', 4], ['Hoja de datos', 5], ['Lazo', 5], ['JB', 5],
  ];
  const rows = [
    ['LT-101', 'Nivel separador', 'P-110-001', 'V-100', 'Radar', '0–2 m', '4-20 mA HART', 'HD-0012', 'DL-0015', 'JB-11'],
    ['PT-102', 'Presión separador', 'P-110-001', 'V-100', 'Manométrico', '0–16 bar', '4-20 mA HART', 'HD-0013', 'DL-0016', 'JB-11'],
    ['FT-205', 'Caudal de salida', 'P-110-002', '6"-P-1023', 'Placa + DP', '0–120 m³/h', '4-20 mA HART', 'HD-0040', 'DL-0031', 'JB-12'],
  ];
  const W = [140, 190, 140, 160, 150, 130, 170, 140, 120, 90];
  const X = W.reduce((acc, w, i) => (acc.push((acc[i - 1] ?? 160) + (i ? W[i - 1] : 0)), acc), []);
  return (
    <SceneM4 start={start} dur={dur}>
      <HeadM14 s={s} dur={dur} kicker="El índice de instrumentos">Una fila por instrumento, <span style={{ color: TL4.orangeD }}>la columna vertebral del proyecto</span>.</HeadM14>
      <div style={{ position: 'absolute', left: 160, top: 320, opacity: pop4(t, s + fr(I, 1)).op, fontFamily: MONO4 }}>
        {cols.map((c, i) => <div key={i} style={{ position: 'absolute', left: X[i] - 160, top: 0, width: W[i] - 4, padding: '10px 8px', background: TL4.blueWash, fontSize: 15, fontWeight: 700, color: TL4.blueD, opacity: pop4(t, s + fr(I, c[1])).op, borderRadius: 6 }}>{c[0]}</div>)}
        {rows.map((r, j) => r.map((v, i) => <div key={j + '-' + i} style={{ position: 'absolute', left: X[i] - 160, top: 50 + j * 52, width: W[i] - 4, padding: '12px 8px', background: TL4.paper, fontSize: 15, color: TL4.ink, fontWeight: i === 0 ? 700 : 500, opacity: pop4(t, s + fr(I, cols[i][1]) + 0.3).op, borderRadius: 6, whiteSpace: 'nowrap', overflow: 'hidden' }}>{v}</div>))}
      </div>
      <div style={{ position: 'absolute', left: 160, top: 620, width: 1600, opacity: pop4(t, s + fr(I, 6)).op }}>
        <NoteT accent={TL4.orange} size={25}>De aquí salen todos los demás: la hoja de datos toma el rango, el diagrama de lazo toma la señal y la caja, y el plano de ubicación toma la línea o el equipo.</NoteT>
      </div>
    </SceneM4>
  );
}

function S_Flow({ start, dur }) {
  const t = useTime(); const s = start; const I = 4;
  const N = {
    pid: [250, 560, 'P&ID', TL4.blue, 1], idx: [640, 560, 'Índice', TL4.orange, 2],
    hd: [1030, 380, 'Hojas de datos', TL4.blueD, 3], req: [1420, 380, 'Requisiciones', TL4.blueD, 3],
    io: [1030, 560, 'Lista de E/S', FA.ok, 4], dl: [1420, 560, 'Lazos e interconexión', FA.ok, 4],
    fil: [640, 780, 'Filosofía de control', TL4.mut, 5], log: [1030, 780, 'Lógicos y causa-efecto', TL4.mut, 5],
  };
  const E = [['pid', 'idx'], ['idx', 'hd'], ['hd', 'req'], ['idx', 'io'], ['io', 'dl'], ['pid', 'fil'], ['fil', 'log']];
  const bw = 290, bh = 84;
  return (
    <SceneM4 start={start} dur={dur}>
      <HeadM14 s={s} dur={dur} kicker="El flujo de información">Todo empieza <span style={{ color: TL4.orangeD }}>en el P&ID</span>.</HeadM14>
      <svg style={SVG_T}>
        <defs><marker id="arD" markerWidth="12" markerHeight="12" refX="10" refY="6" orient="auto"><path d="M0,0 L12,6 L0,12 Z" fill={TL4.blueD} /></marker></defs>
        {E.map(([a, b], i) => { const A = N[a], B = N[b]; const op = pop4(t, s + fr(I, B[4])).op;
          const x1 = A[0] + bw / 2, y1 = A[1], x2 = B[0] - bw / 2, y2 = B[1];
          const path = Math.abs(y1 - y2) < 2 ? `M${x1} ${y1} L${x2 - 6} ${y2}` : a === 'pid' && b === 'fil' ? `M${A[0]} ${A[1] + bh / 2} L${A[0]} ${B[1]} L${x2 - 6} ${B[1]}` : `M${x1} ${y1} L${(x1 + x2) / 2} ${y1} L${(x1 + x2) / 2} ${y2} L${x2 - 6} ${y2}`;
          return <path key={i} d={path} fill="none" stroke={TL4.blueD} strokeWidth={3} markerEnd="url(#arD)" opacity={op} />; })}
        {Object.entries(N).map(([k, n]) => { const op = pop4(t, s + fr(I, n[4])).op; const hot = k === 'pid' && t > s + fr(I, 6);
          return <g key={k} opacity={op}><rect x={n[0] - bw / 2} y={n[1] - bh / 2} width={bw} height={bh} rx={12} fill={hot ? TL4.orangeWash : DI.paper} stroke={hot ? TL4.orange : n[3]} strokeWidth={hot ? 4 : 3} />
            <text x={n[0]} y={n[1] + 8} fill={DI.ink} fontFamily={DISP4} fontSize="23" fontWeight="700" textAnchor="middle">{n[2]}</text></g>; })}
      </svg>
      <div style={{ position: 'absolute', left: 1210, top: 760, width: 560, opacity: pop4(t, s + fr(I, 6)).op }}>
        <NoteT bg={TL4.orangeWash} size={22}>Un cambio en el P&ID puede cambiar <b>todo lo que está aguas abajo</b>.</NoteT>
      </div>
    </SceneM4>
  );
}

function S_Layouts({ start, dur }) {
  const t = useTime(); const s = start; const I = 5;
  const a = (k) => pop4(t, s + fr(I, k)).op;
  return (
    <SceneM4 start={start} dur={dur}>
      <HeadM14 s={s} dur={dur} kicker="Planos de ubicación">Dónde está <span style={{ color: TL4.orangeD }}>cada cosa en la planta</span>.</HeadM14>
      <svg style={SVG_T}>
        <rect x={260} y={300} width={1000} height={560} fill="#f8fbff" stroke={DI.ink} strokeWidth={2.5} opacity={a(0)} />
        {[0, 1, 2, 3, 4].map(i => <line key={i} x1={260 + i * 250} y1={300} x2={260 + i * 250} y2={860} stroke={TL4.lineS} strokeWidth={1.5} opacity={a(0)} />)}
        <g opacity={a(0)}>
          <rect x={340} y={380} width={200} height={110} rx={40} fill="#e9eef4" stroke={DI.ink} strokeWidth={2} /><text x={440} y={442} fill={DI.mut} fontFamily={MONO4} fontSize="18" textAnchor="middle">V-100</text>
          <circle cx={760} cy={640} r={50} fill="#e9eef4" stroke={DI.ink} strokeWidth={2} /><text x={760} y={646} fill={DI.mut} fontFamily={MONO4} fontSize="18" textAnchor="middle">P-101</text>
        </g>
        <g opacity={a(1)}>
          {[[580, 400, 'LT-101'], [580, 470, 'PT-102'], [860, 600, 'FT-205'], [690, 720, 'PI-206']].map(([x, y, tg], i) => <g key={i}><circle cx={x} cy={y} r={14} fill={TL4.orange} /><text x={x + 22} y={y + 6} fill={DI.ink} fontFamily={MONO4} fontSize="17" fontWeight="700">{tg}</text></g>)}
        </g>
        <path d="M300 820 L1000 820 L1000 520 L1200 520" fill="none" stroke={TL4.blue} strokeWidth={12} opacity={a(2) * 0.6} strokeLinejoin="round" />
        <g opacity={a(3)}><rect x={1090} y={470} width={90} height={70} rx={6} fill={TL4.blueWash} stroke={TL4.blueD} strokeWidth={3} /><text x={1135} y={512} fill={TL4.blueD} fontFamily={MONO4} fontSize="18" fontWeight="700" textAnchor="middle">JB-11</text></g>
      </svg>
      <Notes4 x={1320} y={320} w={460}>
        <NoteT op={a(1)} accent={TL4.orange} size={21}><b>Ubicación de instrumentos:</b> cada TAG sobre la planta del área, con su elevación.</NoteT>
        <NoteT op={a(2)} accent={TL4.blue} size={21}><b>Rutas:</b> por dónde van las bandejas y conduits.</NoteT>
        <NoteT op={a(3)} accent={TL4.blueD} size={21}><b>Cajas de conexión (JB):</b> dónde se juntan los cables de campo antes de ir a la sala de control.</NoteT>
      </Notes4>
    </SceneM4>
  );
}

function S_Code({ start, dur }) {
  const t = useTime(); const s = start; const I = 6;
  const parts = [['P420', 'Proyecto', 2, TL4.blue], ['110', 'Área', 3, TL4.blueD], ['IC', 'Disciplina', 5, TL4.orange], ['DL', 'Tipo de documento', 7, FA.ok], ['0015', 'Consecutivo', 8, TL4.mut]];
  return (
    <SceneM4 start={start} dur={dur}>
      <HeadM14 s={s} dur={dur} kicker="La numeración">Un número único <span style={{ color: TL4.orangeD }}>que se puede leer</span>.</HeadM14>
      <div style={{ position: 'absolute', left: 0, right: 0, top: 360, display: 'flex', justifyContent: 'center', gap: 6, opacity: pop4(t, s + fr(I, 1)).op, fontFamily: MONO4 }}>
        {parts.map((p, i) => { const on = t > s + fr(I, p[2]); return (
          <React.Fragment key={i}>
            {i > 0 && <span style={{ fontSize: 76, color: TL4.dim, fontWeight: 600 }}>-</span>}
            <span style={{ fontSize: 76, fontWeight: 700, color: on ? p[3] : TL4.ink, padding: '0 10px', borderBottom: `6px solid ${on ? p[3] : 'transparent'}` }}>{p[0]}</span>
          </React.Fragment>); })}
      </div>
      <div style={{ position: 'absolute', left: 260, top: 540, width: 1400, display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 16, fontFamily: DISP4 }}>
        {parts.map((p, i) => { const q = pop4(t, s + fr(I, p[2])); return (
          <div key={i} style={{ opacity: q.op, transform: `translateY(${q.ty}px)`, background: TL4.paper, borderRadius: 12, boxShadow: TL4.shadowSm, borderTop: `5px solid ${p[3]}`, padding: '16px 18px', textAlign: 'center' }}>
            <div style={{ fontFamily: MONO4, fontSize: 26, fontWeight: 700, color: p[3] }}>{p[0]}</div>
            <div style={{ fontSize: 20, color: TL4.ink, marginTop: 6 }}>{p[1]}</div>
          </div>); })}
      </div>
      <div style={{ position: 'absolute', left: 260, top: 760, width: 1400, opacity: pop4(t, s + fr(I, 7)).op }}>
        <NoteT accent={TL4.blue} size={22}>Tipos comunes: <b>PID</b> P&ID · <b>IN</b> índice · <b>HD</b> hoja de datos · <b>DL</b> diagrama de lazo · <b>DI</b> interconexión · <b>TM</b> típico de montaje · <b>LG</b> lógico. Cada proyecto define los suyos.</NoteT>
      </div>
    </SceneM4>
  );
}

function S_TitleBlk({ start, dur }) {
  const t = useTime(); const s = start; const I = 8;
  const a = (k) => pop4(t, s + fr(I, k)).op;
  const rows = [
    ['CLIENTE', 'Petroandina S.A.', 1], ['PROYECTO', 'P420 · Planta de gas', 1], ['TÍTULO', 'Diagrama de lazo FT-205', 1],
    ['DOCUMENTO', 'P420-110-IC-DL-0031', 2], ['REVISIÓN', '1 · Emitido para construcción', 2],
    ['ELABORÓ', 'J. Pérez · 12-03', 3], ['REVISÓ', 'M. Rojas · 14-03', 3], ['APROBÓ', 'L. Gómez · 15-03', 3],
  ];
  return (
    <SceneM4 start={start} dur={dur}>
      <HeadM14 s={s} dur={dur} kicker="El cajetín">El recuadro que <span style={{ color: TL4.orangeD }}>debes leer primero</span>.</HeadM14>
      <svg style={SVG_T}>
        <g opacity={a(0)}><rect x={200} y={300} width={980} height={600} fill="#fbfdff" stroke={DI.ink} strokeWidth={3} /><rect x={215} y={315} width={950} height={570} fill="none" stroke={DI.ink} strokeWidth={1} /></g>
        {rows.map((r, i) => <g key={i} opacity={a(r[2])}><TitleBlock x={640} y={560 + i * 40 - 260 + 200} w={510} rows={[[r[0], r[1], r[2] === 2]]} /></g>)}
      </svg>
      <div style={{ position: 'absolute', left: 1240, top: 380, width: 520, opacity: a(4) }}>
        <NoteT bg={TL4.orangeWash} size={25}>Antes de usar un plano, revisa el cajetín: <b>número, revisión y estado</b>. Si no es la versión vigente, no lo uses.</NoteT>
      </div>
    </SceneM4>
  );
}

function S_Example({ start, dur }) {
  const t = useTime(); const s = start; const I = 9;
  const docs = [
    ['P&ID', 'P420-110-PR-PID-0002', 2, 'pid', TL4.blue], ['Índice', 'P420-110-IC-IN-0001', 3, 'table', TL4.orange],
    ['Hoja de datos', 'P420-110-IC-HD-0040', 4, 'table', TL4.orange], ['Cálculo de placa', 'P420-110-IC-CA-0007', 4, 'lines', TL4.orange],
    ['Lista de E/S', 'P420-110-IC-IO-0001', 5, 'table', FA.ok], ['Diagrama de lazo', 'P420-110-IC-DL-0031', 5, 'logic', FA.ok],
    ['Interconexión', 'P420-110-IC-DI-0004', 5, 'logic', FA.ok], ['Típico y ubicación', 'P420-110-IC-TM-0003', 6, 'lines', TL4.blueD],
  ];
  return (
    <SceneM4 start={start} dur={dur}>
      <HeadM14 s={s} dur={dur} kicker="Ejemplo">Los documentos <span style={{ color: TL4.orangeD }}>de un solo transmisor</span>.</HeadM14>
      <svg style={SVG_T}>
        <g opacity={pop4(t, s + fr(I, 1)).op}>
          <line x1={150} y1={560} x2={430} y2={560} stroke={DI.ink} strokeWidth={5} /><OrificeSym x={290} y={560} />
          <SigLine x1={290} y1={530} x2={290} y2={470} type="electric" />
          <IsaBubble x={290} y={420} r={50} tag="FT" num="205" />
        </g>
        {docs.map((d, i) => <g key={i} opacity={pop4(t, s + fr(I, d[2]) + (i % 3) * 0.3).op}><DocSheet x={520 + (i % 4) * 330} y={300 + Math.floor(i / 4) * 290} w={120} h={156} kind={d[3]} color={d[4]} code={d[1].slice(-7)} title={d[0]} /></g>)}
      </svg>
      <div style={{ position: 'absolute', left: 150, top: 880, width: 1620, opacity: pop4(t, s + fr(I, 7)).op }}>
        <NoteT bg={TL4.orangeWash} size={24}><b>Más de ocho documentos</b> para un solo transmisor. Por eso los proyectos usan bases de datos y números ordenados.</NoteT>
      </div>
    </SceneM4>
  );
}

function S_Tools({ start, dur }) {
  const t = useTime(); const s = start; const I = 10;
  const a = (k) => pop4(t, s + fr(I, k));
  return (
    <SceneM4 start={start} dur={dur}>
      <HeadM14 s={s} dur={dur} kicker="Las herramientas">Dibujar planos o <span style={{ color: TL4.orangeD }}>guardar datos una sola vez</span>.</HeadM14>
      <InfoCardM4 x={220} y={330} w={680} h={300} accent={TL4.blue} title="Programas de dibujo" sub="AutoCAD, MicroStation. Dibujan P&ID, típicos y planos de ubicación. Cada plano es un archivo independiente." appear={s + fr(I, 1)} t={t} />
      <InfoCardM4 x={1020} y={330} w={680} h={300} accent={TL4.orange} title="Bases de datos de instrumentación" sub="SmartPlant Instrumentation (SPI) y similares. Cada instrumento se guarda una vez y genera índice, hojas de datos y lazos." appear={s + fr(I, 2)} t={t} />
      <div style={{ position: 'absolute', left: 220, top: 700, width: 1480, opacity: a(3).op }}>
        <NoteT bg={TL4.orangeWash} size={25}>Con una base de datos, cambiar el rango de un transmisor se hace <b>en un solo lugar</b> y se refleja en todos los documentos. Sin ella, hay que corregir cada plano y es fácil olvidar uno.</NoteT>
      </div>
    </SceneM4>
  );
}

const Q_DC1C2_1 = { id: 'dc1c2-q1', q: '¿Qué documento reúne en una sola tabla a todos los instrumentos del proyecto?', options: ['El P&ID', 'El índice de instrumentos', 'La hoja de datos', 'El diagrama de lazo'], answer: 1, explain: 'El índice de instrumentos tiene una fila por instrumento y enlaza su P&ID, su hoja de datos, su lazo y su caja de conexiones.', hints: ['El P&ID dibuja los instrumentos, pero no es una tabla.', null, 'La hoja de datos describe un solo instrumento.', 'El diagrama de lazo muestra un solo lazo.'] };
const Q_DC1C2_2 = { id: 'dc1c2-q2', q: 'En el número P420-110-IC-HD-0040, ¿qué indica «110»?', options: ['El proyecto', 'El área de la planta', 'La disciplina', 'La revisión'], answer: 1, explain: 'El orden es proyecto, área, disciplina, tipo de documento y consecutivo: 110 es el área.', hints: ['El proyecto es P420.', null, 'La disciplina es IC.', 'La revisión no va en el número: va en el cajetín.'] };
const Q_DC1C2_3 = { id: 'dc1c2-q3', q: 'Cambias el rango de un transmisor en una base de datos de instrumentación. ¿Qué ventaja tiene?', options: ['El instrumento se calibra solo', 'El cambio se hace una vez y aparece en todos los documentos', 'Ya no hace falta revisar', 'El plano se imprime más rápido'], answer: 1, explain: 'La base de datos guarda cada dato una sola vez: índice, hoja de datos y lazo se generan desde ese dato.', hints: ['La calibración se hace en campo.', null, 'Todo cambio se sigue revisando y aprobando.', 'La ventaja no es la impresión, es la consistencia.'] };

const SCENES_DC1C2 = [
  { C: (p) => <TitleCardM4 {...p} claseNo={2} title="Los entregables de instrumentación" dudur="6 min" objetivo="Las tres familias de documentos, el índice de instrumentos, cómo fluye la información, cómo se numeran los planos y qué dice el cajetín." />, dur: 14, label: 'Apertura' },
  { C: S_Families, dur: 38, label: 'Tres familias' },
  { C: S_Index, dur: 38, label: 'El índice' },
  { C: QuizSceneM4, dur: 12, label: 'Pregunta 1', quiz: Q_DC1C2_1 },
  { C: S_Flow, dur: 42, label: 'El flujo de información' },
  { C: S_Layouts, dur: 28, label: 'Planos de ubicación' },
  { C: S_Code, dur: 34, label: 'La numeración' },
  { C: QuizSceneM4, dur: 12, label: 'Pregunta 2', quiz: Q_DC1C2_2 },
  { C: S_TitleBlk, dur: 32, label: 'El cajetín' },
  { C: S_Example, dur: 38, label: 'Ejemplo' },
  { C: S_Tools, dur: 32, label: 'Las herramientas' },
  { C: QuizSceneM4, dur: 12, label: 'Pregunta 3', quiz: Q_DC1C2_3 },
  { C: (p) => <><ClosingM4 {...p} line="Tres familias, un índice que lo une todo y un número que identifica cada plano." activity="Toma un transmisor de tu planta y busca cuántos documentos lo mencionan: P&ID, índice, hoja de datos, lazo y típico." /><QuizScoreM4 {...p} /></>, dur: 16, label: 'Cierre' },
];
window.SCENES_DC1C2 = SCENES_DC1C2;
