// di-art.jsx — Dibujos del curso «Diseño de Ingeniería I&C»: símbolos ISA 5.1,
// líneas de señal, equipos de un P&ID, borneras, cajas de conexión, pantallas HMI
// y compuertas de ISA 5.2. Después de di-lib.jsx (TL4, DISP4, MONO4, pop4, clamp).

const DI = {
  ink: '#0f2b4a', mut: '#5b7388', line: '#1f3d5c', paper: '#ffffff',
  proc: '#0f2b4a', sig: '#2f86e6', pneu: '#7a4fd0', data: '#2fae6a', alarm: '#d7263d',
  steel: '#d3dae2', steelD: '#9aa6b4', liq: '#b9d8f6', liqD: '#3f86d4',
  hmiBg: '#d9dde2', hmiGrey: '#9aa3ad', hmiDark: '#4a5560', hi: '#df6f1f',
};

// Aparición suave de un grupo SVG
const Fade = ({ t, at, children, d = 0.5 }) => <g opacity={at == null ? 1 : clamp((t - at) / d, 0, 1)}>{children}</g>;

// ── Burbuja ISA 5.1 ──────────────────────────────────────────────────────────
// kind: 'field' (círculo), 'board' (círculo con línea: sala de control),
// 'aux' (línea punteada: panel local, fuera de la vista del operador),
// 'dcs' (círculo dentro de cuadrado: display compartido / DCS),
// 'plc' (rombo dentro de cuadrado: control lógico programable), 'comp' (hexágono: computador),
// 'sis' (rombo dentro de cuadrado con doble borde: sistema instrumentado de seguridad)
function IsaBubble({ x, y, r = 46, tag = 'PT', num = '101', kind = 'field', color = DI.ink, fill = DI.paper, sw = 3, fs }) {
  const f1 = fs || r * 0.5, f2 = (fs || r * 0.5) * 0.86;
  const mid = kind === 'board' || kind === 'dcs' || kind === 'plc' || kind === 'sis' || kind === 'comp';
  const midAux = kind === 'aux';
  const midL = kind === 'local';
  const box = kind === 'dcs' || kind === 'plc' || kind === 'sis';
  return (
    <g>
      {box && <rect x={x - r} y={y - r} width={2 * r} height={2 * r} fill={fill} stroke={color} strokeWidth={sw} />}
      {kind === 'sis' && <rect x={x - r - 6} y={y - r - 6} width={2 * r + 12} height={2 * r + 12} fill="none" stroke={color} strokeWidth={sw * 0.7} />}
      {kind === 'comp' && <polygon points={[0, 1, 2, 3, 4, 5].map(i => `${x + r * Math.cos(Math.PI / 3 * i)},${y + r * Math.sin(Math.PI / 3 * i)}`).join(' ')} fill={fill} stroke={color} strokeWidth={sw} />}
      {(kind === 'plc' || kind === 'sis')
        ? <polygon points={`${x},${y - r} ${x + r},${y} ${x},${y + r} ${x - r},${y}`} fill={fill} stroke={color} strokeWidth={sw} />
        : kind !== 'comp' && <circle cx={x} cy={y} r={r} fill={fill} stroke={color} strokeWidth={sw} />}
      {mid && <line x1={x - r} y1={y} x2={x + r} y2={y} stroke={color} strokeWidth={sw * 0.8} />}
      {midAux && <line x1={x - r} y1={y} x2={x + r} y2={y} stroke={color} strokeWidth={sw * 0.8} strokeDasharray="7 6" />}
      {kind === 'local' && <g><line x1={x - r * 0.98} y1={y - 4} x2={x + r * 0.98} y2={y - 4} stroke={color} strokeWidth={sw * 0.7} /><line x1={x - r * 0.98} y1={y + 4} x2={x + r * 0.98} y2={y + 4} stroke={color} strokeWidth={sw * 0.7} /></g>}
      <text x={x} y={y - (mid || midAux || midL ? 10 : -2) - (mid || midAux || midL ? 0 : r * 0.08)} fill={color} fontFamily={MONO4} fontSize={f1} fontWeight="700" textAnchor="middle" dominantBaseline={mid || midAux ? 'auto' : 'auto'}>{tag}</text>
      <text x={x} y={y + (mid || midAux || midL ? f2 + 8 : r * 0.55)} fill={color} fontFamily={MONO4} fontSize={f2} fontWeight="600" textAnchor="middle">{num}</text>
    </g>
  );
}

