/**
 * ProfixCRM Simple - JavaScript Principal
 * Funcionalidades generales del sistema
 */

// Inicialización del sistema
document.addEventListener('DOMContentLoaded', function() {
    initializeSystem();
    initializeTables();
    initializeAuthUX();
    initializeClientPortalMobileMenu();
    initializeGlobalCalendarReminder();
});

function initializeSystem() {
    // Inicializar componentes básicos
    initializeSidebar();
    initializeTheme();
    initializeModals();
    // Otros inicializadores pueden agregarse aquí
    
    console.log('ProfixCRM Simple inicializado correctamente');
}

// ===== Tablas y listas (UX) =====
function initializeTables() {
    const tables = Array.from(document.querySelectorAll('table.data-table, table.leads-table'));
    tables.forEach(setupTableUX);
}

function setupTableUX(table) {
    if (!table) return;

    // Hover y clic de fila (navega al primer enlace "Ver")
    Array.from(table.tBodies[0]?.rows || []).forEach(row => {
        row.classList.add('row-hover');
        row.addEventListener('click', (e) => {
            // Evitar interferir con enlaces/botones y elementos con clase lead-name-link
            if (e.target.closest('a, button, input, select, label, .lead-name-link')) return;
            
            // Prevenir si el clic fue en una celda que contiene enlaces de nombres
            if (e.target.closest('.lead-first-name, .lead-last-name')) return;
            
            const viewLink = row.querySelector('a[href*="action=view"], .btn[href*="action=view"]');
            if (viewLink && viewLink.href) {
                window.location.href = viewLink.href;
            }
        });
    });

    // Ordenación básica por columna
    const thead = table.tHead;
    if (thead) {
        Array.from(thead.rows[0]?.cells || []).forEach((th, idx) => {
            th.classList.add('sortable');
            if (!th.hasAttribute('onclick')) {
                th.addEventListener('click', () => sortTableByColumn(table, idx));
            }
        });
    }
}

function sortTableByColumn(table, columnIndex) {
    const tbody = table.tBodies[0];
    if (!tbody) return;
    const rows = Array.from(tbody.rows);
    const asc = table.getAttribute('data-sort') !== `col-${columnIndex}-asc`;
    rows.sort((a, b) => {
        const av = (a.cells[columnIndex]?.textContent || '').trim().toLowerCase();
        const bv = (b.cells[columnIndex]?.textContent || '').trim().toLowerCase();
        // Si es número, comparar como número
        const an = parseFloat(av.replace(/[^0-9.-]/g, ''));
        const bn = parseFloat(bv.replace(/[^0-9.-]/g, ''));
        if (!isNaN(an) && !isNaN(bn)) return asc ? an - bn : bn - an;
        return asc ? av.localeCompare(bv) : bv.localeCompare(av);
    });
    rows.forEach(r => tbody.appendChild(r));
    table.setAttribute('data-sort', asc ? `col-${columnIndex}-asc` : `col-${columnIndex}-desc`);
}

// Navegación a perfil de lead
function goToLeadProfile(id) {
    if (!id) return;
    var base = (window.APP_BASE_PATH || '');
    // Normalizar base para evitar dobles slashes y soportar base vacío
    if (typeof base === 'string' && base.endsWith('/')) {
        base = base.slice(0, -1);
    }
    var url = base
        ? (base + '/index.php?module=leads&action=view&id=' + encodeURIComponent(id))
        : ('index.php?module=leads&action=view&id=' + encodeURIComponent(id));
    window.location.href = url;
}

function viewLead(id) { // compatibilidad con otras vistas
    goToLeadProfile(id);
}

// Gestión del sidebar
function initializeSidebar() {
    const sidebarToggle = document.querySelector('.sidebar-toggle');
    const sidebar = document.querySelector('.sidebar');
    
    if (sidebarToggle && sidebar) {
        sidebarToggle.addEventListener('click', function() {
            sidebar.classList.toggle('collapsed');
        });
    }
}

