/**
 * Dashboard — Plataforma Ganadera
 * Chart.js integrations, D3 Hierarchical Bar, KPI counters, alerts, timeline
 */

$(document).ready(function() {
    Dashboard.init();
});

const Dashboard = {
    charts: {},
    data: {},

    period: 'month',

    async init() {
        this.bindPeriodTabs();
        await this.loadDashboard();
    },

    bindPeriodTabs() {
        const self = this;
        $('.pill-tab').on('click', function() {
            $('.pill-tab').removeClass('active');
            $(this).addClass('active');
            self.period = $(this).data('period');
            self.loadDashboard();
        });
    },

    async loadDashboard() {
        const res = await API.get(`/dashboard?period=${this.period}`);
        if (!res.success) return;
        this.data = res.data;
        this.renderStats();
        this.renderAlerts();
        this.renderRecentActivity();
        this.renderSpeciesChart();
        this.renderBirthsChart();
        this.renderHierarchyChart();
        this.renderUpcomingEvents();
        this.animateEntrance();
    },

    // ─── KPI STATS — Gradient Cards ──────────────────────────

    renderStats() {
        const d = this.data;
        const stats = [
            { id: 'totalAnimals',    value: d.total_animals,     label: 'Total Animales',    icon: 'animals',    gradient: 'mint',   color: '#065F46'  },
            { id: 'activeLots',      value: d.active_lots,       label: 'Lotes Activos',     icon: 'lots',       gradient: 'purple', color: '#5B21B6'  },
            { id: 'birthsMonth',     value: d.births_month,      label: 'Nacimientos Mes',   icon: 'births',     gradient: 'blue',   color: '#1E40AF'  },
            { id: 'sickAnimals',     value: d.sick_animals,      label: 'Enfermos',          icon: 'sick',       gradient: 'pink',   color: '#9D174D'  },
            { id: 'quarantine',      value: d.quarantine_animals,label: 'Cuarentena',        icon: 'quarantine', gradient: 'amber',  color: '#92400E'  },
            { id: 'pendingVaccines', value: d.pending_vaccines,  label: 'Vacunas Pendientes',icon: 'vaccines',   gradient: 'cyan',   color: '#155E75'  },
            { id: 'salesMonth',      value: d.sales_month,       label: 'Ventas del Mes',    icon: 'sales',      gradient: 'dark',   color: '#E2E8F0'  },
            { id: 'revenueMonth',    value: d.sales_month_total, label: 'Ingresos del Mes',  icon: 'sales',      gradient: 'mint',   color: '#065F46', prefix: '$', isCurrency: true },
            { id: 'mortalityRate',   value: d.mortality_rate,     label: 'Mortalidad %',      icon: 'mortality',  gradient: 'pink',   color: '#9D174D', suffix: '%' },
        ];

        const $grid = $('#statsGrid');
        $grid.empty();

        stats.forEach((s, i) => {
            const isDark = s.gradient === 'dark';
            const textColor = isDark ? '#E2E8F0' : s.color;
            const $card = $(`
                <div class="dash-kpi grad-card grad-card--${s.gradient} anim-fade-up" style="animation-delay:${i * 70}ms">
                    <div class="dash-kpi-icon" style="color:${textColor}">
                        ${this.getIcon(s.icon)}
                    </div>
                    <div class="dash-kpi-body">
                        <div class="dash-kpi-label" style="color:${textColor}">${s.label}</div>
                        <div class="dash-kpi-value" style="color:${textColor}" data-target="${s.value}"${s.suffix ? ` data-suffix="${s.suffix}"` : ''}${s.isCurrency ? ' data-currency="1"' : ''}${s.prefix ? ` data-prefix="${s.prefix}"` : ''}>0</div>
                    </div>
                </div>
            `);
            $grid.append($card);
        });

        // Animate counters
        setTimeout(() => {
            $('.dash-kpi-value').each(function() {
                const target = parseFloat($(this).data('target')) || 0;
                const suffix = $(this).data('suffix') || '';
                const prefix = $(this).data('prefix') || '';
                const isCurrency = $(this).data('currency');
                if (isCurrency) {
                    App.animateCounter(this, target, 1200, '', '$');
                } else {
                    App.animateCounter(this, target, 1200, suffix);
                }
            });
        }, 200);
    },

    // ─── ALERTS ─────────────────────────────────────────────

    renderAlerts() {
        const d = this.data;
        const $list = $('#alertsList');
        $list.empty();

        const alerts = [];
        if (d.sick_animals > 0) alerts.push({ title: `${d.sick_animals} animales enfermos`, priority: 'critical', count: d.sick_animals });
        if (d.quarantine > 0) alerts.push({ title: `${d.quarantine} en cuarentena`, priority: 'warning', count: d.quarantine });
        if (d.pending_vaccines > 0) alerts.push({ title: `${d.pending_vaccines} vacunas pendientes`, priority: 'warning', count: d.pending_vaccines });
        if (d.critical_inventory > 0) alerts.push({ title: `${d.critical_inventory} insumos en stock crítico`, priority: 'critical', count: d.critical_inventory });
        if (d.pending_tasks > 0) alerts.push({ title: `${d.pending_tasks} tareas pendientes`, priority: 'info', count: d.pending_tasks });

        if (!alerts.length) {
            $list.html('<div class="empty-state-sm">Sin alertas activas</div>');
            return;
        }

        alerts.forEach(alert => {
            const typeClass = { critical: 'danger', warning: 'warning', info: 'info' }[alert.priority] || 'info';
            const $item = $(`
                <div class="alert-item alert-${typeClass}">
                    <div class="alert-indicator"></div>
                    <div class="alert-content">
                        <span class="alert-title">${alert.title}</span>
                    </div>
                    <span class="chip chip-${typeClass}">${alert.count || ''}</span>
                </div>
            `);
            $list.append($item);
        });
    },

    // ─── RECENT ACTIVITY ────────────────────────────────────

    renderRecentActivity() {
        const activities = this.data.recent_activity || [];
        const $list = $('#activityList');
        $list.empty();

        if (!activities.length) {
            $list.html('<div class="empty-state-sm">Sin actividad reciente</div>');
            return;
        }

        activities.slice(0, 10).forEach(act => {
            const $item = $(`
                <div class="activity-item">
                    <div class="activity-dot activity-${act.type || 'info'}"></div>
                    <div class="activity-content">
                        <span class="activity-text">${act.message || ''}</span>
                        <span class="activity-time">${App.timeAgo(act.created_at)}</span>
                    </div>
                </div>
            `);
            $list.append($item);
        });
    },

    // ─── CHARTS ─────────────────────────────────────────────

    renderSpeciesChart() {
        const data = this.data.by_species;
        if (!data || !data.length) return;

        const ctx = document.getElementById('speciesChart');
        if (!ctx) return;

        if (this.charts.species) this.charts.species.destroy();

        this.charts.species = new Chart(ctx, {
            type: 'doughnut',
            data: {
                labels: data.map(d => d.name),
                datasets: [{
                    data: data.map(d => d.total),
                    backgroundColor: [
                        '#10B981', '#8B5CF6', '#3B82F6', '#F59E0B',
                        '#EC4899', '#06B6D4', '#6366F1', '#059669', '#D97706',
                    ],
                    borderColor: 'transparent',
                    borderWidth: 0,
                    hoverOffset: 10,
                    spacing: 3,
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                cutout: '65%',
                plugins: {
                    legend: {
                        position: 'bottom',
                        labels: {
                            color: '#475569',
                            padding: 16,
                            usePointStyle: true,
                            pointStyleWidth: 10,
                            font: { size: 12 },
                        },
                    },
                },
                animation: {
                    animateScale: true,
                    animateRotate: true,
                    duration: 1200,
                    easing: 'easeOutQuart',
                },
            },
        });
    },

    // Births chart removed — no /dashboard/births-monthly endpoint

    // Births monthly chart
    async renderBirthsChart() {
        const ctx = document.getElementById('birthsChart');
        if (!ctx) return;

        if (this.charts.births) this.charts.births.destroy();

        try {
            const res = await API.get('/dashboard/births-monthly');
            const data = res.data || [];
            if (!data.length) return;

            this.charts.births = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: data.map(d => d.label),
                    datasets: [{
                        label: 'Nacimientos',
                        data: data.map(d => d.total),
                        backgroundColor: 'rgba(139, 92, 246, 0.15)',
                        borderColor: '#8B5CF6',
                        borderWidth: 2,
                        borderRadius: 8,
                        hoverBackgroundColor: 'rgba(139, 92, 246, 0.3)',
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: { display: false },
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            ticks: {
                                stepSize: 1,
                                color: '#94a3b8',
                                font: { size: 11 },
                            },
                            grid: { color: 'rgba(148,163,184,0.1)' },
                        },
                        x: {
                            ticks: { color: '#94a3b8', font: { size: 11 } },
                            grid: { display: false },
                        },
                    },
                    animation: {
                        duration: 1000,
                        easing: 'easeOutQuart',
                    },
                },
            });
        } catch(e) {
            console.warn('Could not load births chart:', e);
        }
    },

    // ─── D3.js HIERARCHICAL BAR CHART ───────────────────────

    _hierarchyData: null,
    _hierarchyStack: [],

    async renderHierarchyChart() {
        if (typeof d3 === 'undefined') {
            console.warn('D3.js not loaded');
            return;
        }
        const container = document.getElementById('hierarchyChart');
        if (!container) return;

        try {
            const res = await API.get('/dashboard/hierarchy');
            if (!res.success || !res.data) return;

            this._hierarchyData = res.data;
            this._hierarchyStack = [this._hierarchyData];
            this.drawHierarchyBars(this._hierarchyData, container);
        } catch(e) {
            console.warn('Could not load hierarchy chart:', e);
        }
    },

    drawHierarchyBars(node, container) {
        const { children } = node;
        if (!children || !children.length) return;

        d3.select(container).selectAll('*').remove();

        const rect = container.getBoundingClientRect();
        const margin = { top: 10, right: 30, bottom: 30, left: 120 };
        const width = rect.width - margin.left - margin.right;
        const barHeight = 32;
        const barGap = 6;
        const height = Math.max((children.length * (barHeight + barGap)) + margin.top + margin.bottom, 120);

        // Update container height
        container.style.height = Math.max(height + margin.top + margin.bottom, 200) + 'px';

        const svg = d3.select(container).append('svg')
            .attr('width', rect.width)
            .attr('height', height + margin.top + margin.bottom);

        const g = svg.append('g')
            .attr('transform', `translate(${margin.left},${margin.top})`);

        const maxVal = d3.max(children, d => d.value) || 1;

        const x = d3.scaleLinear()
            .domain([0, maxVal])
            .range([0, width]);

        const y = d3.scaleBand()
            .domain(children.map(d => d.name))
            .range([0, children.length * (barHeight + barGap)])
            .padding(0.15);

        // Color palette
        const colors = ['#10B981', '#8B5CF6', '#3B82F6', '#F59E0B', '#EC4899', '#06B6D4', '#6366F1', '#059669', '#D97706', '#EF4444'];

        // X axis
        g.append('g')
            .attr('class', 'axis')
            .attr('transform', `translate(0,${children.length * (barHeight + barGap)})`)
            .call(d3.axisBottom(x).ticks(Math.min(maxVal, 8)).tickFormat(d3.format('d')))
            .selectAll('text').style('fill', 'var(--text-muted)');

        // Bars
        const bars = g.selectAll('.bar')
            .data(children)
            .join('g')
            .attr('class', 'bar')
            .attr('transform', d => `translate(0,${y(d.name)})`);

        const self = this;

        bars.append('rect')
            .attr('width', 0)
            .attr('height', y.bandwidth())
            .attr('rx', 6)
            .attr('fill', (d, i) => d.color || colors[i % colors.length])
            .attr('opacity', 0.8)
            .style('cursor', d => d.children ? 'pointer' : 'default')
            .on('click', function(event, d) {
                if (d.children && d.children.length) {
                    self._hierarchyStack.push(d);
                    self.drawHierarchyBars(d, container);
                    self.updateBreadcrumb();
                }
            })
            .transition()
            .duration(800)
            .ease(d3.easeCubicOut)
            .attr('width', d => x(d.value));

        // Labels (left side)
        bars.append('text')
            .attr('x', -8)
            .attr('y', y.bandwidth() / 2)
            .attr('text-anchor', 'end')
            .attr('dominant-baseline', 'central')
            .text(d => d.name.length > 14 ? d.name.substring(0, 14) + '…' : d.name)
            .style('font-size', '12px')
            .style('fill', 'var(--text-primary)')
            .style('font-weight', '500');

        // Value labels (inside bar or outside)
        bars.append('text')
            .attr('class', 'bar-value')
            .attr('x', d => Math.min(x(d.value) + 6, width))
            .attr('y', y.bandwidth() / 2)
            .attr('dominant-baseline', 'central')
            .text(d => d.value)
            .style('font-size', '11px')
            .style('fill', 'var(--text-muted)')
            .style('font-weight', '600')
            .style('opacity', 0)
            .transition()
            .delay(600)
            .duration(400)
            .style('opacity', 1);

        // Drill-down indicator
        bars.filter(d => d.children && d.children.length)
            .append('text')
            .attr('x', d => x(d.value) - 6)
            .attr('y', y.bandwidth() / 2)
            .attr('text-anchor', 'end')
            .attr('dominant-baseline', 'central')
            .text('▸')
            .style('font-size', '12px')
            .style('fill', '#fff')
            .style('opacity', 0.7);

        this.updateBreadcrumb();
    },

    updateBreadcrumb() {
        const $bc = $('#hierarchyBreadcrumb');
        if (!$bc.length) return;

        const stack = this._hierarchyStack;
        let html = '';
        const self = this;
        const container = document.getElementById('hierarchyChart');

        stack.forEach((node, i) => {
            if (i > 0) html += ' <span style="color:var(--text-muted); margin:0 4px;">›</span> ';
            const isLast = i === stack.length - 1;
            if (isLast) {
                html += `<span style="color:var(--text-primary); font-weight:600;">${node.name}</span>`;
            } else {
                html += `<span class="bc-link" data-idx="${i}" style="color:var(--color-primary-light); cursor:pointer;">${node.name}</span>`;
            }
        });

        $bc.html(html);
        $bc.find('.bc-link').on('click', function() {
            const idx = parseInt($(this).data('idx'));
            self._hierarchyStack = stack.slice(0, idx + 1);
            self.drawHierarchyBars(self._hierarchyStack[idx], container);
        });
    },

    // ─── UPCOMING EVENTS TIMELINE ───────────────────────────

    async renderUpcomingEvents() {
        const $container = $('#upcomingTimeline');
        if (!$container.length) return;

        try {
            const today = new Date();
            const from = today.toISOString().split('T')[0];
            const toDate = new Date(today);
            toDate.setDate(toDate.getDate() + 7);
            const to = toDate.toISOString().split('T')[0];

            const res = await API.get(`/calendar/events?from=${from}&to=${to}`);
            if (!res.success) return;

            const events = res.data?.events || res.data || [];
            $container.empty();

            if (!events.length) {
                $container.html('<div class="timeline-empty">Sin eventos próximos en los siguientes 7 días</div>');
                return;
            }

            // Group events by date
            const grouped = {};
            events.forEach(ev => {
                const date = ev.date?.split(' ')[0] || ev.date;
                if (!grouped[date]) grouped[date] = [];
                grouped[date].push(ev);
            });

            const dayNames = ['Dom', 'Lun', 'Mar', 'Mié', 'Jue', 'Vie', 'Sáb'];
            const monthNames = ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic'];

            Object.keys(grouped).sort().forEach(dateStr => {
                const d = new Date(dateStr + 'T00:00:00');
                const isToday = dateStr === from;
                const dayLabel = isToday ? 'Hoy' : `${dayNames[d.getDay()]} ${d.getDate()} ${monthNames[d.getMonth()]}`;

                const $group = $(`<div class="timeline-day-group"></div>`);
                $group.append(`
                    <div class="timeline-day-header">
                        <span class="day-badge">${d.getDate()}</span>
                        <span>${dayLabel}</span>
                        <span style="margin-left:auto; font-size:0.72rem; opacity:0.7">${grouped[dateStr].length} evento(s)</span>
                    </div>
                `);

                grouped[dateStr].forEach(ev => {
                    const typeLabel = this.eventTypeLabel(ev.type);
                    const color = ev.color || this.eventTypeColor(ev.type);
                    const statusChip = ev.done ? '<span class="chip" style="background:#059669;color:#fff">Hecho</span>' : '';

                    $group.append(`
                        <div class="timeline-event">
                            <div class="timeline-event-dot" style="background:${color}"></div>
                            <div class="timeline-event-body">
                                <div class="timeline-event-title">${this.escHtml(ev.title)}</div>
                                <div class="timeline-event-meta">
                                    <span class="chip" style="background:${color}22; color:${color}; border:1px solid ${color}44">${typeLabel}</span>
                                    ${statusChip}
                                </div>
                            </div>
                        </div>
                    `);
                });

                $container.append($group);
            });

        } catch(e) {
            $container.html('<div class="timeline-empty">Error al cargar eventos</div>');
            console.warn('Could not load upcoming events:', e);
        }
    },

    eventTypeLabel(type) {
        const labels = {
            task: 'Tarea', vaccine_scheduled: 'Vacuna', vaccine_applied: 'Vacuna ✓',
            pregnancy: 'Parto esperado', birth: 'Nacimiento', health: 'Salud',
        };
        return labels[type] || type || 'Evento';
    },

    eventTypeColor(type) {
        const colors = {
            task: '#3B82F6', vaccine_scheduled: '#0D9488', vaccine_applied: '#6EE7B7',
            pregnancy: '#7C3AED', birth: '#2563EB', health: '#DC2626',
        };
        return colors[type] || '#64748B';
    },

    escHtml(text) {
        if (!text) return '';
        const div = document.createElement('div');
        div.appendChild(document.createTextNode(text));
        return div.innerHTML;
    },

    // ─── GSAP ENTRANCE ANIMATIONS ───────────────────────────

    animateEntrance() {
        if (typeof gsap === 'undefined') return;

        const animate = (selector, props) => {
            if (document.querySelector(selector)) gsap.from(selector, props);
        };

        // Page header fade-in slide
        animate('.page-header', {
            y: -20,
            opacity: 0,
            duration: 0.6,
            ease: 'power3.out',
        });

        // Quick actions stagger
        animate('.dash-quick-btn', {
            y: 15,
            opacity: 0,
            duration: 0.45,
            stagger: 0.07,
            ease: 'power2.out',
            delay: 0.15,
        });

        // KPI cards stagger from below with scale
        animate('.dash-kpi', {
            y: 30,
            opacity: 0,
            scale: 0.92,
            duration: 0.5,
            stagger: 0.08,
            ease: 'back.out(1.4)',
            delay: 0.3,
        });

        // Dashboard panels slide in
        animate('.dash-panel', {
            y: 40,
            opacity: 0,
            duration: 0.6,
            stagger: 0.12,
            ease: 'power3.out',
            delay: 0.55,
        });

        // Alert items stagger
        animate('.alert-item', {
            x: -20,
            opacity: 0,
            duration: 0.4,
            stagger: 0.06,
            ease: 'power2.out',
            delay: 0.7,
        });

        // Activity items stagger
        animate('.activity-item', {
            x: 20,
            opacity: 0,
            duration: 0.4,
            stagger: 0.05,
            ease: 'power2.out',
            delay: 0.75,
        });

        // Timeline events
        animate('.timeline-event', {
            x: -15,
            opacity: 0,
            duration: 0.35,
            stagger: 0.04,
            ease: 'power2.out',
            delay: 0.85,
        });

        // Hierarchy chart
        animate('#hierarchyChart', {
            y: 20,
            opacity: 0,
            duration: 0.6,
            ease: 'power3.out',
            delay: 0.65,
        });
    },

    // ─── ICON HELPER ────────────────────────────────────────

    getIcon(type) {
        const icons = {
            animals:    '<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><circle cx="8" cy="9" r="1" fill="currentColor"/><circle cx="16" cy="9" r="1" fill="currentColor"/><path d="M8 14s1.5 3 4 3 4-3 4-3"/></svg>',
            lots:       '<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="2" y="7" width="20" height="14" rx="2"/><path d="M16 7V5a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v2"/></svg>',
            births:     '<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 2L2 7l10 5 10-5-10-5z"/><path d="M2 17l10 5 10-5"/><path d="M2 12l10 5 10-5"/></svg>',
            sick:       '<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 9v4"/><path d="M12 17h.01"/><circle cx="12" cy="12" r="10"/></svg>',
            quarantine: '<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>',
            vaccines:   '<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M18 2l4 4-4 4"/><path d="M22 6H12a4 4 0 0 0-4 4v1"/><rect x="6" y="13" width="4" height="8" rx="1"/></svg>',
            sales:      '<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="12" y1="1" x2="12" y2="23"/><path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"/></svg>',
            mortality:  '<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="23 6 13.5 15.5 8.5 10.5 1 18"/><polyline points="17 6 23 6 23 12"/></svg>',
        };
        return icons[type] || '';
    },
};