// ── Líneas de señal ISA 5.1 ──────────────────────────────────────────────────
// type: 'process' | 'electric' | 'pneumatic' | 'data' | 'capillary' | 'hydraulic' | 'link'
function SigLine({ x1, y1, x2, y2, type = 'electric', color, w = 3, t, at, dur = 0.7 }) {
  const e = at == null ? 1 : Easing.easeInOutCubic(clamp((t - at) / dur, 0, 1));
  if (e <= 0) return null;
  const c = color || (type === 'process' ? DI.proc : type === 'pneumatic' ? DI.pneu : type === 'data' || type === 'link' ? DI.data : DI.sig);
  const xe = x1 + (x2 - x1) * e, ye = y1 + (y2 - y1) * e;
  const L = Math.hypot(x2 - x1, y2 - y1), ux = (x2 - x1) / L, uy = (y2 - y1) / L, nx = -uy, ny = ux;
  const marks = [];
  const n = Math.floor(L * e / 60);
  for (let i = 1; i <= n; i++) {
    const d = i * 60 - 30, px = x1 + ux * d, py = y1 + uy * d;
    if (type === 'pneumatic') {
      [-5, 5].forEach((o) => marks.push(<line key={i + 'p' + o} x1={px + ux * o - nx * 9 + ux * 5} y1={py + uy * o - ny * 9 + uy * 5} x2={px + ux * o + nx * 9 - ux * 5} y2={py + uy * o + ny * 9 - uy * 5} stroke={c} strokeWidth={w * 0.8} />));
    } else if (type === 'data') {
      marks.push(<circle key={i} cx={px} cy={py} r={5} fill={DI.paper} stroke={c} strokeWidth={w * 0.7} />);
    } else if (type === 'capillary') {
      marks.push(<g key={i}><line x1={px - 7} y1={py - 7} x2={px + 7} y2={py + 7} stroke={c} strokeWidth={w * 0.7} /><line x1={px - 7} y1={py + 7} x2={px + 7} y2={py - 7} stroke={c} strokeWidth={w * 0.7} /></g>);
    } else if (type === 'hydraulic') {
      marks.push(<path key={i} d={`M${px - nx * 9} ${py - ny * 9} L${px + nx * 9} ${py + ny * 9} L${px + nx * 9 + ux * 10} ${py + ny * 9 + uy * 10}`} fill="none" stroke={c} strokeWidth={w * 0.7} />);
    }
  }
  const dash = type === 'electric' ? '12 8' : type === 'link' ? '2 7' : undefined;
  return (
    <g>
      <line x1={x1} y1={y1} x2={xe} y2={ye} stroke={c} strokeWidth={type === 'process' ? w * 1.6 : w} strokeDasharray={dash} strokeLinecap={type === 'link' ? 'round' : 'butt'} />
      {marks}
    </g>
  );
}

// Polilínea de señal por tramos rectos
function SigPath({ pts, type = 'electric', t, at, step = 0.35, color, w }) {
  return <g>{pts.slice(1).map((p, i) => <SigLine key={i} x1={pts[i][0]} y1={pts[i][1]} x2={p[0]} y2={p[1]} type={type} t={t} at={at == null ? null : at + i * step} color={color} w={w} />)}</g>;
}

// Flecha de flujo de proceso
function ProcArrow({ x, y, dir = 'r', s = 14, color = DI.proc }) {
  const P = { r: `${x},${y} ${x - s},${y - s * 0.6} ${x - s},${y + s * 0.6}`, l: `${x},${y} ${x + s},${y - s * 0.6} ${x + s},${y + s * 0.6}`, d: `${x},${y} ${x - s * 0.6},${y - s} ${x + s * 0.6},${y - s}`, u: `${x},${y} ${x - s * 0.6},${y + s} ${x + s * 0.6},${y + s}` }[dir];
  return <polygon points={P} fill={color} />;
}

