<?php
// ==========================================
// 1. CONFIGURACIÓN DE TU BASE DE DATOS CPANEL
// Reemplaza los datos entre comillas con los tuyos
// ==========================================
$db_host = 'localhost'; 
$db_name = 'rtosegur_comisiones'; // Ej: rto_comisiones
$db_user = 'rtosegur_rtosegur_comi333';       // Ej: rto_admin
$db_pass = 'Comisiones8016**';    // Ej: Rto8016*!

// ==========================================
// 2. API DEL SERVIDOR (NO MODIFICAR)
// ==========================================
if (isset($_GET['api'])) {
    header('Content-Type: application/json');
    try {
        $pdo = new PDO("mysql:host=$db_host;dbname=$db_name;charset=utf8mb4", $db_user, $db_pass);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        
        // Crear tabla automáticamente si no existe
        $pdo->exec("CREATE TABLE IF NOT EXISTS rto_app_data (
            doc_key VARCHAR(50) PRIMARY KEY,
            doc_value LONGTEXT
        )");

        if ($_SERVER['REQUEST_METHOD'] === 'GET') {
            $stmt = $pdo->query("SELECT doc_key, doc_value FROM rto_app_data");
            $result = ['config' => null, 'history' => null, 'pending_records' => null, 'pending_extras' => null];
            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                $result[$row['doc_key']] = json_decode($row['doc_value'], true);
            }
            echo json_encode(['success' => true, 'data' => $result]);
        }
        elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $input = json_decode(file_get_contents('php://input'), true);
            if (isset($input['doc_key']) && isset($input['doc_value'])) {
                $stmt = $pdo->prepare("INSERT INTO rto_app_data (doc_key, doc_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE doc_value = ?");
                $val = json_encode($input['doc_value']);
                $stmt->execute([$input['doc_key'], $val, $val]);
                echo json_encode(['success' => true]);
            } else {
                echo json_encode(['success' => false, 'error' => 'Datos incompletos']);
            }
        }
    } catch (PDOException $e) {
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
    exit;
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Planilla Comisiones - RTO Seguros</title>
    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- React & ReactDOM -->
    <script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
    <!-- Babel para JSX -->
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
    <!-- jsPDF para PDFs -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.5.28/jspdf.plugin.autotable.min.js"></script>
    <!-- SheetJS para Excel -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
    
    <style>
        body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background-color: #f0f4f8; }
        .hide-scroll::-webkit-scrollbar { display: none; }
        .hide-scroll { -ms-overflow-style: none; scrollbar-width: none; }
        .glass-card { background: rgba(255, 255, 255, 0.95); backdrop-filter: blur(10px); }
    </style>
</head>
<body>
    <img id="rto-logo" src="https://www.rtoseguros.com/wp-content/uploads/2026/06/LOGO-TEXTO-JP.jpg" crossOrigin="anonymous" style="display:none;" alt="Logo RTO Seguros" />
    <div id="root"></div>

    <script type="text/babel">
        const { useState, useEffect, useMemo } = React;

        const IconSettings = () => <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"></path><circle cx="12" cy="12" r="3"></circle></svg>;
        const IconPlus = () => <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="12" y1="5" x2="12" y2="19"></line><line x1="5" y1="12" x2="19" y2="12"></line></svg>;
        const IconTrash = () => <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="3 6 5 6 21 6"></polyline><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path></svg>;
        const IconEdit = () => <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"></path></svg>;
        const IconFileText = () => <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path><polyline points="14 2 14 8 20 8"></polyline><line x1="16" y1="13" x2="8" y2="13"></line><line x1="16" y1="17" x2="8" y2="17"></line><polyline points="10 9 9 9 8 9"></polyline></svg>;
        const IconFolder = () => <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"></path></svg>;
        const IconDownload = () => <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="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>;
        const IconLock = () => <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect><path d="M7 11V7a5 5 0 0 1 10 0v4"></path></svg>;
        const IconInfo = () => <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="16" x2="12" y2="12"></line><line x1="12" y1="8" x2="12.01" y2="8"></line></svg>;
        const IconCloud = () => <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M18 10h-1.26A8 8 0 1 0 9 20h9a5 5 0 0 0 0-10z"></path></svg>;

        const formatCurrency = (value) => {
            return new Intl.NumberFormat('es-CO', { style: 'currency', currency: 'COP', maximumFractionDigits: 0 }).format(value);
        };

        const App = () => {
            const [currentDate, setCurrentDate] = useState(new Date().toLocaleDateString('es-CO'));
            const [records, setRecords] = useState([]);
            
            // Estado Sincronizado (DB y Local)
            const [advisors, setAdvisors] = useState([]);
            const [companies, setCompanies] = useState([]);
            const [branches, setBranches] = useState([]);
            const [historyData, setHistoryData] = useState([]);
            const [pendingRecords, setPendingRecords] = useState([]);
            const [pendingExtras, setPendingExtras] = useState([]); 
            const [currentExtras, setCurrentExtras] = useState([]); 

            // Estado UI de red
            const [dbStatus, setDbStatus] = useState('Conectando...');

            const [selectedAdvisor, setSelectedAdvisor] = useState('');
            const [cutoffDate, setCutoffDate] = useState('');
            const [client, setClient] = useState('');
            const [policy, setPolicy] = useState('');
            const [netPremium, setNetPremium] = useState('');
            const [selectedCompany, setSelectedCompany] = useState('');
            const [selectedBranch, setSelectedBranch] = useState('');

            // Estado para el formulario de Extras (Descuentos/Adicionales)
            const [extraDesc, setExtraDesc] = useState('');
            const [extraAmount, setExtraAmount] = useState('');
            const [extraType, setExtraType] = useState('descuento');

            const [isConfigOpen, setIsConfigOpen] = useState(false);
            const [isHistoryOpen, setIsHistoryOpen] = useState(false);
            const [isExportModalOpen, setIsExportModalOpen] = useState(false);
            const [editingRecord, setEditingRecord] = useState(null);
            const [activeHistoryId, setActiveHistoryId] = useState(null);

            // Estado para Cuadros de Diálogo Personalizados
            const [dialog, setDialog] = useState(null);

            useEffect(() => {
                fetch('?api=true')
                    .then(async res => {
                        const text = await res.text();
                        try {
                            return JSON.parse(text);
                        } catch (e) {
                            throw new Error("Respuesta no válida del servidor: " + text.substring(0, 60));
                        }
                    })
                    .then(res => {
                        if (res.success) {
                            if (res.data.config) {
                                const loadedAdvisors = res.data.config.advisors || [];
                                setAdvisors(loadedAdvisors.map(a => typeof a === 'string' ? {name: a, account: ''} : a));
                                setCompanies(res.data.config.companies || []);
                                setBranches(res.data.config.branches || []);
                            }
                            if (res.data.history) {
                                setHistoryData(res.data.history || []);
                            }
                            if (res.data.pending_records) {
                                setPendingRecords(res.data.pending_records || []);
                            }
                            if (res.data.pending_extras) {
                                setPendingExtras(res.data.pending_extras || []);
                            }
                            setDbStatus('En Línea');
                        } else {
                            throw new Error(res.error);
                        }
                    })
                    .catch(err => {
                        console.warn("Fallo conexión a DB, usando respaldo local.", err);
                        setDbStatus('Error DB: ' + err.message);
                        setDialog({ 
                            message: 'Aviso: El sistema está usando la memoria local de tu computador. Hubo un fallo conectando con la Base de Datos. Detalle del error: ' + err.message, 
                            type: 'alert' 
                        });
                        const localAdvisors = JSON.parse(localStorage.getItem('rto_advisors')) || [];
                        setAdvisors(localAdvisors.map(a => typeof a === 'string' ? {name: a, account: ''} : a));
                        setCompanies(JSON.parse(localStorage.getItem('rto_companies')) || []);
                        setBranches(JSON.parse(localStorage.getItem('rto_branches')) || []);
                        setHistoryData(JSON.parse(localStorage.getItem('rto_history')) || []);
                        setPendingRecords(JSON.parse(localStorage.getItem('rto_pending')) || []);
                        setPendingExtras(JSON.parse(localStorage.getItem('rto_pending_extras')) || []);
                    });
            }, []);

            const forceSyncToCloud = () => {
                setDialog({ message: 'Sincronizando la memoria de este equipo hacia la Nube...', type: 'alert' });
                Promise.all([
                    fetch('?api=true', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ doc_key: 'config', doc_value: { advisors, companies, branches } }) }),
                    fetch('?api=true', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ doc_key: 'history', doc_value: historyData }) }),
                    fetch('?api=true', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ doc_key: 'pending_records', doc_value: pendingRecords }) }),
                    fetch('?api=true', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ doc_key: 'pending_extras', doc_value: pendingExtras }) })
                ]).then(() => {
                    setDialog({ message: '¡Sincronización exitosa! Los datos de este computador ahora están en la Base de Datos.', type: 'alert' });
                    setDbStatus('En Línea');
                }).catch(e => {
                    setDialog({ message: 'Error al sincronizar: ' + e.message, type: 'alert' });
                });
            };

            const saveConfig = (newAdvisors, newCompanies, newBranches) => {
                setAdvisors(newAdvisors);
                setCompanies(newCompanies);
                setBranches(newBranches);

                localStorage.setItem('rto_advisors', JSON.stringify(newAdvisors));
                localStorage.setItem('rto_companies', JSON.stringify(newCompanies));
                localStorage.setItem('rto_branches', JSON.stringify(newBranches));

                fetch('?api=true', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ doc_key: 'config', doc_value: { advisors: newAdvisors, companies: newCompanies, branches: newBranches } })
                }).catch(e => console.warn('No se pudo guardar en DB', e));
            };

            const saveHistory = (newHistoryData) => {
                setHistoryData(newHistoryData);
                localStorage.setItem('rto_history', JSON.stringify(newHistoryData));

                fetch('?api=true', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ doc_key: 'history', doc_value: newHistoryData })
                }).catch(e => console.warn('No se pudo guardar historial en DB', e));
            };

            const savePendingRecords = (newPendingRecords) => {
                setPendingRecords(newPendingRecords);
                localStorage.setItem('rto_pending', JSON.stringify(newPendingRecords));

                fetch('?api=true', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ doc_key: 'pending_records', doc_value: newPendingRecords })
                }).catch(e => console.warn('No se pudo guardar pendientes en DB', e));
            };

            const savePendingExtras = (newPendingExtras) => {
                setPendingExtras(newPendingExtras);
                localStorage.setItem('rto_pending_extras', JSON.stringify(newPendingExtras));

                fetch('?api=true', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ doc_key: 'pending_extras', doc_value: newPendingExtras })
                }).catch(e => console.warn('No se pudo guardar extras en DB', e));
            };

            const handleAddRecord = (e, isPending = false) => {
                e.preventDefault();
                if (!client || !policy || !netPremium || !selectedCompany || !selectedBranch) {
                    setDialog({ message: 'Por favor llene todos los campos del registro.', type: 'alert' });
                    return;
                }

                if (isPending && !selectedAdvisor) {
                    setDialog({ message: 'Para guardar un negocio como PENDIENTE en la nube, debe seleccionar primero al ASESOR en la parte superior.', type: 'alert' });
                    return;
                }

                const branchData = branches.find(b => b.name === selectedBranch);
                const commissionRate = branchData ? branchData.rate : 0;
                const calculatedCommission = Math.round(Number(netPremium) * (commissionRate / 100));

                const newRecord = {
                    id: editingRecord ? editingRecord.id : Date.now(),
                    client: client.toUpperCase(),
                    policy: policy.substring(0, 40),
                    netPremium: Number(netPremium),
                    company: selectedCompany,
                    branch: selectedBranch,
                    commissionRate: commissionRate,
                    commission: calculatedCommission,
                    advisor: isPending ? selectedAdvisor : (editingRecord?.advisor || selectedAdvisor)
                };

                const processSave = () => {
                    if (isPending) {
                        if (editingRecord && editingRecord.isPending) {
                            savePendingRecords(pendingRecords.map(r => r.id === editingRecord.id ? newRecord : r));
                        } else {
                            savePendingRecords([...pendingRecords, newRecord]);
                            if (editingRecord && !editingRecord.isPending) {
                                setRecords(records.filter(r => r.id !== editingRecord.id));
                            }
                        }
                        setDialog({ message: 'Negocio guardado en la Nube como PENDIENTE exitosamente.', type: 'alert' });
                    } else {
                        if (editingRecord && editingRecord.isPending) {
                            savePendingRecords(pendingRecords.filter(r => r.id !== editingRecord.id));
                            setRecords([...records, newRecord]);
                        } else if (editingRecord && !editingRecord.isPending) {
                            setRecords(records.map(r => r.id === editingRecord.id ? newRecord : r));
                        } else {
                            setRecords([...records, newRecord]);
                        }
                    }

                    setEditingRecord(null);
                    setClient('');
                    setPolicy('');
                    setNetPremium('');
                    setSelectedCompany('');
                    setSelectedBranch('');
                };

                // VALIDACIÓN DE PÓLIZAS DUPLICADAS
                const polToCheck = policy.substring(0, 40).trim().toLowerCase();
                
                // Si solo estamos editando el registro actual y no cambiamos el # de póliza, guardamos normal
                if (editingRecord && editingRecord.policy.trim().toLowerCase() === polToCheck) {
                    processSave();
                    return;
                }

                let duplicateLocation = null;
                
                // 1. Buscar en el Historial
                for (const h of historyData) {
                    if (activeHistoryId && h.id === activeHistoryId) continue; // Si editamos una planilla vieja, ignoramos sus propios registros
                    if (h.records.find(r => r.policy.trim().toLowerCase() === polToCheck)) {
                        duplicateLocation = `el Historial (Asesor: ${h.advisor}, Corte: ${h.cutoff || h.generationDate})`;
                        break;
                    }
                }

                // 2. Buscar en Pendientes Nube
                if (!duplicateLocation) {
                    const pend = pendingRecords.find(r => r.policy.trim().toLowerCase() === polToCheck && r.id !== (editingRecord?.id || null));
                    if (pend) duplicateLocation = `los Negocios Pendientes (Asesor: ${pend.advisor || 'No asignado'})`;
                }

                // 3. Buscar en la Planilla Activa (Pantalla)
                if (!duplicateLocation) {
                    const act = records.find(r => r.policy.trim().toLowerCase() === polToCheck && r.id !== (editingRecord?.id || null));
                    if (act) duplicateLocation = `esta misma Planilla en pantalla`;
                }

                if (duplicateLocation) {
                    setDialog({
                        message: `¡ALERTA! La póliza ${policy} ya se encuentra registrada en ${duplicateLocation}. ¿Deseas continuar y cargarla de todas formas?`,
                        type: 'confirm',
                        onConfirm: () => {
                            processSave();
                            setDialog(null);
                        }
                    });
                } else {
                    processSave();
                }
            };

            const handleEditRecord = (record, isPending = false) => {
                setEditingRecord({...record, isPending});
                setClient(record.client);
                setPolicy(record.policy);
                setNetPremium(record.netPremium);
                setSelectedCompany(record.company);
                setSelectedBranch(record.branch);
            };

            const handleDeleteRecord = (id) => {
                setRecords(records.filter(r => r.id !== id));
            };

            const handleAddExtra = (e, isPending = false) => {
                e.preventDefault();
                if (!extraDesc || !extraAmount) {
                    setDialog({ message: 'Por favor llene la descripción y el valor del rubro.', type: 'alert' });
                    return;
                }

                if (isPending && !selectedAdvisor) {
                    setDialog({ message: 'Para guardar un rubro como PENDIENTE en la nube, debe seleccionar primero al ASESOR en la parte superior.', type: 'alert' });
                    return;
                }

                const newExtra = {
                    id: Date.now(),
                    desc: extraDesc.toUpperCase(),
                    amount: Number(extraAmount),
                    type: extraType,
                    advisor: selectedAdvisor
                };

                if (isPending) {
                    savePendingExtras([...pendingExtras, newExtra]);
                    setDialog({ message: 'Rubro guardado en la Nube como PENDIENTE exitosamente.', type: 'alert' });
                } else {
                    setCurrentExtras([...currentExtras, newExtra]);
                }

                setExtraDesc('');
                setExtraAmount('');
            };

            const handleDeleteExtra = (id, isPending = false) => {
                if (isPending) {
                    savePendingExtras(pendingExtras.filter(x => x.id !== id));
                } else {
                    setCurrentExtras(currentExtras.filter(x => x.id !== id));
                }
            };

            const calculations = useMemo(() => {
                let comisionesNetas = 0;
                const branchTotals = {};

                records.forEach(r => {
                    comisionesNetas += r.commission;
                    branchTotals[r.branch] = (branchTotals[r.branch] || 0) + r.commission;
                });

                const rteFte = Math.round(comisionesNetas * 0.10);
                const rteIca = Math.round(comisionesNetas * 0.01104);
                const comisionMenosImpuestos = Math.round(comisionesNetas - rteFte - rteIca);
                
                const baseSeguridadSocial = Math.round(comisionMenosImpuestos * 0.40);
                const salud = Math.round(baseSeguridadSocial * 0.125);
                const pension = Math.round(baseSeguridadSocial * 0.16);
                const arl = Math.round(baseSeguridadSocial * 0.00522);
                const totalPila = salud + pension + arl;

                const comisionDescontandoPila = Math.round(comisionMenosImpuestos - totalPila);
                
                const asesor80 = Math.round(comisionDescontandoPila * 0.80);
                const rto20 = Math.round(comisionDescontandoPila * 0.20);

                let totalDescuentos = 0;
                let totalAdicionales = 0;
                
                currentExtras.forEach(ex => {
                    if (ex.type === 'descuento') totalDescuentos += ex.amount;
                    else if (ex.type === 'adicional') totalAdicionales += ex.amount;
                });
                
                const netExtras = totalAdicionales - totalDescuentos;
                const asesorFinal = asesor80 + netExtras;

                return {
                    branchTotals,
                    comisionesNetas,
                    rteFte,
                    rteIca,
                    comisionMenosImpuestos,
                    baseSeguridadSocial,
                    salud,
                    pension,
                    arl,
                    totalPila,
                    comisionDescontandoPila,
                    asesor80,
                    rto20,
                    totalDescuentos,
                    totalAdicionales,
                    netExtras,
                    asesorFinal
                };
            }, [records, currentExtras]);

            const handleEditHistoryItem = (item) => {
                if (records.length > 0 || currentExtras.length > 0) {
                    setDialog({
                        message: "Tienes registros actuales sin guardar. Si continúas, se sobrescribirán con los del historial. ¿Deseas editar esta planilla?",
                        type: 'confirm',
                        onConfirm: () => {
                            setActiveHistoryId(item.id);
                            setSelectedAdvisor(item.advisor);
                            setCutoffDate(item.cutoff);
                            setRecords(item.records);
                            setCurrentExtras(item.currentExtras || []);
                            setIsHistoryOpen(false);
                            setDialog(null);
                        }
                    });
                    return;
                }
                setActiveHistoryId(item.id);
                setSelectedAdvisor(item.advisor);
                setCutoffDate(item.cutoff);
                setRecords(item.records);
                setCurrentExtras(item.currentExtras || []);
                setIsHistoryOpen(false);
            };

            const executeExportPDF = (saveToFile, recordsToPrint, calcToPrint, extrasToPrint, advisor, cutoff) => {
                const doc = new window.jspdf.jsPDF();
                const pageWidth = doc.internal.pageSize.width;
                const currentAdv = advisors.find(a => a.name === advisor) || {name: advisor, account: ''};
                
                // --- 1. ENCABEZADO PROFESIONAL ---
                doc.setFillColor(22, 101, 52); // Verde Institucional RTO (green-800)
                doc.rect(0, 0, pageWidth, 28, 'F');
                
                doc.setTextColor(255, 255, 255);
                doc.setFontSize(20);
                doc.setFont(undefined, 'bold');
                doc.text("LIQUIDACIÓN DE COMISIONES", 14, 18);
                
                const logoEl = document.getElementById('rto-logo');
                if (logoEl && logoEl.complete && logoEl.naturalWidth > 0) {
                    try {
                        const imgWidth = 40;
                        const imgHeight = (logoEl.naturalHeight * imgWidth) / logoEl.naturalWidth;
                        // Fondo blanco para que el logo resalte sobre el encabezado verde
                        doc.setFillColor(255, 255, 255);
                        doc.roundedRect(pageWidth - 14 - imgWidth - 2, 4, imgWidth + 4, imgHeight + 4, 2, 2, 'F');
                        doc.addImage(logoEl, 'JPEG', pageWidth - 14 - imgWidth, 6, imgWidth, imgHeight);
                    } catch(e) {
                        console.warn("Restricción en carga de Logo", e);
                    }
                }

                // --- 2. DATOS DE IDENTIFICACIÓN ---
                doc.setTextColor(50, 50, 50);
                doc.setFontSize(11);
                doc.setFont(undefined, 'bold');
                doc.text(`Asesor:`, 14, 40);
                doc.setFont(undefined, 'normal');
                doc.text(`${(advisor || 'NO ESPECIFICADO').toUpperCase()}`, 30, 40);
                
                doc.setFont(undefined, 'bold');
                doc.text(`Corte:`, 14, 46);
                doc.setFont(undefined, 'normal');
                doc.text(`${cutoff || 'N/A'}`, 30, 46);
                
                doc.setFont(undefined, 'bold');
                doc.text(`Cuenta / Llave:`, 14, 52);
                doc.setFont(undefined, 'normal');
                doc.text(`${currentAdv.account || 'No registrada'}`, 42, 52);

                doc.setFont(undefined, 'bold');
                doc.text(`Generado:`, pageWidth - 60, 40);
                doc.setFont(undefined, 'normal');
                doc.text(`${currentDate}`, pageWidth - 40, 40);

                let finalY = 60;

                // --- 3. TABLA DE NEGOCIOS ---
                const tableColumn = ["Cliente", "Póliza", "Cía.", "Ramo", "Prima Neta", "Comisión"];
                const tableRows = recordsToPrint.map(r => [
                    r.client, r.policy, r.company, r.branch,
                    formatCurrency(r.netPremium), formatCurrency(r.commission)
                ]);

                doc.autoTable({
                    startY: finalY,
                    head: [tableColumn],
                    body: tableRows,
                    theme: 'grid',
                    headStyles: { fillColor: [22, 101, 52], textColor: 255, fontStyle: 'bold' }, // Verde RTO (antes azul)
                    alternateRowStyles: { fillColor: [243, 244, 246] }, // Gris claro (gray-100)
                    styles: { fontSize: 8, cellPadding: 3 },
                    columnStyles: {
                        4: { halign: 'right' },
                        5: { halign: 'right', fontStyle: 'bold', textColor: [21, 128, 61] } // Verde para la comisión
                    }
                });

                finalY = doc.lastAutoTable.finalY + 10;

                // --- 4. TABLA DE AJUSTES Y DESCUENTOS (SI EXISTEN) ---
                if (extrasToPrint && extrasToPrint.length > 0) {
                    doc.setFontSize(11);
                    doc.setTextColor(30, 58, 138); // Azul (blue-900) - (antes morado)
                    doc.setFont(undefined, 'bold');
                    doc.text("Ajustes Adicionales y Descuentos Aplicados", 14, finalY);
                    
                    doc.autoTable({
                        startY: finalY + 4,
                        head: [["Tipo de Ajuste", "Concepto / Descripción", "Valor"]],
                        body: extrasToPrint.map(ex => [
                            ex.type === 'descuento' ? 'DESCUENTO (-)' : 'ADICIONAL (+)',
                            ex.desc,
                            formatCurrency(ex.amount)
                        ]),
                        theme: 'grid',
                        headStyles: { fillColor: [30, 58, 138], textColor: 255, fontStyle: 'bold' }, // Azul (antes morado)
                        alternateRowStyles: { fillColor: [239, 246, 255] }, // Fondo azul super claro
                        styles: { fontSize: 8, cellPadding: 3 },
                        columnStyles: {
                            0: { fontStyle: 'bold', cellWidth: 40 },
                            2: { halign: 'right', fontStyle: 'bold', cellWidth: 40 }
                        },
                        didParseCell: function(data) {
                            if (data.section === 'body' && data.column.index === 2) {
                                const isDesc = extrasToPrint[data.row.index].type === 'descuento';
                                data.cell.styles.textColor = isDesc ? [220, 38, 38] : [22, 163, 74];
                            }
                            if (data.section === 'body' && data.column.index === 0) {
                                const isDesc = extrasToPrint[data.row.index].type === 'descuento';
                                data.cell.styles.textColor = isDesc ? [220, 38, 38] : [22, 163, 74];
                            }
                        }
                    });
                    finalY = doc.lastAutoTable.finalY + 10;
                }

                // Evitar que el cuadro de resumen se corte al final de la página
                if (finalY > 210) {
                    doc.addPage();
                    finalY = 20;
                }

                // --- 5. CUADRO RESUMEN IMPUESTOS Y PILA (IZQUIERDA) ---
                doc.setFontSize(11);
                doc.setTextColor(31, 41, 55); // Gris oscuro
                doc.setFont(undefined, 'bold');
                doc.text("Liquidación de Impuestos y PILA", 14, finalY);

                const summaryData = [
                    ["Comisiones Netas", formatCurrency(calcToPrint.comisionesNetas)],
                    ["Rte Fte 10%", "- " + formatCurrency(calcToPrint.rteFte)],
                    ["Rte Ica 11,04 o/oo", "- " + formatCurrency(calcToPrint.rteIca)],
                    ["Comisión menos Impuestos", formatCurrency(calcToPrint.comisionMenosImpuestos)],
                    ["Base liq. Seg. Social (40%)", formatCurrency(calcToPrint.baseSeguridadSocial)],
                    ["Salud (12.5%)", "- " + formatCurrency(calcToPrint.salud)],
                    ["Pensión (16%)", "- " + formatCurrency(calcToPrint.pension)],
                    ["ARL (0.522%)", "- " + formatCurrency(calcToPrint.arl)],
                    ["Total PILA", "- " + formatCurrency(calcToPrint.totalPila)],
                    ["Comisión descontando PILA", formatCurrency(calcToPrint.comisionDescontandoPila)],
                ];

                doc.autoTable({
                    startY: finalY + 4,
                    body: summaryData,
                    theme: 'plain',
                    styles: { fontSize: 9, cellPadding: 2 },
                    columnStyles: { 
                        0: { fontStyle: 'bold', textColor: [75, 85, 99] }, 
                        1: { halign: 'right', fontStyle: 'bold' } 
                    },
                    didParseCell: function(data) {
                        if (data.row.index === 0 || data.row.index === 3 || data.row.index === 9) {
                            data.cell.styles.textColor = [17, 24, 39]; // Negro
                            if (data.row.index === 9) data.cell.styles.fillColor = [229, 231, 235]; // Fondo gris en el subtotal
                        }
                        if ([1, 2, 5, 6, 7, 8].includes(data.row.index) && data.column.index === 1) {
                            data.cell.styles.textColor = [220, 38, 38]; // Rojo para deducciones
                        }
                    },
                    margin: { left: 14, right: pageWidth / 2 + 10 } // Mitad izquierda de la hoja
                });

                // --- 6. BLOQUES DE TOTALES FINALES (DERECHA) ---
                const rightColX = pageWidth / 2 + 10;
                let rightColY = finalY + 4;
                const boxWidth = (pageWidth / 2) - 24;
                const borderRadius = 3; // Nivel de curvatura de las esquinas

                // Bloque: 80% Asesor Base
                doc.setFillColor(240, 253, 244); 
                doc.setDrawColor(34, 197, 94); 
                doc.roundedRect(rightColX, rightColY, boxWidth, 14, borderRadius, borderRadius, 'FD');
                doc.setFontSize(9);
                doc.setTextColor(21, 128, 61); 
                doc.text("80% ASESOR (BASE)", rightColX + 4, rightColY + 6);
                doc.setFontSize(11);
                doc.text(formatCurrency(calcToPrint.asesor80), rightColX + boxWidth - 4, rightColY + 10, { align: 'right' });
                rightColY += 16;

                // Bloque: Adicionales
                if (calcToPrint.totalAdicionales > 0) {
                    doc.setFillColor(247, 254, 231);
                    doc.setDrawColor(132, 204, 22);
                    doc.roundedRect(rightColX, rightColY, boxWidth, 12, borderRadius, borderRadius, 'FD');
                    doc.setFontSize(8);
                    doc.setTextColor(77, 124, 15);
                    doc.text("+ TOTAL ADICIONALES", rightColX + 4, rightColY + 8);
                    doc.setFontSize(10);
                    doc.text(formatCurrency(calcToPrint.totalAdicionales), rightColX + boxWidth - 4, rightColY + 8, { align: 'right' });
                    rightColY += 14;
                }

                // Bloque: Descuentos
                if (calcToPrint.totalDescuentos > 0) {
                    doc.setFillColor(254, 242, 242);
                    doc.setDrawColor(239, 68, 68);
                    doc.roundedRect(rightColX, rightColY, boxWidth, 12, borderRadius, borderRadius, 'FD');
                    doc.setFontSize(8);
                    doc.setTextColor(185, 28, 28);
                    doc.text("- TOTAL DESCUENTOS", rightColX + 4, rightColY + 8);
                    doc.setFontSize(10);
                    doc.text(formatCurrency(calcToPrint.totalDescuentos), rightColX + boxWidth - 4, rightColY + 8, { align: 'right' });
                    rightColY += 14;
                }

                // Bloque: GRAN TOTAL ASESOR
                doc.setFillColor(22, 101, 52); // green-800
                doc.roundedRect(rightColX, rightColY, boxWidth, 22, borderRadius, borderRadius, 'F');
                doc.setTextColor(255, 255, 255);
                doc.setFontSize(10);
                doc.text("TOTAL A PAGAR AL ASESOR", rightColX + boxWidth / 2, rightColY + 8, { align: 'center' });
                doc.setFontSize(15);
                doc.setFont(undefined, 'bold');
                doc.text(formatCurrency(calcToPrint.asesorFinal), rightColX + boxWidth / 2, rightColY + 16, { align: 'center' });
                rightColY += 26;

                // Bloque: 20% RTO SEGUROS
                doc.setFillColor(30, 58, 138); // blue-900
                doc.roundedRect(rightColX, rightColY, boxWidth, 18, borderRadius, borderRadius, 'F');
                doc.setTextColor(255, 255, 255);
                doc.setFontSize(9);
                doc.text("20% RTO SEGUROS", rightColX + boxWidth / 2, rightColY + 7, { align: 'center' });
                doc.setFontSize(13);
                doc.text(formatCurrency(calcToPrint.rto20), rightColX + boxWidth / 2, rightColY + 14, { align: 'center' });

                const fileName = `${advisor || 'Asesor'}_${cutoff || 'Fecha'}.pdf`;
                
                if (saveToFile) {
                    doc.save(fileName);
                } else {
                    window.open(doc.output('bloburl'), '_blank');
                }
            };

            const executeExportExcel = (recordsToPrint, calcToPrint, advisor, cutoff) => {
                const currentAdv = advisors.find(a => a.name === advisor) || {name: advisor, account: ''};
                const wb = window.XLSX.utils.book_new();
                const wsData = [
                    [`Asesor: ${advisor}`, `Cuenta/Llave: ${currentAdv.account || 'No registrada'}`, `Fecha Corte: ${cutoff}`, `Fecha Generación: ${currentDate}`],
                    [],
                    ["CLIENTE", "PÓLIZA", "COMPAÑÍA", "RAMO", "PRIMA NETA", "COMISIÓN"],
                    ...recordsToPrint.map(r => [r.client, r.policy, r.company, r.branch, r.netPremium, r.commission]),
                    [],
                    ["RESUMEN DE LIQUIDACIÓN"],
                    ["Comisiones Netas", calcToPrint.comisionesNetas],
                    ["Rte Fte 10%", calcToPrint.rteFte],
                    ["Rte Ica 11,04 o/oo", calcToPrint.rteIca],
                    ["Comisión menos Impuestos", calcToPrint.comisionMenosImpuestos],
                    ["Base liquidación Seg. Social", calcToPrint.baseSeguridadSocial],
                    ["Salud", calcToPrint.salud],
                    ["Pensión", calcToPrint.pension],
                    ["ARL", calcToPrint.arl],
                    ["Total PILA", calcToPrint.totalPila],
                    ["Comisión descontando PILA", calcToPrint.comisionDescontandoPila],
                    [],
                    ["80% ASESOR BASE", calcToPrint.asesor80],
                    ["+ PAGOS ADICIONALES", calcToPrint.totalAdicionales],
                    ["- DESCUENTOS", calcToPrint.totalDescuentos],
                    ["TOTAL A PAGAR AL ASESOR", calcToPrint.asesorFinal],
                    ["20% RTO SEGUROS", calcToPrint.rto20]
                ];

                const ws = window.XLSX.utils.aoa_to_sheet(wsData);
                window.XLSX.utils.book_append_sheet(wb, ws, "Planilla");
                const fileName = `${advisor || 'Asesor'}_${cutoff || 'Fecha'}.xlsx`;
                window.XLSX.writeFile(wb, fileName);
            };

            const handleExportSelection = (type) => {
                if (type === 'imprimir') {
                    executeExportPDF(false, records, calculations, currentExtras, selectedAdvisor, cutoffDate);
                } else if (type === 'almacenar') {
                    executeExportPDF(true, records, calculations, currentExtras, selectedAdvisor, cutoffDate);
                    executeExportExcel(records, calculations, selectedAdvisor, cutoffDate);
                    
                    if (activeHistoryId) {
                        const updatedHistory = historyData.map(item => item.id === activeHistoryId ? {
                            ...item,
                            generationDate: currentDate,
                            advisor: selectedAdvisor,
                            cutoff: cutoffDate,
                            records: [...records],
                            currentExtras: [...currentExtras],
                            calculations: calculations
                        } : item);
                        saveHistory(updatedHistory);
                        setActiveHistoryId(null);
                        setDialog({ message: "¡Planilla actualizada y guardada exitosamente en el Historial del Servidor!", type: 'alert' });
                    } else {
                        const newHistoryEntry = {
                            id: Date.now(),
                            generationDate: currentDate,
                            advisor: selectedAdvisor,
                            cutoff: cutoffDate,
                            records: [...records],
                            currentExtras: [...currentExtras],
                            calculations: calculations
                        };
                        saveHistory([newHistoryEntry, ...historyData]);
                        setDialog({ message: "¡Planilla generada y guardada exitosamente en el Historial del Servidor!", type: 'alert' });
                    }
                }
                setIsExportModalOpen(false);
            };

            const currentAdvObj = advisors.find(a => a.name === selectedAdvisor);

            return (
                <div className="min-h-screen pb-20 font-sans relative">
                    <header className="bg-gradient-to-r from-green-800 via-green-700 to-green-800 text-white shadow-lg sticky top-0 z-20">
                        <div className="max-w-7xl mx-auto px-4 py-3 flex flex-col sm:flex-row justify-between items-center gap-3">
                            <div className="flex items-center gap-4">
                                <div className="bg-white p-1.5 rounded-xl shadow-md border-2 border-green-400/30">
                                    <img src="https://www.rtoseguros.com/wp-content/uploads/2026/06/LOGO-TEXTO-JP.jpg" alt="RTO Seguros Logo" className="h-10 w-auto object-contain"/>
                                </div>
                                <div className="text-left">
                                    <h1 className="text-xl md:text-2xl font-black tracking-tight">LIQUIDADOR DE COMISIONES</h1>
                                    <p className="text-xs text-green-200 font-medium">Asistente Vito | Status DB: {dbStatus}</p>
                                </div>
                            </div>
                            <div className="flex items-center gap-2">
                                <button onClick={() => setIsHistoryOpen(true)} className="flex items-center gap-2 bg-green-700/50 hover:bg-green-600 border border-green-500/50 px-4 py-2 rounded-xl transition font-semibold text-sm shadow-sm backdrop-blur-sm">
                                    <IconFolder /> <span className="hidden sm:inline">Historial</span>
                                </button>
                                <button onClick={() => setIsConfigOpen(true)} className="flex items-center gap-2 bg-green-700/50 hover:bg-green-600 border border-green-500/50 px-4 py-2 rounded-xl transition font-semibold text-sm shadow-sm backdrop-blur-sm">
                                    <IconSettings /> <span className="hidden sm:inline">Configuración</span>
                                </button>
                            </div>
                        </div>
                    </header>

                    {dialog && (
                        <div className="fixed inset-0 bg-gray-900/60 backdrop-blur-sm flex items-center justify-center p-4 z-[60]">
                            <div className="bg-white rounded-3xl shadow-2xl w-full max-w-sm p-8 text-center transform transition-all">
                                <div className="w-16 h-16 bg-blue-100 text-blue-600 rounded-full flex items-center justify-center mx-auto mb-4">
                                    <IconInfo />
                                </div>
                                <h2 className="text-xl font-black text-gray-800 mb-2">Aviso del Sistema</h2>
                                <p className="text-gray-600 mb-8 font-medium">{dialog.message}</p>
                                
                                <div className="flex justify-center gap-4">
                                    {dialog.type === 'confirm' && (
                                        <button onClick={() => setDialog(null)} className="px-6 py-2.5 bg-gray-100 hover:bg-gray-200 text-gray-700 font-bold rounded-xl transition">Cancelar</button>
                                    )}
                                    <button onClick={() => { if(dialog.type === 'confirm') dialog.onConfirm(); else setDialog(null); }} className="px-6 py-2.5 bg-blue-600 hover:bg-blue-700 text-white font-bold rounded-xl shadow-md transition">Aceptar</button>
                                </div>
                            </div>
                        </div>
                    )}

                    <main className="max-w-7xl mx-auto p-4 space-y-6 mt-4">
                        
                        <div className="glass-card p-6 rounded-2xl shadow-sm border border-gray-200 grid grid-cols-1 md:grid-cols-2 gap-6">
                            <div>
                                <label className="block text-sm font-bold text-gray-700 mb-2">SELECCIÓN DE ASESOR</label>
                                <select value={selectedAdvisor} onChange={(e) => setSelectedAdvisor(e.target.value)} className="w-full border-2 border-gray-200 rounded-xl p-3 bg-gray-50 focus:bg-white focus:border-blue-500 focus:ring-4 focus:ring-blue-500/20 outline-none transition text-gray-800 font-medium">
                                    <option value="">Seleccione un Asesor de la lista...</option>
                                    {advisors.map((a, i) => <option key={i} value={a.name}>{a.name} {a.account ? `- Cta: ${a.account}` : ''}</option>)}
                                </select>
                            </div>
                            <div>
                                <label className="block text-sm font-bold text-gray-700 mb-2">FECHA DE CORTE</label>
                                <input type="date" value={cutoffDate} onChange={(e) => setCutoffDate(e.target.value)} className="w-full border-2 border-gray-200 rounded-xl p-3 bg-gray-50 focus:bg-white focus:border-blue-500 focus:ring-4 focus:ring-blue-500/20 outline-none transition text-gray-800 font-medium"/>
                            </div>
                        </div>

                        <div className="glass-card p-6 rounded-2xl shadow-sm border border-gray-200">
                            <h2 className="text-lg font-black text-gray-800 mb-4 border-b border-gray-200 pb-3 flex items-center gap-2">
                                {editingRecord ? <IconEdit /> : <IconPlus />}
                                {editingRecord ? (editingRecord.isPending ? 'Editar Registro Pendiente' : 'Editar Registro de Planilla') : 'Ingresar Nuevo Negocio'}
                            </h2>
                            <form onSubmit={(e) => e.preventDefault()} className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-4 items-end">
                                <div className="lg:col-span-1">
                                    <label className="block text-xs font-bold text-gray-500 mb-1">CLIENTE</label>
                                    <input type="text" value={client} onChange={(e) => setClient(e.target.value.toUpperCase())} placeholder="Nombre Cliente" className="w-full border-2 border-gray-200 rounded-xl p-2.5 text-sm uppercase bg-gray-50 focus:bg-white focus:border-blue-500 focus:ring-4 focus:ring-blue-500/20 outline-none transition font-medium"/>
                                </div>
                                <div className="lg:col-span-1">
                                    <label className="block text-xs font-bold text-gray-500 mb-1">PÓLIZA (Max 40)</label>
                                    <input type="text" maxLength="40" value={policy} onChange={(e) => setPolicy(e.target.value)} placeholder="No. Póliza" className="w-full border-2 border-gray-200 rounded-xl p-2.5 text-sm bg-gray-50 focus:bg-white focus:border-blue-500 focus:ring-4 focus:ring-blue-500/20 outline-none transition font-medium"/>
                                </div>
                                <div className="lg:col-span-1">
                                    <label className="block text-xs font-bold text-gray-500 mb-1">COMPAÑÍA</label>
                                    <select value={selectedCompany} onChange={(e) => setSelectedCompany(e.target.value)} className="w-full border-2 border-gray-200 rounded-xl p-2.5 text-sm bg-gray-50 focus:bg-white focus:border-blue-500 focus:ring-4 focus:ring-blue-500/20 outline-none transition font-medium">
                                        <option value="">Seleccionar...</option>
                                        {companies.map((c, i) => <option key={i} value={c}>{c}</option>)}
                                    </select>
                                </div>
                                <div className="lg:col-span-1">
                                    <label className="block text-xs font-bold text-gray-500 mb-1">RAMO</label>
                                    <select value={selectedBranch} onChange={(e) => setSelectedBranch(e.target.value)} className="w-full border-2 border-gray-200 rounded-xl p-2.5 text-sm bg-gray-50 focus:bg-white focus:border-blue-500 focus:ring-4 focus:ring-blue-500/20 outline-none transition font-medium">
                                        <option value="">Seleccionar...</option>
                                        {branches.map((b, i) => <option key={i} value={b.name}>{b.name} ({b.rate}%)</option>)}
                                    </select>
                                </div>
                                <div className="lg:col-span-1">
                                    <label className="block text-xs font-bold text-gray-500 mb-1">PRIMA NETA (COP)</label>
                                    <input type="number" value={netPremium} onChange={(e) => setNetPremium(e.target.value)} placeholder="Ej: 1500000" className="w-full border-2 border-gray-200 rounded-xl p-2.5 text-sm bg-gray-50 focus:bg-white focus:border-blue-500 focus:ring-4 focus:ring-blue-500/20 outline-none transition font-medium"/>
                                </div>
                                
                                {/* Botones Dinámicos Nube / Planilla */}
                                <div className="sm:col-span-2 lg:col-span-5 flex flex-wrap justify-end gap-3 mt-2">
                                    {editingRecord && (
                                        <button type="button" onClick={() => { setEditingRecord(null); setClient(''); setPolicy(''); setNetPremium(''); setSelectedCompany(''); setSelectedBranch(''); }} className="px-5 py-2.5 text-sm font-bold text-gray-600 hover:bg-gray-100 rounded-xl transition">Cancelar</button>
                                    )}
                                    <button type="button" onClick={(e) => handleAddRecord(e, true)} className="flex items-center gap-2 bg-orange-500 hover:bg-orange-600 text-white px-6 py-2.5 rounded-xl font-bold shadow-md hover:shadow-lg transition text-sm">
                                        <IconCloud /> {editingRecord && editingRecord.isPending ? 'Actualizar Pendiente' : 'Guardar Pendiente (Nube)'}
                                    </button>
                                    <button type="button" onClick={(e) => handleAddRecord(e, false)} className="flex items-center gap-2 bg-blue-600 hover:bg-blue-700 text-white px-6 py-2.5 rounded-xl font-bold shadow-md hover:shadow-lg transition text-sm">
                                        <IconPlus /> {(editingRecord && !editingRecord.isPending) ? 'Guardar Cambios' : 'Agregar a Planilla'}
                                    </button>
                                </div>
                            </form>
                        </div>

                        {/* Banco de Negocios Pendientes (Nube) */}
                        {pendingRecords.length > 0 && (
                            <div className="glass-card rounded-2xl shadow-sm border border-orange-200 overflow-hidden mb-6">
                                <div className="p-5 bg-gradient-to-r from-orange-50 to-orange-100 border-b border-orange-200 flex flex-col sm:flex-row justify-between items-center gap-4">
                                    <div>
                                        <h2 className="text-lg font-black text-orange-800 flex items-center gap-2">
                                            <IconCloud /> NEGOCIOS PENDIENTES {selectedAdvisor ? `(${selectedAdvisor})` : 'EN LA NUBE'}
                                        </h2>
                                        <p className="text-xs text-orange-700 font-medium">
                                            {selectedAdvisor 
                                                ? 'Estos registros están guardados en la Nube y listos para ser liquidados.' 
                                                : `Hay ${pendingRecords.length} negocios pendientes en total. Seleccione un Asesor arriba para ver los suyos.`}
                                        </p>
                                    </div>
                                    {selectedAdvisor && pendingRecords.filter(r => r.advisor === selectedAdvisor).length > 0 && (
                                        <button onClick={() => {
                                            const advisorPending = pendingRecords.filter(r => r.advisor === selectedAdvisor);
                                            setRecords([...records, ...advisorPending]);
                                            savePendingRecords(pendingRecords.filter(r => r.advisor !== selectedAdvisor));
                                        }} className="text-xs font-bold text-white bg-orange-600 hover:bg-orange-700 px-5 py-2.5 rounded-xl shadow-md transition flex items-center gap-2">
                                            Cargar Todos a la Planilla
                                        </button>
                                    )}
                                </div>
                                
                                {!selectedAdvisor ? (
                                    <div className="p-8 text-center bg-white text-orange-800 font-bold border-t border-orange-100">
                                        👆 Por favor, seleccione un Asesor en la parte superior para visualizar y cargar sus negocios pendientes.
                                    </div>
                                ) : pendingRecords.filter(r => r.advisor === selectedAdvisor).length === 0 ? (
                                    <div className="p-8 text-center bg-white text-orange-800 font-bold border-t border-orange-100">
                                        Este asesor no tiene negocios pendientes guardados en la Nube.
                                    </div>
                                ) : (
                                    <div className="overflow-x-auto">
                                        <table className="w-full text-sm text-left whitespace-nowrap">
                                            <thead className="text-xs text-orange-800 uppercase bg-orange-100/50 font-bold border-b border-orange-200">
                                                <tr>
                                                    <th className="px-5 py-3">Cliente</th>
                                                    <th className="px-5 py-3">Póliza</th>
                                                    <th className="px-5 py-3">Compañía</th>
                                                    <th className="px-5 py-3">Ramo</th>
                                                    <th className="px-5 py-3 text-right">Prima Neta</th>
                                                    <th className="px-5 py-3 text-right">Comisión</th>
                                                    <th className="px-5 py-3 text-center">Acciones</th>
                                                </tr>
                                            </thead>
                                            <tbody className="divide-y divide-orange-100">
                                                {pendingRecords.filter(r => r.advisor === selectedAdvisor).map(record => (
                                                    <tr key={record.id} className="hover:bg-orange-50 transition">
                                                        <td className="px-5 py-2 font-bold text-gray-800">{record.client}</td>
                                                        <td className="px-5 py-2 text-gray-600 font-medium">{record.policy}</td>
                                                        <td className="px-5 py-2 text-gray-600">{record.company}</td>
                                                        <td className="px-5 py-2 text-gray-600">{record.branch}</td>
                                                        <td className="px-5 py-2 text-right font-medium text-gray-600">{formatCurrency(record.netPremium)}</td>
                                                        <td className="px-5 py-2 text-right font-black text-orange-700">{formatCurrency(record.commission)}</td>
                                                        <td className="px-5 py-2 text-center flex justify-center items-center gap-1">
                                                            <button onClick={() => {
                                                                setRecords([...records, record]);
                                                                savePendingRecords(pendingRecords.filter(r => r.id !== record.id));
                                                            }} className="text-white bg-blue-500 hover:bg-blue-600 px-3 py-1.5 rounded-lg text-xs font-bold shadow-sm transition">Adicionar</button>
                                                            <button onClick={() => handleEditRecord(record, true)} className="text-blue-600 hover:text-blue-800 hover:bg-blue-100 p-1.5 rounded-lg transition" title="Editar Pendiente"><IconEdit /></button>
                                                            <button onClick={() => setDialog({
                                                                message: '¿Seguro que deseas eliminar permanentemente este negocio de la base de pendientes en la nube?',
                                                                type: 'confirm',
                                                                onConfirm: () => {
                                                                    savePendingRecords(pendingRecords.filter(x => x.id !== record.id));
                                                                    setDialog(null);
                                                                }
                                                            })} className="text-red-400 hover:text-red-600 hover:bg-red-50 p-1.5 rounded-lg transition" title="Eliminar"><IconTrash /></button>
                                                        </td>
                                                    </tr>
                                                ))}
                                            </tbody>
                                        </table>
                                    </div>
                                )}
                            </div>
                        )}
                        
                        {/* FORMULARIO DE AJUSTES EXTRAS */}
                        {!editingRecord && (
                            <div className="glass-card p-6 rounded-2xl shadow-sm border border-purple-200 mb-6 bg-purple-50/20">
                                <h2 className="text-lg font-black text-purple-900 mb-4 border-b border-purple-200 pb-3 flex items-center gap-2">
                                    <IconPlus /> INGRESAR DESCUENTO O PAGO ADICIONAL
                                </h2>
                                <form onSubmit={(e) => e.preventDefault()} className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 items-end">
                                    <div className="lg:col-span-1">
                                        <label className="block text-xs font-bold text-gray-500 mb-1">TIPO DE AJUSTE</label>
                                        <select value={extraType} onChange={(e) => setExtraType(e.target.value)} className="w-full border-2 border-gray-200 rounded-xl p-2.5 text-sm bg-gray-50 focus:bg-white focus:border-purple-500 focus:ring-4 focus:ring-purple-500/20 outline-none transition font-medium">
                                            <option value="descuento">Descuento (Resta)</option>
                                            <option value="adicional">Pago Adicional (Suma)</option>
                                        </select>
                                    </div>
                                    <div className="lg:col-span-1">
                                        <label className="block text-xs font-bold text-gray-500 mb-1">CONCEPTO / DESCRIPCIÓN</label>
                                        <input type="text" value={extraDesc} onChange={(e) => setExtraDesc(e.target.value.toUpperCase())} placeholder="Ej: Bono, Devolución..." className="w-full border-2 border-gray-200 rounded-xl p-2.5 text-sm uppercase bg-gray-50 focus:bg-white focus:border-purple-500 focus:ring-4 focus:ring-purple-500/20 outline-none transition font-medium"/>
                                    </div>
                                    <div className="lg:col-span-1">
                                        <label className="block text-xs font-bold text-gray-500 mb-1">VALOR (COP)</label>
                                        <input type="number" value={extraAmount} onChange={(e) => setExtraAmount(e.target.value)} placeholder="Ej: 50000" className="w-full border-2 border-gray-200 rounded-xl p-2.5 text-sm bg-gray-50 focus:bg-white focus:border-purple-500 focus:ring-4 focus:ring-purple-500/20 outline-none transition font-medium"/>
                                    </div>
                                    <div className="sm:col-span-2 lg:col-span-4 flex flex-wrap justify-end gap-3 mt-2">
                                        <button type="button" onClick={(e) => handleAddExtra(e, true)} className="flex items-center gap-2 bg-orange-500 hover:bg-orange-600 text-white px-6 py-2.5 rounded-xl font-bold shadow-md hover:shadow-lg transition text-sm">
                                            <IconCloud /> Guardar Pendiente (Nube)
                                        </button>
                                        <button type="button" onClick={(e) => handleAddExtra(e, false)} className="flex items-center gap-2 bg-purple-600 hover:bg-purple-700 text-white px-6 py-2.5 rounded-xl font-bold shadow-md hover:shadow-lg transition text-sm">
                                            <IconPlus /> Agregar a Planilla
                                        </button>
                                    </div>
                                </form>
                            </div>
                        )}

                        {/* TABLA DE EXTRAS PENDIENTES (NUBE) */}
                        {pendingExtras.length > 0 && selectedAdvisor && pendingExtras.filter(r => r.advisor === selectedAdvisor).length > 0 && (
                            <div className="glass-card rounded-2xl shadow-sm border border-purple-300 overflow-hidden mb-6">
                                <div className="p-5 bg-gradient-to-r from-purple-50 to-purple-100 border-b border-purple-200 flex justify-between items-center gap-4">
                                    <div>
                                        <h2 className="text-lg font-black text-purple-900 flex items-center gap-2">
                                            <IconCloud /> AJUSTES PENDIENTES ({selectedAdvisor})
                                        </h2>
                                        <p className="text-xs text-purple-700 font-medium">Estos descuentos o pagos están en la nube esperando ser aplicados.</p>
                                    </div>
                                    <button onClick={() => {
                                        const advisorExtras = pendingExtras.filter(r => r.advisor === selectedAdvisor);
                                        setCurrentExtras([...currentExtras, ...advisorExtras]);
                                        savePendingExtras(pendingExtras.filter(r => r.advisor !== selectedAdvisor));
                                    }} className="text-xs font-bold text-white bg-purple-600 hover:bg-purple-700 px-5 py-2.5 rounded-xl shadow-md transition">
                                        Cargar Todos
                                    </button>
                                </div>
                                <div className="overflow-x-auto">
                                    <table className="w-full text-sm text-left whitespace-nowrap">
                                        <thead className="text-xs text-purple-800 uppercase bg-purple-100/50 font-bold border-b border-purple-200">
                                            <tr>
                                                <th className="px-5 py-3">Tipo</th>
                                                <th className="px-5 py-3">Concepto</th>
                                                <th className="px-5 py-3 text-right">Valor</th>
                                                <th className="px-5 py-3 text-center">Acciones</th>
                                            </tr>
                                        </thead>
                                        <tbody className="divide-y divide-purple-100">
                                            {pendingExtras.filter(r => r.advisor === selectedAdvisor).map(extra => (
                                                <tr key={extra.id} className="hover:bg-purple-50 transition">
                                                    <td className="px-5 py-2 font-bold text-gray-800">
                                                        <span className={`px-2 py-1 rounded text-xs text-white ${extra.type === 'descuento' ? 'bg-red-500' : 'bg-green-500'}`}>
                                                            {extra.type === 'descuento' ? 'DESCUENTO (-)' : 'ADICIONAL (+)'}
                                                        </span>
                                                    </td>
                                                    <td className="px-5 py-2 text-gray-600 font-medium">{extra.desc}</td>
                                                    <td className={`px-5 py-2 text-right font-black ${extra.type === 'descuento' ? 'text-red-600' : 'text-green-600'}`}>
                                                        {formatCurrency(extra.amount)}
                                                    </td>
                                                    <td className="px-5 py-2 text-center flex justify-center gap-1">
                                                        <button onClick={() => {
                                                            setCurrentExtras([...currentExtras, extra]);
                                                            savePendingExtras(pendingExtras.filter(r => r.id !== extra.id));
                                                        }} className="text-white bg-blue-500 hover:bg-blue-600 px-3 py-1.5 rounded-lg text-xs font-bold transition">Adicionar</button>
                                                        <button onClick={() => handleDeleteExtra(extra.id, true)} className="text-red-400 hover:text-red-600 hover:bg-red-50 p-1.5 rounded-lg transition"><IconTrash /></button>
                                                    </td>
                                                </tr>
                                            ))}
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        )}

                        <div className="glass-card rounded-2xl shadow-sm border border-gray-200 overflow-hidden">
                            <div className="p-5 bg-gradient-to-r from-gray-50 to-gray-100 border-b border-gray-200 flex justify-between items-center">
                                <h2 className="text-lg font-black text-gray-800">REGISTROS CARGADOS EN ESTA PLANILLA</h2>
                                <span className="text-xs font-bold text-blue-900 bg-blue-100 px-3 py-1.5 rounded-full shadow-inner">{records.length} negocios</span>
                            </div>
                            <div className="overflow-x-auto">
                                <table className="w-full text-sm text-left whitespace-nowrap">
                                    <thead className="text-xs text-gray-500 uppercase bg-gray-50 font-bold border-b border-gray-200">
                                        <tr>
                                            <th className="px-5 py-4">Cliente</th>
                                            <th className="px-5 py-4">Póliza</th>
                                            <th className="px-5 py-4">Compañía</th>
                                            <th className="px-5 py-4">Ramo</th>
                                            <th className="px-5 py-4 text-right">Prima Neta</th>
                                            <th className="px-5 py-4 text-right">Comisión</th>
                                            <th className="px-5 py-4 text-center">Acciones</th>
                                        </tr>
                                    </thead>
                                    <tbody className="divide-y divide-gray-100">
                                        {records.length === 0 ? (
                                            <tr><td colSpan="7" className="px-5 py-12 text-center text-gray-400 font-medium">No hay negocios registrados en esta planilla actual. Agregue uno en el formulario superior.</td></tr>
                                        ) : (
                                            records.map(record => (
                                                <tr key={record.id} className="hover:bg-blue-50/50 transition">
                                                    <td className="px-5 py-3 font-bold text-gray-800">{record.client}</td>
                                                    <td className="px-5 py-3 text-gray-600 font-medium">{record.policy}</td>
                                                    <td className="px-5 py-3 text-gray-600">{record.company}</td>
                                                    <td className="px-5 py-3 text-gray-600">{record.branch} <span className="text-xs text-blue-600 font-bold bg-blue-50 px-1.5 py-0.5 rounded">({record.commissionRate}%)</span></td>
                                                    <td className="px-5 py-3 text-right font-medium text-gray-600">{formatCurrency(record.netPremium)}</td>
                                                    <td className="px-5 py-3 text-right font-black text-green-700">{formatCurrency(record.commission)}</td>
                                                    <td className="px-5 py-3 text-center">
                                                        <button onClick={() => handleEditRecord(record, false)} className="text-blue-500 hover:text-blue-700 hover:bg-blue-100 p-2 rounded-lg transition mx-1"><IconEdit /></button>
                                                        <button onClick={() => handleDeleteRecord(record.id)} className="text-red-400 hover:text-red-600 hover:bg-red-50 p-2 rounded-lg transition mx-1"><IconTrash /></button>
                                                    </td>
                                                </tr>
                                            ))
                                        )}
                                    </tbody>
                                </table>
                            </div>
                            
                            {/* TABLA DE EXTRAS CARGADOS EN LA PLANILLA */}
                            {currentExtras.length > 0 && (
                                <div>
                                    <div className="px-5 py-3 bg-purple-50 border-t border-purple-200 flex justify-between items-center">
                                        <h3 className="text-sm font-black text-purple-900">AJUSTES ADICIONALES Y DESCUENTOS APLICADOS</h3>
                                    </div>
                                    <table className="w-full text-sm text-left whitespace-nowrap bg-purple-50/30">
                                        <tbody className="divide-y divide-purple-100">
                                            {currentExtras.map(extra => (
                                                <tr key={extra.id} className="hover:bg-purple-100/50 transition">
                                                    <td className="px-5 py-2 font-bold w-32">
                                                        <span className={`px-2 py-1 rounded text-xs text-white ${extra.type === 'descuento' ? 'bg-red-500' : 'bg-green-500'}`}>
                                                            {extra.type === 'descuento' ? 'DESCUENTO' : 'ADICIONAL'}
                                                        </span>
                                                    </td>
                                                    <td className="px-5 py-2 text-gray-700 font-medium">{extra.desc}</td>
                                                    <td colSpan="3"></td>
                                                    <td className={`px-5 py-2 text-right font-black ${extra.type === 'descuento' ? 'text-red-600' : 'text-green-600'}`}>
                                                        {extra.type === 'descuento' ? '-' : '+'} {formatCurrency(extra.amount)}
                                                    </td>
                                                    <td className="px-5 py-2 text-center">
                                                        <button onClick={() => handleDeleteExtra(extra.id, false)} className="text-red-400 hover:text-red-600 hover:bg-red-50 p-1.5 rounded-lg transition"><IconTrash /></button>
                                                    </td>
                                                </tr>
                                            ))}
                                        </tbody>
                                    </table>
                                </div>
                            )}
                        </div>

                        {(records.length > 0 || currentExtras.length > 0) && (
                            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                                <div className="glass-card p-6 rounded-2xl shadow-sm border border-gray-200">
                                    <h3 className="font-black text-gray-800 border-b border-gray-200 pb-3 mb-4">COMISIONES POR RAMO</h3>
                                    <div className="space-y-3 mb-6">
                                        {Object.entries(calculations.branchTotals).map(([branch, total]) => (
                                            <div key={branch} className="flex justify-between text-sm items-center">
                                                <span className="text-gray-600 font-medium">{branch}</span>
                                                <span className="font-bold text-gray-800">{formatCurrency(total)}</span>
                                            </div>
                                        ))}
                                    </div>
                                    <div className="mt-auto pt-4 border-t border-gray-200 flex justify-between items-center bg-blue-50/50 p-4 rounded-xl">
                                        <span className="font-black text-blue-900">COMISIONES NETAS</span>
                                        <span className="font-black text-blue-900 text-xl">{formatCurrency(calculations.comisionesNetas)}</span>
                                    </div>
                                </div>

                                <div className="glass-card p-6 rounded-2xl shadow-sm border border-gray-200">
                                    <h3 className="font-black text-gray-800 border-b border-gray-200 pb-3 mb-4">LIQUIDACIÓN IMPUESTOS Y PILA</h3>
                                    <div className="space-y-3 text-sm">
                                        <div className="flex justify-between items-center text-red-600 font-medium">
                                            <span>Rte Fte 10%</span>
                                            <span className="bg-red-50 px-2 py-0.5 rounded">- {formatCurrency(calculations.rteFte)}</span>
                                        </div>
                                        <div className="flex justify-between items-center text-red-600 font-medium">
                                            <span>Rte Ica 11,04 o/oo</span>
                                            <span className="bg-red-50 px-2 py-0.5 rounded">- {formatCurrency(calculations.rteIca)}</span>
                                        </div>
                                        <div className="flex justify-between font-black text-gray-800 pt-3 border-t border-gray-100">
                                            <span>Comisión menos Impuestos</span>
                                            <span>{formatCurrency(calculations.comisionMenosImpuestos)}</span>
                                        </div>
                                        
                                        <div className="mt-5 pt-5 border-t border-dashed border-gray-300">
                                            <div className="flex justify-between text-gray-500 text-xs mb-3 font-bold">
                                                <span>Base liquidación Seguridad Social (40%)</span>
                                                <span>{formatCurrency(calculations.baseSeguridadSocial)}</span>
                                            </div>
                                            <div className="flex justify-between items-center text-orange-600 font-medium mb-2">
                                                <span>Salud (12.5%)</span>
                                                <span>- {formatCurrency(calculations.salud)}</span>
                                            </div>
                                            <div className="flex justify-between items-center text-orange-600 font-medium mb-2">
                                                <span>Pensión (16%)</span>
                                                <span>- {formatCurrency(calculations.pension)}</span>
                                            </div>
                                            <div className="flex justify-between items-center text-orange-600 font-medium mb-3">
                                                <span>ARL (0.522%)</span>
                                                <span>- {formatCurrency(calculations.arl)}</span>
                                            </div>
                                            <div className="flex justify-between font-black text-orange-800 pt-2 border-t border-orange-100">
                                                <span>Total PILA</span>
                                                <span>- {formatCurrency(calculations.totalPila)}</span>
                                            </div>
                                        </div>

                                        <div className="flex justify-between items-center bg-gray-800 text-white p-4 rounded-xl mt-5 shadow-inner">
                                            <span className="font-bold text-xs tracking-wide">COMISIÓN DESCONTANDO PILA</span>
                                            <span className="text-xl font-black">{formatCurrency(calculations.comisionDescontandoPila)}</span>
                                        </div>
                                    </div>
                                </div>

                                <div className="lg:col-span-2 grid grid-cols-1 sm:grid-cols-2 gap-5 mt-2">
                                    <div className="bg-gradient-to-br from-green-500 to-green-600 text-white p-8 rounded-2xl shadow-lg border border-green-400 text-center flex flex-col justify-center transform transition hover:scale-[1.02]">
                                        <span className="text-green-100 font-bold mb-2 tracking-wider text-sm">TOTAL A PAGAR AL ASESOR (80% + Ajustes)</span>
                                        <span className="text-4xl lg:text-5xl font-black tracking-tight drop-shadow-md">{formatCurrency(calculations.asesorFinal)}</span>
                                        
                                        {selectedAdvisor && currentAdvObj && (
                                            <div className="mt-3 text-sm font-bold text-green-100 bg-black/20 inline-block px-4 py-1.5 rounded-xl mx-auto border border-green-400/30">
                                                💳 Cuenta / Llave: {currentAdvObj.account || 'No registrada'}
                                            </div>
                                        )}

                                        {(calculations.totalAdicionales > 0 || calculations.totalDescuentos > 0) && (
                                            <div className="mt-4 text-xs font-medium bg-black/20 p-3 rounded-xl inline-block mx-auto text-left">
                                                <div className="mb-1 text-white">Base 80%: {formatCurrency(calculations.asesor80)}</div>
                                                {calculations.totalAdicionales > 0 && <div className="text-green-200">+ Adicionales: {formatCurrency(calculations.totalAdicionales)}</div>}
                                                {calculations.totalDescuentos > 0 && <div className="text-red-200">- Descuentos: {formatCurrency(calculations.totalDescuentos)}</div>}
                                            </div>
                                        )}
                                    </div>
                                    <div className="bg-gradient-to-br from-blue-800 to-blue-900 text-white p-8 rounded-2xl shadow-lg border border-blue-700 text-center flex flex-col justify-center transform transition hover:scale-[1.02]">
                                        <span className="text-blue-200 font-bold mb-2 tracking-wider text-sm">20% RTO SEGUROS</span>
                                        <span className="text-4xl lg:text-5xl font-black tracking-tight drop-shadow-md">{formatCurrency(calculations.rto20)}</span>
                                    </div>
                                </div>
                                
                                <div className="lg:col-span-2 flex justify-center mt-8">
                                    <button onClick={() => setIsExportModalOpen(true)} className="flex items-center gap-3 bg-gradient-to-r from-blue-600 to-blue-700 hover:from-blue-500 hover:to-blue-600 text-white px-10 py-5 rounded-2xl font-black text-xl shadow-xl hover:shadow-2xl transition transform hover:-translate-y-1 border border-blue-400">
                                        <IconFileText /> GENERAR PLANILLA
                                    </button>
                                </div>
                            </div>
                        )}
                    </main>

                    {isExportModalOpen && (
                        <div className="fixed inset-0 bg-gray-900/60 backdrop-blur-sm flex items-center justify-center p-4 z-50">
                            <div className="bg-white rounded-3xl shadow-2xl w-full max-w-md p-8 text-center transform transition-all">
                                <div className="w-16 h-16 bg-blue-100 text-blue-600 rounded-full flex items-center justify-center mx-auto mb-4">
                                    <IconFileText />
                                </div>
                                <h2 className="text-2xl font-black text-gray-800 mb-2">Finalizar Planilla</h2>
                                <p className="text-gray-500 mb-8 font-medium">¿Cómo deseas procesar esta liquidación?</p>
                                
                                <div className="space-y-4 flex flex-col">
                                    <button onClick={() => handleExportSelection('imprimir')} className="w-full bg-white hover:bg-gray-50 text-gray-800 font-bold py-4 rounded-xl transition border-2 border-gray-200 shadow-sm flex justify-center items-center gap-2">
                                        Solo Imprimir (PDF)
                                    </button>
                                    <button onClick={() => handleExportSelection('almacenar')} className="w-full bg-blue-600 hover:bg-blue-700 text-white font-bold py-4 rounded-xl transition shadow-md flex justify-center items-center gap-2">
                                        <IconFolder /> Imprimir y Almacenar en Servidor
                                    </button>
                                </div>
                                
                                <button onClick={() => setIsExportModalOpen(false)} className="mt-6 text-sm font-bold text-gray-400 hover:text-gray-600 transition">CANCELAR</button>
                            </div>
                        </div>
                    )}

                    {isHistoryOpen && (
                        <div className="fixed inset-0 bg-gray-900/60 backdrop-blur-sm flex items-center justify-center p-4 z-50">
                            <div className="bg-white rounded-3xl shadow-2xl w-full max-w-4xl max-h-[90vh] flex flex-col">
                                <div className="p-6 border-b border-gray-100 flex justify-between items-center bg-gray-50 rounded-t-3xl">
                                    <div>
                                        <h2 className="text-xl font-black text-gray-800 flex items-center gap-2"><IconFolder /> Historial de Planillas (Servidor)</h2>
                                        <p className="text-xs text-gray-500 mt-1 font-medium">Aquí se almacenan las planillas generadas sincronizadas desde la Base de Datos.</p>
                                    </div>
                                    <button onClick={() => setIsHistoryOpen(false)} className="text-gray-400 hover:text-gray-800 bg-gray-200 hover:bg-gray-300 w-8 h-8 rounded-full flex items-center justify-center transition font-bold">&times;</button>
                                </div>
                                <div className="p-6 overflow-y-auto flex-1 bg-gray-50/50">
                                    {historyData.length === 0 ? (
                                        <div className="text-center text-gray-400 py-10 font-medium">
                                            No hay planillas almacenadas aún.
                                        </div>
                                    ) : (
                                        <div className="grid gap-4">
                                            {historyData.map((item, idx) => (
                                                <div key={item.id} className="bg-white border border-gray-200 p-4 rounded-2xl shadow-sm flex flex-col sm:flex-row justify-between items-center gap-4 hover:shadow-md transition">
                                                    <div>
                                                        <h3 className="font-bold text-gray-800 text-lg">{item.advisor || 'Asesor no especificado'}</h3>
                                                        <div className="text-xs text-gray-500 font-medium mt-1 flex gap-3">
                                                            <span>Corte: {item.cutoff || 'N/A'}</span>
                                                            <span>Generado: {item.generationDate}</span>
                                                            <span className="text-blue-600 font-bold">{item.records.length} Negocios</span>
                                                        </div>
                                                    </div>
                                                    <div className="flex items-center gap-4">
                                                        <div className="text-right mr-2 hidden sm:block">
                                                            <div className="text-xs font-bold text-gray-400">Total Neto</div>
                                                            <div className="font-black text-gray-800">{formatCurrency(item.calculations.comisionesNetas)}</div>
                                                        </div>
                                                        <div className="flex gap-2">
                                                            <button onClick={() => handleEditHistoryItem(item)} className="flex items-center gap-1 bg-blue-50 hover:bg-blue-100 text-blue-600 border border-blue-200 px-3 py-2 rounded-lg font-bold text-xs transition" title="Editar Planilla">
                                                                <IconEdit /> EDITAR
                                                            </button>
                                                            <button onClick={() => executeExportPDF(true, item.records, item.calculations, item.currentExtras || [], item.advisor, item.cutoff)} className="flex items-center gap-1 bg-red-50 hover:bg-red-100 text-red-600 border border-red-200 px-3 py-2 rounded-lg font-bold text-xs transition" title="Descargar PDF">
                                                                <IconDownload /> PDF
                                                            </button>
                                                            <button onClick={() => executeExportExcel(item.records, item.calculations, item.advisor, item.cutoff)} className="flex items-center gap-1 bg-green-50 hover:bg-green-100 text-green-600 border border-green-200 px-3 py-2 rounded-lg font-bold text-xs transition" title="Descargar Excel">
                                                                <IconDownload /> EXCEL
                                                            </button>
                                                            <button onClick={() => setDialog({
                                                                message: '¿Seguro que deseas eliminar permanentemente esta planilla del servidor?',
                                                                type: 'confirm',
                                                                onConfirm: () => {
                                                                    saveHistory(historyData.filter(x => x.id !== item.id));
                                                                    setDialog(null);
                                                                }
                                                            })} className="flex items-center gap-1 bg-gray-100 hover:bg-red-100 hover:text-red-600 text-gray-500 px-3 py-2 rounded-lg font-bold text-xs transition ml-2" title="Eliminar del servidor">
                                                                <IconTrash />
                                                            </button>
                                                        </div>
                                                    </div>
                                                </div>
                                            ))}
                                        </div>
                                    )}
                                </div>
                            </div>
                        </div>
                    )}

                    {isConfigOpen && (
                        <div className="fixed inset-0 bg-gray-900/60 backdrop-blur-sm flex items-center justify-center p-4 z-50">
                            <div className="bg-white rounded-3xl shadow-2xl w-full max-w-4xl max-h-[90vh] flex flex-col">
                                <div className="p-6 border-b border-gray-100 flex justify-between items-center bg-gray-50 rounded-t-3xl">
                                    <h2 className="text-xl font-black text-gray-800 flex items-center gap-2"><IconSettings /> Configuración del Sistema en Servidor</h2>
                                    <div className="flex items-center gap-4">
                                        <button onClick={forceSyncToCloud} className="bg-orange-500 hover:bg-orange-600 text-white text-xs font-bold px-4 py-2 rounded-xl shadow-md transition flex items-center gap-2" title="Sube los datos de este computador a la Nube">
                                            <IconCloud /> Forzar Sincronización
                                        </button>
                                        <button onClick={() => setIsConfigOpen(false)} className="text-gray-400 hover:text-gray-800 bg-gray-200 hover:bg-gray-300 w-8 h-8 rounded-full flex items-center justify-center transition font-bold">&times;</button>
                                    </div>
                                </div>
                                <div className="p-6 overflow-y-auto flex-1 grid grid-cols-1 md:grid-cols-2 gap-8 bg-gray-50/50">
                                    
                                    <div className="bg-white p-5 rounded-2xl border border-gray-100 shadow-sm">
                                        <h3 className="font-black text-gray-700 mb-4 border-b pb-2">Gestión de Asesores</h3>
                                        <div className="flex gap-2 mb-4">
                                            <input type="text" id="newAdvisor" placeholder="Nombre completo" className="flex-1 border-2 border-gray-200 rounded-xl p-2 text-sm focus:border-blue-500 outline-none font-medium"/>
                                            <input type="text" id="newAdvisorAccount" placeholder="No. Cuenta / Llave" className="w-1/3 border-2 border-gray-200 rounded-xl p-2 text-sm focus:border-blue-500 outline-none font-medium"/>
                                            <button onClick={() => {
                                                const name = document.getElementById('newAdvisor').value.trim();
                                                const account = document.getElementById('newAdvisorAccount').value.trim();
                                                if(name) { 
                                                    const exists = advisors.find(x => x.name.toLowerCase() === name.toLowerCase());
                                                    let newAdvisors;
                                                    if (exists) {
                                                        newAdvisors = advisors.map(x => x.name.toLowerCase() === name.toLowerCase() ? {name: x.name, account} : x);
                                                    } else {
                                                        newAdvisors = [...advisors, {name, account}];
                                                    }
                                                    saveConfig(newAdvisors, companies, branches); 
                                                    document.getElementById('newAdvisor').value=''; 
                                                    document.getElementById('newAdvisorAccount').value='';
                                                }
                                            }} className="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-xl text-sm font-bold transition shadow-sm">Guardar</button>
                                        </div>
                                        <ul className="text-sm border border-gray-100 rounded-xl max-h-48 overflow-y-auto divide-y divide-gray-100">
                                            {advisors.map((a, i) => (
                                                <li key={i} className="flex justify-between items-center p-3 hover:bg-gray-50">
                                                    <span className="font-medium text-gray-700">{a.name} {a.account && <span className="text-xs text-blue-600 bg-blue-50 px-2 py-0.5 rounded ml-2 font-bold">(Cta: {a.account})</span>}</span> 
                                                    <div className="flex gap-1">
                                                        <button onClick={() => {
                                                            document.getElementById('newAdvisor').value = a.name;
                                                            document.getElementById('newAdvisorAccount').value = a.account || '';
                                                            document.getElementById('newAdvisorAccount').focus();
                                                        }} className="text-blue-500 hover:text-blue-700 p-1.5 bg-blue-50 rounded transition" title="Editar cuenta"><IconEdit/></button>
                                                        <button onClick={() => saveConfig(advisors.filter(x => x.name !== a.name), companies, branches)} className="text-red-400 hover:text-red-600 p-1.5 bg-red-50 rounded transition" title="Eliminar asesor"><IconTrash/></button>
                                                    </div>
                                                </li>
                                            ))}
                                        </ul>
                                    </div>

                                    <div className="bg-white p-5 rounded-2xl border border-gray-100 shadow-sm">
                                        <h3 className="font-black text-gray-700 mb-4 border-b pb-2">Gestión de Compañías</h3>
                                        <div className="flex gap-2 mb-4">
                                            <input type="text" id="newCompany" placeholder="Nombre de Aseguradora" className="flex-1 border-2 border-gray-200 rounded-xl p-2 text-sm focus:border-blue-500 outline-none font-medium"/>
                                            <button onClick={() => {
                                                const val = document.getElementById('newCompany').value;
                                                if(val) { saveConfig(advisors, [...companies, val], branches); document.getElementById('newCompany').value=''; }
                                            }} className="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-xl text-sm font-bold transition">Agregar</button>
                                        </div>
                                        <ul className="text-sm border border-gray-100 rounded-xl max-h-48 overflow-y-auto divide-y divide-gray-100">
                                            {companies.map((c, i) => (
                                                <li key={i} className="flex justify-between items-center p-3 hover:bg-gray-50">
                                                    <span className="font-medium text-gray-700">{c}</span> 
                                                    <button onClick={() => saveConfig(advisors, companies.filter(x => x !== c), branches)} className="text-red-400 hover:text-red-600 p-1 bg-red-50 rounded"><IconTrash/></button>
                                                </li>
                                            ))}
                                        </ul>
                                    </div>

                                    <div className="md:col-span-2 bg-white p-5 rounded-2xl border border-gray-100 shadow-sm">
                                        <h3 className="font-black text-gray-700 mb-4 border-b pb-2">Matriz de Ramos y Comisiones</h3>
                                        <div className="flex flex-col sm:flex-row gap-3 mb-4">
                                            <input type="text" id="newBranchName" placeholder="Ej: Autos Individual" className="flex-1 border-2 border-gray-200 rounded-xl p-2 text-sm focus:border-blue-500 outline-none font-medium"/>
                                            <div className="flex gap-3">
                                                <input type="number" id="newBranchRate" placeholder="% Com." className="w-24 border-2 border-gray-200 rounded-xl p-2 text-sm focus:border-blue-500 outline-none font-medium text-center"/>
                                                <button onClick={() => {
                                                    const name = document.getElementById('newBranchName').value;
                                                    const rate = document.getElementById('newBranchRate').value;
                                                    if(name && rate) { 
                                                        saveConfig(advisors, companies, [...branches, { name, rate: Number(rate) }]); 
                                                        document.getElementById('newBranchName').value='';
                                                        document.getElementById('newBranchRate').value='';
                                                    }
                                                }} className="bg-blue-600 hover:bg-blue-700 text-white px-6 py-2 rounded-xl text-sm font-bold transition">Agregar Ramo</button>
                                            </div>
                                        </div>
                                        <ul className="text-sm border border-gray-100 rounded-xl max-h-48 overflow-y-auto divide-y divide-gray-100">
                                            {branches.map((b, i) => (
                                                <li key={i} className="flex justify-between items-center p-3 hover:bg-gray-50">
                                                    <span className="font-bold text-gray-700">{b.name} <span className="bg-blue-100 text-blue-800 px-2 py-0.5 rounded ml-2 text-xs">({b.rate}%)</span></span>
                                                    <button onClick={() => saveConfig(advisors, companies, branches.filter(x => x.name !== b.name))} className="text-red-400 hover:text-red-600 p-1 bg-red-50 rounded"><IconTrash/></button>
                                                </li>
                                            ))}
                                            {branches.length === 0 && <li className="p-4 text-gray-400 text-center font-medium">No hay ramos registrados.</li>}
                                        </ul>
                                    </div>
                                </div>
                            </div>
                        </div>
                    )}

                    
                </div>
            );
        };

        const root = ReactDOM.createRoot(document.getElementById('root'));
        root.render(<App />);
    </script>
</body>
</html>