/* ============================================================
   DroidTester — Dashboard JS
   ============================================================ */

(function () {
    'use strict';

    // ── Count-up Animation ──
    function countUp(el, target, duration) {
        let start = 0;
        const step = target / (duration / 16);
        const timer = setInterval(function () {
            start += step;
            if (start >= target) {
                start = target;
                clearInterval(timer);
            }
            el.textContent = Math.floor(start).toLocaleString();
        }, 16);
    }

    const statEls = document.querySelectorAll('[data-count]');
    if (statEls.length) {
        // Intersection Observer for triggering on scroll into view
        const observer = new IntersectionObserver(function (entries) {
            entries.forEach(function (entry) {
                if (entry.isIntersecting && !entry.target.dataset.counted) {
                    entry.target.dataset.counted = 'true';
                    const target = parseInt(entry.target.dataset.count, 10);
                    countUp(entry.target, target, 1500);
                }
            });
        }, { threshold: 0.3 });

        statEls.forEach(function (el) { observer.observe(el); });
    }

    // ── Campaign Reports Donut Chart (Chart.js) ──
    const chartCanvas = document.getElementById('campaignChart');
    if (chartCanvas && typeof Chart !== 'undefined') {
        new Chart(chartCanvas, {
            type: 'doughnut',
            data: {
                labels: ['Total', 'Active', 'Completed'],
                datasets: [{
                    data: [590, 160, 430],
                    backgroundColor: ['#E8DDD0', '#7DC9A0', '#1B7A43'],
                    borderWidth: 0,
                    hoverOffset: 6
                }]
            },
            options: {
                cutout: '72%',
                rotation: -90,
                circumference: 180,
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: { display: false },
                    tooltip: {
                        callbacks: {
                            label: function (ctx) {
                                return ctx.label + ': ' + ctx.parsed;
                            }
                        }
                    }
                }
            }
        });
    }

    // ── Fallback SVG chart if Chart.js not loaded ──
    if (chartCanvas && typeof Chart === 'undefined') {
        const parent = chartCanvas.parentElement;
        const svg = `
      <svg viewBox="0 0 200 110" xmlns="http://www.w3.org/2000/svg" style="width:100%;max-width:220px;margin:0 auto;display:block">
        <path d="M10,100 A90,90 0 0,1 190,100" fill="none" stroke="#E8DDD0" stroke-width="22" stroke-linecap="round"/>
        <path d="M10,100 A90,90 0 0,1 190,100" fill="none" stroke="#1B7A43" stroke-width="22" stroke-linecap="round"
              stroke-dasharray="${(430 / 590) * 283} 283"/>
        <text x="100" y="85" text-anchor="middle" font-size="22" font-weight="800" fill="#1B7A43">75%</text>
        <text x="100" y="102" text-anchor="middle" font-size="10" fill="#6B6B6B">Project Completed</text>
      </svg>`;
        chartCanvas.style.display = 'none';
        parent.insertAdjacentHTML('beforeend', svg);
    }
})();