// ── Equipos de P&ID ───────────────────────────────────────────────────────────
// Válvula de control: cuerpo de dos triángulos y actuador de diafragma
function CtrlValve({ x, y, s = 1, color = DI.ink, fill = DI.paper, act = 'diaphragm', fail, rot = 0 }) {
  const w = 34 * s, h = 22 * s;
  return (
    <g transform={`rotate(${rot} ${x} ${y})`}>
      <polygon points={`${x - w},${y - h} ${x},${y} ${x - w},${y + h}`} fill={fill} stroke={color} strokeWidth={3} strokeLinejoin="round" />
      <polygon points={`${x + w},${y - h} ${x},${y} ${x + w},${y + h}`} fill={fill} stroke={color} strokeWidth={3} strokeLinejoin="round" />
      <line x1={x} y1={y} x2={x} y2={y - 42 * s} stroke={color} strokeWidth={3} />
      {act === 'diaphragm' && <path d={`M${x - 26 * s} ${y - 42 * s} A ${26 * s} ${22 * s} 0 0 1 ${x + 26 * s} ${y - 42 * s} Z`} fill={fill} stroke={color} strokeWidth={3} />}
      {act === 'motor' && <g><circle cx={x} cy={y - 62 * s} r={20 * s} fill={fill} stroke={color} strokeWidth={3} /><text x={x} y={y - 55 * s} fill={color} fontFamily={MONO4} fontSize={20 * s} fontWeight="700" textAnchor="middle">M</text></g>}
      {act === 'solenoid' && <g><rect x={x - 18 * s} y={y - 78 * s} width={36 * s} height={36 * s} fill={fill} stroke={color} strokeWidth={3} /><text x={x} y={y - 52 * s} fill={color} fontFamily={MONO4} fontSize={20 * s} fontWeight="700" textAnchor="middle">S</text></g>}
      {act === 'manual' && <line x1={x - 22 * s} y1={y - 42 * s} x2={x + 22 * s} y2={y - 42 * s} stroke={color} strokeWidth={4} />}
      {fail && <text x={x + w + 8} y={y + 6} fill={DI.mut} fontFamily={MONO4} fontSize={18 * s} fontWeight="600">{fail}</text>}
    </g>
  );
}

// Válvula de bloqueo manual (compuerta)
function HandValve({ x, y, s = 1, color = DI.ink, rot = 0 }) {
  const w = 22 * s, h = 14 * s;
  return (
    <g transform={`rotate(${rot} ${x} ${y})`}>
      <polygon points={`${x - w},${y - h} ${x},${y} ${x - w},${y + h}`} fill={DI.paper} stroke={color} strokeWidth={2.5} />
      <polygon points={`${x + w},${y - h} ${x},${y} ${x + w},${y + h}`} fill={DI.paper} stroke={color} strokeWidth={2.5} />
    </g>
  );
}

// Válvula de seguridad (PSV)
function ReliefValve({ x, y, s = 1, color = DI.ink }) {
  return (
    <g>
      <polygon points={`${x - 20 * s},${y + 30 * s} ${x + 20 * s},${y + 30 * s} ${x},${y}`} fill={DI.paper} stroke={color} strokeWidth={3} />
      <polygon points={`${x},${y} ${x + 30 * s},${y - 20 * s} ${x + 30 * s},${y + 20 * s}`} fill={DI.paper} stroke={color} strokeWidth={3} />
      <path d={`M${x - 8 * s} ${y - 6 * s} l 6 -8 l -8 -6 l 6 -8 l -8 -6`} fill="none" stroke={color} strokeWidth={2.5} />
    </g>
  );
}

// Recipiente vertical con nivel de líquido opcional
function Vessel({ x, y, w = 220, h = 360, level = 0.5, t = 0, name, color = DI.ink, liquid = true }) {
  const r = w / 2;
  const ly = y + h - (h - 40) * level - 20;
  return (
    <g>
      <defs><clipPath id={`vc${x}${y}`}><path d={`M${x} ${y + r * 0.45} Q ${x} ${y} ${x + r} ${y} Q ${x + w} ${y} ${x + w} ${y + r * 0.45} L ${x + w} ${y + h - r * 0.45} Q ${x + w} ${y + h} ${x + r} ${y + h} Q ${x} ${y + h} ${x} ${y + h - r * 0.45} Z`} /></clipPath></defs>
      <path d={`M${x} ${y + r * 0.45} Q ${x} ${y} ${x + r} ${y} Q ${x + w} ${y} ${x + w} ${y + r * 0.45} L ${x + w} ${y + h - r * 0.45} Q ${x + w} ${y + h} ${x + r} ${y + h} Q ${x} ${y + h} ${x} ${y + h - r * 0.45} Z`} fill={DI.paper} stroke={color} strokeWidth={3.5} />
      {liquid && <g clipPath={`url(#vc${x}${y})`}>
        <path d={`M${x - 10} ${ly + Math.sin(t * 2) * 3} Q ${x + w / 4} ${ly - 6} ${x + w / 2} ${ly} T ${x + w + 10} ${ly} L ${x + w + 10} ${y + h + 10} L ${x - 10} ${y + h + 10} Z`} fill={DI.liq} />
        <line x1={x} y1={ly} x2={x + w} y2={ly} stroke={DI.liqD} strokeWidth={2} />
      </g>}
      {name && <text x={x + w / 2} y={y + h + 40} fill={color} fontFamily={MONO4} fontSize="22" fontWeight="700" textAnchor="middle">{name}</text>}
    </g>
  );
}

