// Dashboard Interactive Effects and Animations

class DashboardAnimations {
    constructor() {
        this.canvas = null;
        this.ctx = null;
        this.particles = [];
        this.gridLines = [];
        this.animationId = null;
        this.isVisible = true;
        
        this.config = {
            particleCount: 50,
            gridSpacing: 60,
            particleSpeed: 0.5,
            connectionDistance: 120,
            colors: {
                primary: 'rgba(59, 130, 246, 0.6)',
                secondary: 'rgba(16, 185, 129, 0.4)',
                accent: 'rgba(245, 158, 11, 0.3)',
                grid: 'rgba(255, 255, 255, 0.1)'
            }
        };
        
        this.init();
    }
    
    init() {
        this.setupCanvas();
        this.createParticles();
        this.createGridLines();
        this.setupEventListeners();
        this.animate();
        this.initMiniCharts();
        this.initCounterAnimations();
        this.initScrollAnimations();
    }
    
    setupCanvas() {
        this.canvas = document.getElementById('dashboardCanvas');
        if (!this.canvas) return;
        
        this.ctx = this.canvas.getContext('2d');
        this.resizeCanvas();
    }
    
    resizeCanvas() {
        if (!this.canvas) return;
        
        this.canvas.width = window.innerWidth;
        this.canvas.height = window.innerHeight;
    }
    
    createParticles() {
        this.particles = [];
        const count = Math.min(this.config.particleCount, Math.floor((this.canvas?.width || 1920) * (this.canvas?.height || 1080) / 15000));
        
        for (let i = 0; i < count; i++) {
            this.particles.push(new DashboardParticle(this.canvas, this.config));
        }
    }
    
    createGridLines() {
        this.gridLines = [];
        if (!this.canvas) return;
        
        // Vertical lines
        for (let x = 0; x < this.canvas.width; x += this.config.gridSpacing) {
            this.gridLines.push(new DashboardGridLine(x, 0, x, this.canvas.height, 'vertical'));
        }
        
        // Horizontal lines
        for (let y = 0; y < this.canvas.height; y += this.config.gridSpacing) {
            this.gridLines.push(new DashboardGridLine(0, y, this.canvas.width, y, 'horizontal'));
        }
    }
    
    animate() {
        if (!this.ctx || !this.isVisible) {
            this.animationId = requestAnimationFrame(() => this.animate());
            return;
        }
        
        // Clear canvas with gradient background
        const gradient = this.ctx.createLinearGradient(0, 0, this.canvas.width, this.canvas.height);
        gradient.addColorStop(0, 'rgba(15, 23, 42, 0.02)');
        gradient.addColorStop(0.5, 'rgba(30, 41, 59, 0.03)');
        gradient.addColorStop(1, 'rgba(51, 65, 85, 0.02)');
        
        this.ctx.fillStyle = gradient;
        this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
        
        // Draw grid lines
        this.gridLines.forEach(line => line.draw(this.ctx));
        
        // Update and draw particles
        this.particles.forEach(particle => {
            particle.update();
            particle.draw(this.ctx);
        });
        
        // Draw connections between particles
        this.drawConnections();
        
        this.animationId = requestAnimationFrame(() => this.animate());
    }
    
    drawConnections() {
        for (let i = 0; i < this.particles.length; i++) {
            for (let j = i + 1; j < this.particles.length; j++) {
                const dx = this.particles[i].x - this.particles[j].x;
                const dy = this.particles[i].y - this.particles[j].y;
                const distance = Math.sqrt(dx * dx + dy * dy);
                
                if (distance < this.config.connectionDistance) {
                    const opacity = (1 - distance / this.config.connectionDistance) * 0.3;
                    this.ctx.strokeStyle = `rgba(59, 130, 246, ${opacity})`;
                    this.ctx.lineWidth = 1;
                    this.ctx.beginPath();
                    this.ctx.moveTo(this.particles[i].x, this.particles[i].y);
                    this.ctx.lineTo(this.particles[j].x, this.particles[j].y);
                    this.ctx.stroke();
                }
            }
        }
    }
    
