<?php
session_start();

// 1. Verificación de sesión y rol
if (!isset($_SESSION['Inicio']) || $_SESSION['Inicio'] !== "Ok" || !in_array($_SESSION['Rol'], ["Administrativo", "Titular"])) {
    header("Location: ../Login.php?m=5");
    exit;
}

// 2. Determinar la URL del menú
$urlMenuCorrespondiente = "UCDI_II.php";

// 3. Obtener ID de la evaluación
$id_CDI_II_valor = isset($_GET['id']) ? htmlspecialchars($_GET['id'], ENT_QUOTES, 'UTF-8') : '';
if (empty($id_CDI_II_valor) || !filter_var($id_CDI_II_valor, FILTER_VALIDATE_INT)) {
    die("Error: ID de registro no válido o no proporcionado.");
}

// 4. Función y recuperación de datos de GET
function get_param($key, $default = '') {
    return isset($_GET[$key]) ? htmlspecialchars($_GET[$key], ENT_QUOTES, 'UTF-8') : $default;
}

// Datos del paciente
$clave_paciente = get_param('clave_paciente');
$codigo_paciente = get_param('codigo_paciente');
$nombre_paciente = get_param('nombre_paciente');
$apellido_paterno_paciente = get_param('apellido_paterno_paciente');
$apellido_materno_paciente = get_param('apellido_materno_paciente');
$fecha_nacimiento_paciente = get_param('fecha_nacimiento_paciente');
$semanas_gestacion = get_param('semanas_gestacion');
$sexo_paciente = get_param('sexo_paciente');

// Datos de evaluación
$fecha_evaluacion = get_param('fecha_evaluacion');
$edad = get_param('edad');
$edad_corregida = get_param('edad_corregida'); // Nuevo
$rango_edad = get_param('rango_edad'); // Nuevo

// Puntuaciones brutas
$bruto_uso_palabras = get_param('invent2_bruto_uso_palabras');
$bruto_oraciones_gramatica = get_param('invent2_bruto_oraciones_gramatica');
$bruto_complejidad_frases = get_param('invent2_bruto_complejidad_frases');

// Percentiles
$percentil_uso_palabras = get_param('invent2_percentil_uso_palabras');
$percentil_oraciones_gramatica = get_param('invent2_percentil_oraciones_gramatica');
$percentil_complejidad_frases = get_param('invent2_percentil_complejidad_frases');

