@extends('layouts.layoutadmin')
@section('title', 'Admin Dashboard')

@section('content')
    <style>
        body {
            background: #f4f4f4;
        }

        .admin-dashboard {
            display: flex;
            min-height: 100vh;
            background: #f4f4f4;
        }

        .sidebar {
            width: 260px;
            background: #23272b;
            color: #fff;
            display: flex;
            flex-direction: column;
            padding: 24px 0 0 0;
            border-right: 1px solid #e5e7eb;
        }

        .sidebar .sidebar-header {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 0 24px 24px 24px;
            font-size: 1.1rem;
            font-weight: 700;
        }

        .sidebar .sidebar-header i {
            font-size: 1.6rem;
            color: #22c1b6;
        }

        .sidebar .sidebar-header span {
            font-size: 1.1rem;
            font-weight: 700;
            color: #fff;
        }

        .sidebar-nav {
            flex: 1;
            padding: 0 0 0 0;
        }

        .sidebar-nav ul {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        .sidebar-nav li {
            margin-bottom: 4px;
        }

        .sidebar-nav a {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 10px 28px;
            color: #bfc5c9;
            text-decoration: none;
            border-radius: 8px 0 0 8px;
            font-size: 1rem;
            transition: background 0.2s, color 0.2s;
        }

        .sidebar-nav a.active,
        .sidebar-nav a:hover {
            background: #22c1b6;
            color: #fff;
        }

        .sidebar-footer {
            padding: 18px 24px;
            border-top: 1px solid #333;
            background: #23272b;
            display: flex;
            align-items: center;
            gap: 12px;
            font-size: 0.98rem;
        }

        .sidebar-footer .avatar {
            width: 36px;
            height: 36px;
            border-radius: 50%;
            background: #444;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #fff;
            font-size: 1.2rem;
            font-weight: 700;
        }

        .sidebar-footer .user-info {
            display: flex;
            flex-direction: column;
            gap: 2px;
        }

        .sidebar-footer .user-info span {
            color: #fff;
            font-weight: 600;
            font-size: 1rem;
        }

        .sidebar-footer .user-info small {
            color: #bfc5c9;
            font-size: 0.95rem;
        }

        .main {
            flex: 1;
            display: flex;
            flex-direction: column;
            background: #f4f4f4;
        }

        .main-header {
            background: #fff;
            padding: 24px 32px 16px 32px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            border-bottom: 1px solid #e5e7eb;
        }

        /* Keep admin header/navbar white regardless of site dark/light mode */
        body.dark-mode .admin-dashboard .main-header,
        .admin-dashboard .main-header {
            background: #ffffff !important;
            color: #222 !important;
            border-bottom: 1px solid #e5e7eb !important;
        }

        /* Ensure header child elements keep their intended colors in dark mode */
        body.dark-mode .admin-dashboard .main-header .title,
        body.dark-mode .admin-dashboard .main-header .subtitle,
        body.dark-mode .admin-dashboard .main-header .header-actions,
        body.dark-mode .admin-dashboard .main-header .header-actions * {
            color: inherit !important;
            background: transparent !important;
        }

        .main-header .title {
            font-size: 1.4rem;
            font-weight: 700;
            color: #222;
        }

        .main-header .subtitle {
            color: #6b7280;
            font-size: 1.05rem;
            margin-top: 2px;
        }

        .main-header .header-actions {
            display: flex;
            align-items: center;
            gap: 16px;
        }

        .main-header .header-actions button {
            background: #d72660;
            color: #fff;
            border: none;
            border-radius: 8px;
            padding: 8px 18px;
            font-weight: 600;
            font-size: 1rem;
            cursor: pointer;
        }

        .main-header .header-actions button:hover {
            background: #b61f50;
        }

        .main-header .header-actions i {
            font-size: 1.3rem;
            color: #535963;
            background: #f4f4f4;
            border-radius: 50%;
            padding: 6px;
            margin-right: 2px;
            cursor: pointer;
        }

        .main-content {
            padding: 32px;
        }

        .stat-summary {
            display: flex;
            gap: 24px;
            margin-bottom: 32px;
        }

        .stat-card {
            background: #fff;
            border-radius: 12px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
            flex: 1;
            padding: 24px 18px 18px 18px;
            display: flex;
            flex-direction: column;
            align-items: flex-start;
            min-width: 180px;
        }

        .stat-card .stat-icon {
            width: 44px;
            height: 44px;
            border-radius: 8px;
            background: #eaf6f3;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.6rem;
            margin-bottom: 8px;
        }

        .stat-card .stat-title {
            font-size: 1.05rem;
            color: #444;
            font-weight: 600;
            margin-bottom: 2px;
        }

        .stat-card .stat-value {
            font-size: 2rem;
            font-weight: 700;
            color: #222;
            margin-bottom: 2px;
        }

        .stat-card .stat-growth {
            font-size: 0.98rem;
            color: #22c1b6;
            font-weight: 600;
            margin-bottom: 2px;
        }

        /* Quick Action Cards */
        .quick-action-card {
            background: #fff;
            border-radius: 10px;
            padding: 18px;
            display: flex;
            align-items: center;
            gap: 12px;
            text-decoration: none;
            color: #222;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
            transition: all 0.2s;
            border: 2px solid transparent;
        }

        .quick-action-card:hover {
            box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
            border-color: #22c1b6;
            transform: translateY(-2px);
        }

        .quick-action-card i {
            font-size: 1.8rem;
            color: #22c1b6;
        }

        .quick-action-card span {
            color: #22c1b6;
            font-size: 1rem;
            font-weight: 600;
        }

        /* Content Box */
        .content-box {
            background: #fff;
            border-radius: 12px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
            overflow: hidden;
        }

        .content-box-header {
            padding: 20px 24px;
            border-bottom: 1px solid #e5e7eb;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .content-box-header h3 {
            margin: 0;
            font-size: 1.15rem;
            font-weight: 700;
            color: #222;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .content-box-header h3 i {
            color: #22c1b6;
        }

        .content-box-header a {
            color: #22c1b6;
            text-decoration: none;
            font-size: 0.95rem;
            font-weight: 600;
            transition: color 0.2s;
        }

        .content-box-header a:hover {
            color: #1a9d94;
        }

        .content-box-body {
            padding: 24px;
        }

        /* Article Item */
        .article-item {
            display: flex;
            gap: 14px;
            padding: 14px 0;
            border-bottom: 1px solid #f0f0f0;
        }

        .article-item:last-child {
            border-bottom: none;
        }

        .article-thumbnail {
            width: 80px;
            height: 80px;
            border-radius: 8px;
            object-fit: cover;
            flex-shrink: 0;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 2rem;
        }

        .article-thumbnail::before {
            content: '📰';
            display: none;
        }

        .article-thumbnail[src=""],
        .article-thumbnail:not([src]) {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }

        .article-thumbnail[src=""]::before,
        .article-thumbnail:not([src])::before {
            display: block;
        }

        .article-content {
            flex: 1;
            display: flex;
            flex-direction: column;
            gap: 4px;
        }

        .article-title {
            font-size: 1rem;
            font-weight: 600;
            color: #222;
            line-height: 1.4;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
        }

        .article-meta {
            display: flex;
            align-items: center;
            gap: 12px;
            font-size: 0.88rem;
            color: #777;
        }

        .article-meta i {
            margin-right: 4px;
        }

        /* Activity Item */
        .activity-item {
            display: flex;
            align-items: center;
            gap: 14px;
            padding: 16px 0;
            border-bottom: 1px solid #f0f0f0;
        }

        .activity-item:last-child {
            border-bottom: none;
        }

        .activity-icon {
            width: 48px;
            height: 48px;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.4rem;
            flex-shrink: 0;
        }

        .activity-info {
            flex: 1;
        }

        .activity-label {
            font-size: 0.92rem;
            color: #666;
            margin-bottom: 2px;
        }

        .activity-value {
            font-size: 1.4rem;
            font-weight: 700;
            color: #222;
        }

        /* Design Card */
        .design-card {
            background: #f9f9f9;
            border-radius: 10px;
            overflow: hidden;
            transition: all 0.2s;
            cursor: pointer;
        }

        .design-card:hover {
            box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
            transform: translateY(-4px);
        }

        .design-image {
            width: 100%;
            height: 140px;
            object-fit: cover;
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 3rem;
        }

        .design-image::before {
            content: '🏠';
            display: none;
        }

        .design-image[src=""],
        .design-image:not([src]) {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
        }

        .design-image[src=""]::before,
        .design-image:not([src])::before {
            display: block;
        }

        .design-info {
            padding: 12px;
        }

        .design-title {
            font-size: 0.95rem;
            font-weight: 600;
            color: #222;
            margin-bottom: 4px;
            display: -webkit-box;
            -webkit-line-clamp: 1;
            -webkit-box-orient: vertical;
            overflow: hidden;
        }

        .design-type {
            font-size: 0.85rem;
            color: #666;
        }

        /* Dropdown styles */
        .dropdown-content {
            display: none;
            position: absolute;
            top: 100%;
            left: 0;
            background: #fff;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
            border-radius: 8px;
            min-width: 180px;
            z-index: 10;
        }

        .dropdown-content a {
            display: block;
            padding: 10px 18px;
            color: #222;
            text-decoration: none;
            font-size: 1rem;
            border-bottom: 1px solid #eee;
        }

        .dropdown-content a:hover {
            background: #f4f4f4;
        }
    </style>
    <div class="admin-dashboard">
        @include('admin.components.sidebar')
        <main class="main">
            <div class="main-header">
                <div>
                    <div class="title">Dashboard Admin</div>
                    <div class="subtitle">Selamat datang di Kementrian PKP</div>
                </div>
                <div class="header-actions">
                    <a href="feedback"><i class="fas fa-bell"></i></a>
                    <a href="pengaturan-situs"><i class="fas fa-cog"></i></a>
                    <form method="POST" action="{{ route('logout') }}" style="display:inline;">
                        @csrf
                        <button type="submit">Keluar</button>
                    </form>
                </div>
            </div>
            <div class="main-content">
                <!-- Alert Messages -->
                @if (session('error'))
                    <div class="alert alert-danger"
                        style="background:#fee;border:1px solid #fcc;color:#c33;padding:14px 18px;border-radius:8px;margin-bottom:20px;display:flex;align-items:center;gap:10px;">
                        <i class="fas fa-exclamation-circle"></i>
                        <span>{{ session('error') }}</span>
                    </div>
                @endif

                @if (session('success'))
                    <div class="alert alert-success"
                        style="background:#efe;border:1px solid #cfc;color:#3c3;padding:14px 18px;border-radius:8px;margin-bottom:20px;display:flex;align-items:center;gap:10px;">
                        <i class="fas fa-check-circle"></i>
                        <span>{{ session('success') }}</span>
                    </div>
                @endif

                <!-- Visitor Statistics -->
                <div class="stat-summary">
                    <div class="stat-card">
                        <div class="stat-icon" style="background:#e8f4fd;color:#3498db;"><i class="fas fa-users"></i>
                        </div>
                        <div class="stat-title">Pengunjung Hari Ini</div>
                        <div class="stat-value" id="visitorToday">
                            <i class="fas fa-spinner fa-spin"></i>
                        </div>
                        <div class="stat-growth" id="visitorTodayLabel">Loading...</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon" style="background:#fdf6e3;color:#f7b731;"><i class="fas fa-calendar-alt"></i>
                        </div>
                        <div class="stat-title">Pengunjung Bulan Ini</div>
                        <div class="stat-value" id="visitorMonth">
                            <i class="fas fa-spinner fa-spin"></i>
                        </div>
                        <div class="stat-growth" id="visitorMonthLabel">Loading...</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon" style="background:#fbeaf3;color:#d72660;"><i class="fas fa-chart-line"></i>
                        </div>
                        <div class="stat-title">Total Pengunjung</div>
                        <div class="stat-value" id="visitorTotal">
                            <i class="fas fa-spinner fa-spin"></i>
                        </div>
                        <div class="stat-growth" id="visitorTotalLabel">Loading...</div>
                    </div>
                </div>

                <!-- Hapus Kelola Admin dan Registrasi Admin dari konten utama -->
                <div class="stat-summary">
                    <div class="stat-card">
                        <div class="stat-icon" style="background:#eaf6f3;color:#22c1b6;"><i class="fas fa-university"></i>
                        </div>
                        <div class="stat-title">Bank Design</div>
                        <div class="stat-value" id="designCount">
                            <i class="fas fa-spinner fa-spin"></i>
                        </div>
                        <div class="stat-growth" id="designGrowth">Loading...</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon" style="background:#fdf6e3;color:#f7b731;"><i class="fas fa-newspaper"></i>
                        </div>
                        <div class="stat-title">Berita</div>
                        <div class="stat-value" id="articleCount">
                            <i class="fas fa-spinner fa-spin"></i>
                        </div>
                        <div class="stat-growth" id="articleGrowth">Loading...</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon" style="background:#e8f4fd;color:#3498db;"><i class="fas fa-video"></i></div>
                        <div class="stat-title">Video</div>
                        <div class="stat-value" id="videoCount">
                            <i class="fas fa-spinner fa-spin"></i>
                        </div>
                        <div class="stat-growth" id="videoGrowth">Loading...</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon" style="background:#fbeaf3;color:#d72660;"><i class="fas fa-image"></i></div>
                        <div class="stat-title">Banner</div>
                        <div class="stat-value" id="bannerCount">
                            <i class="fas fa-spinner fa-spin"></i>
                        </div>
                        <div class="stat-growth" id="bannerGrowth">Loading...</div>
                    </div>
                </div>

                <!-- Quick Actions -->
                <div
                    style="display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:16px;margin-bottom:32px;">
                    <a href="{{ url('/admin/berita') }}" class="quick-action-card">
                        <i class="fas fa-plus-circle"></i>
                        <span>Tambah Berita</span>
                    </a>
                    <a href="{{ url('/admin/design-prototype') }}" class="quick-action-card">
                        <i class="fas fa-home"></i>
                        <span>Tambah Design Prototype</span>
                    </a>
                    <a href="{{ url('/admin/video') }}" class="quick-action-card">
                        <i class="fas fa-video"></i>
                        <span>Tambah Video</span>
                    </a>
                    <a href="{{ url('/admin/banner') }}" class="quick-action-card">
                        <i class="fas fa-image"></i>
                        <span>Kelola Banner</span>
                    </a>
                </div>

                <!-- Content Grid -->
                <div style="display:grid;grid-template-columns:2fr 1fr;gap:24px;margin-bottom:32px;">
                    <!-- Recent Articles -->
                    <div class="content-box">
                        <div class="content-box-header">
                            <h3><i class="fas fa-newspaper"></i> Berita Terbaru</h3>
                            <a href="{{ url('/admin/berita') }}">Lihat Semua <i class="fas fa-arrow-right"></i></a>
                        </div>
                        <div class="content-box-body">
                            <div id="recentArticles">
                                <div style="text-align:center;padding:20px;color:#999;">
                                    <i class="fas fa-spinner fa-spin" style="font-size:24px;"></i>
                                    <p>Memuat data...</p>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Activity Stats -->
                    <div class="content-box">
                        <div class="content-box-header">
                            <h3><i class="fas fa-chart-line"></i> Statistik</h3>
                        </div>
                        <div class="content-box-body">
                            <div class="activity-item">
                                <div class="activity-icon" style="background:#eaf6f3;color:#22c1b6;">
                                    <i class="fas fa-file-alt"></i>
                                </div>
                                <div class="activity-info">
                                    <div class="activity-label">Total Konten</div>
                                    <div class="activity-value" id="totalContent">0</div>
                                </div>
                            </div>
                            <div class="activity-item">
                                <div class="activity-icon" style="background:#fdf6e3;color:#f7b731;">
                                    <i class="fas fa-images"></i>
                                </div>
                                <div class="activity-info">
                                    <div class="activity-label">Total Media</div>
                                    <div class="activity-value" id="totalMedia">0</div>
                                </div>
                            </div>
                            <div class="activity-item">
                                <div class="activity-icon" style="background:#e8f4fd;color:#3498db;">
                                    <i class="fas fa-calendar"></i>
                                </div>
                                <div class="activity-info">
                                    <div class="activity-label">Bulan Ini</div>
                                    <div class="activity-value" id="thisMonth">0</div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Recent Designs -->
                <div class="content-box">
                    <div class="content-box-header">
                        <h3><i class="fas fa-home"></i> Design Terbaru</h3>
                        <a href="{{ url('/admin/bankdesign') }}">Lihat Semua <i class="fas fa-arrow-right"></i></a>
                    </div>
                    <div class="content-box-body">
                        <div id="recentDesigns"
                            style="display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:16px;">
                            <div style="text-align:center;padding:20px;color:#999;grid-column:1/-1;">
                                <i class="fas fa-spinner fa-spin" style="font-size:24px;"></i>
                                <p>Memuat data...</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>
    <!-- Pastikan FontAwesome sudah di-load di layout -->
    <script>
        const baseUrl = '{{ env('BASE_URL') }}';

        function getAuthToken() {
            return '{{ session('auth.token') }}';
        }

        // Load visitor statistics
        async function loadVisitorStats(token) {
            try {
                const response = await fetch(`${baseUrl}/api/admin/visitor/stats`, {
                    headers: {
                        'Authorization': `Bearer ${token}`,
                        'Accept': 'application/json'
                    }
                });

                if (response.ok) {
                    const data = await response.json();
                    const stats = data.stats || {};

                    // Update visitor statistics
                    document.getElementById('visitorToday').textContent = stats.today || 0;
                    document.getElementById('visitorTodayLabel').innerHTML =
                        `<i class="fas fa-eye"></i> Kunjungan Hari Ini`;

                    document.getElementById('visitorMonth').textContent = stats.this_month || 0;
                    document.getElementById('visitorMonthLabel').innerHTML =
                        `<i class="fas fa-calendar-check"></i> Bulan Ini`;

                    document.getElementById('visitorTotal').textContent = stats.total || 0;
                    document.getElementById('visitorTotalLabel').innerHTML =
                        `<i class="fas fa-chart-bar"></i> Total Kunjungan`;
                } else {
                    // Handle error
                    document.getElementById('visitorToday').textContent = '0';
                    document.getElementById('visitorTodayLabel').textContent = 'No Data';
                    document.getElementById('visitorMonth').textContent = '0';
                    document.getElementById('visitorMonthLabel').textContent = 'No Data';
                    document.getElementById('visitorTotal').textContent = '0';
                    document.getElementById('visitorTotalLabel').textContent = 'No Data';
                }
            } catch (error) {
                console.error('Error loading visitor stats:', error);
                document.getElementById('visitorToday').textContent = '0';
                document.getElementById('visitorTodayLabel').textContent = 'Error';
                document.getElementById('visitorMonth').textContent = '0';
                document.getElementById('visitorMonthLabel').textContent = 'Error';
                document.getElementById('visitorTotal').textContent = '0';
                document.getElementById('visitorTotalLabel').textContent = 'Error';
            }
        }

        // Load statistics on page load
        document.addEventListener('DOMContentLoaded', async function() {
            await loadStatistics();
        });

        async function loadStatistics() {
            const token = getAuthToken();

            try {
                // Load visitor statistics first
                await loadVisitorStats(token);

                // Load all data in parallel
                const [designResponse, articleResponse, videoResponse, bannerResponse] = await Promise.all([
                    fetch(`${baseUrl}/api/admin/house-design`, {
                        headers: {
                            'Authorization': `Bearer ${token}`,
                            'Accept': 'application/json'
                        }
                    }),
                    fetch(`${baseUrl}/api/admin/article`, {
                        headers: {
                            'Authorization': `Bearer ${token}`,
                            'Accept': 'application/json'
                        }
                    }),
                    fetch(`${baseUrl}/api/admin/video`, {
                        headers: {
                            'Authorization': `Bearer ${token}`,
                            'Accept': 'application/json'
                        }
                    }),
                    fetch(`${baseUrl}/api/admin/banner`, {
                        headers: {
                            'Authorization': `Bearer ${token}`,
                            'Accept': 'application/json'
                        }
                    })
                ]);

                // Process Design data
                let designList = [];
                if (designResponse.ok) {
                    const designData = await designResponse.json();
                    // Handle structure: {site: {...}, local: {houseDesigns: [...]}}
                    designList = designData.local?.houseDesigns || designData.data?.houseDesigns || designData
                        .houseDesigns || (Array.isArray(designData) ? designData : (designData.data || []));
                    document.getElementById('designCount').textContent = designList.length;
                    document.getElementById('designGrowth').innerHTML = `<i class="fas fa-check"></i> Total Design`;
                } else {
                    document.getElementById('designCount').textContent = '0';
                    document.getElementById('designGrowth').textContent = 'No Data';
                }

                // Process Article data
                let articleList = [];
                if (articleResponse.ok) {
                    const articleData = await articleResponse.json();
                    // Handle structure: {site: {...}, local: {articles: [...]}}
                    articleList = articleData.local?.articles || articleData.data?.articles || articleData.articles || (
                        Array.isArray(articleData) ? articleData : (articleData.data || []));
                    document.getElementById('articleCount').textContent = articleList.length;
                    document.getElementById('articleGrowth').innerHTML = `<i class="fas fa-check"></i> Total Berita`;
                } else {
                    document.getElementById('articleCount').textContent = '0';
                    document.getElementById('articleGrowth').textContent = 'No Data';
                }

                // Process Video data
                let videoList = [];
                if (videoResponse.ok) {
                    const videoData = await videoResponse.json();
                    // Handle structure: {site: {...}, local: {videos: [...]}}
                    videoList = videoData.local?.videos || videoData.data?.videos || videoData.videos || (Array.isArray(
                        videoData) ? videoData : (videoData.data || []));
                    document.getElementById('videoCount').textContent = videoList.length;
                    document.getElementById('videoGrowth').innerHTML = `<i class="fas fa-check"></i> Total Video`;
                } else {
                    document.getElementById('videoCount').textContent = '0';
                    document.getElementById('videoGrowth').textContent = 'No Data';
                }

                // Process Banner data
                let bannerList = [];
                if (bannerResponse.ok) {
                    const bannerData = await bannerResponse.json();
                    // Handle structure: {site: {banners: [...]}}
                    bannerList = bannerData.site?.banners || bannerData.data?.banners || bannerData.banners || (Array
                        .isArray(bannerData) ? bannerData : (bannerData.data || []));
                    document.getElementById('bannerCount').textContent = bannerList.length;
                    document.getElementById('bannerGrowth').innerHTML = `<i class="fas fa-check"></i> Total Banner`;
                } else {
                    document.getElementById('bannerCount').textContent = '0';
                    document.getElementById('bannerGrowth').textContent = 'No Data';
                }

                // Update total statistics
                const totalContent = articleList.length + designList.length;
                const totalMedia = videoList.length + bannerList.length;

                document.getElementById('totalContent').textContent = totalContent;
                document.getElementById('totalMedia').textContent = totalMedia;

                // Calculate this month's content
                const currentMonth = new Date().getMonth();
                const currentYear = new Date().getFullYear();
                const thisMonthCount = articleList.filter(article => {
                    const dateStr = article.createdAt || article.created_at;
                    if (dateStr) {
                        const articleDate = new Date(dateStr);
                        return articleDate.getMonth() === currentMonth && articleDate.getFullYear() ===
                            currentYear;
                    }
                    return false;
                }).length;
                document.getElementById('thisMonth').textContent = thisMonthCount;

                // Display recent articles
                displayRecentArticles(articleList);

                // Display recent designs
                displayRecentDesigns(designList);

            } catch (error) {
                console.error('Error loading statistics:', error);
                document.getElementById('designCount').textContent = '0';
                document.getElementById('designGrowth').textContent = 'Error';
                document.getElementById('articleCount').textContent = '0';
                document.getElementById('articleGrowth').textContent = 'Error';
                document.getElementById('videoCount').textContent = '0';
                document.getElementById('videoGrowth').textContent = 'Error';
                document.getElementById('bannerCount').textContent = '0';
                document.getElementById('bannerGrowth').textContent = 'Error';
            }
        }

        function displayRecentArticles(articles) {
            const container = document.getElementById('recentArticles');

            if (!articles || articles.length === 0) {
                container.innerHTML = '<p style="text-align:center;color:#999;padding:20px;">Belum ada berita</p>';
                return;
            }

            // Sort by date and get latest 5
            const recentArticles = articles
                .sort((a, b) => new Date(b.createdAt || b.created_at) - new Date(a.createdAt || a.created_at))
                .slice(0, 5);

            let html = '';
            recentArticles.forEach(article => {
                const dateStr = article.createdAt || article.created_at;
                const date = dateStr ? new Date(dateStr).toLocaleDateString('id-ID', {
                    day: 'numeric',
                    month: 'short',
                    year: 'numeric'
                }) : 'N/A';

                // Construct full image URL from path_image
                let imageUrl = '';
                if (article.path_image) {
                    imageUrl = `${baseUrl}/${article.path_image}`;
                }

                const title = article.title || article.judul || 'Tanpa Judul';
                const category = article.category?.name || article.category_name || article.kategori || 'Umum';

                html += `
                    <div class="article-item">
                        ${imageUrl ? `<img src="${imageUrl}" alt="${title}" class="article-thumbnail" onerror="this.style.display='flex';this.removeAttribute('src');this.onerror=null;">` : '<div class="article-thumbnail"></div>'}
                        <div class="article-content">
                            <div class="article-title">${title}</div>
                            <div class="article-meta">
                                <span><i class="fas fa-calendar"></i>${date}</span>
                                <span><i class="fas fa-tag"></i>${category}</span>
                            </div>
                        </div>
                    </div>
                `;
            });

            container.innerHTML = html;
        }

        function displayRecentDesigns(designs) {
            const container = document.getElementById('recentDesigns');

            if (!designs || designs.length === 0) {
                container.innerHTML =
                    '<p style="text-align:center;color:#999;padding:20px;grid-column:1/-1;">Belum ada design</p>';
                return;
            }

            // Get latest 6 designs
            const recentDesigns = designs
                .sort((a, b) => new Date(b.createdAt || b.created_at) - new Date(a.createdAt || a.created_at))
                .slice(0, 6);

            let html = '';
            recentDesigns.forEach(design => {
                // Construct full image URL from path_image
                let imageUrl = '';
                if (design.path_image) {
                    imageUrl = `${baseUrl}/${design.path_image}`;
                }

                const title = design.title || design.name || design.nama || 'Tanpa Judul';
                const type = design.category?.name || design.house_type || design.type || design.tipe || 'Design';

                html += `
                    <div class="design-card">
                        ${imageUrl ? `<img src="${imageUrl}" alt="${title}" class="design-image" onerror="this.style.display='flex';this.removeAttribute('src');this.onerror=null;">` : '<div class="design-image"></div>'}
                        <div class="design-info">
                            <div class="design-title">${title}</div>
                            <div class="design-type">${type}</div>
                        </div>
                    </div>
                `;
            });

            container.innerHTML = html;
        }

        // Dropdown logic
        document.addEventListener('click', function(e) {
            var dropdown = document.getElementById('admin-dropdown');
            var btn = e.target.closest('button');
            if (!dropdown) return;
            if (!btn || btn.textContent.indexOf('Registrasi Admin') === -1) {
                dropdown.classList.remove('show');
                dropdown.style.display = 'none';
            } else {
                dropdown.style.display = dropdown.classList.contains('show') ? 'block' : 'none';
            }
        });
        // // Sidebar dropdown logic
        // document.getElementById('kelola-admin-link').addEventListener('click', function(e) {
        //     e.preventDefault();
        //     var dropdown = document.getElementById('kelola-admin-dropdown');
        //     dropdown.style.display = dropdown.style.display === 'block' ? 'none' : 'block';
        // });
        // // Hide dropdown when clicking outside
        // document.addEventListener('click', function(e) {
        //     var dropdown = document.getElementById('kelola-admin-dropdown');
        //     var link = document.getElementById('kelola-admin-link');
        //     if (!dropdown || !link) return;
        //     if (!link.contains(e.target) && !dropdown.contains(e.target)) {
        //         dropdown.style.display = 'none';
        //     }
        // });
        // Penanganan session expired global (jaga-jaga jika nanti ada request async di dashboard)
        if (typeof window.handleSessionExpired !== 'function') {
            window.handleSessionExpired = function() {
                if (window.sessionExpiredHandled) return;
                window.sessionExpiredHandled = true;
                alert('Session Anda telah habis. Silakan login ulang.');
                window.location.href = '/login';
            };
        }
    </script>
@endsection
