<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Asistente de Notas de Crédito</title>
    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- html2canvas -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
    <style>
        body { font-family: 'Inter', sans-serif; overflow: hidden; }
        #nota-container { width: 420px; transform: scale(0.8); transform-origin: top center; }
        @media (min-width: 1024px) {
            #nota-container { transform: scale(1); }
        }
        .loader {
            border: 3px solid rgba(255, 255, 255, 0.3);
            border-top: 3px solid #ffffff;
            border-radius: 50%;
            width: 24px;
            height: 24px;
            animation: spin 1s linear infinite;
        }
        @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
        .hide-scroll::-webkit-scrollbar { display: none; }
        .animate-fade-in { animation: fadeIn 0.3s ease-out; }
        @keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
    </style>
</head>
<body class="bg-slate-50 min-h-screen flex flex-col lg:flex-row">

    <!-- SECCIÓN DEL CHAT (BOT) -->
    <div class="w-full lg:w-1/2 flex flex-col border-r border-gray-200 bg-white h-[55vh] lg:h-screen shadow-xl z-20">
        <!-- Header del Bot -->
        <div class="p-4 border-b bg-blue-600 text-white flex justify-between items-center shadow-md z-10">
            <div class="flex items-center gap-3">
                <div class="w-10 h-10 bg-white rounded-full flex items-center justify-center text-blue-600 font-black shadow-inner text-xl">AI</div>
                <div>
                    <h2 class="font-bold leading-none text-lg">Asistente Cofradía</h2>
                    <span class="text-[10px] text-blue-100 flex items-center gap-1 uppercase tracking-tighter">
                        <span class="w-2 h-2 bg-green-400 rounded-full animate-pulse"></span> En línea ahora
                    </span>
                </div>
            </div>
            <div class="flex gap-2 text-white">
                <label for="logo-input" class="text-[10px] uppercase tracking-widest bg-white/20 hover:bg-white/30 px-3 py-2 rounded-xl border border-white/30 cursor-pointer transition-all font-black">📷 Logo</label>
                <input type="file" id="logo-input" accept="image/*" class="hidden">
                <button id="reset-bot-btn" class="text-[10px] uppercase tracking-widest bg-blue-700/50 hover:bg-blue-800 px-3 py-2 rounded-xl border border-blue-400/30 transition-all font-black">Reiniciar</button>
            </div>
        </div>

        <!-- Área de mensajes -->
        <div id="chat-box" class="flex-1 p-4 overflow-y-auto space-y-4 hide-scroll bg-slate-50/50 text-black">
            <!-- Mensajes -->
        </div>

        <!-- Entrada de datos dinámica -->
        <div class="p-4 border-t bg-white shadow-[0_-4px_15px_rgba(0,0,0,0.05)] z-10">
            <div id="input-container" class="flex gap-2">
                <input type="text" id="bot-input" class="flex-1 p-4 border-2 border-slate-100 rounded-2xl focus:border-blue-500 outline-none transition-all shadow-sm font-bold text-black" placeholder="Escribe aquí...">
                <button id="bot-send-btn" class="bg-blue-600 text-white p-4 rounded-2xl hover:bg-blue-700 transition shadow-lg active:scale-95">
                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><line x1="22" y1="2" x2="11" y2="13"></line><polygon points="22 2 15 22 11 13 2 9 22 2"></polygon></svg>
                </button>
            </div>
            
            <div id="camera-container" class="hidden animate-fade-in text-center">
                <label for="camera-input" class="w-full flex flex-col items-center justify-center gap-2 bg-purple-600 text-white p-6 rounded-3xl cursor-pointer hover:bg-purple-700 transition font-black shadow-xl active:scale-95 border-b-4 border-purple-800">
                    <svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"></path><circle cx="12" cy="13" r="4"></circle></svg>
                    <span>ABRIR CÁMARA</span>
                </label>
                <input type="file" id="camera-input" accept="image/*" capture="environment" class="hidden">
            </div>

            <div id="confirm-container" class="hidden flex gap-3 animate-fade-in">
                <button onclick="handleConfirm(true)" class="flex-1 bg-green-600 text-white p-5 rounded-2xl font-black shadow-lg hover:bg-green-700 active:scale-95 border-b-4 border-green-800">SÍ, QUITAR FONDO</button>
                <button onclick="handleConfirm(false)" class="flex-1 bg-slate-300 text-black p-5 rounded-2xl font-black shadow-lg hover:bg-slate-400 active:scale-95 border-b-4 border-slate-500 text-xs uppercase tracking-tighter">No, así está bien</button>
            </div>
        </div>
    </div>

    <!-- SECCIÓN DE VISTA PREVIA E HISTORIAL -->
    <div class="w-full lg:w-1/2 p-4 flex flex-col items-center overflow-y-auto bg-slate-100 h-[45vh] lg:h-screen">
        
        <div class="flex gap-2 mb-4 bg-white p-1.5 rounded-2xl shadow-sm lg:hidden w-full max-w-xs border border-gray-200">
            <button id="tab-preview" class="flex-1 py-2.5 rounded-xl bg-blue-600 text-white font-black text-xs uppercase shadow-md">Ticket</button>
            <button id="tab-history" class="flex-1 py-2.5 rounded-xl text-black font-black text-xs uppercase">Historial</button>
        </div>

        <div id="preview-section" class="w-full flex flex-col items-center">
            <!-- Ticket con letras grandes y negras -->
            <div id="nota-container" class="bg-white p-10 shadow-2xl border border-gray-300 relative mb-4 text-black">
                <div class="absolute top-0 left-0 w-full h-4 bg-black"></div>
                
                <div class="header text-center mb-8">
                    <!-- Logo Fijo -->
                    <img id="logo-img" src="1000125651.jpg" alt="Logo" class="w-36 mx-auto mb-4 block" onerror="this.style.display='none'">
                    <h1 class="text-3xl font-black uppercase text-black leading-none tracking-tighter">LLANTERA MÓVIL COFRADÍA</h1>
                    <p class="text-[14px] font-black text-black uppercase tracking-widest mt-3 border-y-2 border-black py-2 inline-block px-8 font-bold">Nota de Crédito</p>
                    <p class="text-[13px] font-black text-black mt-3">Mazamitla, Jalisco • Tel: 333 485 4080</p>
                </div>

                <div class="border-t-2 border-black my-6"></div>

                <div class="grid grid-cols-2 gap-y-2.5 text-[14px] mb-8">
                    <span class="font-black uppercase">FOLIO:</span>
                    <span id="folio-output" class="text-right font-black text-black text-lg"></span>
                    <span class="font-black uppercase">FECHA:</span>
                    <span id="fecha-output" class="text-right font-black"></span>
                    <span class="font-black uppercase">HORA:</span>
                    <span id="hora-output" class="text-right font-black"></span>
                </div>

                <div class="space-y-8">
                    <div class="bg-slate-50 p-5 rounded-xl border-2 border-black shadow-sm">
                        <strong class="text-[12px] font-black uppercase tracking-widest block mb-2">Cliente</strong>
                        <p id="cliente-output" class="text-[20px] font-black uppercase leading-tight">---</p>
                    </div>

                    <div>
                        <strong class="text-[12px] font-black uppercase tracking-widest block mb-2">Descripción del Servicio</strong>
                        <p id="descripcion-output" class="text-[16px] leading-relaxed font-black border-l-4 border-black pl-4 italic">---</p>
                    </div>

                    <div id="evidence-container" class="hidden">
                        <strong class="text-[12px] font-black uppercase tracking-widest block mb-3">Evidencia del Trabajo</strong>
                        <img id="evidence-image" src="" alt="Evidencia" class="w-full rounded-2xl shadow-lg border-2 border-black">
                    </div>
                </div>

                <div class="border-t-4 border-double border-black my-10"></div>

                <div class="flex justify-between items-end">
                    <div>
                        <span class="text-[13px] font-black uppercase block mb-1">Estado</span>
                        <span class="bg-black text-white px-5 py-2 rounded-full text-[13px] font-black uppercase tracking-widest">Pendiente</span>
                    </div>
                    <div class="text-right">
                        <span class="text-[13px] font-black uppercase block mb-1">Total a Pagar</span>
                        <span id="total-output" class="text-5xl font-black leading-none tracking-tighter">$0.00</span>
                    </div>
                </div>

                <div class="text-center mt-14 pt-8 border-t-2 border-black">
                    <p class="text-[13px] font-black italic">¡Gracias por su preferencia en Llantera Cofradía!</p>
                </div>
            </div>

            <!-- Botones de Acción Final -->
            <div id="final-actions" class="grid grid-cols-2 gap-4 w-full max-w-sm hidden animate-fade-in px-4 pb-16">
                <button id="share-btn-main" class="bg-green-600 text-white p-5 rounded-[1.5rem] font-black shadow-xl hover:bg-green-700 flex flex-col items-center justify-center gap-1 transition-all active:scale-95 border-b-4 border-green-950">
                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><circle cx="18" cy="5" r="3"></circle><circle cx="6" cy="12" r="3"></circle><circle cx="18" cy="19" r="3"></circle><line x1="8.59" y1="13.51" x2="15.42" y2="17.49"></line><line x1="15.41" y1="6.51" x2="8.59" y2="10.49"></line></svg>
                    <span class="text-[11px] uppercase tracking-widest">Compartir</span>
                </button>
                <button id="download-btn-main" class="bg-blue-600 text-white p-5 rounded-[1.5rem] font-black shadow-xl hover:bg-blue-700 flex flex-col items-center justify-center gap-1 transition-all active:scale-95 border-b-4 border-blue-950">
                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="7 10 12 15 17 10"></polyline><line x1="12" y1="15" x2="12" y2="3"></line></svg>
                    <span class="text-[11px] uppercase tracking-widest">Guardar</span>
                </button>
                <button id="ai-reminder-btn" class="col-span-2 bg-violet-600 text-white p-5 rounded-3xl font-black shadow-xl hover:bg-violet-700 flex items-center justify-center gap-3 transition-all active:scale-95 border-b-4 border-violet-950 uppercase text-xs tracking-[0.2em]">
                    ✨ Enviar Recordatorio
                </button>
            </div>
        </div>

        <!-- Historial Robustecido -->
        <div id="history-section" class="w-full max-w-md bg-white p-6 rounded-[3rem] shadow-lg mt-8 hidden lg:block border border-gray-200">
            <div class="flex justify-between items-center mb-6 px-2">
                <h3 class="font-black text-black text-xs uppercase tracking-widest flex items-center gap-3">
                    <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round" class="text-blue-600"><circle cx="12" cy="12" r="10"></circle><polyline points="12 6 12 12 16 14"></polyline></svg>
                    Historial de Dispositivo
                </h3>
                <button id="clear-history-btn" class="text-[9px] font-black text-red-500 uppercase hover:underline">Borrar Todo</button>
            </div>
            <div id="history-list" class="space-y-4 max-h-80 overflow-y-auto pr-2 px-1"></div>
        </div>
    </div>

    <!-- MODAL RECORDATORIO IA -->
    <div id="ai-reminder-modal" class="fixed inset-0 bg-black/80 flex items-center justify-center hidden z-50 p-4 backdrop-blur-md">
        <div class="bg-white w-full max-w-md rounded-[3rem] p-10 shadow-2xl animate-fade-in relative text-center">
            <h3 class="text-3xl font-black text-violet-700 mb-6 font-black">✨ Mensaje Listo</h3>
            <textarea id="ai-reminder-output" rows="8" class="w-full p-6 border-2 border-black rounded-[2rem] bg-violet-50/20 text-black text-sm font-black focus:ring-4 focus:ring-violet-200 outline-none leading-relaxed resize-none" readonly></textarea>
            <div class="grid grid-cols-2 gap-4 mt-8">
                <button id="copy-reminder-btn" class="bg-violet-600 text-white py-5 rounded-2xl font-black shadow-xl hover:bg-violet-700 transition-all active:scale-95 uppercase text-xs">Copiar</button>
                <button id="close-reminder-modal" class="bg-slate-200 text-black py-5 rounded-2xl font-black hover:bg-slate-300 transition-all active:scale-95 uppercase text-xs font-black">Cerrar</button>
            </div>
        </div>
    </div>

    <script>
        // --- CONFIGURACIÓN ---
        const apiKey = "";
        const geminiUrl = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-preview-09-2025:generateContent?key=${apiKey}`;
        const HISTORY_KEY = 'notes_db_final_v1';
        
        let currentStep = 0;
        const steps = [
            { question: "¡Hola! 👋 Soy tu asistente de Llantera Cofradía. ¿A nombre de qué **cliente** hacemos la nota?", key: "cliente" },
            { question: "¿Cuál es el **monto total** a cobrar?", key: "total", type: "number" },
            { question: "Entendido. Ahora por favor, **toma la foto de la evidencia** con tu cámara.", key: "evidencia", type: "camera" },
            { question: "¿Qué servicio realizamos? (Escribe la descripción final)", key: "descripcion" },
            { question: "¿Deseas que le **quite el fondo** a la foto con IA?", key: "bg_remove", type: "confirm" },
            { question: "¡Excelente! He terminado el ticket.", key: "final", type: "actions" }
        ];

        let data = { cliente: "", total: 0, evidencia: "", descripcion: "", folio: "", fecha: "", hora: "" };

        // Referencias
        const chatBox = document.getElementById('chat-box');
        const botInput = document.getElementById('bot-input');
        const botSendBtn = document.getElementById('bot-send-btn');
        const inputArea = document.getElementById('input-container');
        const cameraArea = document.getElementById('camera-container');
        const cameraInput = document.getElementById('camera-input');
        const confirmArea = document.getElementById('confirm-container');
        const logoInput = document.getElementById('logo-input');
        const logoImg = document.getElementById('logo-img');
        
        const clienteOut = document.getElementById('cliente-output');
        const totalOut = document.getElementById('total-output');
        const folioOut = document.getElementById('folio-output');
        const fechaOut = document.getElementById('fecha-output');
        const horaOut = document.getElementById('hora-output');
        const descOut = document.getElementById('descripcion-output');
        const evidenceImg = document.getElementById('evidence-image');
        const evidenceCont = document.getElementById('evidence-container');
        const finalActions = document.getElementById('final-actions');
        const historyList = document.getElementById('history-list');

        // --- BOT LOGIC ---

        function addMessage(text, isBot = true) {
            const div = document.createElement('div');
            div.className = `flex ${isBot ? 'justify-start' : 'justify-end'} animate-fade-in`;
            div.innerHTML = `
                <div class="${isBot ? 'bg-white border-blue-100 border-2 text-black' : 'bg-blue-600 text-white shadow-blue-100 shadow-lg'} max-w-[85%] p-4 rounded-2xl text-sm leading-relaxed font-black">
                    ${text}
                </div>
            `;
            chatBox.appendChild(div);
            chatBox.scrollTop = chatBox.scrollHeight;
        }

        async function processStep(val) {
            const step = steps[currentStep];
            
            if (step.key === "cliente") {
                data.cliente = val;
                clienteOut.textContent = val;
                addMessage(val, false);
            } else if (step.key === "total") {
                data.total = parseFloat(val) || 0;
                totalOut.textContent = `$${data.total.toFixed(2)}`;
                addMessage(`$${val}`, false);
            } else if (step.key === "descripcion") {
                data.descripcion = val;
                descOut.textContent = val;
                addMessage(val, false);
            }

            currentStep++;
            if (currentStep < steps.length) askNext();
            else showFinal();
        }

        function askNext() {
            const next = steps[currentStep];
            addMessage(next.question);

            inputArea.classList.add('hidden');
            cameraArea.classList.add('hidden');
            confirmArea.classList.add('hidden');

            if (next.type === "camera") cameraArea.classList.remove('hidden');
            else if (next.type === "confirm") confirmArea.classList.remove('hidden');
            else if (next.type === "actions") showFinal();
            else {
                inputArea.classList.remove('hidden');
                botInput.type = next.type === "number" ? "number" : "text";
                botInput.value = (next.key === "descripcion" && data.descripcion) ? data.descripcion : "";
                botInput.focus();
            }
        }

        window.handleConfirm = (res) => {
            addMessage(res ? "Sí, quitar fondo" : "No, así está bien", false);
            if (res) removeBackground();
            else processStep("Confirmado");
        }

        function showFinal() {
            finalActions.classList.remove('hidden');
            data.folio = folioOut.textContent;
            data.fecha = fechaOut.textContent;
            data.hora = horaOut.textContent;
            saveToHistory();
            addMessage("¡Listo! El ticket ha sido generado y guardado en este dispositivo.");
        }

        // --- LOGO PERSISTENCIA ---
        logoInput.addEventListener('change', (e) => {
            const file = e.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = (event) => {
                    const base64 = event.target.result;
                    logoImg.src = base64;
                    logoImg.style.display = 'block';
                    localStorage.setItem('user_logo_v7', base64);
                    addMessage("¡Logotipo guardado!", true);
                };
                reader.readAsDataURL(file);
            }
        });

        // --- CÁMARA E IA ---
        cameraInput.addEventListener('change', async (e) => {