// Bomba centrífuga
function Pump({ x, y, r = 34, color = DI.ink, name, on = false, t = 0 }) {
  return (
    <g>
      <circle cx={x} cy={y} r={r} fill={on ? '#e6f6ec' : DI.paper} stroke={color} strokeWidth={3} />
      <line x1={x} y1={y - r} x2={x + r} y2={y - r} stroke={color} strokeWidth={3} />
      <polygon points={`${x - r * 0.4},${y + r * 0.85} ${x + r * 0.4},${y + r * 0.85} ${x + r * 0.7},${y + r * 1.35} ${x - r * 0.7},${y + r * 1.35}`} fill={DI.paper} stroke={color} strokeWidth={2.5} />
      {on && <g transform={`rotate(${(t * 360) % 360} ${x} ${y})`}><line x1={x - r * 0.5} y1={y} x2={x + r * 0.5} y2={y} stroke={TL4.ok} strokeWidth={3} /><line x1={x} y1={y - r * 0.5} x2={x} y2={y + r * 0.5} stroke={TL4.ok} strokeWidth={3} /></g>}
      {name && <text x={x} y={y + r * 1.35 + 30} fill={color} fontFamily={MONO4} fontSize="20" fontWeight="700" textAnchor="middle">{name}</text>}
    </g>
  );
}

// Placa de orificio en P&ID (dos líneas cortas en la tubería)
function OrificeSym({ x, y, h = 26, color = DI.ink }) {
  return <g><line x1={x - 5} y1={y - h} x2={x - 5} y2={y + h} stroke={color} strokeWidth={3} /><line x1={x + 5} y1={y - h} x2={x + 5} y2={y + h} stroke={color} strokeWidth={3} /></g>;
}

// Etiqueta de alarma junto a una burbuja (H, HH, L, LL)
function AlarmTag({ x, y, text, color = DI.alarm }) {
  return <text x={x} y={y} fill={color} fontFamily={MONO4} fontSize="19" fontWeight="700">{text}</text>;
}

// ── Conexionado: bornera, caja de conexiones y cable ─────────────────────────
function TermStrip({ x, y, n = 6, labels = [], name, color = DI.ink, w = 64, h = 40, hi = [] }) {
  return (
    <g>
      {name && <text x={x + w / 2} y={y - 14} fill={color} fontFamily={MONO4} fontSize="18" fontWeight="700" textAnchor="middle">{name}</text>}
      {Array.from({ length: n }, (_, i) => (
        <g key={i}>
          <rect x={x} y={y + i * h} width={w} height={h} fill={hi.includes(i) ? TL4.orangeWash : DI.paper} stroke={color} strokeWidth={2} />
          <circle cx={x + 14} cy={y + i * h + h / 2} r={5} fill={DI.steelD} />
          <text x={x + w / 2 + 8} y={y + i * h + h / 2 + 6} fill={color} fontFamily={MONO4} fontSize="16" fontWeight="600" textAnchor="middle">{labels[i] ?? i + 1}</text>
        </g>
      ))}
    </g>
  );
}

// Caja con título (JB, gabinete, tarjeta)
function BoxSym({ x, y, w, h, title, sub, color = DI.ink, fill = '#f6f9fd', dash, accent }) {
  return (
    <g>
      <rect x={x} y={y} width={w} height={h} rx={10} fill={fill} stroke={accent || color} strokeWidth={3} strokeDasharray={dash} />
      {title && <text x={x + 16} y={y + 30} fill={accent || color} fontFamily={DISP4} fontSize="22" fontWeight="700">{title}</text>}
      {sub && <text x={x + 16} y={y + 54} fill={DI.mut} fontFamily={MONO4} fontSize="16">{sub}</text>}
    </g>
  );
}

// Cable: polilínea gruesa con etiqueta
function Cable({ pts, label, color = '#34495e', w = 6, t, at, lx, ly }) {
  const op = at == null ? 1 : clamp((t - at) / 0.6, 0, 1);
  return (
    <g opacity={op}>
      <polyline points={pts.map(p => p.join(',')).join(' ')} fill="none" stroke={color} strokeWidth={w} strokeLinejoin="round" strokeLinecap="round" />
      {label && <g><rect x={(lx ?? pts[0][0]) - 4} y={(ly ?? pts[0][1]) - 24} width={label.length * 11 + 16} height={30} rx={6} fill={DI.paper} stroke={color} strokeWidth={1.5} />
        <text x={(lx ?? pts[0][0]) + 4} y={(ly ?? pts[0][1]) - 3} fill={color} fontFamily={MONO4} fontSize="17" fontWeight="600">{label}</text></g>}
    </g>
  );
}

