<?php


$csrfToken = Router::csrfToken();
?>


<div class="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-2 mb-4">
    <span class="text-xs text-gray-400"><i class="fa-solid fa-grip-vertical mr-1"></i> Drag widgets to reorder</span>
    <div class="flex items-center gap-2">
        <button onclick="Dashboard.openAddWidget()" class="inline-flex items-center gap-1.5 px-3 py-1.5 bg-primary-600 text-white text-xs font-medium rounded-lg hover:bg-primary-700 transition-colors">
            <i class="fa-solid fa-plus text-[10px]"></i> Add Widget
        </button>
        <button onclick="Dashboard.resetLayout()" class="inline-flex items-center gap-1.5 px-3 py-1.5 bg-white border border-gray-300 text-gray-600 text-xs font-medium rounded-lg hover:bg-gray-50 transition-colors">
            <i class="fa-solid fa-rotate-left text-[10px]"></i> Reset
        </button>
    </div>
</div>


<div id="dashboardGrid" class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
    <?php foreach ($layout as $idx => $item):
        $wId = $item['id'];
        $visible = !empty($item['visible']);
        if (!$visible) continue;  
        $def = $allWidgets[$wId] ?? null;
        if (!$def) continue;
        $size = $def['size'] ?? 'medium';
        $spanClass = match($size) {
            'full' => 'md:col-span-2 xl:col-span-3',
            'large' => 'md:col-span-2 xl:col-span-2',
            default => '',
        };
        $data = $widgetData[$wId] ?? null;
        $removable = $def['removable'] ?? true;
    ?>
    <div class="dashboard-widget <?= $spanClass ?>"
         data-widget-id="<?= $wId ?>"
         data-visible="1">
        <div class="bg-white rounded-lg border border-gray-200 shadow-sm overflow-hidden h-full flex flex-col">
            
            <div class="widget-header px-4 py-2.5 border-b border-gray-100 flex items-center justify-between cursor-grab active:cursor-grabbing bg-gray-50/50 select-none">
                <div class="flex items-center gap-2">
                    <i class="fa-solid fa-grip-vertical text-gray-300 text-xs drag-handle"></i>
                    <i class="fa-solid <?= htmlspecialchars($def['icon']) ?> text-gray-400 text-xs"></i>
                    <h3 class="text-sm font-semibold text-gray-800"><?= htmlspecialchars($def['title']) ?></h3>
                </div>
                <?php if ($removable): ?>
                <button onclick="Dashboard.hideWidget('<?= $wId ?>')" class="p-1 text-gray-300 hover:text-gray-500 transition-colors" title="Hide widget">
                    <i class="fa-solid fa-eye-slash text-xs"></i>
                </button>
                <?php endif; ?>
            </div>
            
            <div class="widget-body flex-1 p-4">
                <?php
                $widgetFile = __DIR__ . '/_dashboard_widget_' . $wId . '.php';
                if (isset($data['_error'])): ?>
                    <div class="text-center py-4 text-red-400 text-xs">
                        <i class="fa-solid fa-triangle-exclamation mr-1"></i> <?= htmlspecialchars($data['_error']) ?>
                    </div>
                <?php elseif ($data !== null && file_exists($widgetFile)): ?>
                    <?php require $widgetFile; ?>
                <?php else: ?>
                    <div class="text-center py-4 text-gray-300 text-xs">No data available</div>
                <?php endif; ?>
            </div>
        </div>
    </div>
    <?php endforeach; ?>
</div>


<div id="addWidgetModal" class="fixed inset-0 z-50" style="display:none;">
    <div class="absolute inset-0 bg-black/40" onclick="Dashboard.closeAddWidget()"></div>
    <div class="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 bg-white rounded-xl shadow-2xl w-full max-w-lg max-h-[80vh] flex flex-col">
        <div class="px-5 py-4 border-b border-gray-200 flex items-center justify-between">
            <h3 class="text-base font-semibold text-gray-900">Manage Widgets</h3>
            <button onclick="Dashboard.closeAddWidget()" class="text-gray-400 hover:text-gray-600 p-1">
                <i class="fa-solid fa-xmark text-lg"></i>
            </button>
        </div>
        <div class="p-5 overflow-y-auto flex-1" id="widgetList"></div>
        <div class="px-5 py-3 border-t border-gray-100 flex justify-end">
            <button onclick="Dashboard.closeAddWidget()" class="px-4 py-2 bg-primary-600 text-white text-sm font-medium rounded-lg hover:bg-primary-700 transition-colors">Done</button>
        </div>
    </div>
</div>


<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.7/dist/chart.umd.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.6/Sortable.min.js"></script>