    setupEventListeners() {
        window.addEventListener('resize', () => {
            this.resizeCanvas();
            this.createParticles();
            this.createGridLines();
        });
        
        // Pause animation when tab is not visible
        document.addEventListener('visibilitychange', () => {
            this.isVisible = !document.hidden;
        });
        
        // Mouse interaction
        if (this.canvas) {
            this.canvas.addEventListener('mousemove', (e) => {
                const rect = this.canvas.getBoundingClientRect();
                const mouseX = e.clientX - rect.left;
                const mouseY = e.clientY - rect.top;
                
                this.particles.forEach(particle => {
                    const dx = mouseX - particle.x;
                    const dy = mouseY - particle.y;
                    const distance = Math.sqrt(dx * dx + dy * dy);
                    
                    if (distance < 100) {
                        particle.vx += dx * 0.0001;
                        particle.vy += dy * 0.0001;
                    }
                });
            });
        }
    }
    
    initMiniCharts() {
        const charts = document.querySelectorAll('.mini-chart');
        charts.forEach(chart => {
            const values = JSON.parse(chart.dataset.values || '[0]');
            this.createMiniChart(chart, values);
        });
    }
    
    createMiniChart(element, values) {
        const canvas = document.createElement('canvas');
        canvas.width = 100;
        canvas.height = 40;
        element.appendChild(canvas);
        
        const ctx = canvas.getContext('2d');
        const max = Math.max(...values);
        const min = Math.min(...values);
        const range = max - min || 1;
        
        ctx.strokeStyle = 'rgba(59, 130, 246, 0.8)';
        ctx.lineWidth = 2;
        ctx.beginPath();
        
        values.forEach((value, index) => {
            const x = (index / (values.length - 1)) * canvas.width;
            const y = canvas.height - ((value - min) / range) * canvas.height;
            
            if (index === 0) {
                ctx.moveTo(x, y);
            } else {
                ctx.lineTo(x, y);
            }
        });
        
        ctx.stroke();
        
        // Add glow effect
        ctx.shadowColor = 'rgba(59, 130, 246, 0.5)';
        ctx.shadowBlur = 10;
        ctx.stroke();
    }
    
    initCounterAnimations() {
        const counters = document.querySelectorAll('.stat-value');
        
        const animateCounter = (element) => {
            const target = parseFloat(element.textContent.replace(/[^0-9.-]/g, '')) || 0;
            const duration = 2000;
            const start = performance.now();
            const prefix = element.textContent.match(/^[^0-9]*/)[0];
            const suffix = element.textContent.match(/[^0-9]*$/)[0];
            
            const animate = (currentTime) => {
                const elapsed = currentTime - start;
                const progress = Math.min(elapsed / duration, 1);
                
                // Easing function
                const easeOutQuart = 1 - Math.pow(1 - progress, 4);
                const current = target * easeOutQuart;
                
                element.textContent = prefix + (target % 1 === 0 ? 
                    Math.floor(current).toLocaleString() : 
                    current.toFixed(2)) + suffix;
                
                if (progress < 1) {
                    requestAnimationFrame(animate);
                }
            };
            
            requestAnimationFrame(animate);
        };
        
        // Intersection Observer for counter animations
        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    animateCounter(entry.target);
                    observer.unobserve(entry.target);
                }
            });
        });
        
        counters.forEach(counter => observer.observe(counter));
    }
    
    initScrollAnimations() {
        const animatedElements = document.querySelectorAll('.stat-card, .account-row, .account-card, .ticker-item');
        
        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    entry.target.style.opacity = '1';
                    entry.target.style.transform = 'translateY(0)';
                }
            });
        }, {
            threshold: 0.1,
            rootMargin: '0px 0px -50px 0px'
        });
        
        animatedElements.forEach(element => {
            element.style.opacity = '0';
            element.style.transform = 'translateY(30px)';
            element.style.transition = 'opacity 0.6s ease, transform 0.6s ease';
            observer.observe(element);
        });
    }
}

class DashboardParticle {
    constructor(canvas, config) {
        this.canvas = canvas;
        this.config = config;
        this.reset();
    }
    
    reset() {
        this.x = Math.random() * (this.canvas?.width || 1920);
        this.y = Math.random() * (this.canvas?.height || 1080);
        this.vx = (Math.random() - 0.5) * this.config.particleSpeed;
        this.vy = (Math.random() - 0.5) * this.config.particleSpeed;
        this.size = Math.random() * 3 + 1;
        this.opacity = Math.random() * 0.5 + 0.2;
        this.color = this.getRandomColor();
    }
    
    getRandomColor() {
        const colors = Object.values(this.config.colors);
        return colors[Math.floor(Math.random() * colors.length)];
    }
    