// Transmisor de campo simplificado (cabezal redondo y cuerpo)
function FieldTx({ x, y, s = 1, color = DI.ink, label }) {
  return (
    <g>
      <rect x={x - 26 * s} y={y - 10 * s} width={52 * s} height={44 * s} rx={8} fill={DI.steel} stroke={color} strokeWidth={2.5} />
      <circle cx={x} cy={y - 34 * s} r={30 * s} fill={DI.paper} stroke={color} strokeWidth={3} />
      <rect x={x - 18 * s} y={y - 46 * s} width={36 * s} height={18 * s} rx={3} fill="#dff3e6" stroke={color} strokeWidth={1.5} />
      <line x1={x} y1={y + 34 * s} x2={x} y2={y + 60 * s} stroke={color} strokeWidth={5} />
      {label && <text x={x} y={y + 90 * s} fill={color} fontFamily={MONO4} fontSize={18 * s} fontWeight="700" textAnchor="middle">{label}</text>}
    </g>
  );
}

// ── Compuertas de ISA 5.2 (diagramas lógicos) ───────────────────────────────
// kind: 'AND' | 'OR' | 'NOT' | 'TON' (retardo a la conexión) | 'SR' (memoria) | 'CMP'
function LogicBox({ x, y, kind = 'AND', w = 110, h = 90, color = DI.ink, label, active }) {
  const txt = { AND: 'A', OR: 'OR', NOT: 'NOT', TON: 'DI', TOF: 'DT', SR: 'S\nR', CMP: '≥' }[kind] || kind;
  const fill = active ? '#e6f6ec' : DI.paper;
  return (
    <g>
      <rect x={x} y={y} width={w} height={h} fill={fill} stroke={active ? TL4.ok : color} strokeWidth={3} />
      {kind === 'SR'
        ? <g><text x={x + 14} y={y + 32} fill={color} fontFamily={MONO4} fontSize="22" fontWeight="700">S</text><text x={x + 14} y={y + h - 14} fill={color} fontFamily={MONO4} fontSize="22" fontWeight="700">R</text></g>
        : <text x={x + w / 2} y={y + h / 2 + 10} fill={color} fontFamily={MONO4} fontSize={txt.length > 2 ? 24 : 30} fontWeight="700" textAnchor="middle">{txt}</text>}
      {label && <text x={x + w / 2} y={y + h + 24} fill={DI.mut} fontFamily={MONO4} fontSize="16" textAnchor="middle">{label}</text>}
    </g>
  );
}

// Entrada o salida de un diagrama lógico (bandera con texto)
function LogicIO({ x, y, text, out = false, w = 250, color = DI.ink, active }) {
  const h = 46;
  const d = out
    ? `M${x} ${y - h / 2} L${x + w - 20} ${y - h / 2} L${x + w} ${y} L${x + w - 20} ${y + h / 2} L${x} ${y + h / 2} Z`
    : `M${x} ${y - h / 2} L${x + w} ${y - h / 2} L${x + w} ${y + h / 2} L${x} ${y + h / 2} L${x + 20} ${y} Z`;
  return (
    <g>
      <path d={d} fill={active ? '#e6f6ec' : DI.paper} stroke={active ? TL4.ok : color} strokeWidth={2.5} />
      <text x={x + w / 2 + (out ? -8 : 10)} y={y + 7} fill={color} fontFamily={DISP4} fontSize="19" fontWeight="600" textAnchor="middle">{text}</text>
    </g>
  );
}

// Conector ortogonal entre dos puntos (para lógica y lazos)
function Wire({ a, b, mid = 0.5, color = DI.ink, w = 2.5, active, t, at }) {
  const op = at == null ? 1 : clamp((t - at) / 0.5, 0, 1);
  const mx = a[0] + (b[0] - a[0]) * mid;
  return <polyline opacity={op} points={`${a[0]},${a[1]} ${mx},${a[1]} ${mx},${b[1]} ${b[0]},${b[1]}`} fill="none" stroke={active ? TL4.ok : color} strokeWidth={active ? w + 1.5 : w} />;
}