// ===== Menú móvil del Client Portal =====
function initializeClientPortalMobileMenu() {
    const toggleBtn = document.querySelector('.mobile-menu-toggle');
    const sidebar = document.getElementById('sidebar') || document.querySelector('.sidebar');
    const overlay = document.getElementById('sidebarOverlay') || document.querySelector('.sidebar-overlay');

    if (!toggleBtn || !sidebar) return;

    const openSidebar = () => {
        sidebar.classList.add('show');
        if (overlay) overlay.classList.add('show');
        toggleBtn.setAttribute('aria-expanded', 'true');
        document.body.style.overflow = 'hidden';
    };

    const closeSidebar = () => {
        sidebar.classList.remove('show');
        if (overlay) overlay.classList.remove('show');
        toggleBtn.setAttribute('aria-expanded', 'false');
        document.body.style.overflow = '';
    };

    toggleBtn.addEventListener('click', () => {
        if (sidebar.classList.contains('show')) {
            closeSidebar();
        } else {
            openSidebar();
        }
    });

    if (overlay) {
        overlay.addEventListener('click', closeSidebar);
    }

    document.addEventListener('keydown', (e) => {
        if (e.key === 'Escape') {
            closeSidebar();
        }
    });

    window.addEventListener('resize', () => {
        if (window.innerWidth > 1024) {
            closeSidebar();
        }
    });
}

// Gestión del tema
function initializeTheme() {
    const themeToggle = document.querySelector('.theme-toggle');
    
    if (themeToggle) {
        themeToggle.addEventListener('click', function() {
            document.body.classList.toggle('dark-theme');
            
            // Guardar preferencia
            const isDark = document.body.classList.contains('dark-theme');
            localStorage.setItem('theme', isDark ? 'dark' : 'light');
        });
        
        // Cargar tema guardado
        const savedTheme = localStorage.getItem('theme');
        if (savedTheme === 'dark') {
            document.body.classList.add('dark-theme');
        }
    }
}

// Gestión de modales
function initializeModals() {
    // Cerrar modales con ESC
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            const openModal = document.querySelector('.modal:not([style*="display: none"])');
            if (openModal) {
                closeModal(openModal);
            }
        }
    });
    
    // Cerrar modales clickeando fuera
    document.addEventListener('click', function(e) {
        if (e.target.classList.contains('modal')) {
            closeModal(e.target);
        }
    });
}

function closeModal(modal) {
    if (modal && modal.parentNode) {
        modal.parentNode.removeChild(modal);
    }
}

function togglePanel(panelId){
    var panel = document.getElementById(panelId);
    if (!panel) return;
    var content = panel.querySelector('.collapsible-content');
    var caret = panel.querySelector('.panel-caret');
    var isOpen = panel.classList.contains('is-open');
    panel.classList.toggle('is-open', !isOpen);
    if (content){
        if (!isOpen){ content.style.maxHeight = content.scrollHeight + 'px'; content.style.opacity = '1'; }
        else { content.style.maxHeight = '0px'; content.style.opacity = '0'; }
    }
    if (caret){ caret.style.transform = !isOpen ? 'rotate(180deg)' : 'rotate(0deg)'; }
}

document.addEventListener('DOMContentLoaded', function(){
    var panels = Array.from(document.querySelectorAll('.panel'));
    panels.forEach(function(panel){
        if (panel.classList.contains('start-collapsed')) return;
        panel.classList.add('is-open');
        var content = panel.querySelector('.collapsible-content');
        var caret = panel.querySelector('.panel-caret');
        if (content){ content.style.maxHeight = content.scrollHeight + 'px'; content.style.opacity = '1'; }
        if (caret){ caret.style.transform = 'rotate(180deg)'; }
    });
});

// Utilidades generales
function showNotification(message, type = 'info') {
    const notification = document.createElement('div');
    notification.className = `notification notification-${type}`;
    notification.textContent = message;
    
    document.body.appendChild(notification);
    
    // Auto-remover despuÃ©s de 3 segundos
    setTimeout(() => {
        if (notification.parentNode) {
            notification.parentNode.removeChild(notification);
        }
    }, 3000);
}

function formatDate(dateString) {
    const date = new Date(dateString);
    return date.toLocaleDateString('es-ES', {
        year: 'numeric',
        month: 'short',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
    });
}