    update() {
        this.x += this.vx;
        this.y += this.vy;
        
        // Bounce off edges
        if (this.x < 0 || this.x > (this.canvas?.width || 1920)) {
            this.vx *= -1;
        }
        if (this.y < 0 || this.y > (this.canvas?.height || 1080)) {
            this.vy *= -1;
        }
        
        // Keep particles in bounds
        this.x = Math.max(0, Math.min(this.x, this.canvas?.width || 1920));
        this.y = Math.max(0, Math.min(this.y, this.canvas?.height || 1080));
    }
    
    draw(ctx) {
        ctx.save();
        ctx.globalAlpha = this.opacity;
        ctx.fillStyle = this.color;
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
        ctx.fill();
        
        // Add glow effect
        ctx.shadowColor = this.color;
        ctx.shadowBlur = this.size * 2;
        ctx.fill();
        ctx.restore();
    }
}

class DashboardGridLine {
    constructor(x1, y1, x2, y2, type) {
        this.x1 = x1;
        this.y1 = y1;
        this.x2 = x2;
        this.y2 = y2;
        this.type = type;
        this.opacity = Math.random() * 0.3 + 0.1;
        this.pulseSpeed = Math.random() * 0.02 + 0.01;
        this.pulseOffset = Math.random() * Math.PI * 2;
    }
    
    draw(ctx) {
        const time = Date.now() * 0.001;
        const pulse = Math.sin(time * this.pulseSpeed + this.pulseOffset) * 0.1 + 0.9;
        
        ctx.strokeStyle = `rgba(255, 255, 255, ${this.opacity * pulse})`;
        ctx.lineWidth = 0.5;
        ctx.beginPath();
        ctx.moveTo(this.x1, this.y1);
        ctx.lineTo(this.x2, this.y2);
        ctx.stroke();
    }
}

// Interactive Features
class DashboardInteractions {
    constructor() {
        this.init();
    }
    
    init() {
        this.setupButtonAnimations();
        this.setupTableInteractions();
        // ticker eliminado
        this.setupProgressBars();
        this.setupSidebarToggle();
        this.setupSidebarOverlay();
        this.setupSidebarMenuBehavior();
        this.setupResponsiveClose();
        this.setupWebTraderButton();
        this.setupContactManager();
        this.setupAccountSwitcher();
        this.setupTradingActions();
        this.setupDocumentsUpload();
        this.setupSupportActions();
        this.setupVerificationAnimations();
    }
    
    setupButtonAnimations() {
        const buttons = document.querySelectorAll('.action-btn, .action-btn-small, .filter-btn, .refresh-btn');
        
        buttons.forEach(button => {
            button.addEventListener('mouseenter', (e) => {
                e.target.style.transform = 'translateY(-3px) scale(1.05)';
            });
            
            button.addEventListener('mouseleave', (e) => {
                e.target.style.transform = 'translateY(0) scale(1)';
            });
            
            button.addEventListener('click', (e) => {
                // Ripple effect
                const ripple = document.createElement('span');
                const rect = e.target.getBoundingClientRect();
                const size = Math.max(rect.width, rect.height);
                const x = e.clientX - rect.left - size / 2;
                const y = e.clientY - rect.top - size / 2;
                
                ripple.style.cssText = `
                    position: absolute;
                    width: ${size}px;
                    height: ${size}px;
                    left: ${x}px;
                    top: ${y}px;
                    background: rgba(255, 255, 255, 0.3);
                    border-radius: 50%;
                    transform: scale(0);
                    animation: ripple 0.6s ease-out;
                    pointer-events: none;
                `;
                
                e.target.style.position = 'relative';
                e.target.style.overflow = 'hidden';
                e.target.appendChild(ripple);
                
                setTimeout(() => ripple.remove(), 600);
            });
        });
        
        // Add ripple animation CSS
        const style = document.createElement('style');
        style.textContent = `
            @keyframes ripple {
                to {
                    transform: scale(2);
                    opacity: 0;
                }
            }
        `;
        document.head.appendChild(style);
    }
    
    setupTableInteractions() {
        const rows = document.querySelectorAll('.account-row, .account-card');
        
        rows.forEach(row => {
            row.addEventListener('mouseenter', () => {
                row.style.background = 'rgba(59, 130, 246, 0.08)';
                row.style.transform = 'translateX(5px) scale(1.01)';
                row.style.boxShadow = '0 8px 25px rgba(0, 0, 0, 0.1)';
            });
            
            row.addEventListener('mouseleave', () => {
                row.style.background = '';
                row.style.transform = '';
                row.style.boxShadow = '';
            });
        });
    }
    