<script>
(function() {
    'use strict';

    const CSRF = <?= json_encode($csrfToken) ?>;
    const allWidgets = <?= json_encode($allWidgets) ?>;
    const widgetData = <?= json_encode($widgetData) ?>;

    // Build layout state from PHP data
    let layout = <?= json_encode($layout) ?>;

    const Dashboard = {
        sortable: null,
        saving: false,
        saveTimeout: null,

        init() {
            this.initSortable();
            this.initCharts();
        },

        initSortable() {
            const grid = document.getElementById('dashboardGrid');
            if (!grid) return;
            this.sortable = new Sortable(grid, {
                animation: 200,
                handle: '.widget-header',
                ghostClass: 'dash-ghost',
                chosenClass: 'dash-chosen',
                dragClass: 'dash-drag',
                onEnd: () => {
                    this.syncLayoutFromDOM();
                    this.saveLayout();
                }
            });
        },

        initCharts() {
            const defaults = {
                responsive: true,
                maintainAspectRatio: false,
                plugins: { legend: { labels: { font: { size: 11 }, padding: 12 } } }
            };

            // Views Chart (line) — enhanced: larger points, crosshair, big tooltip
            this.renderChart('viewsChart', widgetData.views_chart, (ctx, d) => new Chart(ctx, {
                type: 'line',
                data: {
                    labels: d.labels,
                    datasets: [{
                        label: d.source === 'views' ? 'Views' : 'Uploads',
                        data: d.values,
                        borderColor: '#3b82f6',
                        backgroundColor: 'rgba(59,130,246,0.08)',
                        fill: true, tension: 0.35,
                        pointRadius: 3, pointHoverRadius: 7,
                        pointBackgroundColor: '#3b82f6',
                        pointBorderColor: '#fff',
                        pointBorderWidth: 2,
                        pointHitRadius: 20,
                        borderWidth: 2.5
                    }]
                },
                options: { ...defaults,
                    interaction: { mode: 'index', intersect: false },
                    scales: {
                        x: { grid: { display: false }, ticks: { font: { size: 10 }, maxRotation: 45, maxTicksLimit: 10 } },
                        y: { beginAtZero: true, grid: { color: '#f3f4f6' }, ticks: { font: { size: 10 } } }
                    },
                    plugins: {
                        legend: { display: false },
                        tooltip: {
                            backgroundColor: '#1f2937', titleFont: { size: 12 }, bodyFont: { size: 13, weight: 'bold' },
                            padding: 10, cornerRadius: 8, displayColors: false,
                            callbacks: { label: (c) => c.parsed.y.toLocaleString() + ' ' + (d.source === 'views' ? 'views' : 'uploads') }
                        }
                    }
                }
            }));

            // Content Distribution (doughnut)
            this.renderChart('contentDistChart', widgetData.content_distribution, (ctx, d) => new Chart(ctx, {
                type: 'doughnut',
                data: {
                    labels: d.labels,
                    datasets: [{ data: d.values, backgroundColor: ['#3b82f6','#8b5cf6','#ec4899','#f59e0b','#10b981'], borderWidth: 0, hoverOffset: 6 }]
                },
                options: { ...defaults, cutout: '65%',
                    plugins: { legend: { position: 'bottom', labels: { font: { size: 11 }, padding: 12, usePointStyle: true, pointStyleWidth: 8 } } }
                }
            }));

            // Video Status (doughnut)
            this.renderChart('videoStatusChart', widgetData.video_status, (ctx, d) => {
                const colors = { Published: '#22c55e', Draft: '#9ca3af', Private: '#f59e0b' };
                return new Chart(ctx, {
                    type: 'doughnut',
                    data: {
                        labels: d.labels,
                        datasets: [{ data: d.values, backgroundColor: d.labels.map(l => colors[l] || '#6b7280'), borderWidth: 0, hoverOffset: 6 }]
                    },
                    options: { ...defaults, cutout: '65%',
                        plugins: { legend: { position: 'bottom', labels: { font: { size: 11 }, padding: 12, usePointStyle: true, pointStyleWidth: 8 } } }
                    }
                });
            });

            // Top Categories (horizontal bar)
            this.renderChart('topCategoriesChart', widgetData.top_categories, (ctx, d) => new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: d.labels,
                    datasets: [{ data: d.values, backgroundColor: '#3b82f6', borderRadius: 4, barThickness: 18 }]
                },
                options: { ...defaults, indexAxis: 'y',
                    scales: {
                        x: { beginAtZero: true, grid: { color: '#f3f4f6' }, ticks: { font: { size: 10 } } },
                        y: { grid: { display: false }, ticks: { font: { size: 10 } } }
                    },
                    plugins: { legend: { display: false } }
                }
            }));
        },

        renderChart(canvasId, data, factory) {
            const el = document.getElementById(canvasId);
            if (!el || !data) return;
            if (!data.values || !data.labels || data.values.length === 0) return;
            try { factory(el, data); } catch(e) { console.warn('Chart error:', canvasId, e); }
        },

        syncLayoutFromDOM() {
            const grid = document.getElementById('dashboardGrid');
            const domIds = [];
            grid.querySelectorAll('.dashboard-widget').forEach(el => {
                domIds.push(el.dataset.widgetId);
            });
            // Rebuild layout: DOM order for visible, then non-visible in original order
            const newLayout = [];
            domIds.forEach(id => newLayout.push({ id, visible: true }));
            layout.forEach(item => {
                if (!domIds.includes(item.id)) {
                    newLayout.push({ id: item.id, visible: false });
                }
            });
            layout = newLayout;
        },

        async saveLayout(reload) {
            if (this.saving) return;
            clearTimeout(this.saveTimeout);

            const doSave = async () => {
                this.saving = true;
                try {
                    await fetch('/admin/dashboard/save-layout', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': CSRF },
                        body: JSON.stringify({ layout })
                    });
                    if (reload) location.reload();
                } catch(e) {
                    console.error('Save error:', e);
                } finally {
                    this.saving = false;
                }
            };

            if (reload) {
                await doSave();
            } else {
                this.saveTimeout = setTimeout(doSave, 300);
            }
        },

        hideWidget(widgetId) {
            // Hide: remove from DOM, update layout, save (no reload needed)
            const el = document.querySelector(`[data-widget-id="${widgetId}"]`);
            if (el) {
                el.style.transition = 'opacity 0.2s, transform 0.2s';
                el.style.opacity = '0';
                el.style.transform = 'scale(0.95)';
                setTimeout(() => {
                    el.remove();
                    this.syncLayoutFromDOM();
                    // Mark it hidden in layout
                    const item = layout.find(w => w.id === widgetId);
                    if (item) item.visible = false;
                    else layout.push({ id: widgetId, visible: false });
                    this.saveLayout(false);
                }, 200);
            }
        },

        toggleWidget(widgetId) {
            // Toggle from the modal: find layout item and flip visibility
            const item = layout.find(w => w.id === widgetId);
            if (item) {
                item.visible = !item.visible;
            } else {
                layout.push({ id: widgetId, visible: true });
            }
            // Save and reload to get fresh data + chart rendering
            this.saveLayout(true);
        },

        openAddWidget() {
            document.getElementById('addWidgetModal').style.display = '';
            this.refreshWidgetList();
        },

        closeAddWidget() {
            document.getElementById('addWidgetModal').style.display = 'none';
        },

        refreshWidgetList() {
            const container = document.getElementById('widgetList');
            const cats = { stats: 'Statistics', charts: 'Charts', content: 'Content', tools: 'Tools', system: 'System' };
            let html = '';

            for (const [catKey, catLabel] of Object.entries(cats)) {
                const entries = Object.entries(allWidgets).filter(([,w]) => w.category === catKey);
                if (!entries.length) continue;

                html += '<div class="mb-4"><h4 class="text-xs font-semibold text-gray-400 uppercase tracking-wider mb-2">' + catLabel + '</h4>';
                entries.forEach(([id, def]) => {
                    const item = layout.find(w => w.id === id);
                    const isVis = item ? item.visible : false;
                    const removable = def.removable !== false;

                    html += '<label class="flex items-center gap-3 p-2.5 rounded-lg hover:bg-gray-50 cursor-pointer transition-colors' + (removable ? '' : ' opacity-60') + '">'
                        + '<input type="checkbox"' + (isVis ? ' checked' : '') + (removable ? '' : ' disabled')
                        + ' onchange="Dashboard.toggleWidget(\'' + id + '\')"'
                        + ' class="w-4 h-4 rounded border-gray-300 text-primary-600 focus:ring-primary-500 focus:ring-offset-0">'
                        + '<i class="fa-solid ' + def.icon + ' text-gray-400 text-sm w-5 text-center"></i>'
                        + '<div class="flex-1 min-w-0">'
                        + '<div class="text-sm font-medium text-gray-800">' + def.title + '</div>'
                        + '<div class="text-xs text-gray-400 truncate">' + def.description + '</div>'
                        + '</div></label>';
                });
                html += '</div>';
            }
            container.innerHTML = html;
        },

        async resetLayout() {
            if (!confirm('Reset dashboard to default layout?')) return;
            try {
                await fetch('/admin/dashboard/reset-layout', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': CSRF },
                    body: JSON.stringify({})
                });
                location.reload();
            } catch(e) { console.error('Reset error:', e); }
        }
    };

    window.Dashboard = Dashboard;

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', () => Dashboard.init());
    } else {
        Dashboard.init();
    }
})();
</script>

<style>
.dashboard-widget { transition: opacity 0.2s, transform 0.2s; }
.dash-ghost { opacity: 0.25; }
.dash-chosen { z-index: 50; box-shadow: 0 20px 25px -5px rgba(0,0,0,0.1), 0 8px 10px -6px rgba(0,0,0,0.1); }
.dash-drag { transform: rotate(1deg); }
.dashboard-widget .widget-header:hover .drag-handle { color: #9ca3af; }
</style>
