<?php
// =============================================================================
// ARMONIZACION OROFACIAL - FACE MAPPING PROFESIONAL (FMA Pro v2)
// Modulo de armonizacion orofacial con:
//   - Anamnesis estetica especifica (alergias, anticoagulantes, banderas rojas)
//   - Escalas Fitzpatrick, Glogau, Merz
//   - Analisis facial: tercios, quintos, angulos, musculatura hiperactiva
//   - Face chart SVG inline (frontal + lateral) con marcas anotables
//   - Plan por 20 zonas anatomicas con producto/lote/unidades
//   - Resumen totalizado calculado en JS
//   - Consentimiento, seguimiento GAIS, eventos adversos
// Tipo_formato: ARMONIZACION
// =============================================================================
?>
<style>
    .aof-banner { background: linear-gradient(90deg,#7c3aed,#c026d3); color:#fff; padding:14px 18px; border-radius:8px; margin-bottom:14px;
        display:flex; align-items:center; justify-content:space-between; box-shadow:0 4px 10px rgba(0,0,0,.15); }
    .aof-banner h2 { margin:0; font-size:18px; font-weight:700; letter-spacing:.5px; }
    .aof-banner .aof-chip { background:rgba(255,255,255,.2); padding:4px 10px; border-radius:20px; font-size:11px; font-weight:700; text-transform:uppercase; }

    .aof-table { width:100%; border-collapse:collapse; font-size:11px; margin-bottom:10px; }
    .aof-table th, .aof-table td { border:1px solid #e2e8f0; padding:5px 7px; vertical-align:top; }
    .aof-table th { background:#ede9fe; font-weight:700; text-align:center; color:#5b21b6; font-size:11px; text-transform:uppercase; letter-spacing:.3px; }
    .aof-table td.lbl { background:#faf5ff; font-weight:600; color:#5b21b6; width:22%; }
    .aof-table input.in, .aof-table textarea.in, .aof-table select.in {
        width:100%; border:0; padding:3px 4px; background:transparent; font-size:11px; font-family:inherit;
    }
    .aof-table input.in:focus, .aof-table textarea.in:focus, .aof-table select.in:focus {
        background:#fef3c7; outline:1px solid #f59e0b;
    }
    .aof-table td.sn { text-align:center; width:5%; }

    .aof-mini { background:#ede9fe; padding:5px 10px; font-weight:700; font-size:11px; color:#5b21b6; margin:10px 0 4px 0; border-left:4px solid #7c3aed; border-radius:3px; }
    .aof-note { background:#fef3c7; border-left:3px solid #f59e0b; padding:6px 10px; font-size:11px; color:#92400e; margin:6px 0; }
    .aof-warn { background:#fee2e2; border-left:3px solid #dc2626; padding:6px 10px; font-size:11px; color:#991b1b; margin:6px 0; font-weight:600; }

    /* ========= Face chart ========= */
    .aof-fc-wrap { display:grid; grid-template-columns: minmax(320px, 1fr) 320px; gap:14px; align-items:start; margin-bottom:10px; }
    @media (max-width:900px) { .aof-fc-wrap { grid-template-columns: 1fr; } }
    .aof-fc-canvas { position:relative; background:#fafafa; border:1px solid #cbd5e1; border-radius:8px; overflow:hidden; cursor:crosshair; }
    .aof-fc-canvas.disabled { cursor:not-allowed; opacity:.7; }
    .aof-fc-canvas img.fc-base { width:100%; height:auto; display:block; user-select:none; -webkit-user-drag:none; user-drag:none; pointer-events:none; }
    .aof-fc-canvas .fc-label { position:absolute; top:8px; left:8px; background:rgba(124,58,237,.85); color:#fff; padding:3px 8px; border-radius:14px; font-size:11px; font-weight:700; pointer-events:none; }
    .aof-fc-marker { position:absolute; transform:translate(-50%,-50%); pointer-events:auto; cursor:pointer; }
    .aof-fc-marker .dot { width:18px; height:18px; border-radius:50%; border:2px solid #fff; box-shadow:0 1px 3px rgba(0,0,0,.4); display:flex; align-items:center; justify-content:center; color:#fff; font-size:9px; font-weight:700; }
    .aof-fc-marker .tag { position:absolute; left:22px; top:50%; transform:translateY(-50%); background:rgba(255,255,255,.95); padding:1px 6px; border-radius:3px; font-size:10px; font-weight:600; color:#1e293b; border:1px solid #cbd5e1; white-space:nowrap; box-shadow:0 1px 2px rgba(0,0,0,.1); max-width:120px; overflow:hidden; text-overflow:ellipsis; }
    .aof-fc-marker.hidetag .tag { display:none; }

    /* ========= Sidebar herramientas ========= */
    .aof-fc-side { background:#fff; border:1px solid #cbd5e1; border-radius:8px; padding:12px; font-size:12px; max-height:780px; overflow-y:auto; }
    .aof-tool { display:grid; grid-template-columns: 24px 1fr auto; gap:8px; padding:6px; border-radius:5px; cursor:pointer; margin-bottom:3px; align-items:center; }
    .aof-tool:hover { background:#f1f5f9; }
    .aof-tool.active { background:#ede9fe; box-shadow:inset 0 0 0 2px #7c3aed; }
    .aof-tool .sw { width:18px; height:18px; border-radius:50%; border:2px solid #fff; box-shadow:0 0 0 1px #94a3b8; }
    .aof-tool .nm { font-weight:600; color:#1e293b; }
    .aof-tool .ct { background:#7c3aed; color:#fff; font-size:10px; padding:1px 6px; border-radius:10px; font-weight:700; min-width:20px; text-align:center; }
    .aof-tool .ct.zero { background:#cbd5e1; color:#475569; }

    .aof-fc-actions { display:grid; grid-template-columns: 1fr 1fr; gap:6px; margin-top:10px; }
    .aof-fc-actions button { padding:6px; border-radius:5px; border:1px solid #cbd5e1; background:#fff; cursor:pointer; font-size:11px; font-weight:600; }
    .aof-fc-actions button:hover { background:#f1f5f9; }
    .aof-fc-actions button.danger { color:#b91c1c; border-color:#fecaca; }
    .aof-fc-actions button.danger:hover { background:#fee2e2; }

    /* ========= Lista de marcas ========= */
    .aof-mk-list { margin-top:10px; padding-top:10px; border-top:1px dashed #cbd5e1; }
    .aof-mk-list .empty { color:#94a3b8; font-style:italic; font-size:11px; text-align:center; padding:8px; }
    .aof-mk-item { display:grid; grid-template-columns: 22px 14px 1fr auto; gap:6px; padding:4px; border-radius:4px; align-items:center; font-size:11px; }
    .aof-mk-item:hover { background:#f8fafc; }
    .aof-mk-item .num { background:#1e293b; color:#fff; font-size:9px; font-weight:700; padding:2px; border-radius:3px; text-align:center; }
    .aof-mk-item .dot-mini { width:10px; height:10px; border-radius:50%; }
    .aof-mk-item .lbl { color:#334155; font-weight:600; cursor:pointer; }
    .aof-mk-item .lbl:hover { color:#7c3aed; text-decoration:underline; }
    .aof-mk-item .del { color:#dc2626; cursor:pointer; font-weight:700; padding:0 4px; }

    /* ========= Modal de marca ========= */
    .aof-modal { display:none; position:fixed; inset:0; background:rgba(0,0,0,.5); z-index:9999; align-items:center; justify-content:center; }
    .aof-modal.show { display:flex; }
    .aof-modal-box { background:#fff; border-radius:8px; padding:18px; width:480px; max-width:95vw; box-shadow:0 10px 30px rgba(0,0,0,.3); }
    .aof-modal-box h3 { margin:0 0 12px 0; font-size:15px; color:#5b21b6; }
    .aof-modal-box label { display:block; font-size:11px; font-weight:600; color:#475569; margin:8px 0 3px 0; }
    .aof-modal-box input, .aof-modal-box select, .aof-modal-box textarea { width:100%; padding:6px 8px; border:1px solid #cbd5e1; border-radius:4px; font-size:12px; }
    .aof-modal-box .row { display:grid; grid-template-columns:1fr 1fr; gap:8px; }
    .aof-modal-actions { display:flex; gap:8px; justify-content:flex-end; margin-top:12px; }
    .aof-modal-actions button { padding:7px 14px; border-radius:5px; border:1px solid #cbd5e1; background:#fff; cursor:pointer; font-size:12px; font-weight:600; }
    .aof-modal-actions button.primary { background:#7c3aed; color:#fff; border-color:#7c3aed; }
    .aof-modal-actions button.danger { color:#b91c1c; border-color:#fecaca; }

    /* ========= Totales ========= */
    .aof-totals { display:grid; grid-template-columns:repeat(4,1fr); gap:10px; }
    .aof-tot-card { background:linear-gradient(135deg,#ede9fe,#f3e8ff); border:1px solid #c4b5fd; border-radius:8px; padding:12px; text-align:center; }
    .aof-tot-card .v { font-size:22px; font-weight:800; color:#5b21b6; }
    .aof-tot-card .l { font-size:10px; text-transform:uppercase; color:#6b21a8; letter-spacing:.5px; font-weight:700; }
    .aof-tot-card .u { font-size:10px; color:#7c3aed; }

    /* ========= Otros ========= */
    .aof-check-list { display:grid; grid-template-columns:repeat(2,1fr); gap:6px; font-size:11px; }
    .aof-check-list label { display:flex; gap:6px; align-items:center; padding:4px 8px; background:#f8fafc; border-radius:4px; cursor:pointer; }
    .aof-check-list label:hover { background:#ede9fe; }
    .aof-check-list label.danger { background:#fee2e2; color:#991b1b; }
    .aof-flags { display:flex; flex-wrap:wrap; gap:6px; min-height:24px; }
    .aof-flag { background:#fee2e2; color:#991b1b; padding:3px 10px; border-radius:14px; font-size:10px; font-weight:700; }
</style>

<form name="formulariop" id="formulariop" method="POST">
    <input type="hidden" name="idatencion" id="idatencion_aof" value="<?php echo $_POST['idatencion'] ?? ''; ?>">
    <input type="hidden" name="tipo_formato" value="ARMONIZACION">

    <div class="aof-banner">
        <h2><i class="fa fa-magic"></i> Armonizacion Orofacial - FMA Pro</h2>
        <span class="aof-chip">Face Mapping Profesional</span>
    </div>

    <?php include 'partials/patient_header.php'; ?>

    <div class="msp-container">

    <!-- ============================================================== -->
    <!-- 1. DATOS DE LA CONSULTA Y OBJETIVO                              -->
    <!-- ============================================================== -->
    <div class="msp-section">
        <div class="msp-section-title">1. Datos de la consulta y objetivo estetico</div>
        <table class="aof-table">
            <tr>
                <td class="lbl">Fecha</td>
                <td><input type="date" class="in" name="aof_fecha" value="<?php echo date('Y-m-d'); ?>"></td>
                <td class="lbl">Hora</td>
                <td><input type="time" class="in" name="aof_hora" value="<?php echo date('H:i'); ?>"></td>
                <td class="lbl">No. Sesion</td>
                <td><input class="in" name="aof_num_sesion" value="1" placeholder="1 de N"></td>
                <td class="lbl">Codigo seguimiento</td>
                <td><input class="in" name="aof_codigo" placeholder="AOF-2026-..."></td>
            </tr>
            <tr>
                <td class="lbl">Profesional</td>
                <td colspan="3"><input class="in" name="aof_profesional"></td>
                <td class="lbl">Especialidad</td>
                <td colspan="3"><input class="in" name="aof_especialidad" placeholder="Cirujano dentista, medico estetico, etc."></td>
            </tr>
            <tr>
                <td class="lbl">Motivo / objetivo del paciente</td>
                <td colspan="7"><textarea class="in" name="aof_motivo" rows="2" placeholder="En palabras del paciente: que desea cambiar o mejorar..."></textarea></td>
            </tr>
            <tr>
                <td class="lbl">Expectativas</td>
                <td colspan="3"><textarea class="in" name="aof_expectativas" rows="2" placeholder="Resultado esperado, plazos, naturalidad..."></textarea></td>
                <td class="lbl">Plan ideal del profesional</td>
                <td colspan="3"><textarea class="in" name="aof_plan_ideal" rows="2" placeholder="Recomendacion clinica del profesional..."></textarea></td>
            </tr>
        </table>

        <div class="aof-mini">Tratamientos esteticos previos</div>
        <table class="aof-table">
            <thead><tr><th style="width:14%;">Fecha</th><th style="width:18%;">Zona</th><th style="width:18%;">Producto / Marca</th><th style="width:15%;">Profesional / Lugar</th><th>Resultado / Eventos</th></tr></thead>
            <tbody>
            <?php for($i = 0; $i < 4; $i++): ?>
                <tr>
                    <td><input class="in" name="aof_prev_fecha_<?php echo $i; ?>" placeholder="aaaa-mm"></td>
                    <td><input class="in" name="aof_prev_zona_<?php echo $i; ?>"></td>
                    <td><input class="in" name="aof_prev_prod_<?php echo $i; ?>"></td>
                    <td><input class="in" name="aof_prev_prof_<?php echo $i; ?>"></td>
                    <td><input class="in" name="aof_prev_res_<?php echo $i; ?>"></td>
                </tr>
            <?php endfor; ?>
            </tbody>
        </table>
    </div>

    <!-- ============================================================== -->
    <!-- 2. ANAMNESIS ESTETICA ESPECIFICA Y BANDERAS ROJAS               -->
    <!-- ============================================================== -->
    <?php
        $absolutas = [
            'embarazo' => 'Embarazo / lactancia',
            'inf_activa' => 'Infeccion activa en zona de tratamiento',
            'alergia_prod' => 'Alergia conocida al producto a aplicar',
            'enf_grave' => 'Enfermedad sistemica grave descompensada',
            'trastorno_coag' => 'Trastorno de coagulacion no controlado',
        ];
        $relativas = [
            'autoinmune' => 'Enf. autoinmune (lupus, esclerodermia)',
            'miastenia' => 'Miastenia gravis / Eaton-Lambert',
            'esclerosis' => 'Esclerosis multiple',
            'queloide' => 'Cicatrizacion queloide',
            'anticoag' => 'Anticoagulantes / antiagregantes',
            'aines' => 'AINE / aspirina en ultimos 7 dias',
            'suppro' => 'Vit E, Omega 3, Ginkgo, Ajo (ultimos 7d)',
            'tabaquismo' => 'Tabaquismo intenso',
            'isotret' => 'Isotretinoina en ultimos 6 meses',
            'corticoides' => 'Corticoides sistemicos',
            'implantes' => 'Implantes faciales previos',
            'cx_facial' => 'Cirugia facial previa',
            'herpes' => 'Herpes labial recurrente',
            'dismorfia' => 'Sospecha de trastorno dismorfico',
        ];
    ?>
    <div class="msp-section">
        <div class="msp-section-title">2. Anamnesis estetica y banderas rojas</div>

        <div class="aof-warn"><i class="fa fa-exclamation-triangle"></i> <b>Contraindicaciones absolutas</b> (marque si aplica).</div>
        <div class="aof-check-list">
        <?php foreach($absolutas as $k => $lbl): ?>
            <label class="danger"><input type="checkbox" name="aof_abs_<?php echo $k; ?>" value="1" onchange="actualizarFlags()"> <?php echo $lbl; ?></label>
        <?php endforeach; ?>
        </div>

        <div class="aof-note" style="margin-top:10px;"><b>Contraindicaciones relativas / precauciones</b></div>
        <div class="aof-check-list">
        <?php foreach($relativas as $k => $lbl): ?>
            <label><input type="checkbox" name="aof_rel_<?php echo $k; ?>" value="1" onchange="actualizarFlags()"> <?php echo $lbl; ?></label>
        <?php endforeach; ?>
        </div>

        <table class="aof-table" style="margin-top:10px;">
            <tr>
                <td class="lbl">Alergias especificas</td>
                <td colspan="3"><input class="in" name="aof_alergias" placeholder="Lidocaina, ahaluronidasa, latex..."></td>
                <td class="lbl">Anticoagulantes actuales</td>
                <td colspan="3"><input class="in" name="aof_anticoag" placeholder="Warfarina, ASA, rivaroxaban, dabigatran..."></td>
            </tr>
            <tr>
                <td class="lbl">Ultima toxina (fecha y zona)</td>
                <td colspan="3"><input class="in" name="aof_ult_toxina"></td>
                <td class="lbl">Ultima AH (fecha y zona)</td>
                <td colspan="3"><input class="in" name="aof_ult_ah"></td>
            </tr>
            <tr>
                <td class="lbl">Medicacion habitual</td>
                <td colspan="7"><textarea class="in" name="aof_med_habitual" rows="2"></textarea></td>
            </tr>
            <tr>
                <td class="lbl">Banderas rojas activas</td>
                <td colspan="7"><div class="aof-flags" id="aof_flags_box"><span style="color:#94a3b8; font-size:10px;">Ninguna marcada</span></div></td>
            </tr>
        </table>
    </div>

    <!-- ============================================================== -->
    <!-- 3. EVALUACION FACIAL ESTANDARIZADA                              -->
    <!-- ============================================================== -->
    <div class="msp-section">
        <div class="msp-section-title">3. Evaluacion facial estandarizada</div>

        <table class="aof-table">
            <tr>
                <td class="lbl">Fitzpatrick (fototipo)</td>
                <td>
                    <select class="in" name="aof_fitzpatrick">
                        <option value="">Seleccione</option>
                        <option value="I">I - Muy claro, nunca broncea</option>
                        <option value="II">II - Claro, broncea poco</option>
                        <option value="III">III - Intermedio, broncea</option>
                        <option value="IV">IV - Moreno claro</option>
                        <option value="V">V - Moreno oscuro</option>
                        <option value="VI">VI - Negro</option>
                    </select>
                </td>
                <td class="lbl">Glogau (fotoenvejecimiento)</td>
                <td>
                    <select class="in" name="aof_glogau">
                        <option value="">Seleccione</option>
                        <option value="I">I - Sin arrugas (20-30a)</option>
                        <option value="II">II - Arrugas en movimiento (30-40a)</option>
                        <option value="III">III - Arrugas en reposo (50-65a)</option>
                        <option value="IV">IV - Solo arrugas (>65a)</option>
                    </select>
                </td>
                <td class="lbl">Calidad de la piel</td>
                <td>
                    <select class="in" name="aof_calidad_piel">
                        <option value="">Seleccione</option>
                        <option value="EXCELENTE">Excelente</option>
                        <option value="BUENA">Buena</option>
                        <option value="REGULAR">Regular</option>
                        <option value="DEFICIENTE">Deficiente</option>
                    </select>
                </td>
            </tr>
            <tr>
                <td class="lbl">Turgor / elasticidad</td>
                <td><select class="in" name="aof_turgor"><option value="">-</option><option>Conservado</option><option>Disminuido</option><option>Muy disminuido</option></select></td>
                <td class="lbl">Hidratacion</td>
                <td><select class="in" name="aof_hidratacion"><option value="">-</option><option>Buena</option><option>Regular</option><option>Deshidratada</option></select></td>
                <td class="lbl">Poros</td>
                <td><select class="in" name="aof_poros"><option value="">-</option><option>Finos</option><option>Medios</option><option>Dilatados</option></select></td>
            </tr>
            <tr>
                <td class="lbl">Tipo de piel</td>
                <td><select class="in" name="aof_tipo_piel"><option value="">-</option><option>Seca</option><option>Normal</option><option>Mixta</option><option>Grasa</option></select></td>
                <td class="lbl">Manchas / hiperpigmentacion</td>
                <td><input class="in" name="aof_manchas" placeholder="Localizacion y caracteristicas"></td>
                <td class="lbl">Asimetrias</td>
                <td><input class="in" name="aof_asimetrias" placeholder="Descripcion"></td>
            </tr>
        </table>

        <div class="aof-mini">Escala de Merz - Rítides (arrugas) por zona</div>
        <?php
            $merzZonas = [
                'frente' => 'Frente',
                'glabela' => 'Glabela / entrecejo',
                'patas' => 'Patas de gallo',
                'nasogenianos' => 'Surcos nasogenianos',
                'marionetas' => 'Marionetas',
                'labios' => 'Labios (codigo de barras)',
                'cuello' => 'Cuello / bandas',
            ];
        ?>
        <table class="aof-table">
            <thead><tr><th style="width:30%;">Zona</th><th>0 Ninguna</th><th>1 Leve</th><th>2 Moderada</th><th>3 Severa</th><th>4 Muy severa</th></tr></thead>
            <tbody>
            <?php foreach($merzZonas as $k => $lbl): ?>
                <tr>
                    <td><?php echo $lbl; ?></td>
                    <?php for($v = 0; $v <= 4; $v++): ?>
                        <td class="sn"><input type="radio" name="aof_merz_<?php echo $k; ?>" value="<?php echo $v; ?>"></td>
                    <?php endfor; ?>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>

        <div class="aof-mini">Proporciones faciales y angulos</div>
        <table class="aof-table">
            <tr>
                <td class="lbl">Tercios faciales (sup/medio/inf)</td>
                <td>
                    <input class="in" name="aof_tercio_sup" placeholder="sup mm" style="width:30%; display:inline-block;">
                    <input class="in" name="aof_tercio_med" placeholder="med mm" style="width:30%; display:inline-block;">
                    <input class="in" name="aof_tercio_inf" placeholder="inf mm" style="width:30%; display:inline-block;">
                </td>
                <td class="lbl">Quintos faciales</td>
                <td><select class="in" name="aof_quintos"><option value="">-</option><option>Proporcionado (1:1:1:1:1)</option><option>Desproporcionado</option></select></td>
            </tr>
            <tr>
                <td class="lbl">Angulo nasolabial</td>
                <td><input class="in" name="aof_ang_nasolabial" placeholder="90-110 grados"></td>
                <td class="lbl">Angulo mentolabial</td>
                <td><input class="in" name="aof_ang_mentolabial" placeholder="~130 grados"></td>
            </tr>
            <tr>
                <td class="lbl">Angulo cervicomental</td>
                <td><input class="in" name="aof_ang_cervico" placeholder="105-120 grados"></td>
                <td class="lbl">Linea estetica de Ricketts</td>
                <td><select class="in" name="aof_ricketts"><option value="">-</option><option>Labio superior por delante</option><option>Tangencial</option><option>Labio superior retrasado</option></select></td>
            </tr>
        </table>

        <div class="aof-mini">Musculatura hiperactiva (palpacion y observacion)</div>
        <?php
            $musculos = ['frontal'=>'Frontal','corrugador'=>'Corrugador','procerus'=>'Procerus','orbicular_oc'=>'Orbicular ocular','orbicular_or'=>'Orbicular oral','nasalis'=>'Nasalis','masetero'=>'Masetero','mentoniano'=>'Mentoniano','dao'=>'Depresor angular oris','platisma'=>'Platisma','risorio'=>'Risorio','elev_labio'=>'Elevador del labio superior'];
        ?>
        <div class="aof-check-list">
        <?php foreach($musculos as $k => $lbl): ?>
            <label><input type="checkbox" name="aof_musc_<?php echo $k; ?>" value="1"> <?php echo $lbl; ?></label>
        <?php endforeach; ?>
        </div>

        <table class="aof-table" style="margin-top:10px;">
            <tr>
                <td class="lbl">Habitos relevantes</td>
                <td colspan="7">
                    <label style="margin-right:12px;"><input type="checkbox" name="aof_hab_bruxismo" value="1"> Bruxismo</label>
                    <label style="margin-right:12px;"><input type="checkbox" name="aof_hab_apretamiento" value="1"> Apretamiento dental</label>
                    <label style="margin-right:12px;"><input type="checkbox" name="aof_hab_fumar" value="1"> Fumar</label>
                    <label style="margin-right:12px;"><input type="checkbox" name="aof_hab_chupar_labio" value="1"> Chupar labio</label>
                    <label style="margin-right:12px;"><input type="checkbox" name="aof_hab_dormir_lateral" value="1"> Dormir lateral</label>
                </td>
            </tr>
        </table>
    </div>

    <!-- ============================================================== -->
    <!-- 4. FACE CHART ANOTABLE (frontal + lateral)                      -->
    <!-- ============================================================== -->
    <div class="msp-section">
        <div class="msp-section-title">4. Face mapping interactivo - marcas con texto</div>
        <div class="aof-note"><b>Como usar:</b> seleccione una herramienta (panel derecho), haga click sobre el rostro para agregar una marca. Click sobre una marca existente para editar su etiqueta de texto, zona anatomica, producto y unidades. Cada marca se numera automaticamente.</div>

        <div class="aof-fc-wrap">
            <!-- VISTA FRONTAL (imagen) -->
            <div class="aof-fc-canvas" id="fc_front" data-view="FRONT">
                <span class="fc-label">Face chart</span>
                <img class="fc-base" src="../public/img/face_chart.png" alt="Face chart">
            </div>

            <!-- SIDEBAR HERRAMIENTAS Y MARCAS -->
            <div class="aof-fc-side">
                <div style="font-size:13px; font-weight:700; color:#5b21b6; margin-bottom:8px;">Herramientas</div>
                <div id="aof_tools_list"></div>

                <div style="font-size:11px; font-weight:600; color:#5b21b6; margin:10px 0 4px;">Personalizada (color + nombre)</div>
                <div style="display:grid; grid-template-columns:auto 1fr; gap:6px; align-items:center; padding:5px; background:#f8fafc; border-radius:5px;">
                    <input type="color" id="aof_custom_color" value="#06b6d4" style="width:30px; height:28px; border:1px solid #cbd5e1; border-radius:4px; padding:0;">
                    <input class="in" id="aof_custom_name" placeholder="Nombre (ej. Skinbooster)" style="border:1px solid #cbd5e1; padding:4px 6px; border-radius:4px;">
                </div>
                <button type="button" class="aes-tool-btn" onclick="aofSetCustomTool()" style="margin-top:5px; padding:6px; border:1px solid #cbd5e1; background:#fff; border-radius:5px; cursor:pointer; font-size:11px; width:100%; font-weight:600;">
                    + Usar herramienta personalizada
                </button>

                <div class="aof-fc-actions">
                    <button type="button" onclick="aofUndo()"><i class="fa fa-undo"></i> Deshacer</button>
                    <button type="button" onclick="aofToggleTags()" id="btn_tags"><i class="fa fa-tag"></i> Ocultar texto</button>
                    <button type="button" onclick="aofExportSummary()"><i class="fa fa-list"></i> Resumen</button>
                    <button type="button" class="danger" onclick="aofClear()"><i class="fa fa-trash"></i> Borrar todo</button>
                </div>

                <div class="aof-mk-list">
                    <div style="font-size:12px; font-weight:700; color:#5b21b6; margin-bottom:4px;">Marcas registradas (<span id="aof_count">0</span>)</div>
                    <div id="aof_mk_list"><div class="empty">Sin marcas. Haga click sobre el rostro para agregar.</div></div>
                </div>
            </div>
        </div>

        <input type="hidden" name="aof_canvas_data" id="aof_canvas_data">
    </div>

    <!-- ============================================================== -->
    <!-- 5. PLAN DE TRATAMIENTO POR ZONAS ANATOMICAS                     -->
    <!-- ============================================================== -->
    <?php
        $zonas = [
            'frente' => ['Frente', 'Toxina'],
            'glabela' => ['Entrecejo / Glabela', 'Toxina'],
            'patas' => ['Patas de gallo', 'Toxina'],
            'cejas' => ['Elevacion de cejas (browlift)', 'Toxina'],
            'bunny' => ['Bunny lines (dorso nasal)', 'Toxina'],
            'sien' => ['Sien (volumen)', 'Acido hialuronico'],
            'punta_nariz' => ['Punta nasal / rinomodelacion', 'Acido hialuronico'],
            'pomulos' => ['Pomulos / cigomas', 'Acido hialuronico'],
            'ojeras' => ['Valle lagrimal / ojeras', 'Acido hialuronico'],
            'nasogenianos' => ['Surcos nasogenianos', 'Acido hialuronico'],
            'labios_vol' => ['Labios - volumen', 'Acido hialuronico'],
            'labios_cont' => ['Labios - contorno', 'Acido hialuronico'],
            'filtrum' => ['Filtrum', 'Acido hialuronico'],
            'comisuras' => ['Comisuras', 'Acido hialuronico'],
            'marionetas' => ['Lineas de marioneta', 'Acido hialuronico'],
            'menton' => ['Menton (proyeccion)', 'Acido hialuronico / hidroxiapatita'],
            'mandibula' => ['Angulo / cuerpo mandibular', 'Acido hialuronico / hidroxiapatita'],
            'masetero' => ['Masetero (bruxismo)', 'Toxina'],
            'sonrisa_g' => ['Sonrisa gingival', 'Toxina'],
            'platisma' => ['Cuello / bandas platismales', 'Toxina'],
            'papada' => ['Submentom / papada', 'Acido hialuronico / deoxicolato'],
        ];
        $opcionesProducto = ['Toxina botulinica','Acido hialuronico','Hidroxiapatita de calcio','PLLA (Sculptra)','Hilos PDO','PRP / PRFM','Skinbooster','Bioestimulador','Deoxicolato','Otro'];
        $opcionesEstado = ['Planificado','Aplicado','Diferido','NO indicado'];
    ?>
    <div class="msp-section">
        <div class="msp-section-title">5. Plan de tratamiento por zonas anatomicas</div>
        <div class="aof-note">Marque <b>Indicado</b> para activar la zona. Las cantidades se totalizan automaticamente en el resumen.</div>
        <table class="aof-table">
            <thead>
                <tr>
                    <th style="width:5%;">Indic.</th>
                    <th style="width:18%;">Zona</th>
                    <th style="width:14%;">Producto</th>
                    <th style="width:11%;">Marca</th>
                    <th style="width:9%;">Lote</th>
                    <th style="width:8%;">Cantidad</th>
                    <th style="width:8%;">Unidad</th>
                    <th style="width:11%;">Tecnica</th>
                    <th style="width:8%;">Estado</th>
                    <th>Notas</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach($zonas as $k => $z):
                $unidad = stripos($z[1], 'Toxina') !== false ? 'U' : 'mL';
            ?>
                <tr>
                    <td class="sn"><input type="checkbox" name="zona_<?php echo $k; ?>_ind" value="1" class="aof-zona-ind" data-unidad="<?php echo $unidad; ?>"></td>
                    <td class="lbl" style="font-size:10.5px;"><?php echo $z[0]; ?></td>
                    <td>
                        <select class="in aof-zona-prod" name="zona_<?php echo $k; ?>_prod">
                            <option value="">-</option>
                            <?php foreach($opcionesProducto as $op): ?>
                                <option value="<?php echo $op; ?>" <?php if(stripos($z[1], substr($op,0,5))!==false) echo 'selected'; ?>><?php echo $op; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </td>
                    <td><input class="in" name="zona_<?php echo $k; ?>_marca" placeholder="Marca comercial"></td>
                    <td><input class="in" name="zona_<?php echo $k; ?>_lote"></td>
                    <td><input class="in aof-zona-cant" data-zona="<?php echo $k; ?>" type="text" inputmode="decimal" name="zona_<?php echo $k; ?>_cant" oninput="aofRecalc()"></td>
                    <td>
                        <select class="in aof-zona-unidad" name="zona_<?php echo $k; ?>_unidad" onchange="aofRecalc()">
                            <option value="U" <?php if($unidad === 'U') echo 'selected'; ?>>U (unidades)</option>
                            <option value="mL" <?php if($unidad === 'mL') echo 'selected'; ?>>mL</option>
                            <option value="hilos">hilos</option>
                            <option value="viales">viales</option>
                            <option value="sesiones">sesiones</option>
                        </select>
                    </td>
                    <td><input class="in" name="zona_<?php echo $k; ?>_tecnica" placeholder="Lineal, en abanico, bolus..."></td>
                    <td>
                        <select class="in" name="zona_<?php echo $k; ?>_estado">
                            <option value="">-</option>
                            <?php foreach($opcionesEstado as $e): ?>
                                <option><?php echo $e; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </td>
                    <td><input class="in" name="zona_<?php echo $k; ?>_notas"></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>

    <!-- ============================================================== -->
    <!-- 6. RESUMEN TOTALIZADO                                           -->
    <!-- ============================================================== -->
    <div class="msp-section">
        <div class="msp-section-title">6. Resumen totalizado de la sesion</div>
        <div class="aof-totals">
            <div class="aof-tot-card">
                <div class="v" id="tot_toxina">0</div>
                <div class="l">Toxina botulinica</div>
                <div class="u">unidades totales</div>
            </div>
            <div class="aof-tot-card">
                <div class="v" id="tot_filler">0</div>
                <div class="l">Filler / Hialuronico</div>
                <div class="u">mL totales</div>
            </div>
            <div class="aof-tot-card">
                <div class="v" id="tot_hilos">0</div>
                <div class="l">Hilos / vectores</div>
                <div class="u">hilos totales</div>
            </div>
            <div class="aof-tot-card">
                <div class="v" id="tot_zonas">0</div>
                <div class="l">Zonas tratadas</div>
                <div class="u">zonas indicadas</div>
            </div>
        </div>
        <input type="hidden" name="aof_tot_toxina" id="aof_tot_toxina">
        <input type="hidden" name="aof_tot_filler" id="aof_tot_filler">
        <input type="hidden" name="aof_tot_hilos" id="aof_tot_hilos">
        <input type="hidden" name="aof_tot_zonas" id="aof_tot_zonas">
    </div>

    <!-- ============================================================== -->
    <!-- 7. DOCUMENTACION Y CONSENTIMIENTO                               -->
    <!-- ============================================================== -->
    <div class="msp-section">
        <div class="msp-section-title">7. Documentacion legal y consentimiento</div>
        <table class="aof-table">
            <tr>
                <td class="lbl">Consentimiento informado</td>
                <td><label><input type="checkbox" name="aof_doc_consent" value="1"> Firmado y archivado</label></td>
                <td class="lbl">Fotografias antes</td>
                <td><label><input type="checkbox" name="aof_doc_foto_antes" value="1"> Tomadas y archivadas</label></td>
            </tr>
            <tr>
                <td class="lbl">Fotografias inmediatas post</td>
                <td><label><input type="checkbox" name="aof_doc_foto_post" value="1"> Tomadas</label></td>
                <td class="lbl">Instrucciones post entregadas</td>
                <td><label><input type="checkbox" name="aof_doc_instrucciones" value="1"> Entregadas (verbal + escrito)</label></td>
            </tr>
            <tr>
                <td class="lbl">Asepsia y antisepsia</td>
                <td colspan="3"><input class="in" name="aof_asepsia" placeholder="Antiseptico utilizado, tecnica..."></td>
            </tr>
            <tr>
                <td class="lbl">Anestesia / analgesia previa</td>
                <td colspan="3"><input class="in" name="aof_anestesia" placeholder="Crema EMLA, frio, bloqueo, etc."></td>
            </tr>
            <tr>
                <td class="lbl">Eventos adversos durante el procedimiento</td>
                <td colspan="3"><textarea class="in" name="aof_eventos_intra" rows="2" placeholder="Dolor, sangrado, hematoma inmediato, vasovagal..."></textarea></td>
            </tr>
        </table>
    </div>

    <!-- ============================================================== -->
    <!-- 8. PLAN EN SESIONES Y RECOMENDACIONES                           -->
    <!-- ============================================================== -->
    <div class="msp-section">
        <div class="msp-section-title">8. Plan en sesiones y recomendaciones post</div>
        <table class="aof-table">
            <tr>
                <td class="lbl">Sesiones recomendadas (total)</td>
                <td><input class="in" name="aof_ses_total" placeholder="Ej. 3"></td>
                <td class="lbl">Intervalo entre sesiones</td>
                <td><input class="in" name="aof_ses_intervalo" placeholder="Ej. 4 semanas"></td>
                <td class="lbl">Proxima cita</td>
                <td><input class="in" name="aof_proxima_cita" type="date"></td>
            </tr>
            <tr>
                <td class="lbl">Indicaciones inmediatas (24h)</td>
                <td colspan="5"><textarea class="in" name="aof_indic_24h" rows="2" placeholder="Frio local, no maquillaje, no ejercicio, no acostarse 4h..."></textarea></td>
            </tr>
            <tr>
                <td class="lbl">Indicaciones a corto plazo (1-2 sem)</td>
                <td colspan="5"><textarea class="in" name="aof_indic_2sem" rows="2" placeholder="No saunas, no masajes, evitar AINE, evitar exposicion solar..."></textarea></td>
            </tr>
            <tr>
                <td class="lbl">Senales de alarma para consultar</td>
                <td colspan="5"><textarea class="in" name="aof_alarmas" rows="2" placeholder="Dolor intenso, palidez/cianosis cutanea, perdida vision, asimetria progresiva, fiebre..."></textarea></td>
            </tr>
        </table>
    </div>

    <!-- ============================================================== -->
    <!-- 9. SEGUIMIENTO Y SATISFACCION (sesion >= 2)                     -->
    <!-- ============================================================== -->
    <div class="msp-section">
        <div class="msp-section-title">
            9. Seguimiento, resultado y satisfaccion
            <label style="font-weight:normal; font-size:11px; margin-left:10px;">
                <input type="checkbox" name="aof_seg_on" id="aof_seg_on" value="1" onclick="$('#aof_seg_box').toggle(this.checked);"> Aplica (sesion de seguimiento)
            </label>
        </div>
        <div id="aof_seg_box" style="display:none;">
            <table class="aof-table">
                <tr>
                    <td class="lbl">GAIS (Global Aesthetic Improvement Scale)</td>
                    <td colspan="3">
                        <select class="in" name="aof_gais">
                            <option value="">Seleccione</option>
                            <option value="2">+2 Muy mejorado</option>
                            <option value="1">+1 Mejorado</option>
                            <option value="0">0 Sin cambio</option>
                            <option value="-1">-1 Empeorado</option>
                            <option value="-2">-2 Muy empeorado</option>
                        </select>
                    </td>
                    <td class="lbl">Satisfaccion paciente (0-10)</td>
                    <td><input class="in" name="aof_satisfaccion" placeholder="0-10"></td>
                </tr>
                <tr>
                    <td class="lbl">Eventos adversos posteriores</td>
                    <td colspan="5"><textarea class="in" name="aof_eventos_post" rows="2" placeholder="Hematomas, asimetria, nodulo, infeccion, edema persistente..."></textarea></td>
                </tr>
                <tr>
                    <td class="lbl">Necesita retoque</td>
                    <td>
                        <select class="in" name="aof_retoque">
                            <option value="">-</option>
                            <option>NO</option>
                            <option>SI</option>
                        </select>
                    </td>
                    <td class="lbl">Zona del retoque</td>
                    <td colspan="3"><input class="in" name="aof_retoque_zona"></td>
                </tr>
            </table>
        </div>
    </div>

    <!-- ============================================================== -->
    <!-- 10. NOTAS FINALES                                                -->
    <!-- ============================================================== -->
    <div class="msp-section">
        <div class="msp-section-title">10. Notas finales y observaciones generales</div>
        <table class="aof-table">
            <tr>
                <td class="lbl">Notas tecnicas del profesional</td>
                <td><textarea class="in" name="aof_notas_tec" rows="3" placeholder="Tecnica, dilucion, profundidad, particularidades..."></textarea></td>
            </tr>
            <tr>
                <td class="lbl">Recomendaciones para el paciente</td>
                <td><textarea class="in" name="aof_notas_paciente" rows="3"></textarea></td>
            </tr>
        </table>
    </div>

    </div><!-- /msp-container -->
</form>

<!-- Modal de edicion de marca -->
<div class="aof-modal" id="aof_modal">
    <div class="aof-modal-box">
        <h3>Editar marca <span id="aof_modal_num"></span></h3>
        <label>Etiqueta corta (texto sobre el chart)</label>
        <input type="text" id="aof_modal_label" placeholder="Ej. 4U procerus">
        <div class="row">
            <div>
                <label>Zona anatomica</label>
                <input type="text" id="aof_modal_zona" placeholder="Ej. Glabela">
            </div>
            <div>
                <label>Tipo / herramienta</label>
                <select id="aof_modal_tipo"></select>
            </div>
        </div>
        <div class="row">
            <div>
                <label>Producto y marca</label>
                <input type="text" id="aof_modal_prod" placeholder="Ej. Botox 100U">
            </div>
            <div>
                <label>Lote</label>
                <input type="text" id="aof_modal_lote">
            </div>
        </div>
        <div class="row">
            <div>
                <label>Cantidad</label>
                <input type="text" id="aof_modal_cant" inputmode="decimal">
            </div>
            <div>
                <label>Unidad</label>
                <select id="aof_modal_unidad">
                    <option value="U">U (unidades)</option>
                    <option value="mL">mL</option>
                    <option value="hilos">hilos</option>
                    <option value="viales">viales</option>
                </select>
            </div>
        </div>
        <div class="row">
            <div>
                <label>Profundidad</label>
                <select id="aof_modal_prof">
                    <option value="">-</option>
                    <option>Intradermica</option>
                    <option>Subcutanea</option>
                    <option>Supraperiostica</option>
                    <option>Intramuscular</option>
                    <option>Submuscular</option>
                </select>
            </div>
            <div>
                <label>Tecnica</label>
                <input type="text" id="aof_modal_tecnica" placeholder="Lineal, abanico, bolus, picoteos...">
            </div>
        </div>
        <label>Notas</label>
        <textarea id="aof_modal_notas" rows="2"></textarea>
        <div class="aof-modal-actions">
            <button type="button" class="danger" onclick="aofDeleteMarker()">Eliminar marca</button>
            <button type="button" onclick="aofCloseModal()">Cancelar</button>
            <button type="button" class="primary" onclick="aofSaveMarker()">Guardar</button>
        </div>
    </div>
</div>

<script>
// =============================================================================
// FMA Pro v2 - Logica del face chart anotable
// =============================================================================
var aofTools = [
    { id:'toxina',       name:'Toxina botulinica', color:'#dc2626', shape:'circle',   unidad:'U'  },
    { id:'ah',           name:'Acido hialuronico', color:'#2563eb', shape:'drop',     unidad:'mL' },
    { id:'hidroxi',      name:'Hidroxiapatita Ca', color:'#9333ea', shape:'triangle', unidad:'mL' },
    { id:'plla',         name:'PLLA / Sculptra',   color:'#ea580c', shape:'diamond',  unidad:'viales' },
    { id:'hilos',        name:'Hilos PDO',         color:'#16a34a', shape:'arrow',    unidad:'hilos' },
    { id:'prp',          name:'PRP / PRFM',        color:'#db2777', shape:'square',   unidad:'mL' },
    { id:'skinb',        name:'Skinbooster',       color:'#0891b2', shape:'star',     unidad:'mL' },
    { id:'bioestim',     name:'Bioestimulador',    color:'#65a30d', shape:'star',     unidad:'mL' }
];
var aofCustom = null;        // {name,color,shape:'circle',unidad:'mL'}
var aofMarkers = [];         // [{n,view:'FRONT'|'LATERAL',x,y,tool,label,zona,prod,lote,cant,unidad,prof,tecnica,notas}]
var aofCurrentTool = 'toxina';
var aofShowTags = true;
var aofEditingIdx = -1;

function aofRenderTools() {
    var box = document.getElementById('aof_tools_list');
    box.innerHTML = '';
    aofTools.forEach(function(t) {
        var counts = aofMarkers.filter(function(m){ return m.tool === t.id; }).length;
        var div = document.createElement('div');
        div.className = 'aof-tool' + (aofCurrentTool === t.id ? ' active' : '');
        div.innerHTML = '<span class="sw" style="background:' + t.color + ';"></span>'
                      + '<span class="nm">' + t.name + '</span>'
                      + '<span class="ct ' + (counts ? '' : 'zero') + '">' + counts + '</span>';
        div.onclick = function() { aofCurrentTool = t.id; aofRenderTools(); };
        box.appendChild(div);
    });
    if (aofCustom) {
        var counts = aofMarkers.filter(function(m){ return m.tool === 'custom'; }).length;
        var div = document.createElement('div');
        div.className = 'aof-tool' + (aofCurrentTool === 'custom' ? ' active' : '');
        div.innerHTML = '<span class="sw" style="background:' + aofCustom.color + ';"></span>'
                      + '<span class="nm">' + aofCustom.name + ' (custom)</span>'
                      + '<span class="ct ' + (counts ? '' : 'zero') + '">' + counts + '</span>';
        div.onclick = function() { aofCurrentTool = 'custom'; aofRenderTools(); };
        box.appendChild(div);
    }
}

function aofSetCustomTool() {
    var name = document.getElementById('aof_custom_name').value.trim();
    var color = document.getElementById('aof_custom_color').value || '#06b6d4';
    if (!name) { alert('Coloque un nombre para la herramienta personalizada.'); return; }
    aofCustom = { name:name, color:color, shape:'circle', unidad:'mL' };
    aofCurrentTool = 'custom';
    aofRenderTools();
}

function aofToolMeta(toolId) {
    if (toolId === 'custom' && aofCustom) return aofCustom;
    var t = aofTools.find(function(x){ return x.id === toolId; });
    return t || { name:toolId, color:'#000', shape:'circle', unidad:'U' };
}

function aofShape(svg, shape, color, num) {
    // Devuelve el HTML interno del dot
    var html = '<div class="dot" style="background:' + color + '">' + num + '</div>';
    return html;
}

function aofCanvasClick(ev, viewId) {
    if (ev.target.closest('.aof-fc-marker')) return; // click en marker abre modal
    var canvas = document.getElementById(viewId);
    var r = canvas.getBoundingClientRect();
    var x = ((ev.clientX - r.left) / r.width) * 100;
    var y = ((ev.clientY - r.top)  / r.height) * 100;
    if (x < 1 || x > 99 || y < 1 || y > 99) return;
    var meta = aofToolMeta(aofCurrentTool);
    aofMarkers.push({
        n: aofMarkers.length + 1,
        view: canvas.dataset.view,
        x: x, y: y,
        tool: aofCurrentTool,
        toolName: meta.name,
        toolColor: meta.color,
        label: '',
        zona: '', prod: '', lote: '',
        cant: '', unidad: meta.unidad || 'U',
        prof: '', tecnica: '', notas: ''
    });
    aofRedraw();
    aofPersist();
}

function aofRedraw() {
    var canvas = document.getElementById('fc_front');
    canvas.querySelectorAll('.aof-fc-marker').forEach(function(el){ el.remove(); });
    aofMarkers.forEach(function(m, i) {
        m.n = i + 1; // renumerar
        var el = document.createElement('div');
        el.className = 'aof-fc-marker' + (aofShowTags ? '' : ' hidetag');
        el.style.left = m.x + '%';
        el.style.top  = m.y + '%';
        el.innerHTML = '<div class="dot" style="background:' + m.toolColor + ';">' + m.n + '</div>'
                     + (m.label ? '<div class="tag">' + escHtml(m.label) + '</div>' : '');
        el.addEventListener('click', function(e){ e.stopPropagation(); aofOpenModal(i); });
        canvas.appendChild(el);
    });
    aofRenderTools();
    aofRenderList();
}

function escHtml(s) { return (s + '').replace(/[&<>"']/g, function(c) { return {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]; }); }

function aofRenderList() {
    var box = document.getElementById('aof_mk_list');
    document.getElementById('aof_count').textContent = aofMarkers.length;
    if (!aofMarkers.length) {
        box.innerHTML = '<div class="empty">Sin marcas. Haga click sobre el rostro para agregar.</div>';
        return;
    }
    box.innerHTML = '';
    aofMarkers.forEach(function(m, i) {
        var div = document.createElement('div');
        div.className = 'aof-mk-item';
        var lbl = m.label || (m.zona || (m.toolName + ' s/n'));
        div.innerHTML = '<span class="num">' + m.n + '</span>'
                     + '<span class="dot-mini" style="background:' + m.toolColor + ';"></span>'
                     + '<span class="lbl" title="' + escHtml(lbl) + '">' + escHtml(lbl) + '</span>'
                     + '<span class="del" title="Eliminar">&times;</span>';
        div.querySelector('.lbl').onclick = function(){ aofOpenModal(i); };
        div.querySelector('.del').onclick = function(){ aofMarkers.splice(i, 1); aofRedraw(); aofPersist(); };
        box.appendChild(div);
    });
}

function aofOpenModal(idx) {
    aofEditingIdx = idx;
    var m = aofMarkers[idx];
    document.getElementById('aof_modal_num').textContent = '#' + m.n;
    document.getElementById('aof_modal_label').value = m.label || '';
    document.getElementById('aof_modal_zona').value = m.zona || '';
    document.getElementById('aof_modal_prod').value = m.prod || '';
    document.getElementById('aof_modal_lote').value = m.lote || '';
    document.getElementById('aof_modal_cant').value = m.cant || '';
    document.getElementById('aof_modal_unidad').value = m.unidad || 'U';
    document.getElementById('aof_modal_prof').value = m.prof || '';
    document.getElementById('aof_modal_tecnica').value = m.tecnica || '';
    document.getElementById('aof_modal_notas').value = m.notas || '';

    var sel = document.getElementById('aof_modal_tipo');
    sel.innerHTML = '';
    aofTools.forEach(function(t) {
        var opt = document.createElement('option');
        opt.value = t.id; opt.textContent = t.name;
        if (m.tool === t.id) opt.selected = true;
        sel.appendChild(opt);
    });
    if (aofCustom) {
        var opt = document.createElement('option');
        opt.value = 'custom'; opt.textContent = aofCustom.name + ' (custom)';
        if (m.tool === 'custom') opt.selected = true;
        sel.appendChild(opt);
    }

    document.getElementById('aof_modal').classList.add('show');
}

function aofCloseModal() { document.getElementById('aof_modal').classList.remove('show'); aofEditingIdx = -1; }

function aofSaveMarker() {
    if (aofEditingIdx < 0) return;
    var m = aofMarkers[aofEditingIdx];
    m.label   = document.getElementById('aof_modal_label').value.trim();
    m.zona    = document.getElementById('aof_modal_zona').value.trim();
    m.prod    = document.getElementById('aof_modal_prod').value.trim();
    m.lote    = document.getElementById('aof_modal_lote').value.trim();
    m.cant    = document.getElementById('aof_modal_cant').value.trim();
    m.unidad  = document.getElementById('aof_modal_unidad').value;
    m.prof    = document.getElementById('aof_modal_prof').value;
    m.tecnica = document.getElementById('aof_modal_tecnica').value.trim();
    m.notas   = document.getElementById('aof_modal_notas').value.trim();
    var newTool = document.getElementById('aof_modal_tipo').value;
    if (newTool !== m.tool) {
        m.tool = newTool;
        var meta = aofToolMeta(newTool);
        m.toolName = meta.name;
        m.toolColor = meta.color;
    }
    aofCloseModal();
    aofRedraw();
    aofPersist();
    aofRecalc();
}

function aofDeleteMarker() {
    if (aofEditingIdx < 0) return;
    aofMarkers.splice(aofEditingIdx, 1);
    aofCloseModal();
    aofRedraw();
    aofPersist();
    aofRecalc();
}

function aofUndo() {
    if (aofMarkers.length === 0) return;
    aofMarkers.pop();
    aofRedraw();
    aofPersist();
}

function aofClear() {
    if (!confirm('Eliminar TODAS las marcas?')) return;
    aofMarkers = [];
    aofRedraw();
    aofPersist();
}

function aofToggleTags() {
    aofShowTags = !aofShowTags;
    document.getElementById('btn_tags').innerHTML = aofShowTags ? '<i class="fa fa-tag"></i> Ocultar texto' : '<i class="fa fa-tag"></i> Mostrar texto';
    aofRedraw();
}

function aofExportSummary() {
    if (!aofMarkers.length) { alert('No hay marcas para exportar.'); return; }
    var lines = aofMarkers.map(function(m) {
        return m.n + '. ' + m.toolName
             + (m.zona ? ' - ' + m.zona : '')
             + (m.cant ? ' (' + m.cant + ' ' + m.unidad + ')' : '')
             + (m.prod ? ' - ' + m.prod : '');
    });
    alert(lines.join('\n'));
}

function aofPersist() {
    var data = { markers: aofMarkers, custom: aofCustom, ts: new Date().toISOString() };
    document.getElementById('aof_canvas_data').value = JSON.stringify(data);
}

// ============================================================================
// Banderas rojas (resumen visual)
// ============================================================================
function actualizarFlags() {
    var box = document.getElementById('aof_flags_box');
    box.innerHTML = '';
    document.querySelectorAll('input[name^="aof_abs_"]:checked, input[name^="aof_rel_"]:checked').forEach(function(c) {
        var label = c.parentNode.textContent.trim();
        var sp = document.createElement('span');
        sp.className = 'aof-flag';
        sp.textContent = label;
        if (c.name.indexOf('aof_abs_') === 0) sp.style.background = '#dc2626', sp.style.color = '#fff';
        box.appendChild(sp);
    });
    if (!box.children.length) box.innerHTML = '<span style="color:#94a3b8; font-size:10px;">Ninguna marcada</span>';
}

// ============================================================================
// Recalcular totales (zonas + markers)
// ============================================================================
function aofRecalc() {
    var totT = 0, totF = 0, totH = 0, totZ = 0;

    // Zonas
    document.querySelectorAll('.aof-zona-ind').forEach(function(chk) {
        if (!chk.checked) return;
        totZ++;
        var tr = chk.closest('tr');
        var cant = parseFloat(tr.querySelector('.aof-zona-cant').value) || 0;
        var unidad = tr.querySelector('.aof-zona-unidad').value;
        if (unidad === 'U') totT += cant;
        else if (unidad === 'mL') totF += cant;
        else if (unidad === 'hilos') totH += cant;
    });

    // Marcas del face chart
    aofMarkers.forEach(function(m) {
        var c = parseFloat(m.cant) || 0;
        if (m.unidad === 'U') totT += c;
        else if (m.unidad === 'mL') totF += c;
        else if (m.unidad === 'hilos') totH += c;
    });

    document.getElementById('tot_toxina').textContent = totT;
    document.getElementById('tot_filler').textContent = totF.toFixed(1);
    document.getElementById('tot_hilos').textContent  = totH;
    document.getElementById('tot_zonas').textContent  = totZ;
    document.getElementById('aof_tot_toxina').value = totT;
    document.getElementById('aof_tot_filler').value = totF.toFixed(1);
    document.getElementById('aof_tot_hilos').value  = totH;
    document.getElementById('aof_tot_zonas').value  = totZ;
}

// ============================================================================
// Init
// ============================================================================
$(document).ready(function() {
    aofRenderTools();
    // Click handler del canvas
    document.getElementById('fc_front').addEventListener('click', function(ev){ aofCanvasClick(ev, 'fc_front'); });

    // Modal: cerrar al click fuera
    document.getElementById('aof_modal').addEventListener('click', function(ev) {
        if (ev.target === this) aofCloseModal();
    });

    // Si hay datos previos en el hidden (modo edicion), restaurar
    var prev = document.getElementById('aof_canvas_data').value;
    if (prev) {
        try {
            var d = JSON.parse(prev);
            if (d && d.markers) {
                aofMarkers = d.markers;
                if (d.custom) {
                    aofCustom = d.custom;
                    document.getElementById('aof_custom_name').value = d.custom.name || '';
                    document.getElementById('aof_custom_color').value = d.custom.color || '#06b6d4';
                }
                aofRedraw();
            }
        } catch(e) { console.warn('AOF: no se pudo restaurar datos previos', e); }
    }

    // Recalculo inicial y en cualquier cambio relevante
    $(document).on('change', '.aof-zona-ind', aofRecalc);
    aofRecalc();
    actualizarFlags();

    console.log('Armonizacion Orofacial FMA Pro v2 lista.');
});
</script>