// ── Pantalla HMI (marco de monitor) ─────────────────────────────────────────
function HmiFrame({ x, y, w, h, title = 'U-100 · Separador', children, style = 'hp' }) {
  const bg = style === 'hp' ? DI.hmiBg : '#0b0f2a';
  return (
    <g>
      <rect x={x - 14} y={y - 14} width={w + 28} height={h + 56} rx={14} fill="#2b333c" />
      <rect x={x} y={y + 28} width={w} height={h} fill={bg} />
      <rect x={x} y={y} width={w} height={28} fill={style === 'hp' ? '#b9c0c8' : '#1d2bd8'} />
      <text x={x + 12} y={y + 20} fill={style === 'hp' ? '#2b333c' : '#ffff00'} fontFamily={MONO4} fontSize="15" fontWeight="700">{title}</text>
      <g transform={`translate(${x} ${y + 28})`}>{children}</g>
    </g>
  );
}

// Valor de proceso en HMI de alto desempeño (gris; color solo si hay alarma)
function HmiValue({ x, y, tag, value, unit, alarm, w = 170 }) {
  const c = alarm ? DI.alarm : '#2b333c';
  return (
    <g>
      <rect x={x} y={y} width={w} height={54} fill={alarm ? '#f6d4d8' : '#eceff2'} stroke={alarm ? DI.alarm : '#8a939c'} strokeWidth={alarm ? 3 : 1.5} />
      <text x={x + 8} y={y + 20} fill="#5c6670" fontFamily={MONO4} fontSize="14">{tag}</text>
      <text x={x + w - 8} y={y + 45} fill={c} fontFamily={MONO4} fontSize="22" fontWeight="700" textAnchor="end">{value} <tspan fontSize="14">{unit}</tspan></text>
      {alarm && <g><rect x={x + w + 6} y={y + 8} width={36} height={36} fill={DI.alarm} /><text x={x + w + 24} y={y + 33} fill="#fff" fontFamily={MONO4} fontSize="16" fontWeight="700" textAnchor="middle">{alarm}</text></g>}
    </g>
  );
}

// Barra analógica de ISA-101: rango normal sombreado y aguja de valor
function HmiBar({ x, y, h = 200, w = 34, v = 0.5, lo = 0.3, hi = 0.7, alarm }) {
  const py = y + h - v * h;
  return (
    <g>
      <rect x={x} y={y} width={w} height={h} fill="#eceff2" stroke="#8a939c" strokeWidth={1.5} />
      <rect x={x} y={y + h - hi * h} width={w} height={(hi - lo) * h} fill="#c9ced4" />
      <polygon points={`${x + w},${py} ${x + w + 16},${py - 9} ${x + w + 16},${py + 9}`} fill={alarm ? DI.alarm : '#2b333c'} />
    </g>
  );
}

// Cajetín (bloque de título) de un plano
function TitleBlock({ x, y, w = 520, rows }) {
  return (
    <g>
      {rows.map(([k, v, hi], i) => (
        <g key={i}>
          <rect x={x} y={y + i * 40} width={w} height={40} fill={hi ? TL4.orangeWash : DI.paper} stroke={DI.ink} strokeWidth={1.5} />
          <text x={x + 12} y={y + i * 40 + 26} fill={DI.mut} fontFamily={MONO4} fontSize="15">{k}</text>
          <text x={x + 190} y={y + i * 40 + 26} fill={DI.ink} fontFamily={MONO4} fontSize="17" fontWeight="700">{v}</text>
        </g>
      ))}
    </g>
  );
}

