<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>SAVE YOUR MONEY - Cada céntimo cuenta</title>
    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
            -webkit-tap-highlight-color: transparent;
        }
        
        body {
            font-family: 'Segoe UI', -apple-system, BlinkMacSystemFont, Roboto, Helvetica, Arial, sans-serif;
            background-color: #081018;
            color: #ecf0f1;
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: flex-start;
            -webkit-font-smoothing: antialiased;
        }

        .app-viewport {
            width: 100%;
            max-width: 430px;
            min-height: 100vh;
            background-color: #0d1b2a;
            padding: 12px 10px;
            display: flex;
            flex-direction: column;
            box-shadow: 0 0 30px rgba(0,0,0,0.8);
            position: relative;
            overflow-x: hidden;
        }

        .modal-overlay {
            display: none;
            position: fixed;
            top: 0; left: 0; width: 100%; height: 100%;
            background: rgba(0,0,0,0.85);
            z-index: 3000;
            justify-content: center;
            align-items: center;
            padding: 15px;
        }

        .alert-card {
            background: #fff5f5;
            border: 3px solid #e74c3c;
            padding: 20px 15px;
            max-width: 380px;
            width: 100%;
            text-align: center;
            border-radius: 12px;
            box-shadow: 0 10px 30px rgba(231, 76, 60, 0.4);
            color: #2c3e50;
        }
        .alert-card h2 { color: #e74c3c; font-size: 20px; margin-bottom: 10px; font-weight: 800; }
        .alert-card p { font-size: 13px; margin-bottom: 15px; line-height: 1.4; color: #4a1510; }
        .alert-btn {
            background: #e74c3c; color: white; border: none; padding: 10px 20px;
            border-radius: 6px; font-weight: 700; cursor: pointer; font-size: 14px; width: 100%;
        }

        .security-card {
            background: #1b263b;
            border: 2px solid #f1c40f;
            padding: 20px 15px;
            max-width: 380px;
            width: 100%;
            text-align: center;
            border-radius: 12px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.8);
            color: #ffffff;
        }
        .security-card h2 { color: #f1c40f; font-size: 18px; margin-bottom: 10px; font-weight: 800; }
        .security-card p { font-size: 12px; margin-bottom: 12px; line-height: 1.4; color: #ecf0f1; text-align: left; }
        .security-btn {
            background: #f1c40f; color: #0d1b2a; border: none; padding: 10px 20px;
            border-radius: 6px; font-weight: 800; cursor: pointer; font-size: 14px; width: 100%;
        }

        .congrat-card {
            background: #f0fff4;
            border: 3px solid #00ff66;
            padding: 20px 15px;
            max-width: 380px;
            width: 100%;
            text-align: center;
            border-radius: 12px;
            color: #1e4620;
        }
        .congrat-card h2 { color: #27ae60; font-size: 20px; margin-bottom: 10px; font-weight: 800; }
        .congrat-card p { font-size: 13px; margin-bottom: 15px; line-height: 1.4; }
        .congrat-btn {
            background: #27ae60; color: white; border: none; padding: 10px 20px;
            border-radius: 6px; font-weight: 700; cursor: pointer; font-size: 14px; width: 100%;
        }

        .diploma-card {
            background: #fff8eb;
            border: 6px double #d4ac0d;
            padding: 20px 15px;
            max-width: 380px;
            width: 100%;
            text-align: center;
            border-radius: 12px;
            color: #2c3e50;
        }
        .diploma-card h2 { color: #b7950b; font-size: 18px; margin-bottom: 10px; letter-spacing: 1px; }
        .diploma-card p { font-size: 13px; margin-bottom: 15px; line-height: 1.4; }
        .diploma-btn {
            background: #27ae60; color: white; border: none; padding: 10px 20px;
            border-radius: 6px; font-weight: 700; cursor: pointer; font-size: 14px; width: 100%;
        }

        .popup-footer-logo {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            margin-top: 12px;
            padding-top: 10px;
            border-top: 1px dashed rgba(255,255,255,0.2);
        }
        .popup-footer-logo svg { width: 28px; height: 28px; }
        .popup-footer-logo span { font-size: 11px; font-weight: 700; color: #f1c40f; }

        #screen-login {
            flex: 1;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            align-items: center;
            padding: 10px 0;
            width: 100%;
        }

        .login-header {
            display: flex;
            justify-content: center;
            align-items: center;
            width: 100%;
            margin-top: 10px;
        }

        .login-header svg {
            width: 100%;
            max-width: 250px;
            height: auto;
        }

        .pin-container {
            background: rgba(255, 255, 255, 0.05);
            padding: 20px 15px;
            border-radius: 12px;
            border: 1px solid rgba(255,255,255,0.1);
            box-shadow: 0 8px 25px rgba(0,0,0,0.6);
            width: 100%;
            text-align: center;
            margin: auto 0;
        }

        .pin-container h3 {
            margin-bottom: 12px;
            font-size: 13px;
            color: #bdc3c7;
            font-weight: 500;
        }

        .pin-input {
            width: 100%;
            padding: 10px;
            font-size: 22px;
            letter-spacing: 10px;
            text-align: center;
            border: 2px solid #34495e;
            border-radius: 6px;
            background-color: #0d1b2a;
            color: #00ff66;
            outline: none;
            margin-bottom: 12px;
            font-family: inherit;
        }

        .btn-login {
            width: 100%;
            padding: 12px;
            background-color: #27ae60;
            color: white;
            border: none;
            border-radius: 6px;
            font-size: 15px;
            font-weight: 700;
            cursor: pointer;
        }

        .forgot-pin-link {
            display: inline-block;
            margin-top: 10px;
            font-size: 11px;
            color: #e74c3c;
            text-decoration: underline;
            cursor: pointer;
        }

        .login-footer { text-align: center; width: 100%; margin-bottom: 5px; }
        .login-footer p.mission { color: #ffffff; font-style: italic; font-size: 12px; margin-bottom: 4px; }
        .login-footer p.branding { color: #f1c40f; font-style: italic; font-size: 11px; }

        #screen-app {
            display: none;
            flex-direction: column;
            gap: 10px;
            width: 100%;
        }

        .card {
            background: #1b263b;
            padding: 12px;
            border-radius: 10px;
            border: 1px solid rgba(255,255,255,0.08);
            box-shadow: 0 4px 15px rgba(0,0,0,0.3);
            width: 100%;
        }

        /* CABECERA COMPACTA Y ESTILIZADA CON ORDEN INVERTIDO */
        .header-dashboard {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 6px;
            padding: 10px 4px;
        }

        .logo-box svg {
            width: 50px;
            height: 50px;
        }

        .header-title-center {
            text-align: center;
            flex: 1;
        }

        /* TÍTULO PRINCIPAL EN MAYÚSCULA Y AMARILLO DORADO */
        .header-title-center h2 {
            color: #f1c40f;
            font-size: 15px;
            font-weight: 900;
            text-transform: uppercase;
            letter-spacing: 0.8px;
            line-height: 1.2;
        }

        /* SUBTÍTULO EN BLANCO, CURSIVA ESTILIZADA Y CON ESPACIO INTERMEDIO */
        .header-title-center p {
            font-size: 11.5px;
            color: #ffffff;
            font-family: Georgia, 'Times New Roman', serif;
            font-style: italic;
            font-weight: 400;
            margin-top: 5px;
            letter-spacing: 0.3px;
            opacity: 0.95;
        }

        .pie-chart-box {
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        .pie-chart-container {
            position: relative;
            width: 65px;
            height: 65px;
            border-radius: 50%;
            background: conic-gradient(#00ff66 0deg, #1b263b 0deg);
            box-shadow: 0 2px 8px rgba(0,0,0,0.4);
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .pie-chart-inner {
            width: 42px;
            height: 42px;
            background-color: #0d1b2a;
            border-radius: 50%;
            display: flex;
            justify-content: center;
            align-items: center;
            color: white;
            font-size: 10px;
            font-weight: 800;
            text-align: center;
        }

        .form-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 8px;
            margin-bottom: 8px;
        }

        .form-item {
            display: flex;
            flex-direction: column;
            gap: 3px;
        }

        .form-item.full-width {
            grid-column: span 2;
        }

        .form-item label {
            font-size: 11px;
            font-weight: 600;
            color: #bdc3c7;
        }

        input[type="text"] {
            padding: 8px;
            font-size: 13px;
            border: 1px solid #34495e;
            border-radius: 5px;
            font-family: inherit;
            width: 100%;
            background-color: #0d1b2a;
            color: #ffffff;
        }

        input[type="text"]:focus {
            outline: none;
            border-color: #00ff66;
        }

        #objetivo {
            color: #ffffff !important;
            font-weight: 700;
        }

        .checkbox-container {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 5px;
            font-weight: 700;
            color: #ff3333;
            cursor: pointer;
            background: rgba(231, 76, 60, 0.15);
            padding: 8px;
            border-radius: 5px;
            border: 1px solid rgba(231, 76, 60, 0.4);
            font-size: 12px;
            height: 36px;
        }

        .btn-action {
            padding: 8px;
            font-size: 13px;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-weight: 700;
            font-family: inherit;
            width: 100%;
            height: 36px;
        }

        .btn-register { background-color: #3498db; }
        .btn-print { background-color: #27ae60; }

        .btn-clear { 
            background-color: #e74c3c !important; 
            color: #ffffff !important;
            font-weight: 800 !important;
            font-size: 11px; 
            padding: 5px 8px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        .summary {
            display: flex;
            justify-content: space-between;
            background: rgba(0, 255, 102, 0.05);
            padding: 8px;
            border-radius: 6px;
            border-left: 3px solid #00ff66;
            gap: 4px;
        }

        .summary-item { 
            font-size: 11px; 
            font-weight: 600; 
            text-align: center; 
            color: #ecf0f1; 
            flex: 1;
        }

        .texto-positivo { color: #00ff66 !important; font-weight: 800; }
        .texto-negativo { color: #ff3333 !important; font-weight: 800; }
        .texto-restante { color: #f1c40f !important; font-weight: 800; }

        .table-header-container {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 8px;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            background: #0d1b2a;
            border-radius: 6px;
            overflow: hidden;
            table-layout: fixed;
        }

        th, td {
            border: 1px solid #1b263b;
            padding: 7px 3px;
            text-align: center;
            font-size: 10.5px;
            word-wrap: break-word;
        }

        th { 
            background-color: #162436; 
            color: #ffffff; 
            font-weight: 700;
        }

        th:nth-child(1) { width: 25%; }
        th:nth-child(2) { width: 40%; }
        th:nth-child(3) { width: 35%; }

        tr:nth-child(even) { background-color: #121e2e; }
        .row-reintegro { background-color: rgba(255, 51, 51, 0.15) !important; }

        .print-summary-header { display: none; }
        .print-footer-info { display: none; }

        @media print {
            body { background-color: white !important; color: black !important; }
            .app-viewport { max-width: 100% !important; box-shadow: none !important; padding: 0 !important; }
            .modal-overlay, .form-grid, .btn-clear, #screen-login, .card.header-dashboard, .pie-chart-box {
                display: none !important;
            }
            #screen-app { display: block !important; padding: 0; background-color: white !important; }
            .card { background-color: white !important; color: black !important; box-shadow: none !important; border: 1px solid #ccc !important; }
            table { background: white !important; color: black !important; table-layout: auto !important; }
            th { background-color: #f2f2f2 !important; color: black !important; }
            td { color: black !important; border-color: #ddd !important; }
            .print-summary-header, .print-footer-info { display: block !important; }
            #objetivo { color: black !important; }
        }
    </style>
</head>
<body>

    <div class="app-viewport">

        <!-- POPUP ADVERTENCIA REINTEGROS -->
        <div id="modal-alert-reintegro" class="modal-overlay">
            <div class="alert-card">
                <h2>¡AVISO!</h2>
                <p>Comprendiendo que la intención emocional siempre es guardar la mayor cantidad posible, desde <b>Save Your Money</b> y la esencia de esta aplicación, sugerimos que guarde, aunque sea en más registros, una cantidad que pueda mantener, evitando realizar extracciones reiteradas que puedan desanimarle en el proceso de lograr su objetivo.</p>
                <button class="alert-btn" onclick="cerrarAvisoReintegro()">Cerrar</button>
                <div class="popup-footer-logo">
                    <svg viewBox="0 0 500 500">
                        <rect width="500" height="500" rx="90" fill="#0c0d0e"/>
                        <text x="250" y="140" font-family="Arial Black, sans-serif" font-size="110" font-weight="900" fill="#f1c40f" text-anchor="middle">SYM</text>
                        <circle cx="250" cy="300" r="100" fill="#f1c40f"/>
                        <circle cx="210" cy="280" r="10" fill="#0c0d0e"/>
                        <path d="M 270 270 Q 285 255 300 270" stroke="#0c0d0e" stroke-width="8" fill="none" stroke-linecap="round"/>
                        <path d="M 225 320 Q 250 340 275 320" stroke="#0c0d0e" stroke-width="10" fill="none" stroke-linecap="round"/>
                        <text x="250" y="440" font-family="Arial Black, sans-serif" font-size="28" font-weight="900" fill="#ffffff" text-anchor="middle">SAVE YOUR MONEY</text>
                    </svg>
                    <span>SAVE YOUR MONEY</span>
                </div>
            </div>
        </div>

        <!-- POPUP SEGURIDAD PASWORD 7 DÍGITOS -->
        <div id="modal-security-7" class="modal-overlay">
            <div class="security-card">
                <h2>🔐 PROTOCOLO DE SEGURIDAD</h2>
                <p>Ha superado el límite de 3 intentos fallidos con el PIN corto.</p>
                <p>Se requiere configurar/introducir la <b>Contraseña de Seguridad de 7 dígitos</b>.</p>
                <p style="background: rgba(241, 196, 15, 0.15); padding: 8px; border-radius: 5px; border-left: 3px solid #f1c40f; color: #f1c40f; font-size: 11px;">
                    <b>Recomendación importante:</b> Memorice sus contraseñas y apúntelas únicamente en un cuaderno o soporte físico. Evite guardarlas en notas digitales o carpetas en línea que puedan ser espiadas.
                </p>
                <div style="margin: 12px 0;">
                    <input type="password" id="pin-7-input" class="pin-input" maxlength="7" placeholder="•••••••" style="letter-spacing: 6px;">
                </div>
                <button class="security-btn" onclick="validarOEstablecerPin7()">Confirmar Contraseña</button>
            </div>
        </div>

        <!-- POPUP FELICITACIÓN HITOS -->
        <div id="modal-congratulation" class="modal-overlay">
            <div class="congrat-card">
                <h2 id="congrat-title">¡ENHORABUENA!</h2>
                <p id="congrat-message">Tu saldo ha alcanzado un nuevo tramo de tu objetivo. ¡Sigue adelante!</p>
                <button class="congrat-btn" onclick="cerrarFelicitacion()">Continuar</button>
                <div class="popup-footer-logo">
                    <svg viewBox="0 0 500 500">
                        <rect width="500" height="500" rx="90" fill="#0c0d0e"/>
                        <text x="250" y="140" font-family="Arial Black, sans-serif" font-size="110" font-weight="900" fill="#f1c40f" text-anchor="middle">SYM</text>
                        <circle cx="250" cy="300" r="100" fill="#f1c40f"/>
                        <circle cx="210" cy="280" r="10" fill="#0c0d0e"/>
                        <path d="M 270 270 Q 285 255 300 270" stroke="#0c0d0e" stroke-width="8" fill="none" stroke-linecap="round"/>
                        <path d="M 225 320 Q 250 340 275 320" stroke="#0c0d0e" stroke-width="10" fill="none" stroke-linecap="round"/>
                        <text x="250" y="440" font-family="Arial Black, sans-serif" font-size="28" font-weight="900" fill="#ffffff" text-anchor="middle">SAVE YOUR MONEY</text>
                    </svg>
                    <span>SAVE YOUR MONEY</span>
                </div>
            </div>
        </div>

        <!-- MODAL DIPLOMA -->
        <div id="modal-diploma" class="modal-overlay">
            <div class="diploma-card">
                <h2>📜 DIPLOMA AL ESFUERZO</h2>
                <p>Se otorga el presente reconocimiento por demostrar que <b>Cada céntimo cuenta</b>.</p>
                <p>Por haber alcanzado con éxito el <b>100% de tu objetivo de ahorro</b> en tu saldo acumulado.</p>
                <button class="diploma-btn" onclick="cerrarDiploma()">Aceptar</button>
                <div class="popup-footer-logo">
                    <svg viewBox="0 0 500 500">
                        <rect width="500" height="500" rx="90" fill="#0c0d0e"/>
                        <text x="250" y="140" font-family="Arial Black, sans-serif" font-size="110" font-weight="900" fill="#f1c40f" text-anchor="middle">SYM</text>
                        <circle cx="250" cy="300" r="100" fill="#f1c40f"/>
                        <circle cx="210" cy="280" r="10" fill="#0c0d0e"/>
                        <path d="M 270 270 Q 285 255 300 270" stroke="#0c0d0e" stroke-width="8" fill="none" stroke-linecap="round"/>
                        <path d="M 225 320 Q 250 340 275 320" stroke="#0c0d0e" stroke-width="10" fill="none" stroke-linecap="round"/>
                        <text x="250" y="440" font-family="Arial Black, sans-serif" font-size="28" font-weight="900" fill="#ffffff" text-anchor="middle">SAVE YOUR MONEY</text>
                    </svg>
                    <span>SAVE YOUR MONEY</span>
                </div>
            </div>
        </div>

        <!-- PANTALLA DE INICIO / LOGIN -->
        <div id="screen-login">
            <div class="login-header">
                <svg viewBox="0 0 500 500">
                    <rect width="500" height="500" rx="90" fill="#0c0d0e"/>
                    <text x="250" y="140" font-family="Arial Black, sans-serif" font-size="110" font-weight="900" fill="#f1c40f" text-anchor="middle">SYM</text>
                    <circle cx="250" cy="300" r="100" fill="#f1c40f"/>
                    <circle cx="210" cy="280" r="10" fill="#0c0d0e"/>
                    <path d="M 270 270 Q 285 255 300 270" stroke="#0c0d0e" stroke-width="8" fill="none" stroke-linecap="round"/>
                    <path d="M 225 320 Q 250 340 275 320" stroke="#0c0d0e" stroke-width="10" fill="none" stroke-linecap="round"/>
                    <text x="250" y="440" font-family="Arial Black, sans-serif" font-size="28" font-weight="900" fill="#ffffff" text-anchor="middle">SAVE YOUR MONEY</text>
                </svg>
            </div>

            <div class="pin-container">
                <h3 id="login-title">PIN de acceso (5 dígitos):</h3>
                <input type="password" id="pin-input" class="pin-input" maxlength="5" placeholder="•••••" pattern="[0-9]*" inputmode="numeric">
                <button class="btn-login" onclick="validarOEstablecerPin()" id="btn-login-action">Ingresar</button>

                <div id="forgot-container" style="display: none;">
                    <span class="forgot-pin-link" onclick="resetearPin()">¿Olvidaste tu PIN? Restablecer</span>
                </div>
            </div>

            <div class="login-footer">
                <p class="mission">Si te estamos ayudando, hemos cumplido nuestra misión.</p>
                <p class="branding">Powered by Tony Socias&amp;viviraltiempo.com. TM 2026</p>
            </div>
        </div>

        <!-- PANTALLA PRINCIPAL DE LA APLICACIÓN -->
        <div id="screen-app">

            <!-- CABECERA PARA REPORT IMPRESO -->
            <div class="print-summary-header" style="padding: 15px; border: 2px solid #34495e; border-radius: 8px; margin-bottom: 15px;">
                <div style="display: flex; justify-content: space-between; align-items: center;">
                    <svg viewBox="0 0 500 500" style="width:80px; height:80px;">
                        <rect width="500" height="500" rx="90" fill="#0c0d0e"/>
                        <text x="250" y="140" font-family="Arial Black, sans-serif" font-size="110" font-weight="900" fill="#f1c40f" text-anchor="middle">SYM</text>
                        <circle cx="250" cy="300" r="100" fill="#f1c40f"/>
                    </svg>
                    <div style="text-align: right;">
                        <h1 style="font-size: 18px; color: #1a252f;">SAVE YOUR MONEY</h1>
                        <p style="font-size: 11px; color: #7f8c8d; font-style: italic;">Cada céntimo cuenta - INFORME DE CONTROL</p>
                    </div>
                </div>
                <div style="margin-top: 10px; border-top: 1px solid #eee; padding-top: 8px; font-size: 11px; color: #333;">
                    <p><b>Objetivo Total:</b> <span id="print-objetivo">0,00 €</span></p>
                    <p><b>Ahorro Acumulado:</b> <span id="print-acumulado">0,00 €</span></p>
                    <p><b>Situación en Porcentaje:</b> <span id="print-porcentaje">0%</span></p>
                    <p><b>Fecha de emisión:</b> <span id="print-fecha"></span></p>
                </div>
            </div>

            <!-- CABECERA PRINCIPAL EN MÓVIL CON ORDEN Y FUENTE ACTUALIZADOS -->
            <div class="card header-dashboard">
                <div class="logo-box">
                    <svg viewBox="0 0 500 500">
                        <rect width="500" height="500" rx="90" fill="#0c0d0e"/>
                        <text x="250" y="140" font-family="Arial Black, sans-serif" font-size="110" font-weight="900" fill="#f1c40f" text-anchor="middle">SYM</text>
                        <circle cx="250" cy="300" r="100" fill="#f1c40f"/>
                        <circle cx="210" cy="280" r="10" fill="#0c0d0e"/>
                        <path d="M 270 270 Q 285 255 300 270" stroke="#0c0d0e" stroke-width="8" fill="none" stroke-linecap="round"/>
                        <path d="M 225 320 Q 250 340 275 320" stroke="#0c0d0e" stroke-width="10" fill="none" stroke-linecap="round"/>
                    </svg>
                </div>

                <div class="header-title-center">
                    <h2>SAVE YOUR MONEY</h2>
                    <p>Cada céntimo cuenta</p>
                </div>

                <div class="pie-chart-box">
                    <div id="pie-chart" class="pie-chart-container">
                        <div id="pie-inner-text" class="pie-chart-inner">0%</div>
                    </div>
                </div>
            </div>

            <!-- PANEL DE REGISTRO FORMULARIO MÓVIL -->
            <div class="card">
                <div class="form-grid">
                    <div class="form-item">
                        <label for="objetivo">Objetivo (€):</label>
                        <input type="text" id="objetivo" value="1.000,00" onfocus="limpiarFormato(this)" onblur="aplicarFormato(this); actualizarInterfaz();">
                    </div>

                    <div class="form-item">
                        <label for="importe">Importe (€):</label>
                        <input type="text" id="importe" placeholder="0,00" onfocus="limpiarFormato(this)" onblur="aplicarFormato(this)">
                    </div>
                    
                    <div class="form-item full-width">
                        <label for="concepto">Concepto:</label>
                        <input type="text" id="concepto" placeholder="Aportación habitual">
                    </div>

                    <div class="form-item full-width">
                        <label class="checkbox-container">
                            <input type="checkbox" id="esReintegro"> Reintegro / Extracción (-)
                        </label>
                    </div>

                    <div class="form-item">
                        <button class="btn-action btn-register" onclick="registrarOperacion()">Registrar</button>
                    </div>

                    <div class="form-item">
                        <button class="btn-action btn-print" onclick="imprimirOpdf()">Imprimir</button>
                    </div>
                </div>

                <div class="summary">
                    <div class="summary-item">Ops:<br><span id="total-operaciones" style="color: #3498db; font-weight: 800;">0</span></div>
                    <div class="summary-item">Ahorrado:<br><span id="total-ahorrado" class="texto-positivo">0,00 €</span></div>
                    <div class="summary-item">Restante:<br><span id="total-restante" class="texto-restante">0,00 €</span></div>
                </div>
            </div>

            <!-- TABLA HISTÓRICA MÓVIL SIN SCROLL LATERAL -->
            <div class="card">
                <div class="table-header-container">
                    <h3 style="font-size: 13px; color: #ffffff;">Histórico de Registros</h3>
                    <button class="btn-clear" onclick="limpiarHistorial()">Borrar</button>
                </div>
                <table>
                    <thead>
                        <tr>
                            <th>Fecha</th>
                            <th>Detalle</th>
                            <th>Importe (€)</th>
                        </tr>
                    </thead>
                    <tbody id="tabla-cuerpo">
                    </tbody>
                </table>
            </div>

            <!-- PIE DE PÁGINA IMPRESO -->
            <div class="print-footer-info" style="text-align: center; margin-top: 20px; font-size: 11px;">
                <p style="color: #0056b3; font-style: italic; font-weight: 600;">Si te estamos ayudando, hemos cumplido nuestra misión.</p>
                <p style="color: #555555; font-style: italic; font-size: 10px;">Powered by Tony Socias&amp;viviraltiempo.com TM 2026</p>
            </div>
        </div>

    </div>

    <script>
        let registros = [];
        let acumuladoAhorro = 0.0;
        let pinGuardado = localStorage.getItem('app_pin_v1');
        let pin7Guardado = localStorage.getItem('app_pin_7_v1');
        let intentosFallidos = parseInt(localStorage.getItem('app_intentos_fallidos') || '0');
        let hitosSuperados = JSON.parse(localStorage.getItem('app_hitos_superados_v4') || '[]');

        function formatearMoneda(valor) {
            return new Intl.NumberFormat('es-ES', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(valor);
        }

        function parsearMoneda(texto) {
            if (typeof texto === 'number') return texto;
            if (!texto) return 0;
            let limpio = texto.toString().replace(/\./g, '').replace(',', '.');
            return parseFloat(limpio) || 0;
        }

        function limpiarFormato(input) {
            let num = parsearMoneda(input.value);
            input.value = num !== 0 ? num : '';
        }

        function aplicarFormato(input) {
            let num = parsearMoneda(input.value);
            if (num !== 0) {
                input.value = formatearMoneda(num);
            }
        }

        window.onload = function() {
            comprobarEstadoPin();

            const datosGuardados = localStorage.getItem('ahorro_registros_v4');
            if (datosGuardados) {
                registros = JSON.parse(datosGuardados);
                if (registros.length > 0) {
                    acumuladoAhorro = parseFloat(registros[registros.length - 1].acumuladoAhorro);
                }
            }

            const objetivoGuardado = localStorage.getItem('ahorro_objetivo_v1');
            if (objetivoGuardado) {
                document.getElementById('objetivo').value = formatearMoneda(parseFloat(objetivoGuardado));
            }
        };

        function comprobarEstadoPin() {
            const titleEl = document.getElementById('login-title');
            const btnEl = document.getElementById('btn-login-action');
            const forgotContainer = document.getElementById('forgot-container');

            pinGuardado = localStorage.getItem('app_pin_v1');

            if (!pinGuardado) {
                titleEl.innerText = "Crea tu PIN inicial (5 dígitos):";
                btnEl.innerText = "Guardar y Entrar";
                forgotContainer.style.display = 'none';
            } else {
                titleEl.innerText = "PIN de acceso (5 dígitos):";
                btnEl.innerText = "Ingresar";
                forgotContainer.style.display = 'block';
            }
        }

        function validarOEstablecerPin() {
            const pinInput = document.getElementById('pin-input').value;

            if (pinInput.length !== 5 || isNaN(pinInput)) {
                alert("Por favor, introduce un PIN de exactamente 5 números.");
                return;
            }

            if (!pinGuardado) {
                localStorage.setItem('app_pin_v1', pinInput);
                pinGuardado = pinInput;
                alert("PIN configurado correctamente.");
                mostrarApp();
            } else {
                if (pinInput === pinGuardado) {
                    intentosFallidos = 0;
                    localStorage.setItem('app_intentos_fallidos', '0');
                    mostrarApp();
                } else {
                    intentosFallidos++;
                    localStorage.setItem('app_intentos_fallidos', intentosFallidos.toString());
                    document.getElementById('pin-input').value = '';

                    if (intentosFallidos >= 3) {
                        abrirModalSeguridad7();
                    } else {
                        alert(`PIN incorrecto. Intentos fallidos: ${intentosFallidos}/3`);
                    }
                }
            }
        }

        function abrirModalSeguridad7() {
            document.getElementById('modal-security-7').style.display = 'flex';
        }

        function validarOEstablecerPin7() {
            const pin7Input = document.getElementById('pin-7-input').value;

            if (pin7Input.length !== 7 || isNaN(pin7Input)) {
                alert("Por favor, introduce una Contraseña de exactamente 7 números.");
                return;
            }

            if (!pin7Guardado) {
                localStorage.setItem('app_pin_7_v1', pin7Input);
                pin7Guardado = pin7Input;
                alert("Contraseña de 7 dígitos configurada con éxito.");
                intentosFallidos = 0;
                localStorage.setItem('app_intentos_fallidos', '0');
                document.getElementById('modal-security-7').style.display = 'none';
                mostrarApp();
            } else {
                if (pin7Input === pin7Guardado) {
                    intentosFallidos = 0;
                    localStorage.setItem('app_intentos_fallidos', '0');
                    document.getElementById('modal-security-7').style.display = 'none';
                    mostrarApp();
                } else {
                    alert("Contraseña de 7 dígitos incorrecta.");
                    document.getElementById('pin-7-input').value = '';
                }
            }
        }

        function resetearPin() {
            if (confirm("¿Deseas restablecer tu PIN de acceso para crear uno nuevo? Tus datos de ahorro no se borrarán.")) {
                localStorage.removeItem('app_pin_v1');
                localStorage.removeItem('app_pin_7_v1');
                localStorage.setItem('app_intentos_fallidos', '0');
                intentosFallidos = 0;
                document.getElementById('pin-input').value = '';
                comprobarEstadoPin();
                alert("PIN borrado. Introduce ahora tu nuevo PIN de 5 dígitos.");
            }
        }

        function mostrarApp() {
            document.getElementById('screen-login').style.display = 'none';
            document.getElementById('screen-app').style.display = 'flex';
            actualizarInterfaz();
        }

        function guardarEnAlmacenamiento() {
            localStorage.setItem('ahorro_registros_v4', JSON.stringify(registros));
            localStorage.setItem('ahorro_objetivo_v1', parsearMoneda(document.getElementById('objetivo').value));
            localStorage.setItem('app_hitos_superados_v4', JSON.stringify(hitosSuperados));
        }

        function registrarOperacion() {
            const inputImporte = document.getElementById('importe');
            const inputConcepto = document.getElementById('concepto');
            const chkReintegro = document.getElementById('esReintegro');

            let importe = parsearMoneda(inputImporte.value);

            if (isNaN(importe) || importe === 0) {
                alert("Por favor, introduce un importe válido.");
                return;
            }

            const esExtraccion = chkReintegro.checked || importe < 0;

            if (esExtraccion) {
                if (importe > 0) importe = -importe;
            }

            const concepto = inputConcepto.value.trim() || (esExtraccion ? "Extracción" : "Aportación");

            acumuladoAhorro += importe;

            const ahora = new Date();
            const YY = String(ahora.getFullYear()).slice(-2);
            const MM = String(ahora.getMonth() + 1).padStart(2, '0');
            const DD = String(ahora.getDate()).padStart(2, '0');

            const fechaCorta = `${DD}/${MM}/${YY}`;

            const nuevoRegistro = {
                fecha: fechaCorta,
                tipo: esExtraccion ? "REINTEGRO" : "APORTACIÓN",
                concepto: concepto,
                importe: importe.toFixed(2),
                operacionNum: registros.length + 1,
                acumuladoAhorro: acumuladoAhorro.toFixed(2),
                esExtraccion: esExtraccion
            };

            registros.push(nuevoRegistro);
            guardarEnAlmacenamiento();
            actualizarInterfaz();

            if (esExtraccion || acumuladoAhorro < 0) {
                mostrarAvisoReintegro();
            } else {
                evaluarHitosSaldoObjetivo();
            }
            
            inputImporte.value = "";
            chkReintegro.checked = false;
        }

        function mostrarAvisoReintegro() {
            document.getElementById('modal-alert-reintegro').style.display = 'flex';
        }

        function cerrarAvisoReintegro() {
            document.getElementById('modal-alert-reintegro').style.display = 'none';
        }

        function evaluarHitosSaldoObjetivo() {
            const objetivo = parsearMoneda(document.getElementById('objetivo').value);
            if (objetivo <= 0) return;

            const porcentajeSaldo = (acumuladoAhorro / objetivo) * 100;

            if (porcentajeSaldo >= 100) {
                mostrarDiploma();
                return;
            }

            const tramos = [25, 50, 75];
            for (let tramo of tramos) {
                const hitoKey = `${objetivo}_${tramo}`;
                if (porcentajeSaldo >= tramo && !hitosSuperados.includes(hitoKey)) {
                    hitosSuperados.push(hitoKey);
                    guardarEnAlmacenamiento();
                    mostrarFelicitacion(tramo, porcentajeSaldo);
                    break;
                }
            }
        }

        function mostrarFelicitacion(tramo, porcentajeSaldo) {
            document.getElementById('congrat-title').innerText = `¡ENHORABUENA! (${tramo}%)`;
            document.getElementById('congrat-message').innerText = `Tu saldo acumulado (${formatearMoneda(acumuladoAhorro)} €) ha alcanzado el ${porcentajeSaldo.toFixed(1)}% de tu objetivo.`;
            document.getElementById('modal-congratulation').style.display = 'flex';
        }

        function cerrarFelicitacion() {
            document.getElementById('modal-congratulation').style.display = 'none';
        }

        function mostrarDiploma() {
            document.getElementById('modal-diploma').style.display = 'flex';
        }

        function cerrarDiploma() {
            document.getElementById('modal-diploma').style.display = 'none';
        }

        function actualizarInterfaz() {
            actualizarTabla();
            actualizarGrafica();
            localStorage.setItem('ahorro_objetivo_v1', parsearMoneda(document.getElementById('objetivo').value));
        }

        function actualizarTabla() {
            const cuerpo = document.getElementById('tabla-cuerpo');
            cuerpo.innerHTML = '';

            [...registros].reverse().forEach(reg => {
                const claseFila = reg.esExtraccion ? 'row-reintegro' : '';
                const claseTexto = reg.esExtraccion ? 'texto-negativo' : 'texto-positivo';
                const signo = parseFloat(reg.importe) > 0 ? '+' : '';

                const fila = `<tr class="${claseFila}">
                    <td>${reg.fecha}</td>
                    <td style="text-align: left;"><span class="${claseTexto}">${reg.tipo}</span><br><span style="font-size:9px; color:#bdc3c7;">${reg.concepto}</span></td>
                    <td class="${claseTexto}">${signo}${formatearMoneda(parseFloat(reg.importe))} €</td>
                </tr>`;
                cuerpo.innerHTML += fila;
            });

            document.getElementById('total-operaciones').innerText = registros.length;
            
            const elTotal = document.getElementById('total-ahorrado');
            elTotal.innerText = formatearMoneda(acumuladoAhorro) + ' €';
            elTotal.className = acumuladoAhorro >= 0 ? 'texto-positivo' : 'texto-negativo';
        }

        function actualizarGrafica() {
            const objetivo = parsearMoneda(document.getElementById('objetivo').value) || 1;
            const porcentajeReal = (acumuladoAhorro / objetivo) * 100;
            
            const pieChart = document.getElementById('pie-chart');
            const pieInnerText = document.getElementById('pie-inner-text');

            let estiloFondo = '';
            let textoPorcentaje = '';
            let colorTexto = '#ffffff';

            if (acumuladoAhorro < 0) {
                textoPorcentaje = `${porcentajeReal.toFixed(1)}%`;
                colorTexto = '#ff3333';
                let pctAbsoluto = Math.min(Math.abs(porcentajeReal), 100);
                let grados = (pctAbsoluto / 100) * 360;
                estiloFondo = `conic-gradient(#ff3333 ${grados}deg, #1b263b ${grados}deg)`;
            } else {
                textoPorcentaje = `${porcentajeReal.toFixed(1)}%`;
                colorTexto = '#ffffff';
                let pctGrafico = Math.min(porcentajeReal, 100);
                let grados = (pctGrafico / 100) * 360;
                estiloFondo = `conic-gradient(#00ff66 ${grados}deg, #1b263b ${grados}deg)`;
            }

            pieChart.style.background = estiloFondo;
            pieInnerText.innerText = textoPorcentaje;
            pieInnerText.style.color = colorTexto;

            const restante = objetivo - acumuladoAhorro;
            document.getElementById('total-restante').innerText = formatearMoneda(restante > 0 ? restante : 0) + ' €';

            document.getElementById('print-objetivo').innerText = formatearMoneda(objetivo) + ' €';
            document.getElementById('print-acumulado').innerText = formatearMoneda(acumuladoAhorro) + ' €';
            document.getElementById('print-porcentaje').innerText = `${porcentajeReal.toFixed(1)}%`;
            document.getElementById('print-fecha').innerText = new Date().toLocaleString('es-ES');
        }

        function imprimirOpdf() {
            window.print();
        }

        function limpiarHistorial() {
            if (confirm("¿Estás seguro de que deseas borrar todo el historial guardado? Esta acción no se puede deshacer.")) {
                localStorage.removeItem('ahorro_registros_v4');
                localStorage.removeItem('app_hitos_superados_v4');
                registros = [];
                acumuladoAhorro = 0.0;
                hitosSuperados = [];
                actualizarInterfaz();
            }
        }
    </script>
</body>
</html>