function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// Funciones especÃ­ficas para mÃ³dulos
function refreshTable(tableId) {
    const table = document.getElementById(tableId);
    if (table) {
        // LÃ³gica para refrescar tabla
        console.log(`Refrescando tabla: ${tableId}`);
    }
}

function confirmAction(message, callback) {
    // Modal de confirmaciÃ³n en lugar de confirm() nativo
    showModalNotification({
        type: 'info',
        title: 'ConfirmaciÃ³n',
        message,
        actions: [
            { text: 'Cancelar', variant: 'secondary' },
            { text: 'Confirmar', variant: 'primary', onClick: () => callback() }
        ]
    });
}

// Exportar funciones globales
window.ProfixCRM = {
    showNotification,
    showModalNotification,
    formatDate,
    escapeHtml,
    refreshTable,
    confirmAction,
    closeModal,
    goToLeadProfile,
    viewLead
};

// Notificaciones Modales
function showModalNotification({ type = 'info', title = '', message = '', actions = [] } = {}) {
    // Backdrop
    const backdrop = document.createElement('div');
    backdrop.className = 'modal-backdrop';
    // Modal
    const modal = document.createElement('div');
    modal.className = 'modal modal-premium modal-notification modal-' + type;
    modal.innerHTML = `
        <div class="modal-header">
            <div class="modal-title">
                <span class="modal-icon">${getIconForType(type)}</span>
                <h3>${escapeHtml(title || capitalize(type))}</h3>
            </div>
            <button class="btn btn-ghost" data-close>&times;</button>
        </div>
        <div class="modal-body">
            <p>${escapeHtml(message)}</p>
        </div>
        <div class="modal-footer"></div>
    `;
    // Footer actions
    const footer = modal.querySelector('.modal-footer');
    if (Array.isArray(actions) && actions.length) {
        actions.forEach((a) => {
            const btn = document.createElement('button');
            btn.className = 'btn btn-' + (a.variant || 'secondary');
            btn.textContent = a.text || 'OK';
            btn.addEventListener('click', () => {
                try { a.onClick && a.onClick(); } finally { document.body.removeChild(backdrop); }
            });
            footer.appendChild(btn);
        });
    } else {
        const btn = document.createElement('button');
        btn.className = 'btn btn-primary';
        btn.textContent = 'Aceptar';
        btn.addEventListener('click', () => document.body.removeChild(backdrop));
        footer.appendChild(btn);
    }
    // Cerrar
    modal.querySelector('[data-close]').addEventListener('click', () => document.body.removeChild(backdrop));
    backdrop.addEventListener('click', (e) => { if (e.target === backdrop) document.body.removeChild(backdrop); });
    backdrop.appendChild(modal);
    document.body.appendChild(backdrop);
}

// ===== Auth UX (Login) =====
function initializeAuthUX() {
    // Toggle mostrar/ocultar contraseÃ±a
    const pwdInput = document.getElementById('password');
    const toggle = document.getElementById('togglePassword');
    if (pwdInput && toggle) {
        toggle.addEventListener('click', () => {
            const isText = pwdInput.type === 'text';
            pwdInput.type = isText ? 'password' : 'text';
            toggle.textContent = isText ? 'Mostrar' : 'Ocultar';
        });
    }
}

function getIconForType(type) {
    switch (type) {
        case 'success': return 'âœ…';
        case 'error': return 'â›”';
        case 'warning': return 'âš ï¸';
        default: return 'â„¹ï¸';
    }
}

function capitalize(s){ return (s||'').charAt(0).toUpperCase() + (s||'').slice(1); }

// ===== Asistente de Citas y Recordatorios Globales =====
function addEventToCalendar({ title, description = '', start, end, calendar = 'personal', color = '#2ea5e9' }){
    try {
        const uid = (window.__CALENDAR_USER_ID__ || 1);
        const key = `calendarEvents:${uid}`;
        let list = [];
        try { list = JSON.parse(localStorage.getItem(key) || '[]') || []; } catch (e) { list = []; }
        const id = Date.now();
        list.push({
            id,
            userId: uid,
            title: title || 'Cita',
            description: description || '',
            startISO: start.toISOString(),
            endISO: end.toISOString(),
            allDay: false,
            color,
            calendar
        });
        localStorage.setItem(key, JSON.stringify(list));
        return id;
    } catch (e) {
        console.error('No se pudo guardar el evento en el calendario', e);
        return null;
    }
}

