```html
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>QuímLab · Pizarra Animada de Formulación</title>
    <style>
        :root {
            --bg-main: #090d16;
            --bg-card: #111827;
            --bg-inner: #060911;
            --border: #1f2937;
            --text-main: #f3f4f6;
            --text-muted: #9ca3af;
            --indigo: #4f46e5;
            --indigo-light: #818cf8;
            --blue: #3b82f6;
            --blue-light: #93c5fd;
            --rose: #f43f5e;
            --rose-light: #fda4af;
            --emerald: #10b981;
            --emerald-light: #6ee7b7;
            --amber: #f59e0b;
            --amber-light: #fcd34d;
            --purple: #8b5cf6;
            --purple-light: #c4b5fd;
        }
        * { box-sizing: border-box; margin: 0; padding: 0; }
        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
            background-color: var(--bg-main);
            color: var(--text-main);
            line-height: 1.5;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }
        .mono { font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; }
        header {
            background: rgba(17, 24, 39, 0.95);
            border-bottom: 1px solid var(--border);
            padding: 12px 16px;
            position: sticky;
            top: 0;
            z-index: 20;
        }
        .container { max-width: 1080px; margin: 0 auto; width: 100%; }
        .header-flex { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 12px; }
        .brand { display: flex; align-items: center; gap: 10px; }
        .brand-icon {
            background: linear-gradient(135deg, #4f46e5, #06b6d4);
            padding: 8px;
            border-radius: 10px;
            display: flex;
        }
        .brand h1 { font-size: 1.1rem; font-weight: 800; }
        .brand p { font-size: 0.75rem; color: var(--text-muted); }
        .nav-tabs {
            display: flex;
            background: #1f2937;
            padding: 4px;
            border-radius: 10px;
            gap: 4px;
        }
        .nav-btn {
            border: none;
            background: transparent;
            color: var(--text-muted);
            padding: 7px 14px;
            border-radius: 7px;
            font-size: 0.85rem;
            font-weight: 600;
            cursor: pointer;
            transition: 0.2s;
        }
        .nav-btn.active { background: var(--indigo); color: #fff; }
        main { flex: 1; padding: 18px 16px; }

        /* SELECTOR DE BLOQUES (PRIMERO BINARIOS, LUEGO TERNARIOS) */
        .levels-grid {
            display: grid;
            grid-template-columns: 1.15fr 1fr;
            gap: 12px;
            margin-bottom: 18px;
        }
        @media (max-width: 860px) { .levels-grid { grid-template-columns: 1fr; } }
        .level-box {
            background: var(--bg-card);
            border: 1px solid var(--border);
            border-radius: 16px;
            padding: 12px;
        }
        .level-badge {
            display: inline-block;
            font-size: 0.68rem;
            font-weight: 700;
            text-transform: uppercase;
            padding: 3px 8px;
            border-radius: 6px;
            margin-bottom: 8px;
            letter-spacing: 0.04em;
        }
        .badge-bin { background: rgba(59, 130, 246, 0.15); color: var(--blue-light); border: 1px solid rgba(59, 130, 246, 0.3); }
        .badge-ter { background: rgba(139, 92, 246, 0.15); color: var(--purple-light); border: 1px solid rgba(139, 92, 246, 0.3); }
        .fam-grid-4 { display: grid; grid-template-columns: repeat(4, 1fr); gap: 6px; }
        .fam-grid-3 { display: grid; grid-template-columns: repeat(3, 1fr); gap: 6px; }
        @media (max-width: 540px) {
            .fam-grid-4 { grid-template-columns: repeat(2, 1fr); }
            .fam-grid-3 { grid-template-columns: repeat(3, 1fr); }
        }
        .fam-btn {
            background: var(--bg-inner);
            border: 1px solid var(--border);
            border-radius: 10px;
            padding: 8px 9px;
            text-align: left;
            color: var(--text-main);
            cursor: pointer;
            transition: 0.2s;
        }
        .fam-btn:hover { border-color: #4b5563; }
        .fam-btn.active-bin { border-color: var(--blue); background: rgba(59, 130, 246, 0.16); }
        .fam-btn.active-ter { border-color: var(--purple); background: rgba(139, 92, 246, 0.16); }
        .fam-top { display: flex; justify-content: space-between; align-items: center; font-weight: 700; font-size: 0.78rem; margin-bottom: 2px; }
        .fam-sub { font-size: 0.68rem; color: var(--text-muted); }

        /* BARRA DE CONTROLES DE LA PIZARRA AUTOMÁTICA */
        .control-bar {
            background: var(--bg-card);
            border: 1px solid var(--border);
            border-radius: 16px;
            padding: 12px 16px;
            margin-bottom: 18px;
            display: flex;
            flex-wrap: wrap;
            align-items: center;
            justify-content: space-between;
            gap: 10px;
        }
        .btn-primary {
            background: linear-gradient(135deg, #4f46e5, #2563eb);
            color: #fff;
            border: none;
            padding: 10px 18px;
            border-radius: 10px;
            font-weight: 700;
            font-size: 0.88rem;
            cursor: pointer;
            display: inline-flex;
            align-items: center;
            gap: 6px;
            box-shadow: 0 4px 12px rgba(79, 70, 229, 0.35);
            transition: transform 0.1s;
        }
        .btn-primary:active { transform: scale(0.97); }
        .btn-sec {
            background: #1f2937;
            color: #e5e7eb;
            border: 1px solid #374151;
            padding: 8px 13px;
            border-radius: 10px;
            font-weight: 600;
            font-size: 0.8rem;
            cursor: pointer;
            transition: 0.2s;
        }
        .btn-sec:hover { background: #374151; }
        .btn-sec.active-loop {
            background: rgba(16, 185, 129, 0.2);
            border-color: var(--emerald);
            color: var(--emerald-light);
        }

        /* ESCENARIO ANIMADO CENTRAL */
        .stage-card {
            background: var(--bg-card);
            border: 1px solid var(--border);
            border-radius: 22px;
            padding: 20px;
            position: relative;
            overflow: hidden;
        }
        .progress-track {
            position: absolute;
            top: 0; left: 0; right: 0;
            height: 4px;
            background: #1f2937;
        }
        .progress-fill {
            height: 100%;
            width: 0%;
            background: linear-gradient(90deg, var(--blue), var(--purple), var(--emerald));
            transition: width 0.3s linear;
        }
        .stage-header {
            display: flex;
            flex-wrap: wrap;
            justify-content: space-between;
            align-items: center;
            gap: 10px;
            margin-bottom: 14px;
        }
        .enunciado-box {
            background: rgba(79, 70, 229, 0.12);
            border: 1px solid rgba(79, 70, 229, 0.3);
            border-radius: 14px;
            padding: 12px 16px;
            text-align: center;
            margin-bottom: 18px;
        }
        .enunciado-label { font-size: 0.72rem; text-transform: uppercase; letter-spacing: 0.05em; color: var(--indigo-light); font-weight: 700; }
        .enunciado-text { font-size: 1.25rem; font-weight: 800; color: #fff; margin-top: 2px; }

        /* CÁLCULO PREVIO DE OXOANIÓN (SOLO PARA OXOÁCIDOS Y OXISALES) */
        .anion-calc-box {
            background: rgba(139, 92, 246, 0.1);
            border: 1px dashed rgba(139, 92, 246, 0.45);
            border-radius: 14px;
            padding: 12px 16px;
            margin-bottom: 18px;
            display: flex;
            flex-wrap: wrap;
            align-items: center;
            justify-content: space-between;
            gap: 12px;
            transition: opacity 0.5s, transform 0.5s;
        }
        .anion-calc-title { font-size: 0.74rem; font-weight: 700; text-transform: uppercase; color: var(--purple-light); }
        .anion-math { font-size: 1.05rem; font-weight: 700; color: #fff; }

        /* ZONA DE ANIMACIÓN DE CRUCE Y DESPEJE */
        .animation-arena {
            display: grid;
            grid-template-columns: 1fr auto 1fr auto 1fr;
            align-items: stretch;
            gap: 10px;
            margin: 10px 0 18px 0;
        }
        @media (max-width: 780px) {
            .animation-arena { grid-template-columns: 1fr; gap: 12px; }
            .arena-arrow { transform: rotate(90deg); margin: -4px auto; }
        }
        .arena-arrow {
            display: flex;
            align-items: center;
            justify-content: center;
            color: #4b5563;
            font-size: 1.4rem;
            font-weight: 800;
            transition: color 0.4s;
        }
        .arena-arrow.lit { color: var(--indigo-light); }

        .phase-box {
            background: var(--bg-inner);
            border: 1px solid var(--border);
            border-radius: 18px;
            padding: 16px 12px;
            text-align: center;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            min-height: 215px;
            opacity: 0.25;
            transform: translateY(10px) scale(0.98);
            transition: opacity 0.6s ease, transform 0.6s cubic-bezier(0.22, 1, 0.36, 1), border-color 0.5s;
        }
        .phase-box.visible {
            opacity: 1;
            transform: translateY(0) scale(1);
        }
        .phase-box.highlight-cross { border-color: rgba(99, 102, 241, 0.6); }
        .phase-box.highlight-final { border: 2px solid rgba(16, 185, 129, 0.65); box-shadow: 0 0 25px rgba(16, 185, 129, 0.12); }

        .phase-tag {
            display: inline-block;
            font-size: 0.68rem;
            font-weight: 700;
            text-transform: uppercase;
            padding: 3px 10px;
            border-radius: 99px;
            background: #1f2937;
            color: var(--text-muted);
            margin: 0 auto;
        }
        .phase-tag.blue { background: rgba(59, 130, 246, 0.2); color: var(--blue-light); }
        .phase-tag.indigo { background: rgba(99, 102, 241, 0.2); color: var(--indigo-light); }
        .phase-tag.green { background: rgba(16, 185, 129, 0.2); color: var(--emerald-light); }
        .phase-tag.amber { background: rgba(245, 158, 11, 0.2); color: var(--amber-light); }

        /* FÓRMULAS Y ANIMACIÓN DE NÚMEROS QUE BAJAN CRUZADOS */
        .chem-display {
            margin: auto 0;
            padding: 12px 0;
            position: relative;
        }
        .sym-big { font-size: 2.3rem; font-weight: 800; letter-spacing: -0.02em; }
        .sup-badge {
            font-size: 0.95rem;
            font-weight: 800;
            padding: 2px 6px;
            border-radius: 6px;
            vertical-align: super;
            margin-left: 2px;
            display: inline-block;
        }
        .c-pos { color: var(--blue-light); }
        .c-neg { color: var(--rose-light); }
        .bg-pos { background: rgba(59, 130, 246, 0.2); border: 1px solid rgba(59, 130, 246, 0.45); color: var(--blue-light); }
        .bg-neg { background: rgba(244, 63, 94, 0.2); border: 1px solid rgba(244, 63, 94, 0.45); color: var(--rose-light); }

        /* Animación de cruce en Fase 2 */
        .cross-diagram {
            position: relative;
            display: inline-block;
        }
        .cross-arcs {
            font-size: 0.85rem;
            font-weight: 800;
            margin-bottom: 2px;
            display: flex;
            justify-content: center;
            gap: 18px;
        }
        @keyframes flyDownLeft {
            0% { opacity: 0; transform: translate(24px, -28px) scale(1.25); }
            100% { opacity: 1; transform: translate(0, 0) scale(1); }
        }
        @keyframes flyDownRight {
            0% { opacity: 0; transform: translate(-24px, -28px) scale(1.25); }
            100% { opacity: 1; transform: translate(0, 0) scale(1); }
        }
        .sub-fly-left {
            display: inline-block;
            font-size: 1.35rem;
            font-weight: 800;
            color: var(--rose-light);
            vertical-align: sub;
            animation: flyDownLeft 0.85s cubic-bezier(0.16, 1, 0.3, 1) forwards;
        }
        .sub-fly-right {
            display: inline-block;
            font-size: 1.35rem;
            font-weight: 800;
            color: var(--blue-light);
            vertical-align: sub;
            animation: flyDownRight 0.85s cubic-bezier(0.16, 1, 0.3, 1) forwards;
        }

        /* Fase 3: Despeje / Resultado */
        @keyframes popFinal {
            0% { opacity: 0; transform: scale(0.82); }
            70% { transform: scale(1.06); }
            100% { opacity: 1; transform: scale(1); }
        }
        .final-pop {
            animation: popFinal 0.6s cubic-bezier(0.22, 1, 0.36, 1) forwards;
        }
        .final-formula { font-size: 2.5rem; font-weight: 800; color: #fff; }
        .final-formula sub { font-size: 1.4rem; color: var(--emerald-light); }
        .despeje-pill {
            display: inline-block;
            font-size: 0.72rem;
            font-weight: 700;
            padding: 4px 10px;
            border-radius: 8px;
            margin-top: 8px;
            background: #1f2937;
            color: #d1d5db;
        }
        .despeje-pill.simp { background: rgba(245, 158, 11, 0.2); color: var(--amber-light); border: 1px solid rgba(245, 158, 11, 0.35); }
        .phase-caption { font-size: 0.75rem; color: var(--text-muted); }

        /* NOMENCLATURA (SE REVELA AL DESPEJAR) */
        .nom-panel {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 12px;
            opacity: 0.2;
            transform: translateY(8px);
            transition: opacity 0.6s ease, transform 0.6s ease;
        }
        .nom-panel.visible { opacity: 1; transform: translateY(0); }
        @media (max-width: 600px) { .nom-panel { grid-template-columns: 1fr; } }
        .nom-box {
            background: var(--bg-inner);
            border: 1px solid var(--border);
            border-radius: 14px;
            padding: 13px 16px;
        }
        .nom-type { font-size: 0.7rem; font-weight: 700; text-transform: uppercase; margin-bottom: 3px; }
        .nom-val { font-size: 1.15rem; font-weight: 800; color: #fff; text-transform: capitalize; }

        /* MODO TEST */
        .hidden { display: none !important; }
        .card {
            background: var(--bg-card);
            border: 1px solid var(--border);
            border-radius: 20px;
            padding: 20px;
        }
        .btn-small {
            background: #1f2937;
            color: #d1d5db;
            border: 1px solid #374151;
            padding: 5px 10px;
            border-radius: 8px;
            font-size: 0.75rem;
            font-weight: 600;
            cursor: pointer;
        }
        .btn-small.active { background: var(--indigo); color: #fff; border-color: var(--indigo); }
        .quiz-input {
            width: 100%;
            max-width: 280px;
            background: var(--bg-inner);
            border: 2px solid #374151;
            color: #fff;
            font-size: 1.5rem;
            font-weight: 700;
            text-align: center;
            padding: 12px;
            border-radius: 12px;
            margin: 12px auto;
            display: block;
        }
        .opt-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-top: 14px; }
        @media (max-width: 560px) { .opt-grid { grid-template-columns: 1fr; } }
        .opt-btn {
            background: var(--bg-inner);
            border: 1px solid #374151;
            color: #f3f4f6;
            padding: 12px;
            border-radius: 12px;
            font-weight: 600;
            text-align: left;
            cursor: pointer;
        }
        .opt-btn.ok { border-color: var(--emerald); background: rgba(16, 185, 129, 0.2); color: var(--emerald-light); }
        .opt-btn.bad { border-color: var(--rose); background: rgba(244, 63, 94, 0.2); color: var(--rose-light); }
        .fb-box { margin-top: 16px; padding: 14px; border-radius: 14px; border: 1px solid var(--border); }
        .fb-box.ok { background: rgba(16, 185, 129, 0.12); border-color: rgba(16, 185, 129, 0.4); }
        .fb-box.bad { background: rgba(244, 63, 94, 0.12); border-color: rgba(244, 63, 94, 0.4); }
        footer { text-align: center; padding: 14px; font-size: 0.75rem; color: #6b7280; border-top: 1px solid var(--border); }
    </style>
</head>
<body>

<header>
    <div class="container header-flex">
        <div class="brand">
            <div class="brand-icon">
                <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="2"><path d="M10 2v7.527a2 2 0 0 1-.211.896L4.72 20.55a1 1 0 0 0 .9 1.45h12.76a1 1 0 0 0 .9-1.45l-5.069-10.127A2 2 0 0 1 14 9.527V2"/><path d="M8.5 2h7"/><path d="M7 16h10"/></svg>
            </div>
            <div>
                <h1>QuímLab · Pizarra Animada</h1>
                <p>Ejemplos aleatorios · Cruce automático en movimiento y despeje</p>
            </div>
        </div>
        <div class="nav-tabs">
            <button class="nav-btn active" id="tab-lab" onclick="switchMode('lab')">Pizarra Animada</button>
            <button class="nav-btn" id="tab-prac" onclick="switchMode('practice')">Practicar (Test)</button>
        </div>
    </div>
</header>

<main class="container">
    <!-- VISTA 1: PIZARRA ANIMADA AUTOMÁTICA -->
    <div id="view-lab">
        <!-- BLOQUES DE COMPUESTOS -->
        <div class="levels-grid">
            <div class="level-box">
                <span class="level-badge badge-bin">1º · Compuestos Binarios</span>
                <div class="fam-grid-4">
                    <button class="fam-btn active-bin" id="fam-oxidos" onclick="selectFamily('oxidos')">
                        <div class="fam-top"><span>Óxidos</span><span class="mono">O²⁻</span></div>
                        <div class="fam-sub">Elem. + O</div>
                    </button>
                    <button class="fam-btn" id="fam-hidruros_met" onclick="selectFamily('hidruros_met')">
                        <div class="fam-top"><span>Hidruros</span><span class="mono">H⁻¹</span></div>
                        <div class="fam-sub">Metal + H</div>
                    </button>
                    <button class="fam-btn" id="fam-hidruros_nomet" onclick="selectFamily('hidruros_nomet')">
                        <div class="fam-top"><span>Hidrácidos</span><span class="mono">H⁺¹</span></div>
                        <div class="fam-sub">H + No Metal</div>
                    </button>
                    <button class="fam-btn" id="fam-sales" onclick="selectFamily('sales')">
                        <div class="fam-top"><span>Sales Bin.</span><span class="mono">M+NM</span></div>
                        <div class="fam-sub">Metal + NM</div>
                    </button>
                </div>
            </div>

            <div class="level-box">
                <span class="level-badge badge-ter">2º · Ternarios (Método Oxoanión)</span>
                <div class="fam-grid-3">
                    <button class="fam-btn" id="fam-hidroxidos" onclick="selectFamily('hidroxidos')">
                        <div class="fam-top"><span>Hidróxidos</span></div>
                        <div class="fam-sub">M⁺ + (OH)⁻¹</div>
                    </button>
                    <button class="fam-btn" id="fam-oxoacidos" onclick="selectFamily('oxoacidos')">
                        <div class="fam-top"><span>Oxoácidos</span></div>
                        <div class="fam-sub">H⁺¹ + (XOᵧ)ᶻ⁻</div>
                    </button>
                    <button class="fam-btn" id="fam-oxisales" onclick="selectFamily('oxisales')">
                        <div class="fam-top"><span>Oxisales</span></div>
                        <div class="fam-sub">Mⁿ⁺ + (XOᵧ)ᶻ⁻</div>
                    </button>
                </div>
            </div>
        </div>

        <!-- CONTROLES DE REPRODUCCIÓN AUTOMÁTICA -->
        <div class="control-bar">
            <div style="display: flex; flex-wrap: wrap; gap: 8px; align-items: center;">
                <button class="btn-primary" onclick="triggerNewRandomExample()">
                    <span>🎲 Nuevo Ejemplo Al Azar</span>
                </button>
                <button class="btn-sec" onclick="replayCurrentAnimation()">↺ Repetir cruce</button>
                <button class="btn-sec" id="btn-pause" onclick="togglePause()">⏸ Pausar</button>
            </div>
            <div style="display: flex; flex-wrap: wrap; gap: 8px; align-items: center;">
                <button class="btn-sec" id="btn-autoplay" onclick="toggleAutoLoop()">🔁 Bucle continuo: OFF</button>
                <button class="btn-sec" id="btn-speed" onclick="cycleSpeed()">⏱ Velocidad: Normal</button>
            </div>
        </div>

        <!-- ESCENARIO DE ANIMACIÓN -->
        <div class="stage-card">
            <div class="progress-track"><div class="progress-fill" id="anim-progress"></div></div>

            <div class="stage-header">
                <span class="phase-tag blue" id="stage-family-badge">Compuesto Binario · Óxido</span>
                <span class="mono" style="font-size: 0.78rem; color: var(--text-muted);" id="stage-status-text">Paso 1: Identificando valencias arriba...</span>
            </div>

            <!-- ENUNCIADO QUE SE LE DA AL ALUMNO -->
            <div class="enunciado-box">
                <div class="enunciado-label" id="enunciado-subtitle">Fórmula a construir con sus estados de oxidación</div>
                <div class="enunciado-text" id="enunciado-main">Hierro (valencia +3) + Oxígeno (valencia -2)</div>
            </div>

            <!-- CÁLCULO PREVIO DEL OXOANIÓN (SOLO EN OXOÁCIDOS Y OXISALES) -->
            <div class="anion-calc-box hidden" id="anion-calc-panel">
                <div>
                    <div class="anion-calc-title">Cálculo previo del anión (XOᵧ)ᶻ⁻ (siempre carga negativa)</div>
                    <div style="font-size: 0.78rem; color: #d1d5db; margin-top: 2px;" id="anion-calc-explain">
                        Buscamos el mínimo número de oxígenos (-2) para que la carga total sea negativa.
                    </div>
                </div>
                <div class="anion-math mono" id="anion-calc-formula">
                    S<sup>+6</sup> + 4 O<sup>-2</sup> → (+6) + 4(-2) = <span style="color: var(--rose-light);">(SO<sub>4</sub>)<sup>-2</sup></span>
                </div>
            </div>

            <!-- ARENA DE 3 FASES ANIMADAS -->
            <div class="animation-arena">
                <!-- FASE 1: ARRIBA -->
                <div class="phase-box visible" id="box-phase-1">
                    <span class="phase-tag blue">1. Cargas Arriba</span>
                    <div class="chem-display" id="vis-phase-1"></div>
                    <p class="phase-caption" id="cap-phase-1">Se colocan los símbolos y sus cargas arriba.</p>
                </div>

                <div class="arena-arrow" id="arrow-1-2">➔</div>

                <!-- FASE 2: CRUCE EN MOVIMIENTO -->
                <div class="phase-box" id="box-phase-2">
                    <span class="phase-tag indigo">2. Cruce Abajo (sin signo)</span>
                    <div class="chem-display" id="vis-phase-2"></div>
                    <p class="phase-caption" id="cap-phase-2">Las cargas bajan cruzadas como subíndices.</p>
                </div>

                <div class="arena-arrow" id="arrow-2-3">➔</div>

                <!-- FASE 3: DESPEJE Y SIMPLIFICACIÓN -->
                <div class="phase-box" id="box-phase-3">
                    <span class="phase-tag green" id="tag-phase-3">3. Despeje Final</span>
                    <div class="chem-display" id="vis-phase-3"></div>
                    <p class="phase-caption" id="cap-phase-3">Se simplifica si es divisible y se quitan los 1.</p>
                </div>
            </div>

            <!-- NOMENCLATURA (APARECE AL COMPLETARSE EL DESPEJE) -->
            <div class="nom-panel" id="nom-panel">
                <div class="nom-box">
                    <div class="nom-type" id="nom-label-1" style="color: var(--amber-light);">Nomenclatura Sistemática</div>
                    <div class="nom-val" id="nom-val-1">Trióxido de dihierro</div>
                </div>
                <div class="nom-box">
                    <div class="nom-type" id="nom-label-2" style="color: var(--blue-light);">Nomenclatura de Stock / Tradicional</div>
                    <div class="nom-val" id="nom-val-2">Óxido de hierro (III)</div>
                </div>
            </div>
        </div>
    </div>

    <!-- VISTA 2: PRÁCTICA (TEST) -->
    <div id="view-practice" class="hidden" style="max-width: 720px; margin: 0 auto;">
        <div class="card" style="margin-bottom: 16px; display: flex; flex-wrap: wrap; justify-content: space-between; align-items: center; gap: 12px;">
            <div style="display: flex; gap: 12px; font-size: 0.85rem;">
                <div>Aciertos: <strong class="mono" style="color: var(--emerald-light);" id="score-correct">0</strong></div>
                <div>Fallos: <strong class="mono" style="color: var(--rose-light);" id="score-wrong">0</strong></div>
                <div>Racha: <strong class="mono" style="color: var(--amber-light);" id="score-streak">0</strong></div>
            </div>
            <div style="display: flex; gap: 6px; flex-wrap: wrap;">
                <button class="btn-small active" id="qlevel-binarios" onclick="setQuizLevel('binarios')">Solo Binarios</button>
                <button class="btn-small" id="qlevel-todos" onclick="setQuizLevel('todos')">Binarios + Ternarios</button>
            </div>
            <div style="display: flex; gap: 6px;">
                <button class="btn-small active" id="qtype-all" onclick="setQuizType('all')">Mixto</button>
                <button class="btn-small" id="qtype-formulate" onclick="setQuizType('formulate')">Formular</button>
                <button class="btn-small" id="qtype-name" onclick="setQuizType('name')">Nombrar</button>
            </div>
        </div>

        <div class="card">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px;">
                <span class="phase-tag blue" id="quiz-tag">Ejercicio</span>
                <button class="btn-small" onclick="toggleQuizHint()">Ver pista de valencias</button>
            </div>

            <div style="text-align: center; margin: 18px 0;">
                <p style="font-size: 0.85rem; color: var(--text-muted); margin-bottom: 6px;" id="quiz-prompt-label">Escribe la fórmula correcta para:</p>
                <h2 style="font-size: 1.9rem; font-weight: 800;" id="quiz-question">Óxido de calcio</h2>
            </div>

            <div id="quiz-hint-box" class="hidden enunciado-box" style="font-size: 0.85rem;"></div>

            <div id="quiz-input-formulate" style="text-align: center;">
                <input type="text" id="user-formula-input" class="quiz-input mono" placeholder="Ej: H2SO4 o Ca3(PO4)2" autocomplete="off">
                <p class="phase-caption">Escribe los subíndices como números normales (ej: Fe2O3, Ca(OH)2, H2SO4).</p>
            </div>

            <div id="quiz-input-name" class="hidden opt-grid"></div>

            <div id="quiz-submit-container" style="text-align: center; margin-top: 18px;">
                <button class="btn-primary" onclick="checkFormulaAnswer()">Comprobar Respuesta</button>
            </div>

            <div id="quiz-feedback" class="hidden fb-box">
                <h4 id="feedback-title" style="margin-bottom: 6px;"></h4>
                <p id="feedback-explanation" style="font-size: 0.85rem; margin-bottom: 12px;"></p>
                <button class="btn-primary" onclick="nextQuestion()">Siguiente Pregunta →</button>
            </div>
        </div>
    </div>
</main>

<footer>
    QuímLab · Pizarra Animada de Formulación Inorgánica
</footer>

<script>
const ELEMENTS = {
    Li: { symbol: 'Li', name: 'litio', valences: [1], type: 'metal' },
    Na: { symbol: 'Na', name: 'sodio', valences: [1], type: 'metal' },
    K:  { symbol: 'K',  name: 'potasio', valences: [1], type: 'metal' },
    Ag: { symbol: 'Ag', name: 'plata', valences: [1], type: 'metal' },
    Mg: { symbol: 'Mg', name: 'magnesio', valences: [2], type: 'metal' },
    Ca: { symbol: 'Ca', name: 'calcio', valences: [2], type: 'metal' },
    Ba: { symbol: 'Ba', name: 'bario', valences: [2], type: 'metal' },
    Zn: { symbol: 'Zn', name: 'cinc', valences: [2], type: 'metal' },
    Al: { symbol: 'Al', name: 'aluminio', valences: [3], type: 'metal' },
    Fe: { symbol: 'Fe', name: 'hierro', valences: [2, 3], type: 'metal' },
    Co: { symbol: 'Co', name: 'cobalto', valences: [2, 3], type: 'metal' },
    Ni: { symbol: 'Ni', name: 'níquel', valences: [2, 3], type: 'metal' },
    Cu: { symbol: 'Cu', name: 'cobre', valences: [1, 2], type: 'metal' },
    Au: { symbol: 'Au', name: 'oro', valences: [1, 3], type: 'metal' },
    Pb: { symbol: 'Pb', name: 'plomo', valences: [2, 4], type: 'metal' },
    Sn: { symbol: 'Sn', name: 'estaño', valences: [2, 4], type: 'metal' },
    C:  { symbol: 'C',  name: 'carbono', root: 'carbur', oxoRoot: 'carbón', atoRoot: 'carbonato', valences: [2, 4], oxoValences: [4], negValence: -4, type: 'nonmetal', group: 14 },
    N:  { symbol: 'N',  name: 'nitrógeno', root: 'nitrur', oxoRoot: 'nítr', atoRoot: 'nitrat', valences: [1, 2, 3, 4, 5], oxoValences: [3, 5], negValence: -3, type: 'nonmetal', group: 15 },
    P:  { symbol: 'P',  name: 'fósforo', root: 'fosfur', oxoRoot: 'fosfór', atoRoot: 'fosfat', valences: [3, 5], oxoValences: [3, 5], negValence: -3, type: 'nonmetal', group: 15 },
    S:  { symbol: 'S',  name: 'azufre', root: 'sulfur', oxoRoot: 'sulfúr', atoRoot: 'sulfat', valences: [2, 4, 6], oxoValences: [4, 6], negValence: -2, type: 'nonmetal', group: 16, acidName: 'ácido sulfhídrico' },
    Se: { symbol: 'Se', name: 'selenio', root: 'seleniur', oxoRoot: 'selén', atoRoot: 'seleniat', valences: [2, 4, 6], oxoValences: [4, 6], negValence: -2, type: 'nonmetal', group: 16, acidName: 'ácido selenhídrico' },
    F:  { symbol: 'F',  name: 'flúor', root: 'fluorur', valences: [], oxoValences: [], negValence: -1, type: 'halogen', group: 17, acidName: 'ácido fluorhídrico' },
    Cl: { symbol: 'Cl', name: 'cloro', root: 'clorur', oxoRoot: 'clór', atoRoot: 'clorat', valences: [1, 3, 5, 7], oxoValences: [1, 3, 5, 7], negValence: -1, type: 'halogen', group: 17, acidName: 'ácido clorhídrico' },
    Br: { symbol: 'Br', name: 'bromo', root: 'bromur', oxoRoot: 'bróm', atoRoot: 'bromat', valences: [1, 3, 5, 7], oxoValences: [1, 3, 5, 7], negValence: -1, type: 'halogen', group: 17, acidName: 'ácido bromhídrico' },
    I:  { symbol: 'I',  name: 'yodo', root: 'yodur', oxoRoot: 'yód', atoRoot: 'yodat', valences: [1, 3, 5, 7], oxoValences: [1, 3, 5, 7], negValence: -1, type: 'halogen', group: 17, acidName: 'ácido yodhídrico' },
    O:  { symbol: 'O',  name: 'oxígeno', root: 'óxid', negValence: -2, type: 'oxygen' },
    H:  { symbol: 'H',  name: 'hidrógeno', root: 'hidrur', valences: [1], negValence: -1, type: 'hydrogen' },
    OH: { symbol: 'OH', name: 'hidróxido', root: 'hidróxid', negValence: -1, type: 'hydroxide' }
};

const PREFIXES = { 1: 'mono', 2: 'di', 3: 'tri', 4: 'tetra', 5: 'penta', 6: 'hexa', 7: 'hepta' };
const OXO_OUTER_PREFIXES = { 2: 'bis', 3: 'tris', 4: 'tetrakis' };
const ROMANS = { 1: 'I', 2: 'II', 3: 'III', 4: 'IV', 5: 'V', 6: 'VI', 7: 'VII' };

function gcd(a, b) { return b === 0 ? a : gcd(b, a % b); }

function combinePrefixAndRoot(prefixCount, anionName, omitMono = false) {
    if (prefixCount === 1 && omitMono) return anionName;
    const pref = PREFIXES[prefixCount];
    if (pref === 'mono' && anionName.startsWith('ó')) return 'mon' + anionName;
    if (['tetra', 'penta', 'hexa', 'hepta'].includes(pref) && anionName.startsWith('ó')) {
        return pref.slice(0, -1) + anionName;
    }
    return pref + anionName;
}

function getTradOxoacidAndSaltNames(elObj, val) {
    const vals = elObj.oxoValences;
    let acid = '', salt = '';
    const baseIto = elObj.atoRoot.replace('at', 'it') + 'o';
    const baseAto = elObj.atoRoot + 'o';
    const baseOso = elObj.oxoRoot.replace('ór','or').replace('úr','ur').replace('óm','om').replace('ód','od') + 'oso';
    const baseIco = elObj.oxoRoot + 'ico';

    if (vals.length === 1) {
        acid = `ácido ${baseIco}`;
        salt = baseAto;
    } else if (vals.length === 2) {
        if (val === vals[0]) { acid = `ácido ${baseOso}`; salt = baseIto; }
        else { acid = `ácido ${baseIco}`; salt = baseAto; }
    } else if (vals.length === 4) {
        if (val === 1) { acid = `ácido hipo${baseOso}`; salt = `hipo${baseIto}`; }
        if (val === 3) { acid = `ácido ${baseOso}`; salt = baseIto; }
        if (val === 5) { acid = `ácido ${baseIco}`; salt = baseAto; }
        if (val === 7) { acid = `ácido per${baseIco}`; salt = `per${baseAto}`; }
    }
    return { acid, salt };
}

/* CONSTRUYE CUALQUIER COMPUESTO (BINARIOS Y TERNARIOS CON MÉTODO DIRECTO DE OXOANIÓN) */
function buildCompoundData(family) {
    let el1Key, val1, el2Key, val2;

    if (family === 'oxidos') {
        const c = Object.values(ELEMENTS).filter(e => e.type === 'metal' || e.type === 'nonmetal');
        const ch = c[Math.floor(Math.random() * c.length)];
        el1Key = ch.symbol; val1 = ch.valences[Math.floor(Math.random() * ch.valences.length)];
        el2Key = 'O'; val2 = -2;
    } else if (family === 'hidruros_met') {
        const c = Object.values(ELEMENTS).filter(e => e.type === 'metal');
        const ch = c[Math.floor(Math.random() * c.length)];
        el1Key = ch.symbol; val1 = ch.valences[Math.floor(Math.random() * ch.valences.length)];
        el2Key = 'H'; val2 = -1;
    } else if (family === 'hidruros_nomet') {
        const c = Object.values(ELEMENTS).filter(e => e.type === 'halogen' || (e.type === 'nonmetal' && e.group === 16));
        const ch = c[Math.floor(Math.random() * c.length)];
        el1Key = 'H'; val1 = 1;
        el2Key = ch.symbol; val2 = ch.negValence;
    } else if (family === 'sales') {
        const ms = Object.values(ELEMENTS).filter(e => e.type === 'metal');
        const nms = Object.values(ELEMENTS).filter(e => e.type === 'halogen' || e.type === 'nonmetal');
        const m = ms[Math.floor(Math.random() * ms.length)];
        const nm = nms[Math.floor(Math.random() * nms.length)];
        el1Key = m.symbol; val1 = m.valences[Math.floor(Math.random() * m.valences.length)];
        el2Key = nm.symbol; val2 = nm.negValence;
    } else if (family === 'hidroxidos') {
        const ms = Object.values(ELEMENTS).filter(e => e.type === 'metal');
        const m = ms[Math.floor(Math.random() * ms.length)];
        el1Key = m.symbol; val1 = m.valences[Math.floor(Math.random() * m.valences.length)];
        el2Key = 'OH'; val2 = -1;
    } else if (family === 'oxoacidos' || family === 'oxisales') {
        // Método directo: Calcular oxoanión (X O_y)^z- donde z = valX - 2*y < 0 (mínimo y para que sea negativo)
        const nms = Object.values(ELEMENTS).filter(e => e.oxoValences && e.oxoValences.length > 0);
        const xEl = nms[Math.floor(Math.random() * nms.length)];
        const valX = xEl.oxoValences[Math.floor(Math.random() * xEl.oxoValences.length)];
        // Mínimo y entero tal que valX - 2*y < 0 -> y = floor(valX / 2) + 1
        const numO = Math.floor(valX / 2) + 1;
        const anionCharge = valX - (2 * numO); // Siempre -1 o -2

        const anionCoreHTML = `${xEl.symbol}O${numO > 1 ? `<sub>${numO}</sub>` : ''}`;
        const anionCorePlain = `${xEl.symbol}O${numO > 1 ? numO : ''}`;

        let catEl, catVal;
        if (family === 'oxoacidos') {
            catEl = ELEMENTS['H'];
            catVal = 1;
        } else {
            const ms = Object.values(ELEMENTS).filter(e => e.type === 'metal');
            catEl = ms[Math.floor(Math.random() * ms.length)];
            catVal = catEl.valences[Math.floor(Math.random() * catEl.valences.length)];
        }

        const rawSub1 = Math.abs(anionCharge);
        const rawSub2 = Math.abs(catVal);
        const divisor = gcd(rawSub1, rawSub2);
        const finalSub1 = rawSub1 / divisor;
        const finalSub2 = rawSub2 / divisor;
        const wasSimplified = divisor > 1;

        // En oxoácidos nunca se dejan paréntesis en el resultado final (ej. H2SO4); en oxisales solo si finalSub2 > 1 (ej. Ca3(PO4)2)
        const keepParensFinal = (family === 'oxisales' && finalSub2 > 1);
        const rightFinalHTML = keepParensFinal ? `(${anionCoreHTML})` : anionCoreHTML;
        const rightFinalPlain = keepParensFinal ? `(${anionCorePlain})` : anionCorePlain;

        const formulaHTML = `${catEl.symbol}${finalSub1 > 1 ? `<sub>${finalSub1}</sub>` : ''}${rightFinalHTML}${finalSub2 > 1 ? `<sub>${finalSub2}</sub>` : ''}`;
        const formulaPlain = `${catEl.symbol}${finalSub1 > 1 ? finalSub1 : ''}${rightFinalPlain}${finalSub2 > 1 ? finalSub2 : ''}`;

        const names = getTradOxoacidAndSaltNames(xEl, valX);
        const oPref = combinePrefixAndRoot(numO, 'óxido', false);
        const xAto = xEl.atoRoot + 'o';

        let sysName = '', stockName = '';
        if (family === 'oxoacidos') {
            const hPref = finalSub1 > 1 ? `${PREFIXES[finalSub1]}hidrogeno` : 'hidrogeno';
            sysName = `${hPref}(${oPref}${xAto})`;
            stockName = names.acid;
        } else {
            const romanStr = catEl.valences.length > 1 ? ` (${ROMANS[catVal]})` : '';
            stockName = `${names.salt} de ${catEl.name}${romanStr}`;
            const outerPref = finalSub2 > 1 ? `${OXO_OUTER_PREFIXES[finalSub2]}(` : '';
            const outerClose = finalSub2 > 1 ? ')' : '';
            const catPref = finalSub1 > 1 ? PREFIXES[finalSub1] : '';
            sysName = `${outerPref}${oPref}${xAto}${outerClose} de ${catPref}${catEl.name}`;
        }

        return {
            family,
            isOxo: true,
            familyTitle: family === 'oxoacidos' ? 'Ternario · Oxoácido' : 'Ternario · Oxisal',
            enunciado: family === 'oxoacidos'
                ? `Hidrógeno (+1) + Oxoanión del ${xEl.name} con estado +${valX}`
                : `${catEl.name.charAt(0).toUpperCase() + catEl.name.slice(1)} (+${catVal}) + Oxoanión del ${xEl.name} (+${valX})`,
            anionMathHTML: `${xEl.symbol}<sup>+${valX}</sup> + ${numO} O<sup>-2</sup> → (+${valX}) + ${numO}·(-2) = <span style="color:var(--rose-light);">(${anionCoreHTML})<sup>${anionCharge}</sup></span>`,
            anionExplain: `Con ${numO} oxígeno${numO > 1 ? 's' : ''} (-2) obtenemos la mínima carga negativa posible (${anionCharge}).`,
            leftSym: catEl.symbol,
            leftVal: `+${catVal}`,
            rightTopHTML: `(${anionCoreHTML})`,
            rightMidHTML: `(${anionCoreHTML})`,
            rightVal: `${anionCharge}`,
            rawSub1, rawSub2, finalSub1, finalSub2, wasSimplified, divisor,
            formulaHTML, formulaPlain,
            sysName, stockName,
            hint: `Catión ${catEl.symbol} (+${catVal}) y oxoanión (${anionCorePlain}) con carga ${anionCharge}.`
        };
    }

    // COMPUESTOS BINARIOS E HIDRÓXIDOS
    const e1 = ELEMENTS[el1Key];
    const e2 = ELEMENTS[el2Key];
    const rawSub1 = Math.abs(val2);
    const rawSub2 = Math.abs(val1);
    const divisor = gcd(rawSub1, rawSub2);
    const finalSub1 = rawSub1 / divisor;
    const finalSub2 = rawSub2 / divisor;
    const wasSimplified = divisor > 1;

    const isOH = (el2Key === 'OH');
    const rightTopHTML = isOH ? '(OH)' : e2.symbol;
    const rightMidHTML = (isOH && rawSub2 > 1) ? '(OH)' : e2.symbol;
    const rightFinalHTML = (isOH && finalSub2 > 1) ? '(OH)' : e2.symbol;

    const formulaHTML = `${e1.symbol}${finalSub1 > 1 ? `<sub>${finalSub1}</sub>` : ''}${rightFinalHTML}${finalSub2 > 1 ? `<sub>${finalSub2}</sub>` : ''}`;
    const formulaPlain = `${e1.symbol}${finalSub1 > 1 ? finalSub1 : ''}${rightFinalHTML}${finalSub2 > 1 ? finalSub2 : ''}`;

    let anionBase = '';
    if (e2.symbol === 'O') anionBase = 'óxido';
    else if (e2.symbol === 'H') anionBase = 'hidruro';
    else if (e2.symbol === 'OH') anionBase = 'hidróxido';
    else anionBase = e2.root + 'o';

    const prefixEl1 = finalSub1 > 1 ? PREFIXES[finalSub1] : '';
    const needsMono = (e1.valences && e1.valences.length > 1) || (family === 'hidruros_nomet');
    const anionWithPrefix = combinePrefixAndRoot(finalSub2, anionBase, !needsMono && finalSub2 === 1);
    const sysName = `${anionWithPrefix} de ${prefixEl1}${e1.name}`;

    let stockName = '';
    if (family === 'hidruros_nomet') {
        stockName = `${anionBase} de ${e1.name}${e2.acidName ? ` (${e2.acidName})` : ''}`;
    } else {
        const romanStr = e1.valences.length > 1 ? ` (${ROMANS[val1]})` : '';
        stockName = `${anionBase} de ${e1.name}${romanStr}`;
    }

    const famTitles = {
        oxidos: 'Binario · Óxido',
        hidruros_met: 'Binario · Hidruro Metálico',
        hidruros_nomet: 'Binario · Hidrácido',
        sales: 'Binario · Sal Binaria',
        hidroxidos: 'Ternario · Hidróxido'
    };

    return {
        family,
        isOxo: false,
        familyTitle: famTitles[family],
        enunciado: `${e1.name.charAt(0).toUpperCase() + e1.name.slice(1)} (valencia +${val1}) + ${e2.name.charAt(0).toUpperCase() + e2.name.slice(1)} (valencia ${val2})`,
        leftSym: e1.symbol,
        leftVal: `+${val1}`,
        rightTopHTML,
        rightMidHTML,
        rightVal: `${val2}`,
        rawSub1, rawSub2, finalSub1, finalSub2, wasSimplified, divisor,
        formulaHTML, formulaPlain,
        sysName, stockName,
        hint: `Valencias: ${e1.symbol} (+${val1}) y ${e2.symbol} (${val2}).`
    };
}

/* CONTROLADOR DE PIZARRA ANIMADA */
let animState = {
    family: 'oxidos',
    currentData: null,
    timers: [],
    isPaused: false,
    autoLoop: false,
    speedMultiplier: 1 // 1 = Normal, 0.6 = Rápido, 1.6 = Lento
};

function clearAllTimers() {
    animState.timers.forEach(t => clearTimeout(t));
    animState.timers = [];
}

function selectFamily(fam) {
    animState.family = fam;
    document.querySelectorAll('.fam-btn').forEach(b => b.classList.remove('active-bin', 'active-ter'));
    const isTer = ['hidroxidos', 'oxoacidos', 'oxisales'].includes(fam);
    document.getElementById(`fam-${fam}`).classList.add(isTer ? 'active-ter' : 'active-bin');
    triggerNewRandomExample();
}

function triggerNewRandomExample() {
    animState.currentData = buildCompoundData(animState.family);
    renderStaticContent(animState.currentData);
    replayCurrentAnimation();
}

function renderStaticContent(d) {
    document.getElementById('stage-family-badge').textContent = d.familyTitle;
    document.getElementById('enunciado-main').textContent = d.enunciado;

    const anionPanel = document.getElementById('anion-calc-panel');
    if (d.isOxo) {
        anionPanel.classList.remove('hidden');
        document.getElementById('anion-calc-formula').innerHTML = d.anionMathHTML;
        document.getElementById('anion-calc-explain').textContent = d.anionExplain;
    } else {
        anionPanel.classList.add('hidden');
    }

    // Fase 1: Arriba
    document.getElementById('vis-phase-1').innerHTML = `
        <span class="sym-big mono c-pos">${d.leftSym}</span><span class="sup-badge bg-pos mono">${d.leftVal}</span>
        <span style="margin:0 8px;"></span>
        <span class="sym-big mono c-neg">${d.rightTopHTML}</span><span class="sup-badge bg-neg mono">${d.rightVal}</span>
    `;

    // Fase 2: Cruce en movimiento
    document.getElementById('vis-phase-2').innerHTML = `
        <div class="cross-diagram">
            <div class="cross-arcs mono">
                <span class="c-pos">${d.leftVal}</span>
                <span style="color:#6b7280;">↘ ↙</span>
                <span class="c-neg">${d.rightVal}</span>
            </div>
            <div class="sym-big mono">
                ${d.leftSym}<span class="sub-fly-left">${d.rawSub1}</span>${d.rightMidHTML}<span class="sub-fly-right">${d.rawSub2}</span>
            </div>
        </div>
    `;

    // Fase 3: Despeje final
    const tag3 = document.getElementById('tag-phase-3');
    const despejeText = d.wasSimplified
        ? `Simplificado ÷${d.divisor} (${d.rawSub1}:${d.rawSub2} → ${d.finalSub1}:${d.finalSub2})`
        : (d.isOxo ? 'Se quitan subíndices 1 y paréntesis si sobran' : 'Subíndices 1 se omiten');

    tag3.textContent = d.wasSimplified ? `3. Despeje (Simplifica ÷${d.divisor})` : '3. Despeje Final';
    tag3.className = d.wasSimplified ? 'phase-tag amber' : 'phase-tag green';

    document.getElementById('vis-phase-3').innerHTML = `
        <div class="final-pop">
            <div class="final-formula mono">${d.formulaHTML}</div>
            <div class="despeje-pill ${d.wasSimplified ? 'simp' : ''}">${despejeText}</div>
        </div>
    `;

    // Nomenclaturas
    document.getElementById('nom-label-1').textContent = d.family === 'oxoacidos' ? 'Nomenclatura de Hidrógeno (IUPAC)' : 'Nomenclatura Sistemática';
    document.getElementById('nom-label-2').textContent = (d.family === 'oxoacidos' || d.family === 'oxisales') ? 'Nomenclatura Tradicional / Stock' : 'Nomenclatura de Stock';
    document.getElementById('nom-val-1').textContent = d.sysName;
    document.getElementById('nom-val-2').textContent = d.stockName;
}

function replayCurrentAnimation() {
    clearAllTimers();
    animState.isPaused = false;
    document.getElementById('btn-pause').textContent = '⏸ Pausar';

    const box1 = document.getElementById('box-phase-1');
    const box2 = document.getElementById('box-phase-2');
    const box3 = document.getElementById('box-phase-3');
    const arr12 = document.getElementById('arrow-1-2');
    const arr23 = document.getElementById('arrow-2-3');
    const nomPanel = document.getElementById('nom-panel');
    const prog = document.getElementById('anim-progress');
    const status = document.getElementById('stage-status-text');

    // Reset visual inmediato
    box1.className = 'phase-box visible';
    box2.className = 'phase-box';
    box3.className = 'phase-box';
    arr12.className = 'arena-arrow';
    arr23.className = 'arena-arrow';
    nomPanel.className = 'nom-panel';
    prog.style.transition = 'none';
    prog.style.width = '15%';
    status.textContent = 'Paso 1: Observa los elementos y sus cargas arriba...';

    // Re-instanciar el HTML interno de fase 2 para que la animación CSS de vuelo se dispare de nuevo
    const vis2 = document.getElementById('vis-phase-2');
    const saved2 = vis2.innerHTML;
    vis2.innerHTML = '';
    void vis2.offsetWidth;
    vis2.innerHTML = saved2;

    const m = animState.speedMultiplier;
    const tCross = Math.round(1700 * m);
    const tDespeje = Math.round(3600 * m);
    const tNext = Math.round(6800 * m);

    // Tiempo 1 -> 2: Cruce automático en movimiento
    animState.timers.push(setTimeout(() => {
        arr12.classList.add('lit');
        box2.classList.add('visible', 'highlight-cross');
        prog.style.transition = `width ${tDespeje - tCross}ms linear`;
        prog.style.width = '65%';
        status.textContent = 'Paso 2: ¡Cruzando las valencias hacia abajo sin signo!';
    }, tCross));

    // Tiempo 2 -> 3: Despeje, simplificación y nombres
    animState.timers.push(setTimeout(() => {
        arr23.classList.add('lit');
        box3.classList.add('visible', 'highlight-final');
        nomPanel.classList.add('visible');
        prog.style.transition = `width ${tNext - tDespeje}ms linear`;
        prog.style.width = '100%';
        status.textContent = 'Paso 3: ¡Despeje completado y fórmula nombrada!';
    }, tDespeje));

    // Si el bucle automático está activo, pasa al siguiente ejemplo solo
    animState.timers.push(setTimeout(() => {
        if (animState.autoLoop && !animState.isPaused) {
            triggerNewRandomExample();
        }
    }, tNext));
}

function togglePause() {
    if (!animState.isPaused) {
        animState.isPaused = true;
        clearAllTimers();
        document.getElementById('btn-pause').textContent = '▶ Reanudar';
        document.getElementById('stage-status-text').textContent = 'Animación en pausa';
    } else {
        replayCurrentAnimation();
    }
}

function toggleAutoLoop() {
    animState.autoLoop = !animState.autoLoop;
    const btn = document.getElementById('btn-autoplay');
    btn.textContent = animState.autoLoop ? '🔁 Bucle continuo: ON' : '🔁 Bucle continuo: OFF';
    btn.classList.toggle('active-loop', animState.autoLoop);
    if (animState.autoLoop) triggerNewRandomExample();
}

function cycleSpeed() {
    const btn = document.getElementById('btn-speed');
    if (animState.speedMultiplier === 1) {
        animState.speedMultiplier = 1.6;
        btn.textContent = '⏱ Velocidad: Lenta (Clase)';
    } else if (animState.speedMultiplier === 1.6) {
        animState.speedMultiplier = 0.65;
        btn.textContent = '⏱ Velocidad: Rápida';
    } else {
        animState.speedMultiplier = 1;
        btn.textContent = '⏱ Velocidad: Normal';
    }
    replayCurrentAnimation();
}

/* MODO TEST / PRÁCTICA */
function switchMode(mode) {
    document.getElementById('view-lab').classList.toggle('hidden', mode !== 'lab');
    document.getElementById('view-practice').classList.toggle('hidden', mode === 'lab');
    document.getElementById('tab-lab').classList.toggle('active', mode === 'lab');
    document.getElementById('tab-prac').classList.toggle('active', mode !== 'lab');
    if (mode !== 'lab') {
        clearAllTimers();
        if (!quizState.currentQuestion) nextQuestion();
    } else {
        replayCurrentAnimation();
    }
}

let quizState = { level: 'binarios', typeFilter: 'all', correct: 0, wrong: 0, streak: 0, currentQuestion: null, answered: false };

function setQuizLevel(lvl) {
    quizState.level = lvl;
    document.getElementById('qlevel-binarios').classList.toggle('active', lvl === 'binarios');
    document.getElementById('qlevel-todos').classList.toggle('active', lvl === 'todos');
    nextQuestion();
}

function setQuizType(type) {
    quizState.typeFilter = type;
    ['all', 'formulate', 'name'].forEach(t => document.getElementById(`qtype-${t}`).classList.toggle('active', t === type));
    nextQuestion();
}

function generateQuizCompound() {
    const fams = quizState.level === 'binarios'
        ? ['oxidos', 'hidruros_met', 'hidruros_nomet', 'sales']
        : ['oxidos', 'hidruros_met', 'hidruros_nomet', 'sales', 'hidroxidos', 'oxoacidos', 'oxisales'];
    const fam = fams[Math.floor(Math.random() * fams.length)];
    return buildCompoundData(fam);
}

function nextQuestion() {
    quizState.answered = false;
    document.getElementById('quiz-feedback').classList.add('hidden');
    document.getElementById('quiz-hint-box').classList.add('hidden');

    const compound = generateQuizCompound();
    const qMode = quizState.typeFilter === 'all' ? (Math.random() > 0.5 ? 'formulate' : 'name') : quizState.typeFilter;
    quizState.currentQuestion = { mode: qMode, compound };

    document.getElementById('quiz-hint-box').textContent = compound.hint;

    if (qMode === 'formulate') {
        document.getElementById('quiz-tag').textContent = 'Ejercicio: Formular';
        document.getElementById('quiz-prompt-label').textContent = 'Escribe la fórmula química para:';
        const pName = Math.random() > 0.4 ? compound.stockName : compound.sysName;
        document.getElementById('quiz-question').textContent = pName.charAt(0).toUpperCase() + pName.slice(1);
        document.getElementById('quiz-input-formulate').classList.remove('hidden');
        document.getElementById('quiz-input-name').classList.add('hidden');
        document.getElementById('quiz-submit-container').classList.remove('hidden');
        const inp = document.getElementById('user-formula-input');
        inp.value = ''; inp.disabled = false;
    } else {
        document.getElementById('quiz-tag').textContent = 'Ejercicio: Nombrar';
        document.getElementById('quiz-prompt-label').textContent = 'Selecciona el nombre correcto para:';
        document.getElementById('quiz-question').innerHTML = compound.formulaHTML;
        document.getElementById('quiz-input-formulate').classList.add('hidden');
        document.getElementById('quiz-input-name').classList.remove('hidden');
        document.getElementById('quiz-submit-container').classList.add('hidden');

        const correctName = Math.random() > 0.4 ? compound.stockName : compound.sysName;
        const distractors = new Set();
        while (distractors.size < 3) {
            const fake = generateQuizCompound();
            const fName = Math.random() > 0.4 ? fake.stockName : fake.sysName;
            if (fName !== compound.stockName && fName !== compound.sysName) distractors.add(fName);
        }
        const opts = [correctName, ...Array.from(distractors)].sort(() => Math.random() - 0.5);
        document.getElementById('quiz-input-name').innerHTML = opts.map(o => {
            const cap = o.charAt(0).toUpperCase() + o.slice(1);
            return `<button class="opt-btn" onclick="checkNameAnswer('${o.replace(/'/g, "\\'")}', '${correctName.replace(/'/g, "\\'")}')">${cap}</button>`;
        }).join('');
    }
}