    setupTickerAnimations() {
        const tickerItems = document.querySelectorAll('.ticker-item');
        
        tickerItems.forEach((item, index) => {
            // Animate prices
            const priceElement = item.querySelector('.price');
            const changeElement = item.querySelector('.change');
            
            setInterval(() => {
                const currentPrice = parseFloat(priceElement.textContent.replace(/,/g, ''));
                const change = (Math.random() - 0.5) * currentPrice * 0.001;
                const newPrice = currentPrice + change;
                
                priceElement.textContent = newPrice.toLocaleString(undefined, {
                    minimumFractionDigits: 2,
                    maximumFractionDigits: 2
                });
                
                // Update change indicator
                const changeValue = change >= 0 ? `+${change.toFixed(4)}` : change.toFixed(4);
                changeElement.textContent = changeValue;
                changeElement.className = `change ${change >= 0 ? 'positive' : 'negative'}`;
                
                // Flash animation
                item.style.background = change >= 0 ? 
                    'rgba(16, 185, 129, 0.1)' : 
                    'rgba(239, 68, 68, 0.1)';
                
                setTimeout(() => {
                    item.style.background = '';
                }, 500);
                
            }, 3000 + index * 500);
        });
    }
    
    setupProgressBars() {
        const progressBars = document.querySelectorAll('.balance-fill, .indicator-fill');
        
        progressBars.forEach(bar => {
            const targetWidth = bar.style.width;
            bar.style.width = '0%';
            
            setTimeout(() => {
                bar.style.width = targetWidth;
            }, 500);
        });
    }

    setupSidebarToggle() {
        const toggle = document.querySelector('.sidebar-toggle');
        const sidebar = document.getElementById('sidebar');
        if (!toggle || !sidebar) return;
        toggle.addEventListener('click', () => {
            // En móviles usar la clase .show del sidebar global
            if (window.innerWidth <= 1024) {
                sidebar.classList.toggle('show');
                const overlay = document.querySelector('.sidebar-overlay');
                if (overlay) overlay.style.display = sidebar.classList.contains('show') ? 'block' : 'none';
            } else {
                document.body.classList.toggle('sidebar-open');
                const overlay = document.querySelector('.sidebar-overlay');
                if (overlay) overlay.style.display = document.body.classList.contains('sidebar-open') ? 'block' : 'none';
            }
        });
    }

    setupSidebarOverlay() {
        // Create overlay element if not present
        let overlay = document.querySelector('.sidebar-overlay');
        if (!overlay) {
            overlay = document.createElement('div');
            overlay.className = 'sidebar-overlay';
            document.body.appendChild(overlay);
        }
        overlay.addEventListener('click', () => {
            document.body.classList.remove('sidebar-open');
            overlay.style.display = 'none';
        });
    }

    setupSidebarMenuBehavior() {
        const menuLinks = document.querySelectorAll('.sidebar-menu .menu-item');
        menuLinks.forEach(link => {
            link.addEventListener('click', () => {
                // Close sidebar on mobile after navigation
                if (window.innerWidth <= 992 && document.body.classList.contains('sidebar-open')) {
                    document.body.classList.remove('sidebar-open');
                    const overlay = document.querySelector('.sidebar-overlay');
                    if (overlay) overlay.style.display = 'none';
                }
                // Active state
                menuLinks.forEach(l => l.classList.remove('active'));
                link.classList.add('active');
            });
        });
    }