// Hoja de documento con líneas (icono de entregable)
function DocSheet({ x, y, w = 120, h = 156, title, code, color = TL4.blue, op = 1, kind = 'lines' }) {
  return (
    <g opacity={op}>
      <path d={`M${x} ${y} L${x + w - 28} ${y} L${x + w} ${y + 28} L${x + w} ${y + h} L${x} ${y + h} Z`} fill={DI.paper} stroke={color} strokeWidth={2.5} />
      <path d={`M${x + w - 28} ${y} L${x + w - 28} ${y + 28} L${x + w} ${y + 28}`} fill="none" stroke={color} strokeWidth={2} />
      {kind === 'lines' && [0, 1, 2, 3, 4].map(i => <line key={i} x1={x + 16} y1={y + 46 + i * 18} x2={x + w - 16 - (i % 2) * 22} y2={y + 46 + i * 18} stroke={DI.steelD} strokeWidth={3} />)}
      {kind === 'pid' && <g><rect x={x + 18} y={y + 44} width={30} height={60} rx={12} fill="none" stroke={DI.steelD} strokeWidth={2.5} /><line x1={x + 48} y1={y + 90} x2={x + w - 14} y2={y + 90} stroke={DI.steelD} strokeWidth={2.5} /><circle cx={x + 80} cy={y + 60} r={13} fill="none" stroke={color} strokeWidth={2.5} /></g>}
      {kind === 'logic' && <g><rect x={x + 30} y={y + 50} width={34} height={30} fill="none" stroke={color} strokeWidth={2.5} /><line x1={x + 12} y1={y + 58} x2={x + 30} y2={y + 58} stroke={DI.steelD} strokeWidth={2.5} /><line x1={x + 12} y1={y + 72} x2={x + 30} y2={y + 72} stroke={DI.steelD} strokeWidth={2.5} /><line x1={x + 64} y1={y + 65} x2={x + w - 12} y2={y + 65} stroke={DI.steelD} strokeWidth={2.5} /></g>}
      {kind === 'table' && <g>{[0, 1, 2, 3].map(i => <line key={i} x1={x + 12} y1={y + 46 + i * 22} x2={x + w - 12} y2={y + 46 + i * 22} stroke={DI.steelD} strokeWidth={2} />)}{[0, 1].map(i => <line key={'v' + i} x1={x + 44 + i * 36} y1={y + 40} x2={x + 44 + i * 36} y2={y + 112} stroke={DI.steelD} strokeWidth={2} />)}</g>}
      {title && <text x={x + w / 2} y={y + h + 28} fill={DI.ink} fontFamily={DISP4} fontSize="19" fontWeight="700" textAnchor="middle">{title}</text>}
      {code && <text x={x + w / 2} y={y + h - 14} fill={color} fontFamily={MONO4} fontSize="14" fontWeight="700" textAnchor="middle">{code}</text>}
    </g>
  );
}

Object.assign(window, {
  DI, Fade, IsaBubble, SigLine, SigPath, ProcArrow, CtrlValve, HandValve, ReliefValve, Vessel, Pump, OrificeSym, AlarmTag,
  TermStrip, BoxSym, Cable, FieldTx, LogicBox, LogicIO, Wire, HmiFrame, HmiValue, HmiBar, TitleBlock, DocSheet,
});

// Nube de revisión alrededor de un rectángulo y triángulo con el número de revisión
function RevCloud({ x, y, w, h, color = DI.alarm, r = 16, sw = 3 }) {
  const arcs = [];
  const nx = Math.max(2, Math.round(w / (2 * r))), ny = Math.max(2, Math.round(h / (2 * r)));
  const dx = w / nx, dy = h / ny;
  let d = `M${x} ${y}`;
  for (let i = 0; i < nx; i++) d += ` a ${dx / 2} ${r * 0.8} 0 0 1 ${dx} 0`;
  for (let i = 0; i < ny; i++) d += ` a ${r * 0.8} ${dy / 2} 0 0 1 0 ${dy}`;
  for (let i = 0; i < nx; i++) d += ` a ${dx / 2} ${r * 0.8} 0 0 1 ${-dx} 0`;
  for (let i = 0; i < ny; i++) d += ` a ${r * 0.8} ${dy / 2} 0 0 1 0 ${-dy}`;
  return <path d={d} fill="none" stroke={color} strokeWidth={sw} />;
}
function RevTri({ x, y, n = '1', color = DI.alarm, s = 30 }) {
  return <g><polygon points={`${x},${y - s} ${x + s * 0.9},${y + s * 0.6} ${x - s * 0.9},${y + s * 0.6}`} fill={DI.paper} stroke={color} strokeWidth={3} />
    <text x={x} y={y + s * 0.38} fill={color} fontFamily={MONO4} fontSize={s * 0.75} fontWeight="700" textAnchor="middle">{n}</text></g>;
}
Object.assign(window, { RevCloud, RevTri });