function toggleQuizHint() { document.getElementById('quiz-hint-box').classList.toggle('hidden'); }

function checkFormulaAnswer() {
    if (quizState.answered) return;
    const inp = document.getElementById('user-formula-input');
    const val = inp.value.trim();
    if (!val) return;
    const comp = quizState.currentQuestion.compound;
    inp.disabled = true;
    document.getElementById('quiz-submit-container').classList.add('hidden');
    showFeedback(val === comp.formulaPlain, comp);
}

function checkNameAnswer(selected, correct) {
    if (quizState.answered) return;
    const comp = quizState.currentQuestion.compound;
    const isOk = selected === correct;
    document.querySelectorAll('.opt-btn').forEach(b => {
        b.disabled = true;
        if (b.textContent.trim().toLowerCase() === correct.toLowerCase()) b.classList.add('ok');
        else if (b.textContent.trim().toLowerCase() === selected.toLowerCase() && !isOk) b.classList.add('bad');
    });
    showFeedback(isOk, comp);
}

function showFeedback(isOk, comp) {
    quizState.answered = true;
    if (isOk) { quizState.correct++; quizState.streak++; } else { quizState.wrong++; quizState.streak = 0; }
    document.getElementById('score-correct').textContent = quizState.correct;
    document.getElementById('score-wrong').textContent = quizState.wrong;
    document.getElementById('score-streak').textContent = quizState.streak;

    const fb = document.getElementById('quiz-feedback');
    fb.className = `fb-box ${isOk ? 'ok' : 'bad'}`;
    document.getElementById('feedback-title').textContent = isOk ? '¡Correcto!' : `Incorrecto. La fórmula es ${comp.formulaPlain}`;
    document.getElementById('feedback-explanation').innerHTML = `<strong>Fórmula:</strong> ${comp.formulaHTML} · <strong>Nombres:</strong> ${comp.stockName} / ${comp.sysName}`;
}

document.getElementById('user-formula-input').addEventListener('keypress', e => { if (e.key === 'Enter') checkFormulaAnswer(); });

// Arrancar directamente con un óxido aleatorio animado
selectFamily('oxidos');
</script>
</body>
</html>
```