function openAppointmentAssistant(context = {}){
    const { clientName = 'Cliente', leadId = 0 } = context;
    try { console.debug('[AppointmentAssistant] init', { clientName, leadId }); } catch(e){}

    // Estilos aislados para evitar conflictos con .modal del módulo Leads
    if (!document.getElementById('appointmentAssistantStyles')) {
        const styles = document.createElement('style');
        styles.id = 'appointmentAssistantStyles';
        styles.textContent = `
        .appointment-backdrop { position: fixed; inset: 0; background: rgba(0,0,0,.6); backdrop-filter: blur(8px); display:flex; align-items:center; justify-content:center; z-index: 10050; animation: fadeIn .2s ease-out; }
        .appointment-dialog { width: min(680px, calc(100% - 2rem)); max-height: 90vh; overflow: hidden; background: #fff; border-radius: 16px; box-shadow: 0 20px 60px rgba(0,0,0,.25); transform: translateY(8px); animation: popIn .2s ease-out forwards; }
        .appointment-header { display:flex; align-items:center; justify-content:space-between; padding: 16px 20px; border-bottom: 1px solid #eee; }
        .appointment-title { display:flex; align-items:center; gap: 10px; }
        .appointment-title h3 { margin: 0; font-size: 18px; }
        .appointment-body { padding: 16px 20px; }
        .appointment-footer { padding: 14px 20px; display:flex; justify-content:flex-end; gap: 10px; border-top: 1px solid #eee; }
        .step { display:none; }
        .step.active { display:block; }
        .stepper { display:flex; gap:8px; padding: 10px 0 16px; }
        .stepper .dot { width:10px; height:10px; border-radius:50%; background:#ddd; }
        .stepper .dot.active { background:#2ea5e9; }
        .lead-context { display:flex; align-items:center; gap:10px; margin-bottom:12px; }
        .lead-avatar { width:36px; height:36px; border-radius:50%; background:#2ea5e9; color:#fff; display:flex; align-items:center; justify-content:center; font-weight:600; }
        .form-grid { display:grid; grid-template-columns: 1fr 1fr; gap:12px; }
        .form-group { display:flex; flex-direction:column; gap:6px; }
        .form-label { font-weight:600; font-size:13px; }
        .form-control { border:1px solid #ddd; border-radius:8px; padding:10px; font-size:14px; }
        .summary { background:#f7fafc; border:1px solid #e5e7eb; border-radius:12px; padding:12px; }
        .suggestions { margin-top:12px; display:flex; flex-wrap:wrap; gap:8px; }
        .suggestion-title { font-size:12px; color:#555; width:100%; }
        .suggestion-btn { border:1px solid #2ea5e9; color:#2ea5e9; background:#eff6ff; padding:6px 10px; border-radius:8px; cursor:pointer; }
        .btn { border: none; border-radius: 8px; padding: 10px 14px; cursor: pointer; font-weight: 600; }
        .btn-primary { background:#2ea5e9; color:#fff; }
        .btn-secondary { background:#e5e7eb; color:#111; }
        .btn-ghost { background:transparent; color:#555; font-size:18px; }
        @keyframes popIn { from { transform: translateY(8px); opacity: .0; } to { transform: translateY(0); opacity: 1; } }
        @keyframes fadeIn { from { opacity:0; } to { opacity:1; } }
        `;
        document.head.appendChild(styles);
    }

    // Backdrop y diálogo centrado
    const backdrop = document.createElement('div');
    backdrop.className = 'appointment-backdrop';
    const dialog = document.createElement('div');
    dialog.className = 'appointment-dialog';

    // Contenido del asistente (3 pasos)
    dialog.innerHTML = `
        <div class="appointment-header">
            <div class="appointment-title"><span class="modal-icon">🤝</span><h3>Programar Cita</h3></div>
            <button class="btn btn-ghost" data-close>&times;</button>
        </div>
        <div class="appointment-body">
            <div class="lead-context">
                <div class="lead-avatar">${(clientName||'C').charAt(0).toUpperCase()}</div>
                <div>
                    <div style="font-weight:600">${escapeHtml(clientName)}</div>
                    ${leadId ? '<div style="font-size:12px;color:#666">Lead #'+leadId+'</div>' : ''}
                </div>
            </div>
            <div class="stepper">
                <div class="dot" data-dot="0"></div>
                <div class="dot" data-dot="1"></div>
                <div class="dot" data-dot="2"></div>
            </div>
            <div class="step" data-step="0">
                <div class="form-grid">
                    <div class="form-group">
                        <label class="form-label" for="apptDate">Fecha</label>
                        <input type="date" id="apptDate" class="form-control" />
                    </div>
                    <div class="form-group">
                        <label class="form-label" for="apptTime">Hora</label>
                        <input type="time" id="apptTime" class="form-control" />
                    </div>
                </div>
                <div id="apptSuggestions" class="suggestions" style="display:none">
                    <div class="suggestion-title">Sugerencias disponibles:</div>
                </div>
            </div>
            <div class="step" data-step="1">
                <div class="form-grid">
                    <div class="form-group">
                        <label class="form-label" for="apptDur">Duración</label>
                        <select id="apptDur" class="form-control">
                            <option value="30">30 min</option>
                            <option value="45">45 min</option>
                            <option value="60">60 min</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="form-label" for="apptCalendar">Calendario (Desk)</label>
                        <select id="apptCalendar" class="form-control"></select>
                    </div>
                </div>
            </div>
            <div class="step" data-step="2">
                <div class="form-group">
                    <label class="form-label" for="apptNotes">Notas</label>
                    <textarea id="apptNotes" rows="4" class="form-control" placeholder="Detalles de la cita"></textarea>
                </div>
                <div class="summary" id="apptSummary"></div>
            </div>
        </div>
        <div class="appointment-footer">
            <button class="btn btn-secondary" data-back>Atrás</button>
            <span style="flex:1"></span>
            <button class="btn btn-primary" data-next>Siguiente</button>
            <button class="btn btn-primary" data-save style="display:none">Guardar</button>
        </div>
    `;

    backdrop.appendChild(dialog);
    document.body.appendChild(backdrop);

    // Estado y helpers
    const pad = (n)=> String(n).padStart(2,'0');
    const now = new Date();
    const dateStr = `${now.getFullYear()}-${pad(now.getMonth()+1)}-${pad(now.getDate())}`;
    const timeStr = `${pad(now.getHours())}:${pad(now.getMinutes())}`;
    dialog.querySelector('#apptDate').value = dateStr;
    dialog.querySelector('#apptTime').value = timeStr;

    let step = 0;
    const steps = Array.from(dialog.querySelectorAll('.step'));
    const dots = Array.from(dialog.querySelectorAll('.stepper .dot'));
    const btnBack = dialog.querySelector('[data-back]');
    const btnNext = dialog.querySelector('[data-next]');
    const btnSave = dialog.querySelector('[data-save]');

    const updateSummary = () => {
        const date = dialog.querySelector('#apptDate').value;
        const time = dialog.querySelector('#apptTime').value;
        const dur  = dialog.querySelector('#apptDur').value || '30';
        const cal  = dialog.querySelector('#apptCalendar').options[0]?.text || 'Mi Desk';
        const notes = dialog.querySelector('#apptNotes').value.trim();
        dialog.querySelector('#apptSummary').innerHTML = `
            <div><strong>Cliente:</strong> ${escapeHtml(clientName)} ${leadId ? '(Lead #'+leadId+')' : ''}</div>
            <div><strong>Fecha:</strong> ${escapeHtml(date)} <strong>Hora:</strong> ${escapeHtml(time)} (${dur} min)</div>
            <div><strong>Calendario:</strong> ${escapeHtml(cal)}</div>
            ${notes ? '<div><strong>Notas:</strong> '+escapeHtml(notes)+'</div>' : ''}
        `;
    };

    const renderStep = () => {
        steps.forEach((s,i)=> s.classList.toggle('active', i===step));
        dots.forEach((d,i)=> d.classList.toggle('active', i<=step));
        btnBack.disabled = step===0;
        btnNext.style.display = step<steps.length-1 ? 'inline-block' : 'none';
        btnSave.style.display = step===steps.length-1 ? 'inline-block' : 'none';
        if (step===steps.length-1) updateSummary();
    };
    renderStep();

    // Cerrar
    const close = ()=>{ try{ document.body.removeChild(backdrop); }catch(e){} };
    dialog.querySelector('[data-close]').addEventListener('click', close);
    backdrop.addEventListener('click', (e)=>{ if (e.target === backdrop) close(); });
    document.addEventListener('keydown', function escClose(e){ if(e.key==='Escape'){ close(); document.removeEventListener('keydown', escClose);} });

    // Navegación
    btnBack.addEventListener('click', ()=>{ if (step>0){ step--; renderStep(); } });
    btnNext.addEventListener('click', ()=>{
        // Validaciones básicas
        if (step===0){
            const date = dialog.querySelector('#apptDate').value;
            const time = dialog.querySelector('#apptTime').value;
            if (!date || !time){
                showNotification('Completa fecha y hora de la cita', 'warning');
                return;
            }
        }
        step = Math.min(step+1, steps.length-1);
        renderStep();
    });

    // Guardar
    btnSave.addEventListener('click', async ()=>{
        const date = dialog.querySelector('#apptDate').value;
        const time = dialog.querySelector('#apptTime').value;
        const dur = parseInt(dialog.querySelector('#apptDur').value || '30', 10);
        const notes = dialog.querySelector('#apptNotes').value.trim();
        const calendar = 'desk';
        if (!date || !time){
            showNotification('Completa fecha y hora de la cita', 'warning');
            return;
        }
        const start = new Date(`${date}T${time}`);
        const end = new Date(start.getTime() + (dur * 60000));
        const title = `Cita con ${clientName || 'Cliente'}`;
        const eventId = addEventToCalendar({ title, description: notes, start, end, calendar, color: '#2ea5e9' });
        if (eventId){
            showNotification('Cita programada y agregada al calendario', 'success');
        } else {
            showNotification('No se pudo guardar la cita en el calendario', 'error');
        }
        if (leadId && leadId > 0){
            try{
                const scheduled = `${start.getFullYear()}-${pad(start.getMonth()+1)}-${pad(start.getDate())} ${pad(start.getHours())}:${pad(start.getMinutes())}:00`;
                const params = new URLSearchParams({
                    lead_id: String(leadId), type: 'meeting', subject: title, description: notes, status: 'pending', scheduled_at: scheduled, duration_min: String(dur)
                });
                const resp = await fetch('/modules/leads/add_activity.php', {
                    method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: params.toString()
                });
                const data = await resp.json().catch(()=>({}));
                if (resp.ok && data && (data.ok || data.success)){
                    showNotification('Actividad registrada en el historial del lead', 'success');

                    // Refrescar timeline y paginación (si está disponible en la vista)
                    try { if (typeof window.loadActivitiesPage === 'function') { window.loadActivitiesPage(1); } } catch(e){}

                    // Refrescar contador real de "Reuniones programadas" desde el servidor para evitar reseteos
                    try {
                        const statsResp = await fetch(`/modules/leads/get_lead_stats.php?lead_id=${encodeURIComponent(String(leadId))}`);
                        const statsData = await statsResp.json().catch(()=>({}));
                        if (statsData && statsData.success && statsData.stats) {
                            const totalMeetings = parseInt(statsData.stats.total_meetings || 0, 10);
                            const labels = document.querySelectorAll('.stat-card .stat-label');
                            labels.forEach(label => {
                                if ((label.textContent || '').trim().toLowerCase() === 'reuniones programadas') {
                                    const numEl = label.parentElement?.querySelector('.stat-number');
                                    if (numEl) { numEl.textContent = String(totalMeetings); }
                                }
                            });
                        }
                    } catch(e) { console.warn('No se pudo refrescar el contador de reuniones', e); }
                    // Cerrar modal solo en éxito
                    close();
                } else {
                    // Manejar conflictos y errores
                    const msg = (data && data.error) ? data.error : 'No se pudo registrar la actividad de cita';
                    showNotification(msg, 'error');
                    // Sugerencias de horarios alternativos
                    try {
                        const sugBox = dialog.querySelector('#apptSuggestions');
                        if (sugBox) {
                            const suggestions = (data && Array.isArray(data.suggestions)) ? data.suggestions : [];
                            if (suggestions.length > 0) {
                                sugBox.style.display = 'flex';
                                // Limpiar previos excepto el título
                                Array.from(sugBox.querySelectorAll('.suggestion-btn')).forEach(el=> el.remove());
                                suggestions.slice(0,3).forEach(sISO => {
                                    const sDate = new Date(sISO);
                                    const label = `${String(sDate.getFullYear())}-${String(sDate.getMonth()+1).padStart(2,'0')}-${String(sDate.getDate()).padStart(2,'0')} ${String(sDate.getHours()).padStart(2,'0')}:${String(sDate.getMinutes()).padStart(2,'0')}`;
                                    const btn = document.createElement('button');
                                    btn.className = 'suggestion-btn';
                                    btn.textContent = label;
                                    btn.addEventListener('click', ()=>{
                                        dialog.querySelector('#apptDate').value = label.slice(0,10);
                                        dialog.querySelector('#apptTime').value = label.slice(11,16);
                                        showNotification('Aplicada sugerencia de horario', 'info');
                                        step = 1; renderStep();
                                    });
                                    sugBox.appendChild(btn);
                                });
                            }
                        }
                    } catch(e) {}
                    // Mantener el modal abierto para que el usuario ajuste fecha/hora
                }
                // No crear nota adicional: el comentario queda dentro de la actividad de reunión
            }catch(e){ console.warn('No se pudo registrar la actividad de cita', e); }
        }
    });
}