    setupResponsiveClose() {
        // Close sidebar with Escape key
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape' && document.body.classList.contains('sidebar-open')) {
                document.body.classList.remove('sidebar-open');
                const overlay = document.querySelector('.sidebar-overlay');
                if (overlay) overlay.style.display = 'none';
            }
            // cerrar en móviles si está abierto
            const sidebar = document.getElementById('sidebar');
            if (e.key === 'Escape' && sidebar && sidebar.classList.contains('show')) {
                sidebar.classList.remove('show');
                const overlay = document.querySelector('.sidebar-overlay');
                if (overlay) overlay.style.display = 'none';
            }
        });
        // Ensure overlay closes when resizing to desktop
        window.addEventListener('resize', () => {
            if (window.innerWidth > 992 && document.body.classList.contains('sidebar-open')) {
                document.body.classList.remove('sidebar-open');
                const overlay = document.querySelector('.sidebar-overlay');
                if (overlay) overlay.style.display = 'none';
            }
            const sidebar = document.getElementById('sidebar');
            if (window.innerWidth > 1024 && sidebar && sidebar.classList.contains('show')) {
                sidebar.classList.remove('show');
                const overlay = document.querySelector('.sidebar-overlay');
                if (overlay) overlay.style.display = 'none';
            }
        });
    }

    setupWebTraderButton() {
        const btn = document.querySelector('.webtrader-btn');
        if (!btn) return;
        btn.addEventListener('click', (e) => {
            e.preventDefault();
            this.showToast('WebTrader estará disponible próximamente.');
        });
    }

    setupContactManager() {
        const btn = document.querySelector('.contact-manager');
        if (!btn) return;
        btn.addEventListener('click', () => {
            const email = btn.getAttribute('data-email');
            if (email) {
                window.location.href = `mailto:${email}`;
            } else {
                this.showToast('No hay gestor asignado actualmente.');
            }
        });
    }

    showToast(message) {
        const toast = document.createElement('div');
        toast.className = 'toast';
        toast.textContent = message;
        document.body.appendChild(toast);
        // Force reflow
        void toast.offsetWidth;
        toast.classList.add('show');
        setTimeout(() => {
            toast.classList.remove('show');
            setTimeout(() => toast.remove(), 300);
        }, 2500);
    }

    setupAccountSwitcher() {
        const select = document.querySelector('.account-switcher');
        if (!select) return;
        select.addEventListener('change', () => {
            const id = select.value;
            const row = [...document.querySelectorAll('.account-row, .account-card')]
                .find(r => r.querySelector('.account-number')?.textContent.trim() === id);
            if (row) {
                row.scrollIntoView({ behavior: 'smooth', block: 'center' });
                row.style.boxShadow = '0 0 0 3px rgba(59,130,246,0.35)';
                setTimeout(() => { row.style.boxShadow = ''; }, 1500);
            }
            this.showToast(`Cuenta ${id} seleccionada`);
        });
    }

    setupTradingActions() {
        const cards = document.querySelectorAll('.account-card');
        cards.forEach(card => {
            const account = card.querySelector('.account-number')?.textContent.trim();
            const depositBtn = card.querySelector('.action-btn-small.deposit');
            const withdrawBtn = card.querySelector('.action-btn-small.withdraw');
            if (depositBtn) depositBtn.addEventListener('click', () => {
                this.showToast(`Depositar a cuenta ${account}`);
                // Redirigir a sección de depósitos si existe
                const depositsAnchor = document.querySelector('#deposits');
                if (depositsAnchor) window.location.hash = '#deposits';
            });
            if (withdrawBtn) withdrawBtn.addEventListener('click', () => {
                this.showToast(`Retirar de cuenta ${account}`);
                const transactionsAnchor = document.querySelector('#transactions');
                if (transactionsAnchor) window.location.hash = '#transactions';
            });
        });
    }

    setupDocumentsUpload() {
        const input = document.querySelector('.document-input');
        const uploadButtons = document.querySelectorAll('.documents-table .upload');
        if (!input) return;

        let currentType = null;
        uploadButtons.forEach(btn => btn.addEventListener('click', () => {
            currentType = btn.getAttribute('data-type') || null;
            input.value = '';
            input.click();
        }));

        input.addEventListener('change', async (e) => {
            const file = e.target.files?.[0];
            if (!file || !currentType) return;

            const fd = new FormData();
            fd.append('type', currentType);
            fd.append('file', file);

            try {
                const res = await fetch('/modules/client_portal/upload_document.php', {
                    method: 'POST',
                    body: fd
                });
                const data = await res.json();
                if (!data.success) throw new Error(data.error || 'Error al subir');

                // Actualizar UI de la fila
                const row = document.querySelector(`.documents-table tr[data-type="${currentType}"]`);
                if (row) {
                    const dateCell = row.querySelector('.doc-date');
                    const statusCell = row.querySelector('.doc-status');
                    if (dateCell) dateCell.textContent = (data.date || '').slice(0, 10);
                    if (statusCell) statusCell.innerHTML = '<span class="doc-badge pending"><i class="fas fa-hourglass-half"></i> En revisión</span>';
                    // Enable view link
                    const viewBtn = row.querySelector('.view');
                    if (viewBtn && viewBtn.tagName.toLowerCase() === 'button') {
                        const a = document.createElement('a');
                        a.className = 'action-btn-small view';
                        a.href = data.filename;
                        a.target = '_blank';
                        a.innerHTML = '<i class="fas fa-eye"></i>';
                        viewBtn.replaceWith(a);
                    } else if (viewBtn && viewBtn.tagName.toLowerCase() === 'a') {
                        viewBtn.href = data.filename;
                        viewBtn.target = '_blank';
                    }
                }

                // Recalcular progreso de verificación
                this.updateVerificationProgress();
                this.showToast(`Documento "${file.name}" subido correctamente`);
            } catch (err) {
                this.showToast(err.message || 'Error al subir documento');
            }
        });
    }

    setupSupportActions() {
        const ticketBtn = document.querySelector('.open-ticket');
        const faqBtn = document.querySelector('.open-faq');
        const contactBtn = document.querySelector('.contact-support');
        if (ticketBtn) ticketBtn.addEventListener('click', async () => {
            const subject = prompt('Asunto del ticket:');
            if (!subject) return;
            const message = prompt('Describe tu solicitud:');
            if (!message) return;
            try {
                const res = await fetch('/modules/client_portal/create_ticket.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    body: new URLSearchParams({ subject, message, priority: 'medium' }).toString()
                });
                const data = await res.json();
                if (!data.success) throw new Error(data.error || 'Error al crear ticket');
                this.showToast('Ticket creado correctamente');
            } catch (err) {
                this.showToast(err.message || 'Error creando ticket');
            }
        });
        if (faqBtn) faqBtn.addEventListener('click', () => this.showToast('Abrir FAQ próximamente'));
        if (contactBtn) contactBtn.addEventListener('click', () => {
            const email = 'support@' + (window.location.hostname || 'example.com');
            window.location.href = `mailto:${email}`;
        });
    }

    updateVerificationProgress() {
        const progress = document.querySelector('.verification-section .progress-fill');
        const label = document.querySelector('.verification-section .progress-label');
        if (!progress || !label) return;
        // 1 paso por datos personales + documentos subidos/revisión
        const docRows = document.querySelectorAll('.documents-table tbody tr');
        let completed = 1;
        docRows.forEach(row => {
            const status = row.querySelector('.doc-status .doc-badge');
            if (status && !status.classList.contains('pending')) {
                completed += 1; // approved/rejected contarían; en revisión ya subido también
            } else {
                // Si está "En revisión" lo marcamos como completado parcial
                if (status && status.textContent.includes('Revisión')) completed += 1;
            }
        });
        const pct = Math.min(100, Math.round((completed / 4) * 100));
        progress.style.width = pct + '%';
        label.textContent = pct + '% completado';
    }

    setupVerificationAnimations() {
        const progress = document.querySelector('.progress-fill');
        if (progress) {
            setTimeout(() => { progress.style.width = '25%'; }, 300);
        }
        const steps = document.querySelectorAll('.verification-steps .step');
        steps.forEach(step => {
            step.addEventListener('mouseenter', () => { step.style.transform = 'translateY(-2px)'; step.style.boxShadow = '0 12px 30px rgba(0,0,0,0.1)'; });
            step.addEventListener('mouseleave', () => { step.style.transform = ''; step.style.boxShadow = ''; });
        });
    }
}

// Initialize when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
    new DashboardAnimations();
    new DashboardInteractions();
    
    // Add loading animation
    document.body.style.opacity = '0';
    document.body.style.transition = 'opacity 0.5s ease';
    
    setTimeout(() => {
        document.body.style.opacity = '1';
    }, 100);

    // Notificar estados de documentos aprobados/rechazados al cargar
    try {
        const badges = document.querySelectorAll('.documents-section .doc-badge');
        let notified = false;
        badges.forEach(b => {
            const text = b.textContent || '';
            if (text.includes('Aprobado')) {
                window.DashboardInteractions?.showToast('Documento aprobado');
                notified = true;
            }
            if (text.includes('Rechazado')) {
                window.DashboardInteractions?.showToast('Documento rechazado');
                notified = true;
            }
        });
        if (!notified) {
            // Si hay documentos en revisión, recordatorio suave
            const anyReview = Array.from(badges).some(b => (b.textContent || '').includes('Revisión'));
            if (anyReview) window.DashboardInteractions?.showToast('Tus documentos están en revisión');
        }
    } catch {}
});

// Export for potential external use
window.DashboardAnimations = DashboardAnimations;
window.DashboardInteractions = DashboardInteractions;