// ── P&ID de ejemplo: separador V-100 con sus lazos ──────────────────────────
// show: grupos visibles ('base','lvl','press','psv','sd','flow','temp','notes');
// hi: grupo resaltado (los demás se atenúan). t: tiempo (para el nivel).
function SepPid({ t = 0, show = ['base', 'lvl', 'press', 'psv', 'sd', 'flow', 'temp'], hi, ops = {} }) {
  const vis = (k) => show.includes(k);
  const op = (k) => (ops[k] ?? 1) * (!hi || hi === k || k === 'base' ? 1 : 0.22);
  const P = DI.ink;
  return (
    <g>
      {vis('base') && <g opacity={op('base')}>
        <Vessel x={560} y={360} w={220} h={440} level={0.5 + 0.03 * Math.sin(t)} t={t} />
        <text x={545} y={780} fill={P} fontFamily={MONO4} fontSize="20" fontWeight="700" textAnchor="end">V-100</text><text x={545} y={804} fill={DI.mut} fontFamily={MONO4} fontSize="15" textAnchor="end">Separador</text>
        <line x1={150} y1={470} x2={560} y2={470} stroke={P} strokeWidth={5} /><ProcArrow x={540} y={470} />
        <text x={160} y={455} fill={DI.mut} fontFamily={MONO4} fontSize="15">8"-P-1001-A1 · de pozos</text>
        <path d="M740 360 L740 300 L1320 300" fill="none" stroke={P} strokeWidth={5} /><ProcArrow x={1330} y={300} />
        <text x={1250} y={285} fill={DI.mut} fontFamily={MONO4} fontSize="15" textAnchor="end">6"-G-1002 · gas</text>
        <path d="M670 800 L670 860 L1320 860" fill="none" stroke={P} strokeWidth={5} /><ProcArrow x={1330} y={860} />
        <text x={1250} y={895} fill={DI.mut} fontFamily={MONO4} fontSize="15" textAnchor="end">4"-P-1003 · crudo</text>
      </g>}
      {vis('lvl') && <g opacity={op('lvl')}>
        <path d="M780 480 L830 480 L830 720 L780 720" fill="none" stroke={P} strokeWidth={3} />
        <SigLine x1={830} y1={600} x2={862} y2={600} type="electric" />
        <IsaBubble x={900} y={600} r={38} tag="LT" num="101" />
        <SigLine x1={938} y1={600} x2={1012} y2={600} type="electric" />
        <IsaBubble x={1050} y={600} r={38} tag="LIC" num="101" kind="dcs" />
        <AlarmTag x={1092} y={570} text="H" /><AlarmTag x={1092} y={650} text="L" />
        <SigPath pts={[[1088, 600], [1180, 600], [1180, 818]]} type="electric" />
        <CtrlValve x={1180} y={860} fail="FC" />
      </g>}
      {vis('press') && <g opacity={op('press')}>
        <SigLine x1={880} y1={300} x2={880} y2={352} type="electric" />
        <IsaBubble x={880} y={390} r={38} tag="PT" num="102" />
        <SigLine x1={918} y1={390} x2={1012} y2={390} type="electric" />
        <IsaBubble x={1050} y={390} r={38} tag="PIC" num="102" kind="dcs" />
        <SigPath pts={[[1088, 390], [1180, 390], [1180, 344]]} type="electric" />
        <CtrlValve x={1180} y={300} rot={180} />
        <text x={1222} y={345} fill={DI.mut} fontFamily={MONO4} fontSize="16" fontWeight="600">FO</text>
      </g>}
      {vis('psv') && <g opacity={op('psv')}>
        <line x1={610} y1={360} x2={610} y2={340} stroke={P} strokeWidth={3} />
        <ReliefValve x={610} y={310} s={1} />
        <path d="M640 310 L690 310 L690 250" fill="none" stroke={P} strokeWidth={3} />
        <text x={700} y={250} fill={DI.mut} fontFamily={MONO4} fontSize="15">a tea</text>
        <text x={540} y={300} fill={P} fontFamily={MONO4} fontSize="16" fontWeight="700" textAnchor="end">PSV-106</text>
      </g>}
      {vis('sd') && <g opacity={op('sd')}>
        <line x1={560} y1={400} x2={510} y2={400} stroke={P} strokeWidth={3} />
        <IsaBubble x={472} y={400} r={38} tag="LSHH" num="104" fs={17} />
        <SigPath pts={[[434, 400], [300, 400], [300, 392]]} type="electric" />
        <CtrlValve x={300} y={470} act="solenoid" fail="FC" />
        <text x={300} y={530} fill={P} fontFamily={MONO4} fontSize="16" fontWeight="700" textAnchor="middle">SDV-100</text>
      </g>}
      {vis('flow') && <g opacity={op('flow')}>
        <OrificeSym x={950} y={860} h={22} />
        <SigLine x1={950} y1={882} x2={950} y2={922} type="electric" />
        <IsaBubble x={950} y={958} r={36} tag="FQI" num="103" kind="dcs" fs={17} />
      </g>}
      {vis('temp') && <g opacity={op('temp')}>
        <line x1={210} y1={470} x2={210} y2={420} stroke={P} strokeWidth={3} />
        <IsaBubble x={210} y={384} r={36} tag="TI" num="105" fs={17} />
      </g>}
    </g>
  );
}
Object.assign(window, { SepPid });