// Exportar la función dentro de ProfixCRM si no estuviera
try { window.ProfixCRM = window.ProfixCRM || {}; window.ProfixCRM.openAppointmentAssistant = openAppointmentAssistant; } catch(e){}

function initializeGlobalCalendarReminder(){
    // Evitar duplicar recordatorios si la página del calendario ya corre su propio scheduler
    if (document.getElementById('calendar')) return;
    const uid = (window.__CALENDAR_USER_ID__ || 1);
    const key = `calendarEvents:${uid}`;
    const notified = (window.__CAL_REM_NOTIFIED__ = window.__CAL_REM_NOTIFIED__ || new Set());
    const offsetMin = 15;
    const check = ()=>{
        let list = [];
        try { list = JSON.parse(localStorage.getItem(key) || '[]') || []; } catch(e) { list = []; }
        const now = Date.now();
        const offsetMs = offsetMin * 60 * 1000;
        list.forEach(ev => {
            const startMs = new Date(ev.startISO).getTime();
            const notifKey = `rem:${ev.id}:${ev.startISO}`;
            if (startMs - now <= offsetMs && startMs - now > 0 && !notified.has(notifKey)){
                notified.add(notifKey);
                const hh = String(new Date(ev.startISO).getHours()).padStart(2,'0');
                const mm = String(new Date(ev.startISO).getMinutes()).padStart(2,'0');
                showNotification(`Recordatorio: ${ev.title || 'Evento'} a las ${hh}:${mm}`, 'info');
            }
        });
    };
    try { check(); } catch(e){}
    try { window.__CAL_REM_TIMER__ && clearInterval(window.__CAL_REM_TIMER__); } catch(e){}
    window.__CAL_REM_TIMER__ = setInterval(check, 30000);
}

// Exponer nuevas utilidades en el objeto global
if (!window.ProfixCRM) {
    window.ProfixCRM = {};
}
Object.assign(window.ProfixCRM, { openAppointmentAssistant, addEventToCalendar });