// Datos clínicos
$interpretacion = get_param('invent2_interpretacion');
$seguimiento = get_param('invent2_seguimiento');
$referir_terapia = get_param('invent2_datos_clini_referir_terapi');
$prox_eval = get_param('invent2_prox_eval');
$otras_observ = get_param('invent2_datos_clini_otras_observ');
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&family=Montserrat:wght@700&display=swap" rel="stylesheet">
    <link rel="icon" type="image/png" href="./img/UNAM amarillo.png"> 
    <link rel="stylesheet" type="text/css" href="../Css/EstilosUpdateWi.css">
    <title>Modificar CDI-II</title>
    <style>
        .auto-filled { background-color: #e9ecef; cursor: not-allowed; }
        .header-section { display: flex; justify-content: space-between; align-items: center; margin-bottom: 25px; padding-bottom: 15px; border-bottom: 2px solid #f0f0f0; }
        .main-tittle {margin: 0;padding: 0;border: none;font-size: 1.6rem; /* <-- AÑADE ESTA LÍNEA (o ajusta el valor, ej. 1.5rem, 1.7rem) */}        .btn-salir { white-space: nowrap; padding: 8px 20px; flex-shrink: 0; font-size: 0.9rem; }
        .hidden { display: none; }
        .age-fields-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 1rem; align-items: flex-end; /* Añadido para alinear mejor */ }.edad-activa { background-color: #e0e8f0; border-color: #0056b3; box-shadow: 0 0 5px rgba(0, 86, 179, 0.3); }
        .edad-activa { background-color: #e0e8f0; border-color: #0056b3; box-shadow: 0 0 5px rgba(0, 86, 179, 0.3); }
        .instruccion-evaluacion { font-size: 0.9em; color: #555; background-color: #f8f9fa; padding: 10px; border-left: 4px solid #007bff; margin-top: 0; margin-bottom: 15px; border-radius: 0 4px 4px 0; }
        .instruccion-evaluacion strong { color: #0056b3; }
        .prox-eval-container { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; align-items: flex-end; }
        .hidden { display: none; }
        .baremo-container { display: flex; gap: 2px; align-items: flex-end; }
        .baremo-container > .input-box { flex-grow: 10; }
        
    </style>
</head>
<body>
    <div class="container">
        <div class="header-section"> <!-- Contenedor nuevo -->
                <h1 class="main-tittle">Modificar Inventario del Desarrollo de Habilidades Comunicativas (CDI-II)</h1>
                <a href="UCDI_II.php" class="btn-salir">Volver a la lista</a> 
        </div>

        <form method="POST" action="USCDI_II.php" id="cdiForm">
            <input type="hidden" name="id_CDI_II_a_modificar" value="<?php echo $id_CDI_II_valor; ?>">
            <input type="hidden" name="clave_paciente" value="<?php echo $clave_paciente; ?>">
            <input type="hidden" id="sexo_paciente" value="<?php echo $sexo_paciente; ?>">
            <input type="hidden" id="semanas_gestacion_hidden" value="<?php echo $semanas_gestacion; ?>">

            <!-- SECCIÓN 1: DATOS DEL PACIENTE Y EVALUACIÓN (ESTRUCTURA MEJORADA) -->
<div class="form-section">
    <h2 class="section-tittle">Datos Personales del Paciente</h2>
    <div class="input-grid">
        <div class="input-box"><label>Código</label><input type="text" value="<?php echo $codigo_paciente; ?>" readonly class="auto-filled"></div>
        <div class="input-box"><label>Nombre</label><input type="text" value="<?php echo $nombre_paciente; ?>" readonly class="auto-filled"></div>
        <div class="input-box"><label>A. Paterno</label><input type="text" value="<?php echo $apellido_paterno_paciente; ?>" readonly class="auto-filled"></div>
        <div class="input-box"><label>A. Materno</label><input type="text" value="<?php echo $apellido_materno_paciente; ?>" readonly class="auto-filled"></div>
        <div class="input-box"><label>F. Nacimiento</label><input type="date" id="fecha_nacimiento_paciente" value="<?php echo $fecha_nacimiento_paciente; ?>" readonly class="auto-filled"></div>
        <div class="input-box"><label>Semanas Gestación</label><input type="text" value="<?php echo isset($_GET['semanas_gestacion']) ? htmlspecialchars($_GET['semanas_gestacion']) : ''; ?>" readonly class="auto-filled"></div>
        <div class="input-box"><label>Sexo</label><input type="text" value="<?php echo $sexo_paciente; ?>" readonly class="auto-filled"></div>
    </div>

    <h2 class="section-tittle" style="margin-top: 20px;">Datos de Evaluación</h2>
    <div class="age-fields-grid">
        <div class="input-box"><label>Fecha de Evaluación</label><input type="date" class="input-field" id="fecha_evaluacion" name="fecha_evaluacion" value="<?php echo $fecha_evaluacion; ?>" required></div>
        <div class="input-box"><label>Edad Cronológica</label><input type="text" class="input-field auto-filled" id="edad" name="edad" value="<?php echo $edad; ?>" readonly></div>
        <div class="input-box"><label>Edad Corregida</label><input type="text" class="input-field auto-filled" id="edad_corregida" name="edad_corregida" value="<?php echo isset($_GET['edad_corregida']) ? htmlspecialchars($_GET['edad_corregida']) : ''; ?>" readonly></div>
        <div class="input-box"><label>Condición</label><input type="text" id="condicion_paciente" value="" readonly class="auto-filled"></div>
        <div class="input-box">
            <label>Baremo de Edad Utilizado</label>
            <input type="text" id="rango_edad" name="rango_edad" value="<?php echo isset($_GET['rango_edad']) ? htmlspecialchars($_GET['rango_edad']) : ''; ?>" readonly class="input-field">
            <input type="hidden" id="rango_edad_obs" name="rango_edad_obs">
        </div>
        <div class="input-box">
            <label>&nbsp;</label> 
            <select id="baremo_manual_select" class="input-field hidden">
                <option value="0">Seleccione baremo</option>
                <?php for ($i = 16; $i <= 30; $i++) { echo "<option value='{$i}'>{$i} Meses</option>"; } ?>
            </select>
        </div>
    </div>
</div>

            <!-- SECCIÓN 2: PUNTUACIONES BRUTAS -->
            <div class="form-section">
                <h2 class="section-tittle">Puntuaciones Brutas</h2>
                <div class="input-grid grid-thirds">
                    <div class="input-box"><label>Producción de Palabras</label><input type="text" class="input-field" id="invent2_bruto_uso_palabras" name="invent2_bruto_uso_palabras" value="<?php echo $bruto_uso_palabras; ?>" placeholder="0-680" validate="numeric" required></div>
                    <div class="input-box"><label>Oraciones y Gramática</label><input type="text" class="input-field" id="invent2_bruto_oraciones_gramatica" name="invent2_bruto_oraciones_gramatica" value="<?php echo $bruto_oraciones_gramatica; ?>" placeholder="0-12" validate="numeric" required></div>
                    <div class="input-box"><label>Complejidad de Frases</label><input type="text" class="input-field" id="invent2_bruto_complejidad_frases" name="invent2_bruto_complejidad_frases" value="<?php echo $bruto_complejidad_frases; ?>" placeholder="0-37" validate="numeric" required></div>
                </div>
            </div>

            <!-- SECCIÓN 3: PERCENTILES -->
            <div class="form-section">
                <h2 class="section-tittle">Percentiles</h2>
                <div class="input-grid grid-thirds">
                     <div class="input-box"><label>Producción de Palabras (%)</label><input type="text" class="input-field auto-filled" id="invent2_percentil_uso_palabras" name="invent2_percentil_uso_palabras" value="<?php echo $percentil_uso_palabras; ?>" placeholder="%" readonly required></div>
                     <div class="input-box"><label>Oraciones y Gramática (%)</label><input type="text" class="input-field auto-filled" id="invent2_percentil_oraciones_gramatica" name="invent2_percentil_oraciones_gramatica" value="<?php echo $percentil_oraciones_gramatica; ?>" placeholder="%" readonly required></div>
                     <div class="input-box"><label>Complejidad de Frases (%)</label><input type="text" class="input-field auto-filled" id="invent2_percentil_complejidad_frases" name="invent2_percentil_complejidad_frases" value="<?php echo $percentil_complejidad_frases; ?>" placeholder="%" readonly required></div>
                </div>
            </div>

            <!-- SECCIÓN 4: DATOS CLÍNICOS (ESTRUCTURA MEJORADA) -->
<div class="form-section">
    <h2 class="section-tittle">Datos Clínicos y Observaciones</h2>
    <div class="input-grid">
        <div class="input-box">
            <label>Interpretación</label>
            <select class="input-field" name="invent2_interpretacion">
                <option value="" <?php if(empty($interpretacion)) echo 'selected'; ?>>Seleccione</option>
                <option value="Limites Normales" <?php if($interpretacion == 'Limites Normales') echo 'selected'; ?>>Límites Normales</option>
                <option value="Por debajo de los limites normales" <?php if($interpretacion == 'Por debajo de los limites normales') echo 'selected'; ?>>Por debajo de los límites normales</option>
            </select>
        </div>
        <div class="input-box">
            <label>Seguimiento</label>
            <select class="input-field" name="invent2_seguimiento">
                <option value="" <?php if(empty($seguimiento)) echo 'selected'; ?>>Seleccione</option>
                <option value="Revalorar" <?php if($seguimiento == 'Revalorar') echo 'selected'; ?>>Revalorar</option>
                <option value="Terapia" <?php if($seguimiento == 'Terapia') echo 'selected'; ?>>Terapia</option>
            </select>
        </div>
        <div class="input-box">
            <label>Referir a Terapia</label>
            <select class="input-field" name="invent2_datos_clini_referir_terapi">
                <option value="No" <?php if($referir_terapia == 'No') echo 'selected'; ?>>No</option>
                <option value="Si" <?php if($referir_terapia == 'Si') echo 'selected'; ?>>Sí</option>
                <option value="Habla" <?php if($referir_terapia == 'Habla') echo 'selected'; ?>>Habla</option>
                <option value="Lenguaje" <?php if($referir_terapia == 'Lenguaje') echo 'selected'; ?>>Lenguaje</option>
                <option value="Ambas" <?php if($referir_terapia == 'Ambas') echo 'selected'; ?>>Ambas</option>
            </select>
        </div>
        <div class="input-box input-box-fullwidth">
            <label>Próxima Evaluación</label>
             <div class="prox-eval-container">
                <div class="input-box"><label style="font-size: 0.8em;">Calcular en base a meses</label><select class="input-field" id="meses_prox_eval"><option value="0">No calcular</option><option value="3">3 meses</option><option value="6">6 meses</option><option value="9">9 meses</option><option value="12">12 meses</option></select></div>
                <div class="input-box"><label style="font-size: 0.8em;">Fecha Calculada</label><input type="date" class="input-field" id="invent2_prox_eval" name="invent2_prox_eval" value="<?php echo $prox_eval; ?>"></div>
            </div>
        </div>
        <div class="input-box input-box-fullwidth"><label>Otras Observaciones</label><textarea class="input-field" name="invent2_datos_clini_otras_observ" rows="4"><?php echo $otras_observ; ?></textarea></div>
    </div>
</div>
 <input type="submit" class="btn-submit" value="Guardar Cambios">
    </form>
        <script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>
        
        <!-- ======================   INICIO DEL SCRIPT COMPLETAMENTE NUEVO Y CORRECTO   ========================= -->
    <script>
// =====================================================
    // --- FUNCIÓN DE VALIDACIÓN MEJORADA ---
    // =====================================================
   function setupFieldValidation(selector, regex, maxValue) {
        document.querySelectorAll(selector).forEach(input => {
            input.setAttribute('data-prev-value', input.value);
            input.addEventListener('input', e => {
                if (e.target.readOnly) return;
                if (!regex.test(e.target.value)) {
                    e.target.value = e.target.getAttribute('data-prev-value') || '';
                }
                e.target.setAttribute('data-prev-value', e.target.value);
            });
            input.addEventListener('blur', e => {
                const valor = e.target.value;
                if (valor === '' || valor.toUpperCase() === 'NA') return;
                const numValue = parseInt(valor, 10);
                if (!isNaN(numValue) && numValue > maxValue) {
                    const labelText = e.target.labels[0]?.textContent || 'este campo';
                    Swal.fire({
                        icon: 'error',
                        title: 'Valor fuera de rango',
                        text: `El puntaje para "${labelText}" no puede ser mayor a ${maxValue}.`
                    }).then(() => { e.target.value = ''; e.target.focus(); });
                }
            });
        });
    }

   const percentileData = {
                'invent2_bruto_uso_palabras': {
                    'niños': {
                        16: [{min:0,max:7,p:5},{min:8,max:10,p:10},{min:11,max:14,p:15},{min:15,max:18,p:20},{min:19,max:21,p:25},{min:22,max:24,p:30},{min:25,max:27,p:35},{min:28,max:30,p:40},{min:31,max:33,p:45},{min:34,max:43,p:50},{min:44,max:47,p:55},{min:48,max:55,p:60},{min:56,max:69,p:65},{min:70,max:87,p:70},{min:88,max:104,p:75},{min:105,max:131,p:80},{min:132,max:195,p:85},{min:196,max:286,p:90},{min:287,max:445,p:95},{min:446,max:Infinity,p:99}],
                        17: [{min:0,max:9,p:5},{min:10,max:13,p:10},{min:14,max:18,p:15},{min:19,max:23,p:20},{min:24,max:27,p:25},{min:28,max:31,p:30},{min:32,max:35,p:35},{min:36,max:38,p:40},{min:39,max:42,p:45},{min:43,max:55,p:50},{min:56,max:60,p:55},{min:61,max:69,p:60},{min:70,max:87,p:65},{min:88,max:107,p:70},{min:108,max:127,p:75},{min:128,max:158,p:80},{min:159,max:228,p:85},{min:229,max:322,p:90},{min:323,max:478,p:95},{min:479,max:Infinity,p:99}],
                        18: [{min:0,max:11,p:5},{min:12,max:16,p:10},{min:17,max:22,p:15},{min:23,max:28,p:20},{min:29,max:33,p:25},{min:34,max:38,p:30},{min:39,max:43,p:35},{min:44,max:48,p:40},{min:49,max:54,p:45},{min:55,max:69,p:50},{min:70,max:75,p:55},{min:76,max:87,p:60},{min:88,max:107,p:65},{min:108,max:131,p:70},{min:132,max:154,p:75},{min:155,max:189,p:80},{min:190,max:263,p:85},{min:264,max:359,p:90},{min:360,max:508,p:95},{min:509,max:Infinity,p:99}],
                        19: [{min:0,max:14,p:5},{min:15,max:20,p:10},{min:21,max:28,p:15},{min:29,max:35,p:20},{min:36,max:42,p:25},{min:43,max:48,p:30},{min:49,max:54,p:35},{min:55,max:60,p:40},{min:61,max:68,p:45},{min:69,max:86,p:50},{min:87,max:94,p:55},{min:95,max:108,p:60},{min:109,max:131,p:65},{min:132,max:158,p:70},{min:159,max:185,p:75},{min:186,max:223,p:80},{min:224,max:300,p:85},{min:301,max:396,p:90},{min:397,max:534,p:95},{min:535,max:Infinity,p:99}],
                        20: [{min:0,max:18,p:5},{min:19,max:25,p:10},{min:26,max:35,p:15},{min:36,max:44,p:20},{min:45,max:52,p:25},{min:53,max:59,p:30},{min:60,max:67,p:35},{min:68,max:75,p:40},{min:76,max:85,p:45},{min:86,max:106,p:50},{min:107,max:117,p:55},{min:118,max:134,p:60},{min:135,max:160,p:65},{min:161,max:189,p:70},{min:190,max:219,p:75},{min:220,max:260,p:80},{min:261,max:338,p:85},{min:339,max:431,p:90},{min:432,max:558,p:95},{min:559,max:Infinity,p:99}],
                        21: [{min:0,max:22,p:5},{min:23,max:31,p:10},{min:32,max:44,p:15},{min:45,max:54,p:20},{min:55,max:64,p:25},{min:65,max:73,p:30},{min:74,max:83,p:35},{min:84,max:92,p:40},{min:93,max:105,p:45},{min:106,max:130,p:50},{min:131,max:143,p:55},{min:144,max:164,p:60},{min:165,max:192,p:65},{min:193,max:223,p:70},{min:224,max:256,p:75},{min:257,max:299,p:80},{min:300,max:376,p:85},{min:377,max:464,p:90},{min:465,max:578,p:95},{min:579,max:Infinity,p:99}],
                        22: [{min:0,max:27,p:5},{min:28,max:39,p:10},{min:40,max:54,p:15},{min:55,max:66,p:20},{min:67,max:78,p:25},{min:79,max:90,p:30},{min:91,max:102,p:35},{min:103,max:113,p:40},{min:114,max:130,p:45},{min:131,max:158,p:50},{min:159,max:174,p:55},{min:175,max:197,p:60},{min:198,max:227,p:65},{min:228,max:261,p:70},{min:262,max:296,p:75},{min:297,max:339,p:80},{min:340,max:413,p:85},{min:414,max:495,p:90},{min:496,max:596,p:95},{min:597,max:Infinity,p:99}],
                        23: [{min:0,max:33,p:5},{min:34,max:48,p:10},{min:49,max:67,p:15},{min:68,max:81,p:20},{min:82,max:95,p:25},{min:96,max:109,p:30},{min:110,max:125,p:35},{min:126,max:137,p:40},{min:138,max:159,p:45},{min:160,max:190,p:50},{min:191,max:208,p:55},{min:209,max:235,p:60},{min:236,max:266,p:65},{min:267,max:300,p:70},{min:301,max:336,p:75},{min:337,max:379,p:80},{min:380,max:448,p:85},{min:449,max:523,p:90},{min:524,max:611,p:95},{min:612,max:Infinity,p:99}],
                        24: [{min:0,max:40,p:5},{min:41,max:60,p:10},{min:61,max:82,p:15},{min:83,max:99,p:20},{min:100,max:116,p:25},{min:117,max:132,p:30},{min:133,max:151,p:35},{min:152,max:165,p:40},{min:166,max:191,p:45},{min:192,max:225,p:50},{min:226,max:247,p:55},{min:248,max:276,p:60},{min:277,max:307,p:65},{min:308,max:341,p:70},{min:342,max:377,p:75},{min:378,max:418,p:80},{min:419,max:481,p:85},{min:482,max:548,p:90},{min:549,max:623,p:95},{min:624,max:Infinity,p:99}],
                        25: [{min:0,max:49,p:5},{min:50,max:73,p:10},{min:74,max:101,p:15},{min:102,max:119,p:20},{min:120,max:139,p:25},{min:140,max:158,p:30},{min:159,max:180,p:35},{min:181,max:196,p:40},{min:197,max:228,p:45},{min:229,max:264,p:50},{min:265,max:287,p:55},{min:288,max:319,p:60},{min:320,max:348,p:65},{min:349,max:381,p:70},{min:382,max:417,p:75},{min:418,max:455,p:80},{min:456,max:511,p:85},{min:512,max:569,p:90},{min:570,max:634,p:95},{min:635,max:Infinity,p:99}],
                        26: [{min:0,max:59,p:5},{min:60,max:89,p:10},{min:90,max:122,p:15},{min:123,max:143,p:20},{min:144,max:166,p:25},{min:167,max:188,p:30},{min:189,max:213,p:35},{min:214,max:231,p:40},{min:232,max:268,p:45},{min:269,max:305,p:50},{min:306,max:330,p:55},{min:331,max:362,p:60},{min:363,max:390,p:65},{min:391,max:421,p:70},{min:422,max:454,p:75},{min:455,max:490,p:80},{min:491,max:538,p:85},{min:539,max:588,p:90},{min:589,max:642,p:95},{min:643,max:Infinity,p:99}],
                        27: [{min:0,max:71,p:5},{min:72,max:108,p:10},{min:109,max:147,p:15},{min:148,max:170,p:20},{min:171,max:196,p:25},{min:197,max:221,p:30},{min:222,max:249,p:35},{min:250,max:268,p:40},{min:269,max:310,p:45},{min:311,max:346,p:50},{min:347,max:373,p:55},{min:374,max:405,p:60},{min:406,max:430,p:65},{min:431,max:458,p:70},{min:459,max:489,p:75},{min:490,max:520,p:80},{min:521,max:561,p:85},{min:562,max:604,p:90},{min:605,max:650,p:95},{min:651,max:Infinity,p:99}],
                        28: [{min:0,max:85,p:5},{min:86,max:130,p:10},{min:131,max:175,p:15},{min:176,max:200,p:20},{min:201,max:229,p:25},{min:230,max:257,p:30},{min:258,max:287,p:35},{min:288,max:308,p:40},{min:309,max:352,p:45},{min:353,max:388,p:50},{min:389,max:414,p:55},{min:415,max:445,p:60},{min:446,max:467,p:65},{min:468,max:492,p:70},{min:493,max:520,p:75},{min:521,max:547,p:80},{min:548,max:581,p:85},{min:582,max:618,p:90},{min:619,max:655,p:95},{min:656,max:Infinity,p:99}],
                        29: [{min:0,max:102,p:5},{min:103,max:156,p:10},{min:157,max:207,p:15},{min:208,max:233,p:20},{min:234,max:265,p:25},{min:266,max:294,p:30},{min:295,max:327,p:35},{min:328,max:348,p:40},{min:349,max:395,p:45},{min:396,max:428,p:50},{min:429,max:454,p:55},{min:455,max:483,p:60},{min:484,max:502,p:65},{min:503,max:523,p:70},{min:524,max:548,p:75},{min:549,max:571,p:80},{min:572,max:599,p:85},{min:600,max:629,p:90},{min:630,max:660,p:95},{min:661,max:Infinity,p:99}],
                        30: [{min:0,max:121,p:5},{min:122,max:184,p:10},{min:185,max:241,p:15},{min:242,max:268,p:20},{min:269,max:302,p:25},{min:303,max:333,p:30},{min:334,max:367,p:35},{min:368,max:388,p:40},{min:389,max:435,p:45},{min:436,max:465,p:50},{min:466,max:490,p:55},{min:491,max:517,p:60},{min:518,max:532,p:65},{min:533,max:550,p:70},{min:551,max:571,p:75},{min:572,max:591,p:80},{min:592,max:613,p:85},{min:614,max:638,p:90},{min:639,max:664,p:95},{min:665,max:Infinity,p:99}]
                    },
                    'niñas': {
                        16: [{min:0,max:10,p:5},{min:11,max:12,p:10},{min:13,max:15,p:15},{min:16,max:19,p:20},{min:20,max:22,p:25},{min:23,max:27,p:30},{min:28,max:37,p:35},{min:38,max:42,p:40},{min:43,max:47,p:45},{min:48,max:59,p:50},{min:60,max:70,p:55},{min:71,max:85,p:60},{min:86,max:108,p:65},{min:109,max:115,p:70},{min:116,max:128,p:75},{min:129,max:160,p:80},{min:161,max:193,p:85},{min:194,max:271,p:90},{min:272,max:498,p:95},{min:499,max:Infinity,p:99}],
                        17: [{min:0,max:13,p:5},{min:14,max:16,p:10},{min:17,max:19,p:15},{min:20,max:25,p:20},{min:26,max:28,p:25},{min:29,max:34,p:30},{min:35,max:46,p:35},{min:47,max:53,p:40},{min:54,max:59,p:45},{min:60,max:73,p:50},{min:74,max:85,p:55},{min:86,max:103,p:60},{min:104,max:129,p:65},{min:130,max:139,p:70},{min:140,max:157,p:75},{min:158,max:197,p:80},{min:198,max:236,p:85},{min:237,max:328,p:90},{min:329,max:539,p:95},{min:540,max:Infinity,p:99}],
                        18: [{min:0,max:16,p:5},{min:17,max:20,p:10},{min:21,max:25,p:15},{min:26,max:32,p:20},{min:33,max:36,p:25},{min:37,max:44,p:30},{min:45,max:57,p:35},{min:58,max:65,p:40},{min:66,max:73,p:45},{min:74,max:89,p:50},{min:90,max:104,p:55},{min:105,max:124,p:60},{min:125,max:153,p:65},{min:154,max:167,p:70},{min:168,max:191,p:75},{min:192,max:238,p:80},{min:239,max:282,p:85},{min:283,max:387,p:90},{min:388,max:573,p:95},{min:574,max:Infinity,p:99}],
                        19: [{min:0,max:20,p:5},{min:21,max:25,p:10},{min:26,max:32,p:15},{min:33,max:40,p:20},{min:41,max:46,p:25},{min:47,max:55,p:30},{min:56,max:70,p:35},{min:71,max:80,p:40},{min:81,max:91,p:45},{min:92,max:109,p:50},{min:110,max:126,p:55},{min:127,max:149,p:60},{min:150,max:181,p:65},{min:182,max:199,p:70},{min:200,max:229,p:75},{min:230,max:283,p:80},{min:284,max:331,p:85},{min:332,max:442,p:90},{min:443,max:600,p:95},{min:601,max:Infinity,p:99}],
                        20: [{min:0,max:25,p:5},{min:26,max:32,p:10},{min:33,max:40,p:15},{min:41,max:52,p:20},{min:53,max:59,p:25},{min:60,max:69,p:30},{min:70,max:86,p:35},{min:87,max:98,p:40},{min:99,max:111,p:45},{min:112,max:132,p:50},{min:133,max:152,p:55},{min:153,max:176,p:60},{min:177,max:211,p:65},{min:212,max:234,p:70},{min:235,max:271,p:75},{min:272,max:329,p:80},{min:330,max:381,p:85},{min:382,max:493,p:90},{min:494,max:621,p:95},{min:622,max:Infinity,p:99}],
                        21: [{min:0,max:31,p:5},{min:32,max:40,p:10},{min:41,max:51,p:15},{min:52,max:65,p:20},{min:66,max:74,p:25},{min:75,max:87,p:30},{min:88,max:105,p:35},{min:106,max:119,p:40},{min:120,max:135,p:45},{min:136,max:159,p:50},{min:160,max:181,p:55},{min:182,max:207,p:60},{min:208,max:243,p:65},{min:244,max:271,p:70},{min:272,max:314,p:75},{min:315,max:376,p:80},{min:377,max:428,p:85},{min:429,max:536,p:90},{min:537,max:637,p:95},{min:638,max:Infinity,p:99}],
                        22: [{min:0,max:38,p:5},{min:39,max:51,p:10},{min:52,max:63,p:15},{min:64,max:82,p:20},{min:83,max:93,p:25},{min:94,max:108,p:30},{min:109,max:127,p:35},{min:128,max:143,p:40},{min:144,max:163,p:45},{min:164,max:189,p:50},{min:190,max:213,p:55},{min:214,max:241,p:60},{min:242,max:278,p:65},{min:279,max:310,p:70},{min:311,max:358,p:75},{min:359,max:422,p:80},{min:423,max:472,p:85},{min:473,max:571,p:90},{min:572,max:649,p:95},{min:650,max:Infinity,p:99}],
                        23: [{min:0,max:47,p:5},{min:48,max:63,p:10},{min:64,max:79,p:15},{min:80,max:102,p:20},{min:103,max:116,p:25},{min:117,max:132,p:30},{min:133,max:153,p:35},{min:154,max:171,p:40},{min:172,max:194,p:45},{min:195,max:223,p:50},{min:224,max:248,p:55},{min:249,max:276,p:60},{min:277,max:314,p:65},{min:315,max:350,p:70},{min:351,max:402,p:75},{min:403,max:465,p:80},{min:466,max:512,p:85},{min:513,max:599,p:90},{min:600,max:661,p:95},{min:662,max:Infinity,p:99}],
                        24: [{min:0,max:57,p:5},{min:58,max:78,p:10},{min:79,max:98,p:15},{min:99,max:127,p:20},{min:128,max:142,p:25},{min:143,max:161,p:30},{min:162,max:182,p:35},{min:183,max:202,p:40},{min:203,max:228,p:45},{min:229,max:259,p:50},{min:260,max:285,p:55},{min:286,max:314,p:60},{min:315,max:351,p:65},{min:352,max:390,p:70},{min:391,max:444,p:75},{min:445,max:503,p:80},{min:504,max:546,p:85},{min:547,max:621,p:90},{min:622,max:664,p:95},{min:665,max:Infinity,p:99}],
                        25: [{min:0,max:70,p:5},{min:71,max:97,p:10},{min:98,max:120,p:15},{min:121,max:155,p:20},{min:156,max:173,p:25},{min:174,max:194,p:30},{min:195,max:214,p:35},{min:215,max:236,p:40},{min:237,max:266,p:45},{min:267,max:297,p:50},{min:298,max:324,p:55},{min:325,max:351,p:60},{min:352,max:387,p:65},{min:388,max:428,p:70},{min:429,max:482,p:75},{min:483,max:537,p:80},{min:538,max:575,p:85},{min:576,max:637,p:90},{min:638,max:668,p:95},{min:669,max:Infinity,p:99}],
                        26: [{min:0,max:84,p:5},{min:85,max:118,p:10},{min:119,max:147,p:15},{min:148,max:188,p:20},{min:189,max:208,p:25},{min:209,max:231,p:30},{min:232,max:250,p:35},{min:251,max:272,p:40},{min:273,max:305,p:45},{min:306,max:337,p:50},{min:338,max:363,p:55},{min:364,max:389,p:60},{min:390,max:422,p:65},{min:423,max:464,p:70},{min:465,max:517,p:75},{min:518,max:566,p:80},{min:567,max:598,p:85},{min:599,max:649,p:90},{min:650,max:672,p:95},{min:673,max:Infinity,p:99}],
                        27: [{min:0,max:102,p:5},{min:103,max:143,p:10},{min:144,max:177,p:15},{min:178,max:224,p:20},{min:225,max:247,p:25},{min:248,max:270,p:30},{min:271,max:287,p:35},{min:288,max:310,p:40},{min:311,max:345,p:45},{min:346,max:376,p:50},{min:377,max:401,p:55},{min:402,max:425,p:60},{min:426,max:456,p:65},{min:457,max:497,p:70},{min:498,max:547,p:75},{min:548,max:590,p:80},{min:591,max:617,p:85},{min:618,max:658,p:90},{min:659,max:676,p:95},{min:677,max:Infinity,p:99}],
                        28: [{min:0,max:122,p:5},{min:123,max:172,p:10},{min:173,max:211,p:15},{min:212,max:264,p:20},{min:265,max:288,p:25},{min:289,max:312,p:30},{min:313,max:326,p:35},{min:327,max:349,p:40},{min:350,max:385,p:45},{min:386,max:415,p:50},{min:416,max:438,p:55},{min:439,max:460,p:60},{min:461,max:487,p:65},{min:488,max:527,p:70},{min:528,max:572,p:75},{min:573,max:609,p:80},{min:610,max:632,p:85},{min:633,max:664,p:90},{min:665,max:677,p:95},{min:678,max:Infinity,p:99}],
                        29: [{min:0,max:145,p:5},{min:146,max:205,p:10},{min:206,max:248,p:15},{min:249,max:306,p:20},{min:307,max:331,p:25},{min:332,max:354,p:30},{min:355,max:365,p:35},{min:366,max:387,p:40},{min:388,max:424,p:45},{min:425,max:451,p:50},{min:452,max:473,p:55},{min:474,max:492,p:60},{min:493,max:515,p:65},{min:516,max:553,p:70},{min:554,max:594,p:75},{min:595,max:625,p:80},{min:626,max:643,p:85},{min:644,max:669,p:90},{min:670,max:677,p:95},{min:678,max:Infinity,p:99}],
                        30: [{min:0,max:171,p:5},{min:172,max:240,p:10},{min:241,max:287,p:15},{min:288,max:349,p:20},{min:350,max:374,p:25},{min:375,max:396,p:30},{min:397,max:403,p:35},{min:404,max:425,p:40},{min:426,max:461,p:45},{min:462,max:485,p:50},{min:486,max:504,p:55},{min:505,max:520,p:60},{min:521,max:541,p:65},{min:542,max:575,p:70},{min:576,max:612,p:75},{min:613,max:638,p:80},{min:639,max:652,p:85},{min:653,max:672,p:90},{min:673,max:678,p:95},{min:679,max:Infinity,p:99}]
                    }
                },
                'invent2_bruto_oraciones_gramatica': {
                    'niños': {
                        16:[{min:0,max:0,p:5},{min:1,max:1,p:70},{min:2,max:2,p:90},{min:3,max:Infinity,p:99}],
                        17:[{min:0,max:0,p:5},{min:1,max:1,p:65},{min:2,max:2,p:90},{min:3,max:Infinity,p:99}],
                        18:[{min:0,max:0,p:5},{min:1,max:1,p:60},{min:2,max:2,p:85},{min:3,max:3,p:95},{min:4,max:Infinity,p:99}],
                        19:[{min:0,max:0,p:5},{min:1,max:1,p:60},{min:2,max:2,p:80},{min:3,max:3,p:90},{min:4,max:4,p:95},{min:5,max:Infinity,p:99}],
                        20:[{min:0,max:0,p:5},{min:1,max:1,p:50},{min:2,max:2,p:75},{min:3,max:3,p:90},{min:4,max:4,p:95},{min:5,max:Infinity,p:99}],
                        21:[{min:0,max:0,p:5},{min:1,max:1,p:30},{min:2,max:2,p:70},{min:3,max:3,p:85},{min:4,max:4,p:90},{min:5,max:5,p:95},{min:6,max:Infinity,p:99}],
                        22:[{min:0,max:0,p:5},{min:1,max:1,p:25},{min:2,max:2,p:60},{min:3,max:3,p:85},{min:4,max:4,p:90},{min:5,max:6,p:95},{min:7,max:Infinity,p:99}],
                        23:[{min:0,max:0,p:5},{min:1,max:1,p:25},{min:2,max:2,p:60},{min:3,max:3,p:75},{min:4,max:5,p:90},{min:6,max:6,p:95},{min:7,max:Infinity,p:99}],
                        24:[{min:0,max:0,p:5},{min:1,max:1,p:15},{min:2,max:2,p:50},{min:3,max:3,p:70},{min:4,max:4,p:85},{min:5,max:5,p:90},{min:6,max:7,p:95},{min:8,max:Infinity,p:99}],
                        25:[{min:0,max:0,p:5},{min:1,max:1,p:15},{min:2,max:2,p:40},{min:3,max:3,p:60},{min:4,max:4,p:85},{min:5,max:6,p:90},{min:7,max:8,p:95},{min:9,max:Infinity,p:99}],
                        26:[{min:0,max:0,p:5},{min:1,max:1,p:10},{min:2,max:2,p:30},{min:3,max:3,p:55},{min:4,max:4,p:75},{min:5,max:5,p:85},{min:6,max:7,p:90},{min:8,max:8,p:95},{min:9,max:Infinity,p:99}],
                        27:[{min:0,max:0,p:5},{min:1,max:1,p:10},{min:2,max:2,p:25},{min:3,max:3,p:50},{min:4,max:4,p:70},{min:5,max:5,p:85},{min:6,max:7,p:90},{min:8,max:9,p:95},{min:10,max:Infinity,p:99}],
                        28:[{min:0,max:0,p:5},{min:1,max:1,p:10},{min:2,max:2,p:25},{min:3,max:3,p:40},{min:4,max:4,p:60},{min:5,max:5,p:80},{min:6,max:6,p:85},{min:7,max:8,p:90},{min:9,max:9,p:95},{min:10,max:Infinity,p:99}],
                        29:[{min:0,max:0,p:5},{min:1,max:1,p:10},{min:2,max:2,p:25},{min:3,max:3,p:35},{min:4,max:4,p:50},{min:5,max:5,p:75},{min:6,max:6,p:85},{min:7,max:8,p:90},{min:9,max:10,p:95},{min:11,max:Infinity,p:99}],
                        30:[{min:0,max:0,p:5},{min:1,max:1,p:10},{min:2,max:2,p:20},{min:3,max:3,p:30},{min:4,max:4,p:45},{min:5,max:5,p:60},{min:6,max:7,p:85},{min:8,max:9,p:90},{min:10,max:10,p:95},{min:11,max:Infinity,p:99}]
                    },
                    'niñas': {
                        16:[{min:0,max:0,p:5},{min:1,max:1,p:60},{min:2,max:2,p:90},{min:3,max:3,p:95},{min:4,max:Infinity,p:99}],
                        17:[{min:0,max:0,p:5},{min:1,max:1,p:55},{min:2,max:2,p:90},{min:3,max:4,p:95},{min:5,max:Infinity,p:99}],
                        18:[{min:0,max:0,p:5},{min:1,max:1,p:55},{min:2,max:2,p:80},{min:3,max:3,p:90},{min:4,max:4,p:95},{min:5,max:Infinity,p:99}],
                        19:[{min:0,max:0,p:5},{min:1,max:1,p:50},{min:2,max:2,p:70},{min:3,max:4,p:90},{min:5,max:5,p:95},{min:6,max:Infinity,p:99}],
                        20:[{min:0,max:0,p:5},{min:1,max:1,p:35},{min:2,max:2,p:65},{min:3,max:3,p:85},{min:4,max:4,p:90},{min:5,max:6,p:95},{min:7,max:Infinity,p:99}],
                        21:[{min:0,max:0,p:5},{min:1,max:1,p:30},{min:2,max:2,p:55},{min:3,max:3,p:80},{min:4,max:5,p:90},{min:6,max:7,p:95},{min:8,max:Infinity,p:99}],
                        22:[{min:0,max:0,p:5},{min:1,max:1,p:20},{min:2,max:2,p:55},{min:3,max:3,p:70},{min:4,max:4,p:85},{min:5,max:6,p:90},{min:7,max:8,p:95},{min:9,max:Infinity,p:99}],
                        23:[{min:0,max:0,p:5},{min:1,max:1,p:15},{min:2,max:2,p:45},{min:3,max:3,p:65},{min:4,max:4,p:80},{min:5,max:7,p:90},{min:8,max:8,p:95},{min:9,max:Infinity,p:99}],
                        24:[{min:0,max:0,p:5},{min:1,max:1,p:15},{min:2,max:2,p:35},{min:3,max:3,p:60},{min:4,max:4,p:75},{min:5,max:5,p:85},{min:6,max:7,p:90},{min:8,max:9,p:95},{min:10,max:Infinity,p:99}],
                        25:[{min:0,max:0,p:5},{min:1,max:1,p:10},{min:2,max:2,p:30},{min:3,max:3,p:50},{min:4,max:4,p:65},{min:5,max:5,p:80},{min:6,max:8,p:90},{min:9,max:10,p:95},{min:11,max:Infinity,p:99}],
                        26:[{min:0,max:0,p:5},{min:1,max:1,p:10},{min:2,max:2,p:25},{min:3,max:3,p:45},{min:4,max:4,p:65},{min:5,max:5,p:75},{min:6,max:6,p:85},{min:7,max:9,p:90},{min:10,max:10,p:95},{min:11,max:Infinity,p:99}],
                        27:[{min:0,max:0,p:5},{min:1,max:1,p:5},{min:2,max:2,p:20},{min:3,max:3,p:35},{min:4,max:4,p:55},{min:5,max:5,p:70},{min:6,max:6,p:80},{min:7,max:7,p:85},{min:8,max:9,p:90},{min:10,max:11,p:95},{min:12,max:Infinity,p:99}],
                        28:[{min:0,max:0,p:5},{min:1,max:1,p:5},{min:2,max:2,p:15},{min:3,max:3,p:30},{min:4,max:4,p:45},{min:5,max:5,p:65},{min:6,max:6,p:75},{min:7,max:7,p:85},{min:8,max:10,p:90},{min:11,max:11,p:95},{min:12,max:Infinity,p:99}],
                        29:[{min:0,max:0,p:5},{min:1,max:1,p:5},{min:2,max:2,p:15},{min:3,max:3,p:25},{min:4,max:4,p:40},{min:5,max:5,p:60},{min:6,max:6,p:70},{min:7,max:7,p:80},{min:8,max:8,p:85},{min:9,max:10,p:90},{min:11,max:11,p:95},{min:12,max:Infinity,p:99}],
                        30:[{min:0,max:0,p:5},{min:1,max:1,p:5},{min:2,max:2,p:15},{min:3,max:3,p:20},{min:4,max:4,p:30},{min:5,max:5,p:45},{min:6,max:6,p:65},{min:7,max:7,p:75},{min:8,max:8,p:85},{min:9,max:11,p:90},{min:12,max:Infinity,p:99}]
                    }
                },
                'invent2_bruto_complejidad_frases': {
                    'niños': {
                        16:[{min:0,max:2,p:90},{min:3,max:11,p:95},{min:12,max:Infinity,p:99}],
                        17:[{min:0,max:4,p:90},{min:5,max:14,p:95},{min:15,max:Infinity,p:99}],
                        18:[{min:0,max:0,p:85},{min:1,max:6,p:90},{min:7,max:17,p:95},{min:18,max:Infinity,p:99}],
                        19:[{min:0,max:0,p:85},{min:1,max:9,p:90},{min:10,max:20,p:95},{min:21,max:Infinity,p:99}],
                        20:[{min:0,max:0,p:80},{min:1,max:1,p:85},{min:2,max:12,p:90},{min:13,max:24,p:95},{min:25,max:Infinity,p:99}],
                        21:[{min:0,max:0,p:75},{min:1,max:1,p:80},{min:2,max:3,p:85},{min:4,max:16,p:90},{min:17,max:26,p:95},{min:27,max:Infinity,p:99}],
                        22:[{min:0,max:0,p:70},{min:1,max:1,p:75},{min:2,max:2,p:80},{min:3,max:5,p:85},{min:6,max:20,p:90},{min:21,max:29,p:95},{min:30,max:Infinity,p:99}],
                        23:[{min:0,max:0,p:65},{min:1,max:1,p:70},{min:2,max:2,p:75},{min:3,max:5,p:80},{min:6,max:10,p:85},{min:11,max:24,p:90},{min:25,max:31,p:95},{min:32,max:Infinity,p:99}],
                        24:[{min:0,max:0,p:50},{min:1,max:1,p:65},{min:2,max:2,p:70},{min:3,max:5,p:75},{min:6,max:9,p:80},{min:10,max:16,p:85},{min:17,max:27,p:90},{min:28,max:32,p:95},{min:33,max:Infinity,p:99}],
                        25:[{min:0,max:0,p:45},{min:1,max:1,p:50},{min:2,max:2,p:60},{min:3,max:3,p:65},{min:4,max:5,p:70},{min:6,max:9,p:75},{min:10,max:15,p:80},{min:16,max:22,p:85},{min:23,max:30,p:90},{min:31,max:34,p:95},{min:35,max:Infinity,p:99}],
                        26:[{min:0,max:0,p:40},{min:1,max:1,p:45},{min:2,max:3,p:50},{min:4,max:4,p:55},{min:5,max:5,p:60},{min:6,max:7,p:65},{min:8,max:10,p:70},{min:11,max:15,p:75},{min:16,max:22,p:80},{min:23,max:28,p:85},{min:29,max:32,p:90},{min:33,max:35,p:95},{min:36,max:Infinity,p:99}],
                        27:[{min:0,max:0,p:35},{min:1,max:1,p:40},{min:2,max:2,p:45},{min:3,max:5,p:50},{min:6,max:7,p:55},{min:8,max:9,p:60},{min:10,max:13,p:65},{min:14,max:17,p:70},{min:18,max:22,p:75},{min:23,max:28,p:80},{min:29,max:32,p:85},{min:33,max:34,p:90},{min:35,max:35,p:95},{min:36,max:Infinity,p:99}],
                        28:[{min:0,max:0,p:30},{min:1,max:2,p:35},{min:3,max:4,p:45},{min:5,max:10,p:50},{min:11,max:12,p:55},{min:13,max:16,p:60},{min:17,max:20,p:65},{min:21,max:24,p:70},{min:25,max:28,p:75},{min:29,max:32,p:80},{min:33,max:34,p:85},{min:35,max:35,p:90},{min:36,max:36,p:95},{min:37,max:Infinity,p:99}],
                        29:[{min:0,max:0,p:30},{min:1,max:1,p:35},{min:2,max:5,p:40},{min:6,max:8,p:45},{min:9,max:15,p:50},{min:16,max:19,p:55},{min:20,max:22,p:60},{min:23,max:26,p:65},{min:27,max:29,p:70},{min:30,max:32,p:75},{min:33,max:34,p:80},{min:35,max:35,p:85},{min:36,max:36,p:90},{min:37,max:Infinity,p:99}],
                        30:[{min:0,max:0,p:25},{min:1,max:1,p:30},{min:2,max:3,p:35},{min:4,max:9,p:40},{min:10,max:14,p:45},{min:15,max:21,p:50},{min:22,max:25,p:55},{min:26,max:28,p:60},{min:29,max:31,p:65},{min:32,max:33,p:70},{min:34,max:34,p:75},{min:35,max:35,p:80},{min:36,max:36,p:85},{min:37,max:Infinity,p:99}]
                    },
                    'niñas': {
                        16:[{min:0,max:0,p:85},{min:1,max:3,p:90},{min:4,max:23,p:95},{min:24,max:Infinity,p:99}],
                        17:[{min:0,max:0,p:85},{min:1,max:5,p:90},{min:6,max:26,p:95},{min:27,max:Infinity,p:99}],
                        18:[{min:0,max:1,p:85},{min:2,max:8,p:90},{min:9,max:28,p:95},{min:29,max:Infinity,p:99}],
                        19:[{min:0,max:0,p:80},{min:1,max:2,p:85},{min:3,max:11,p:90},{min:12,max:29,p:95},{min:30,max:Infinity,p:99}],
                        20:[{min:0,max:1,p:80},{min:2,max:4,p:85},{min:5,max:15,p:90},{min:16,max:31,p:95},{min:32,max:Infinity,p:99}],
                        21:[{min:0,max:0,p:65},{min:1,max:2,p:80},{min:3,max:8,p:85},{min:9,max:19,p:90},{min:20,max:32,p:95},{min:33,max:Infinity,p:99}],
                        22:[{min:0,max:0,p:60},{min:1,max:1,p:70},{min:2,max:5,p:80},{min:6,max:12,p:85},{min:13,max:23,p:90},{min:24,max:33,p:95},{min:34,max:Infinity,p:99}],
                        23:[{min:0,max:0,p:60},{min:1,max:1,p:65},{min:2,max:3,p:70},{min:4,max:4,p:75},{min:5,max:9,p:80},{min:10,max:18,p:85},{min:19,max:27,p:90},{min:28,max:34,p:95},{min:35,max:Infinity,p:99}],
                        24:[{min:0,max:0,p:50},{min:1,max:1,p:55},{min:2,max:2,p:60},{min:3,max:4,p:65},{min:5,max:6,p:70},{min:7,max:9,p:75},{min:10,max:15,p:80},{min:16,max:23,p:85},{min:24,max:30,p:90},{min:31,max:34,p:95},{min:35,max:Infinity,p:99}],
                        25:[{min:0,max:0,p:45},{min:1,max:1,p:50},{min:2,max:3,p:55},{min:4,max:4,p:60},{min:5,max:8,p:65},{min:9,max:12,p:70},{min:13,max:17,p:75},{min:18,max:22,p:80},{min:23,max:28,p:85},{min:29,max:32,p:90},{min:33,max:35,p:95},{min:36,max:Infinity,p:99}],
                        26:[{min:0,max:0,p:40},{min:1,max:1,p:45},{min:2,max:4,p:50},{min:5,max:7,p:55},{min:8,max:9,p:60},{min:10,max:14,p:65},{min:15,max:19,p:70},{min:20,max:25,p:75},{min:26,max:28,p:80},{min:29,max:31,p:85},{min:32,max:34,p:90},{min:35,max:35,p:95},{min:36,max:Infinity,p:99}],
                        27:[{min:0,max:0,p:30},{min:1,max:2,p:35},{min:3,max:3,p:40},{min:4,max:8,p:50},{min:9,max:13,p:55},{min:14,max:16,p:60},{min:17,max:21,p:65},{min:22,max:26,p:70},{min:27,max:30,p:75},{min:31,max:32,p:80},{min:33,max:34,p:85},{min:35,max:35,p:90},{min:36,max:36,p:95},{min:37,max:Infinity,p:99}],
                        28:[{min:0,max:0,p:20},{min:1,max:1,p:30},{min:2,max:4,p:35},{min:5,max:6,p:40},{min:7,max:7,p:45},{min:8,max:15,p:50},{min:16,max:20,p:55},{min:21,max:23,p:60},{min:24,max:27,p:65},{min:28,max:31,p:70},{min:32,max:34,p:75},{min:35,max:35,p:85},{min:36,max:36,p:90},{min:37,max:Infinity,p:99}],
                        29:[{min:0,max:0,p:20},{min:1,max:2,p:30},{min:3,max:8,p:35},{min:9,max:10,p:40},{min:11,max:13,p:45},{min:14,max:22,p:50},{min:23,max:27,p:55},{min:28,max:29,p:60},{min:30,max:32,p:65},{min:33,max:34,p:70},{min:35,max:36,p:75},{min:37,max:Infinity,p:99}],
                        30:[{min:0,max:1,p:20},{min:2,max:4,p:30},{min:5,max:13,p:35},{min:14,max:17,p:40},{min:18,max:19,p:45},{min:20,max:28,p:50},{min:29,max:32,p:55},{min:33,max:33,p:60},{min:34,max:34,p:65},{min:35,max:35,p:70},{min:36,max:36,p:75},{min:37,max:Infinity,p:99}]
                    }
                }
            };


    // 3. LÓGICA DE CÁLCULO Y MANEJO DEL FORMULARIO (Adaptada para CDI-II)
    function gestionarModoFormulario(esManual, mensaje = '') {
        const percentileInputs = document.querySelectorAll('input[name^="invent2_percentil_"]');
        const baremoManualSelect = document.getElementById('baremo_manual_select');
        percentileInputs.forEach(input => {
            input.readOnly = !esManual;
            input.classList.toggle('auto-filled', !esManual);
            if (esManual) {
                input.placeholder = "Manual o seleccionar baremo";
                if (baremoManualSelect.value === '0') input.value = '';
            } else { input.placeholder = "%"; }
        });
        baremoManualSelect.classList.toggle('hidden', !esManual);
        if (esManual && mensaje) {
            Swal.fire({ icon: 'warning', title: 'Atención', text: mensaje });
        }
    }

    function calculatePreciseAge(startDate, endDate) {
        if (!(startDate instanceof Date) || !(endDate instanceof Date) || isNaN(startDate) || isNaN(endDate)) return { years: 0, months: 0, days: 0 };
        let years = endDate.getFullYear() - startDate.getFullYear();
        let months = endDate.getMonth() - startDate.getMonth();
        let days = endDate.getDate() - startDate.getDate();
        if (days < 0) { months--; days += new Date(endDate.getFullYear(), endDate.getMonth(), 0).getDate(); }
        if (months < 0) { years--; months += 12; }
        return { years, months, days };
    }

    function setPatientCondition() {
        const gestWeeksElem = document.getElementById('semanas_gestacion_hidden');
        const conditionElem = document.getElementById('condicion_paciente');
        if (!gestWeeksElem || !conditionElem) return;
        const gestWeeks = parseInt(gestWeeksElem.value, 10);
        if (gestWeeks > 0 && gestWeeks < 37) { conditionElem.value = "Prematuro"; } 
        else if (gestWeeks >= 37) { conditionElem.value = "Nacido a término"; } 
        else { conditionElem.value = "No especificado"; }
    }

    function getPercentile(category, gender, ageInMonths, score) {
        if (isNaN(score) || score === null || score === '' || ageInMonths < 16 || ageInMonths > 30) return '';
        const ageData = percentileData[category]?.[gender]?.[ageInMonths];
        if (!ageData) return 'NA (Sin baremo)';
        for (const range of ageData) { if (score >= range.min && score <= range.max) return String(range.p); }
        return 'NA (Fuera de rango)';
    }

    function updateAllPercentiles() {
        const rangoEdadElem = document.getElementById('rango_edad');
        const baremoText = rangoEdadElem.value;
        if (!baremoText.includes('Meses')) return;

        const ageInMonthsToUse = parseInt(baremoText, 10);
        if (isNaN(ageInMonthsToUse)) return;

        const sexoValue = document.getElementById('sexo_paciente').value.trim().toLowerCase();
        const gender = (sexoValue.startsWith('femenin')) ? 'niñas' : 'niños';
        
        const fieldsToCalculate = {
            'invent2_bruto_uso_palabras': 'invent2_percentil_uso_palabras',
            'invent2_bruto_oraciones_gramatica': 'invent2_percentil_oraciones_gramatica',
            'invent2_bruto_complejidad_frases': 'invent2_percentil_complejidad_frases'
        };

        for (const [scoreId, percentileId] of Object.entries(fieldsToCalculate)) {
            const percentileInput = document.querySelector(`[name="${percentileId}"]`);
            const scoreInput = document.querySelector(`[name="${scoreId}"]`);
            if (percentileInput && scoreInput && percentileInput.readOnly) {
                const scoreStr = scoreInput.value.trim().toUpperCase();
                let score = (scoreStr === 'NA' || scoreStr === '') ? NaN : parseInt(scoreStr, 10);
                percentileInput.value = getPercentile(scoreId, gender, ageInMonthsToUse, score);
            }
        }
    }

    function calculateAllAgesAndUpdate() {
        document.querySelectorAll('input[name^="invent2_percentil_"]').forEach(input => input.value = '');
        const birthDateElem = document.getElementById('fecha_nacimiento_paciente');
        const evalDateElem = document.getElementById('fecha_evaluacion');
        const cronoAgeElem = document.getElementById('edad');
        const correctedAgeElem = document.getElementById('edad_corregida');
        const rangoEdadElem = document.getElementById('rango_edad');
        const rangoEdadObsElem = document.getElementById('rango_edad_obs');

        cronoAgeElem.classList.remove('edad-activa'); 
        correctedAgeElem.classList.remove('edad-activa');
        if (!birthDateElem.value || !evalDateElem.value) { gestionarModoFormulario(true); return; }
        
        const startDate = new Date(birthDateElem.value);
        const endDate = new Date(evalDateElem.value);
        if (startDate > endDate) {
            gestionarModoFormulario(true);
            Swal.fire({ icon: 'error', title: 'Error', text: 'La fecha de nacimiento no puede ser posterior a la de evaluación.' });
            return;
        }

        const cronoAge = calculatePreciseAge(startDate, endDate);
        cronoAgeElem.value = `${cronoAge.years}A ${cronoAge.months}M ${cronoAge.days}D`;
        const chronologicalTotalMonths = (cronoAge.years * 12) + cronoAge.months;
        
        let ageInMonthsForPercentiles = chronologicalTotalMonths;
        let tipoDeEdadUsada = "cronológica";
        cronoAgeElem.classList.add('edad-activa');

        const gestWeeks = parseInt(document.getElementById('semanas_gestacion_hidden').value, 10);
        if (gestWeeks > 0 && gestWeeks < 37 && chronologicalTotalMonths < 36) {
            const correctedAge = calculatePreciseAge(startDate, new Date(endDate.getTime() - ((40 - gestWeeks) * 7 * 24 * 60 * 60 * 1000)));
            correctedAgeElem.value = `${correctedAge.years}A ${correctedAge.months}M ${correctedAge.days}D`;
            ageInMonthsForPercentiles = (correctedAge.years * 12) + correctedAge.months;
            tipoDeEdadUsada = "corregida";
            cronoAgeElem.classList.remove('edad-activa');
            correctedAgeElem.classList.add('edad-activa');
        } else {
            correctedAgeElem.value = 'No Aplica';
        }

        if (ageInMonthsForPercentiles < 16 || ageInMonthsForPercentiles > 30) {
            rangoEdadElem.value = "Fuera de Baremo";
            rangoEdadObsElem.value = `Edad para cálculo (${ageInMonthsForPercentiles}m) fuera de baremo.`;
            const mensaje = `La edad ${tipoDeEdadUsada} (${ageInMonthsForPercentiles} meses) está fuera del baremo (16-30 meses). Seleccione un baremo o ingrese los percentiles.`;
            gestionarModoFormulario(true, mensaje);
        } else {
            rangoEdadElem.value = `${ageInMonthsForPercentiles} Meses`;
            rangoEdadObsElem.value = "";
            gestionarModoFormulario(false);
            updateAllPercentiles();
        }
    }

    // 4. CÓDIGO PRINCIPAL QUE SE EJECUTA AL CARGAR LA PÁGINA
    document.addEventListener('DOMContentLoaded', function() {
        // --- A. CONFIGURACIÓN DE VALIDACIONES ---
        const numericRegex = /^(|NA|\d*)$/;
        setupFieldValidation('input[name="invent2_bruto_uso_palabras"]', numericRegex, 680);
        setupFieldValidation('input[name="invent2_bruto_oraciones_gramatica"]', numericRegex, 12);
        setupFieldValidation('input[name="invent2_bruto_complejidad_frases"]', numericRegex, 37);
        
        // --- B. REFERENCIAS A ELEMENTOS Y ESTADO INICIAL ---
        const evalDateInput = document.getElementById('fecha_evaluacion');
        const scoreInputs = document.querySelectorAll('input[name^="invent2_bruto_"]'); // Obtiene los 3 campos de puntaje bruto
        const baremoManualSelect = document.getElementById('baremo_manual_select');
        const mesesSelect = document.getElementById('meses_prox_eval');
        const proxEvalInput = document.getElementById('invent2_prox_eval');

        function initializeFormState() {
            setPatientCondition();
            const rangoGuardado = document.getElementById('rango_edad').value;
            if (rangoGuardado === 'Fuera de Baremo') {
                gestionarModoFormulario(true, 'La edad original estaba fuera de baremo. Los percentiles son manuales.');
            } else {
                gestionarModoFormulario(false);
            }
        }
        initializeFormState();

        // --- C. ASIGNACIÓN DE EVENTOS ---
        evalDateInput.addEventListener('change', calculateAllAgesAndUpdate);

        // ===== ESTA ES LA PARTE CLAVE QUE FALTABA O ERA INCORRECTA =====
        // Agrega un "escuchador" a cada campo de puntaje bruto.
        // Cuando el usuario escribe ('input'), se ejecuta la función de recálculo.
        scoreInputs.forEach(input => {
            input.addEventListener('input', updateAllPercentiles);
        });
        // ===============================================================

        baremoManualSelect.addEventListener('change', function() {
            const manualAge = parseInt(this.value, 10);
            if (manualAge > 0) {
                document.getElementById('rango_edad').value = `${manualAge} Meses`;
                document.getElementById('rango_edad_obs').value = "Baremo seleccionado manualmente.";
                gestionarModoFormulario(false);
                updateAllPercentiles();
            } else {
                calculateAllAgesAndUpdate();
            }
        });

        mesesSelect.addEventListener('change', function() {
            const mesesASumar = parseInt(this.value, 10);
            if (mesesASumar === 0 || !evalDateInput.value) {
                proxEvalInput.value = ''; return;
            }
            const fechaEval = new Date(evalDateInput.value + 'T00:00:00');
            fechaEval.setMonth(fechaEval.getMonth() + mesesASumar);
            proxEvalInput.value = fechaEval.toISOString().split('T')[0];
        });

        document.getElementById('cdiForm').addEventListener('submit', function(e) {
            this.querySelectorAll('input, select, textarea').forEach(field => {
                if (field.readOnly) { field.removeAttribute('readonly'); }
                if (field.disabled) { field.disabled = false; }
            });
        });
    });
</script>
        <!-- ======================   FIN DEL SCRIPT ACTUALIZADO   ========================= -->
    </div>
</body>
</html>