%PDF- %PDF-
Mini Shell

Mini Shell

Direktori : /home2/rezakur1/ternakdolar.my.id/Ternak-Dolar/
Upload File :
Create Path :
Current File : /home2/rezakur1/ternakdolar.my.id/Ternak-Dolar/index.php

<?php
require_once __DIR__ . '/auth.php';
requireAuth();
$user = getCurrentUser();

header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
?>
<!DOCTYPE html>
<html lang="id" class="dark">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ternak Dolar</title>

    <script src="https://cdn.tailwindcss.com"></script>

    <script>
        tailwind.config = {
            darkMode: 'class',
            theme: {
                extend: {
                    colors: {
                        ink: {
                            950: '#08090d', 900: '#0d0f15', 850: '#12151d',
                            800: '#171b26', 750: '#1d2230', 700: '#252b3a',
                            600: '#333a4d', 500: '#4a5268',
                        }
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                        mono: ['JetBrains Mono', 'ui-monospace', 'monospace']
                    },
                    animation: {
                        'fade-in': 'fadeIn .3s ease-out',
                        'slide-up': 'slideUp .3s ease-out',
                        'pulse-soft': 'pulseSoft 2s ease-in-out infinite'
                    },
                    keyframes: {
                        fadeIn:  { '0%': { opacity: 0 }, '100%': { opacity: 1 } },
                        slideUp: { '0%': { opacity: 0, transform: 'translateY(6px)' }, '100%': { opacity: 1, transform: 'translateY(0)' } },
                        pulseSoft: { '0%, 100%': { opacity: 1 }, '50%': { opacity: .5 } }
                    }
                }
            }
        }
    </script>

    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">

    <style>
        html, body { height: 100%; }
        body {
            background: #f1f5f9;
            transition: background .3s ease;
            font-feature-settings: 'cv02', 'cv03', 'cv04', 'cv11';
        }
        .dark body {
            background: #08090d;
            color: #e2e8f0;
            background-image:
                radial-gradient(ellipse 80% 60% at 50% -10%, rgba(56, 189, 248, .06), transparent),
                radial-gradient(ellipse 60% 50% at 90% 100%, rgba(239, 68, 68, .05), transparent);
        }
        ::-webkit-scrollbar { width: 10px; height: 10px; }
        ::-webkit-scrollbar-track { background: transparent; }
        ::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 10px; border: 2px solid transparent; background-clip: padding-box; }
        ::-webkit-scrollbar-thumb:hover { background-color: #94a3b8; background-clip: padding-box; border: 2px solid transparent; }
        .dark ::-webkit-scrollbar-thumb { background: #252b3a; background-clip: padding-box; border: 2px solid transparent; }
        .dark ::-webkit-scrollbar-thumb:hover { background-color: #333a4d; background-clip: padding-box; }

        .theme-switch {
            position: relative; width: 44px; height: 24px; border-radius: 999px;
            background: #cbd5e1; transition: background .3s; cursor: pointer; flex-shrink: 0;
        }
        .dark .theme-switch { background: #252b3a; }
        .theme-switch::after {
            content: ''; position: absolute; top: 2px; left: 2px;
            width: 20px; height: 20px; border-radius: 50%; background: #fff;
            transition: transform .3s cubic-bezier(.4, 0, .2, 1);
            box-shadow: 0 2px 4px rgba(0,0,0,.2);
        }
        .dark .theme-switch::after { transform: translateX(20px); background: #e2e8f0; }

        tbody tr { transition: background .15s ease, box-shadow .15s ease; }
        tbody tr:hover { box-shadow: inset 3px 0 0 0 rgb(16 185 129); }

        .grid-bg {
            background-image:
                linear-gradient(rgba(148, 163, 184, .04) 1px, transparent 1px),
                linear-gradient(90deg, rgba(148, 163, 184, .04) 1px, transparent 1px);
            background-size: 40px 40px;
        }
        .stat-card { position: relative; overflow: hidden; }
        .stat-card::before {
            content: ''; position: absolute; inset: 0;
            background: linear-gradient(135deg, transparent 60%, currentColor 200%);
            opacity: .04; pointer-events: none;
        }
        .btn-copy:active { transform: scale(.97); }
        .btn-copy { transition: transform .1s, background .2s, color .2s; }

        .modal-backdrop { animation: fadeIn .2s ease-out; }
        .modal-content { animation: slideUp .25s cubic-bezier(.4, 0, .2, 1); }
        @keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
        @keyframes slideUp { from { opacity: 0; transform: translateY(20px) scale(.98) } to { opacity: 1; transform: translateY(0) scale(1) } }

        input[type="datetime-local"] { color-scheme: light; }
        .dark input[type="datetime-local"] { color-scheme: dark; }

        .tab-btn { position: relative; transition: all .2s ease; }
        .tab-btn.active { color: #0f172a; background: #fff; box-shadow: 0 1px 3px rgba(0,0,0,.08); }
        .dark .tab-btn.active { color: #fff; background: #1d2230; box-shadow: 0 1px 3px rgba(0,0,0,.3); }
        .dark .tab-btn:not(.active) { color: #94a3b8; }

        .cal-day {
            transition: all .15s ease;
            min-height: 110px;
            position: relative;
        }
        .cal-day.other-month { opacity: .3; }
        .cal-day.today { background: linear-gradient(135deg, rgba(59, 130, 246, .08), rgba(99, 102, 241, .08)); }
        .dark .cal-day.today { background: linear-gradient(135deg, rgba(59, 130, 246, .12), rgba(99, 102, 241, .12)); }
        .cal-day:hover:not(.other-month) { background: rgba(148, 163, 184, .08); }
        .dark .cal-day:hover:not(.other-month) { background: rgba(148, 163, 184, .06); }

        .cal-event { transition: all .15s ease; cursor: pointer; }
        .cal-event:hover { transform: translateX(2px); }

        /* Badge jumlah di cell kalender */
        .cal-count-badge {
            display: inline-flex;
            align-items: center;
            gap: 3px;
            padding: 2px 7px;
            border-radius: 999px;
            font-size: 10px;
            font-weight: 800;
            letter-spacing: -0.02em;
            box-shadow: 0 1px 3px rgba(0,0,0,.1);
        }
        .cal-count-badge.high {
            background: linear-gradient(135deg, #ef4444, #dc2626);
            color: #fff;
            animation: pulseSoft 2s ease-in-out infinite;
        }
        .cal-count-badge.medium {
            background: linear-gradient(135deg, #f59e0b, #d97706);
            color: #fff;
        }
        .cal-count-badge.low {
            background: linear-gradient(135deg, #3b82f6, #2563eb);
            color: #fff;
        }
    </style>
</head>

<body class="min-h-screen text-slate-800 dark:text-slate-200 antialiased">

    <div class="flex min-h-screen flex-col grid-bg">

        <!-- Navbar -->
        <nav class="sticky top-0 z-40 border-b border-slate-200/80 bg-white/70 backdrop-blur-xl dark:border-ink-700/60 dark:bg-ink-900/60">
            <div class="flex items-center justify-between gap-4 px-6 py-3.5 lg:px-8">
                <div class="flex items-center gap-3.5 min-w-0">
                    <div class="relative grid h-10 w-10 shrink-0 place-items-center rounded-xl bg-gradient-to-br from-emerald-500 via-emerald-600 to-green-700 text-white shadow-lg shadow-emerald-500/20">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                            <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>
                        <span id="statusDot" class="absolute -bottom-0.5 -right-0.5 h-3 w-3 rounded-full bg-slate-400 ring-2 ring-white dark:ring-ink-900 transition-colors"></span>
                    </div>
                    <div class="min-w-0">
                        <h1 class="truncate text-base font-bold tracking-tight text-slate-900 dark:text-white">
                            Ternak Dolar
                        </h1>
                        <p class="truncate text-[11px] font-medium text-slate-500 dark:text-slate-500">
                            Ternak Dolar
                        </p>
                    </div>
                </div>

                <div class="flex items-center gap-3">
                    <div id="dbStatus" class="hidden items-center gap-1.5 rounded-full border border-slate-200 bg-white/60 px-3 py-1.5 text-[11px] font-medium text-slate-500 sm:flex dark:border-ink-700 dark:bg-ink-850/60 dark:text-slate-400">
                        <span class="h-1.5 w-1.5 animate-pulse-soft rounded-full bg-amber-500"></span>
                        <span>Connecting...</span>
                    </div>

                    <div class="theme-switch" onclick="toggleTheme()" title="Toggle theme"></div>

                    <!-- User Menu -->
                    <div class="hidden items-center gap-2 rounded-xl border border-slate-200 bg-white/60 px-3 py-1.5 sm:flex dark:border-ink-700 dark:bg-ink-850/60">
                        <div class="grid h-6 w-6 place-items-center rounded-full bg-violet-100 text-[10px] font-bold text-violet-600 dark:bg-violet-900/50 dark:text-violet-400">
                            <?= strtoupper(substr($user['name'] ?: $user['email'], 0, 1)) ?>
                        </div>
                        <span class="text-[11px] font-semibold text-slate-700 dark:text-slate-300"><?= htmlspecialchars($user['name'] ?: $user['email']) ?></span>
                        <a href="logout.php"
                            class="ml-1 grid h-6 w-6 place-items-center rounded-lg text-slate-400 transition hover:bg-red-50 hover:text-red-500 dark:text-slate-500 dark:hover:bg-red-950/40 dark:hover:text-red-400"
                            title="Logout">
                            <svg xmlns="http://www.w3.org/2000/svg" class="h-3.5 w-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                                <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/>
                            </svg>
                        </a>
                    </div>

                    <button
                        onclick="document.getElementById('jsonInput').click()"
                        class="group flex items-center gap-2 rounded-xl bg-gradient-to-b from-slate-900 to-slate-800 px-4 py-2 text-xs font-semibold text-white shadow-lg shadow-slate-900/10 transition-all hover:from-slate-800 hover:to-slate-700 hover:shadow-slate-900/20 active:scale-[.97] dark:from-white dark:to-slate-100 dark:text-ink-900 dark:shadow-white/5 dark:hover:from-slate-100 dark:hover:to-white"
                    >
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-3.5 w-3.5 transition-transform group-hover:-translate-y-0.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                            <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
                            <polyline points="17 8 12 3 7 8"/>
                            <line x1="12" y1="3" x2="12" y2="15"/>
                        </svg>
                        Import JSON
                    </button>

                    <input id="jsonInput" type="file" accept=".json,application/json" class="hidden" onchange="importJSON(event)">
                </div>
            </div>

            <!-- Tab Navigation -->
            <div class="border-t border-slate-200/60 px-6 lg:px-8 dark:border-ink-700/40">
                <div class="flex items-center gap-1 py-2">
                    <button
                        id="tab-list"
                        onclick="switchTab('list')"
                        class="tab-btn active flex items-center gap-2 rounded-lg px-4 py-2 text-xs font-semibold text-slate-500 transition hover:bg-slate-100 dark:text-slate-400 dark:hover:bg-ink-800"
                    >
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-3.5 w-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                            <line x1="8" y1="6" x2="21" y2="6"/>
                            <line x1="8" y1="12" x2="21" y2="12"/>
                            <line x1="8" y1="18" x2="21" y2="18"/>
                            <line x1="3" y1="6" x2="3.01" y2="6"/>
                            <line x1="3" y1="12" x2="3.01" y2="12"/>
                            <line x1="3" y1="18" x2="3.01" y2="18"/>
                        </svg>
                        Daftar
                    </button>

                    <button
                        id="tab-calendar"
                        onclick="switchTab('calendar')"
                        class="tab-btn flex items-center gap-2 rounded-lg px-4 py-2 text-xs font-semibold text-slate-500 transition hover:bg-slate-100 dark:text-slate-400 dark:hover:bg-ink-800"
                    >
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-3.5 w-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                            <rect x="3" y="4" width="18" height="18" rx="2" ry="2"/>
                            <line x1="16" y1="2" x2="16" y2="6"/>
                            <line x1="8" y1="2" x2="8" y2="6"/>
                            <line x1="3" y1="10" x2="21" y2="10"/>
                        </svg>
                        Kalender
                        <span id="calBadge" class="hidden rounded-full bg-blue-500 px-1.5 py-0.5 text-[9px] font-bold text-white">0</span>
                    </button>

                    <button
                        id="tab-referensi"
                        onclick="switchTab('referensi')"
                        class="tab-btn flex items-center gap-2 rounded-lg px-4 py-2 text-xs font-semibold text-slate-500 transition hover:bg-slate-100 dark:text-slate-400 dark:hover:bg-ink-800"
                    >
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-3.5 w-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                            <path d="M4 20h16a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.93a2 2 0 0 1-1.66-.9l-.82-1.2A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13c0 1.1.9 2 2 2Z"/>
                        </svg>
                        Referensi
                        <span id="catBadge" class="hidden rounded-full bg-violet-500 px-1.5 py-0.5 text-[9px] font-bold text-white">0</span>
                    </button>
                </div>
            </div>
        </nav>


        <!-- Main -->
        <main class="flex flex-1 flex-col gap-5 px-6 py-6 lg:px-8">

            <!-- ============ TAB: LIST ============ -->
            <div id="view-list" class="flex flex-1 flex-col gap-5">

                <div class="animate-fade-in">
                    <h2 class="text-2xl font-bold tracking-tight text-slate-900 dark:text-white lg:text-3xl">
                        Video Library
                    </h2>
                    <p class="mt-1 text-sm text-slate-500 dark:text-slate-400">
                        Data tersimpan di MySQL — bisa diakses dari perangkat manapun.
                    </p>
                </div>

                <!-- Statistics + Progress -->
                <div class="grid grid-cols-1 gap-4 xl:grid-cols-5 animate-slide-up">
                    <div class="stat-card rounded-2xl border border-slate-200 bg-white p-4 shadow-sm text-slate-900 dark:border-ink-700 dark:bg-ink-850 dark:text-white">
                        <div class="flex items-start justify-between">
                            <div>
                                <p class="text-[11px] font-semibold uppercase tracking-wider text-slate-400 dark:text-slate-500">Total Video</p>
                                <p id="totalCount" class="mt-2 text-3xl font-bold tracking-tight">0</p>
                            </div>
                            <div class="grid h-9 w-9 place-items-center rounded-lg bg-slate-100 text-slate-500 dark:bg-ink-800 dark:text-slate-400">
                                <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="16" rx="2"/><path d="M9 9h6M9 13h6M9 17h4"/></svg>
                            </div>
                        </div>
                    </div>

                    <div class="stat-card rounded-2xl border border-slate-200 bg-white p-4 shadow-sm text-emerald-600 dark:border-ink-700 dark:bg-ink-850 dark:text-emerald-400">
                        <div class="flex items-start justify-between">
                            <div>
                                <p class="text-[11px] font-semibold uppercase tracking-wider text-slate-400 dark:text-slate-500">Sudah Disalin</p>
                                <p id="copiedCount" class="mt-2 text-3xl font-bold tracking-tight">0</p>
                            </div>
                            <div class="grid h-9 w-9 place-items-center rounded-lg bg-emerald-50 text-emerald-600 dark:bg-emerald-950/50 dark:text-emerald-400">
                                <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
                            </div>
                        </div>
                    </div>

                    <div class="stat-card rounded-2xl border border-slate-200 bg-white p-4 shadow-sm text-orange-500 dark:border-ink-700 dark:bg-ink-850 dark:text-orange-400">
                        <div class="flex items-start justify-between">
                            <div>
                                <p class="text-[11px] font-semibold uppercase tracking-wider text-slate-400 dark:text-slate-500">Belum Disalin</p>
                                <p id="remainingCount" class="mt-2 text-3xl font-bold tracking-tight">0</p>
                            </div>
                            <div class="grid h-9 w-9 place-items-center rounded-lg bg-orange-50 text-orange-500 dark:bg-orange-950/50 dark:text-orange-400">
                                <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
                            </div>
                        </div>
                    </div>

                    <div class="rounded-2xl border border-slate-200 bg-white p-4 shadow-sm xl:col-span-2 dark:border-ink-700 dark:bg-ink-850">
                        <div class="mb-3 flex items-center justify-between">
                            <span class="text-[11px] font-semibold uppercase tracking-wider text-slate-400 dark:text-slate-500">Progress</span>
                            <span id="progressText" class="rounded-md bg-slate-100 px-2 py-0.5 text-xs font-bold text-slate-900 dark:bg-ink-800 dark:text-white">0%</span>
                        </div>
                        <div class="h-2.5 overflow-hidden rounded-full bg-slate-100 dark:bg-ink-800">
                            <div id="progressBar" class="h-full rounded-full bg-gradient-to-r from-emerald-400 via-emerald-500 to-teal-500 shadow-sm shadow-emerald-500/40 transition-all duration-500" style="width: 0%"></div>
                        </div>
                        <div class="mt-2 flex items-center justify-between text-[10px] font-medium text-slate-400 dark:text-slate-500">
                            <span id="progressDetail">0 dari 0</span>
                            <span id="scheduledCount">0 terjadwal</span>
                        </div>
                    </div>
                </div>

                <!-- Toolbar -->
                <div class="flex flex-col gap-3 md:flex-row md:items-center animate-slide-up">
                    <div class="relative flex-1">
                        <svg xmlns="http://www.w3.org/2000/svg" class="pointer-events-none absolute left-3.5 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400 dark:text-slate-500" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
                        <input id="searchInput" type="text" placeholder="Cari judul video..." oninput="debouncedSearch()"
                            class="w-full rounded-xl border border-slate-200 bg-white py-2.5 pl-10 pr-4 text-sm outline-none transition-all placeholder:text-slate-400 focus:border-emerald-400 focus:ring-4 focus:ring-emerald-500/10 dark:border-ink-700 dark:bg-ink-850 dark:text-slate-200 dark:placeholder:text-slate-500 dark:focus:border-emerald-500/60 dark:focus:ring-emerald-500/10">
                    </div>

                    <div class="relative">
                        <svg xmlns="http://www.w3.org/2000/svg" class="pointer-events-none absolute left-3.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-slate-400 dark:text-slate-500" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3"/></svg>
                        <select id="statusFilter" onchange="currentPage=1; loadVideos()"
                            class="cursor-pointer appearance-none rounded-xl border border-slate-200 bg-white py-2.5 pl-10 pr-9 text-sm outline-none transition-all focus:border-emerald-400 focus:ring-4 focus:ring-emerald-500/10 dark:border-ink-700 dark:bg-ink-850 dark:text-slate-200 dark:focus:border-emerald-500/60 dark:focus:ring-emerald-500/10">
                            <option value="all">Semua Status</option>
                            <option value="pending">Belum Disalin</option>
                            <option value="copied">Sudah Disalin</option>
                            <option value="scheduled">Sudah Dijadwalkan</option>
                            <option value="unscheduled">Belum Dijadwalkan</option>
                        </select>
                        <svg xmlns="http://www.w3.org/2000/svg" class="pointer-events-none absolute right-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-slate-400" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 9 12 15 18 9"/></svg>
                    </div>

                    <div class="relative">
                        <svg xmlns="http://www.w3.org/2000/svg" class="pointer-events-none absolute left-3.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-slate-400 dark:text-slate-500" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 20h16a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.93a2 2 0 0 1-1.66-.9l-.82-1.2A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13c0 1.1.9 2 2 2Z"/></svg>
                        <select id="categoryFilter" onchange="currentPage=1; loadVideos()"
                            class="cursor-pointer appearance-none rounded-xl border border-slate-200 bg-white py-2.5 pl-10 pr-9 text-sm outline-none transition-all focus:border-violet-400 focus:ring-4 focus:ring-violet-500/10 dark:border-ink-700 dark:bg-ink-850 dark:text-slate-200 dark:focus:border-violet-500/60 dark:focus:ring-violet-500/10">
                            <option value="all">Semua Kategori</option>
                            <option value="none">Tanpa Kategori</option>
                        </select>
                        <svg xmlns="http://www.w3.org/2000/svg" class="pointer-events-none absolute right-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-slate-400" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 9 12 15 18 9"/></svg>
                    </div>

                    <button onclick="shuffleVideos()"
                        class="flex items-center justify-center gap-2 rounded-xl border border-slate-200 bg-white px-4 py-2.5 text-sm font-semibold text-slate-600 transition-all hover:border-violet-300 hover:bg-violet-50 hover:text-violet-600 active:scale-[.97] dark:border-ink-700 dark:bg-ink-850 dark:text-slate-300 dark:hover:border-violet-800 dark:hover:bg-violet-950/40 dark:hover:text-violet-400" title="Acak ulang urutan video">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-3.5 w-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><polyline points="16 3 21 3 21 8"/><line x1="4" y1="20" x2="21" y2="3"/><polyline points="21 16 21 21 16 21"/><line x1="15" y1="15" x2="21" y2="21"/><line x1="4" y1="4" x2="9" y2="9"/></svg>
                        Acak
                    </button>

                    <button onclick="resetCopiedStatus()"
                        class="flex items-center justify-center gap-2 rounded-xl border border-red-200 bg-white px-4 py-2.5 text-sm font-semibold text-red-600 transition-all hover:border-red-300 hover:bg-red-50 active:scale-[.97] dark:border-red-900/40 dark:bg-ink-850 dark:text-red-400 dark:hover:border-red-800/60 dark:hover:bg-red-950/40">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-3.5 w-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 12a9 9 0 1 0 3-6.7L3 8"/><path d="M3 3v5h5"/></svg>
                        Reset Status
                    </button>
                </div>

                <!-- Empty State -->
                <div id="emptyState" class="hidden flex-1 animate-fade-in rounded-2xl border border-dashed border-slate-300 bg-white/50 p-16 text-center backdrop-blur dark:border-ink-700 dark:bg-ink-850/40">
                    <div class="mx-auto mb-4 grid h-16 w-16 place-items-center rounded-2xl bg-slate-100 text-3xl dark:bg-ink-800">📂</div>
                    <h3 class="text-base font-semibold text-slate-900 dark:text-white">Belum ada data video</h3>
                    <p class="mx-auto mt-2 max-w-md text-sm text-slate-500 dark:text-slate-400">
                        Import file <code class="rounded bg-slate-100 px-1.5 py-0.5 text-xs font-mono dark:bg-ink-800">shorts.json</code> untuk mulai.
                    </p>
                </div>

                <!-- Loading State -->
                <div id="loadingState" class="flex flex-1 items-center justify-center rounded-2xl border border-slate-200 bg-white dark:border-ink-700 dark:bg-ink-850">
                    <div class="flex flex-col items-center gap-3">
                        <div class="h-10 w-10 rounded-full border-2 border-slate-200 border-t-emerald-500 animate-spin dark:border-ink-700 dark:border-t-emerald-400"></div>
                        <p class="text-sm font-medium text-slate-500 dark:text-slate-400">Memuat data...</p>
                    </div>
                </div>

                <!-- Table -->
                <div id="tableContainer" class="hidden flex-1 animate-fade-in overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-sm dark:border-ink-700 dark:bg-ink-850">
                    <div class="h-full overflow-auto">
                        <table class="w-full text-left">
                            <thead class="sticky top-0 z-10 border-b border-slate-200 bg-slate-50/95 backdrop-blur dark:border-ink-700 dark:bg-ink-800/95">
                                <tr>
                                    <th class="w-12 px-4 py-3 text-[10px] font-bold uppercase tracking-wider text-slate-400 dark:text-slate-500">#</th>
                                    <th class="px-4 py-3 text-[10px] font-bold uppercase tracking-wider text-slate-400 dark:text-slate-500">Title</th>
                                    <th class="w-52 px-4 py-3 text-[10px] font-bold uppercase tracking-wider text-slate-400 dark:text-slate-500">Video ID</th>
                                    <th class="w-36 px-4 py-3 text-[10px] font-bold uppercase tracking-wider text-slate-400 dark:text-slate-500">Kategori</th>
                                    <th class="w-48 px-4 py-3 text-[10px] font-bold uppercase tracking-wider text-slate-400 dark:text-slate-500">Status</th>
                                    <th class="w-52 px-4 py-3 text-[10px] font-bold uppercase tracking-wider text-slate-400 dark:text-slate-500">Jadwal Upload</th>
                                    <th class="w-44 px-4 py-3 text-right text-[10px] font-bold uppercase tracking-wider text-slate-400 dark:text-slate-500">Action</th>
                                </tr>
                            </thead>
                            <tbody id="videoTable" class="divide-y divide-slate-100 dark:divide-ink-700/60"></tbody>
                        </table>
                    </div>
                    <!-- Pagination -->
                    <div id="paginationContainer" class="hidden border-t border-slate-200 bg-slate-50/80 px-4 py-3 dark:border-ink-700 dark:bg-ink-800/80">
                        <div class="flex items-center justify-between">
                            <p class="text-[11px] font-medium text-slate-500 dark:text-slate-400">
                                Menampilkan <span id="pagStart" class="font-bold text-slate-700 dark:text-slate-200">0</span>–<span id="pagEnd" class="font-bold text-slate-700 dark:text-slate-200">0</span> dari <span id="pagTotal" class="font-bold text-slate-700 dark:text-slate-200">0</span> video
                            </p>
                            <div class="flex items-center gap-1" id="pagButtons"></div>
                        </div>
                    </div>
                </div>
            </div>


            <!-- ============ TAB: CALENDAR ============ -->
            <div id="view-calendar" class="hidden flex-1 flex-col gap-5">

                <div class="flex flex-col justify-between gap-3 sm:flex-row sm:items-center">
                    <div>
                        <h2 class="text-2xl font-bold tracking-tight text-slate-900 dark:text-white lg:text-3xl">
                            Kalender Upload
                        </h2>
                        <p class="mt-1 text-sm text-slate-500 dark:text-slate-400">
                            Lihat jadwal upload konten dalam tampilan kalender bulanan.
                        </p>
                    </div>

                    <div class="flex items-center gap-2">
                        <button onclick="changeMonth(-1)" class="grid h-9 w-9 place-items-center rounded-lg border border-slate-200 bg-white text-slate-600 transition hover:bg-slate-50 active:scale-95 dark:border-ink-700 dark:bg-ink-850 dark:text-slate-300 dark:hover:bg-ink-800">
                            <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                                <polyline points="15 18 9 12 15 6"/>
                            </svg>
                        </button>

                        <button onclick="goToToday()" class="rounded-lg border border-slate-200 bg-white px-3 py-2 text-xs font-semibold text-slate-600 transition hover:bg-slate-50 dark:border-ink-700 dark:bg-ink-850 dark:text-slate-300 dark:hover:bg-ink-800">
                            Hari Ini
                        </button>

                        <div class="min-w-[140px] text-center">
                            <span id="calMonthLabel" class="text-sm font-bold text-slate-900 dark:text-white">Januari 2026</span>
                        </div>

                        <button onclick="changeMonth(1)" class="grid h-9 w-9 place-items-center rounded-lg border border-slate-200 bg-white text-slate-600 transition hover:bg-slate-50 active:scale-95 dark:border-ink-700 dark:bg-ink-850 dark:text-slate-300 dark:hover:bg-ink-800">
                            <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                                <polyline points="9 18 15 12 9 6"/>
                            </svg>
                        </button>
                    </div>
                </div>

                <!-- Legend -->
                <div class="flex flex-wrap items-center gap-4 text-[11px] font-medium text-slate-500 dark:text-slate-400">
                    <span class="flex items-center gap-1.5">
                        <span class="h-2 w-2 rounded-full bg-blue-500"></span> Terjadwal
                    </span>
                    <span class="flex items-center gap-1.5">
                        <span class="h-2 w-2 rounded-full bg-emerald-500"></span> Sudah Diupload
                    </span>
                    <span class="flex items-center gap-1.5">
                        <span class="h-2 w-2 rounded-full bg-red-500"></span> Hari Ini
                    </span>
                    <span class="flex items-center gap-1.5">
                        <span class="rounded-full bg-gradient-to-br from-red-500 to-red-600 px-1.5 py-0.5 text-[9px] font-bold text-white">5</span>
                        Banyak konten
                    </span>
                    <span id="calTotalInfo" class="ml-auto"></span>
                </div>

                <!-- Calendar Grid -->
                <div class="flex-1 overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-sm dark:border-ink-700 dark:bg-ink-850">

                    <div class="grid grid-cols-7 border-b border-slate-200 bg-slate-50/80 dark:border-ink-700 dark:bg-ink-800/60">
                        <div class="px-3 py-2.5 text-center text-[10px] font-bold uppercase tracking-wider text-slate-400 dark:text-slate-500">Min</div>
                        <div class="px-3 py-2.5 text-center text-[10px] font-bold uppercase tracking-wider text-slate-400 dark:text-slate-500">Sen</div>
                        <div class="px-3 py-2.5 text-center text-[10px] font-bold uppercase tracking-wider text-slate-400 dark:text-slate-500">Sel</div>
                        <div class="px-3 py-2.5 text-center text-[10px] font-bold uppercase tracking-wider text-slate-400 dark:text-slate-500">Rab</div>
                        <div class="px-3 py-2.5 text-center text-[10px] font-bold uppercase tracking-wider text-slate-400 dark:text-slate-500">Kam</div>
                        <div class="px-3 py-2.5 text-center text-[10px] font-bold uppercase tracking-wider text-slate-400 dark:text-slate-500">Jum</div>
                        <div class="px-3 py-2.5 text-center text-[10px] font-bold uppercase tracking-wider text-slate-400 dark:text-slate-500">Sab</div>
                    </div>

                    <div id="calendarGrid" class="grid grid-cols-7 divide-x divide-y divide-slate-100 dark:divide-ink-700/60"></div>
                </div>

            </div>


            <!-- ============ TAB: REFERENSI ============ -->
            <div id="view-referensi" class="hidden flex-1 flex-col gap-5">

                <div class="flex flex-col justify-between gap-3 sm:flex-row sm:items-center animate-fade-in">
                    <div>
                        <h2 class="text-2xl font-bold tracking-tight text-slate-900 dark:text-white lg:text-3xl">
                            Master Referensi
                        </h2>
                        <p class="mt-1 text-sm text-slate-500 dark:text-slate-400">
                            Kelola kategori untuk mengelompokkan video.
                        </p>
                    </div>

                    <button
                        onclick="openCategoryModal()"
                        class="group flex items-center gap-2 rounded-xl bg-gradient-to-b from-violet-600 to-violet-700 px-4 py-2.5 text-xs font-semibold text-white shadow-lg shadow-violet-500/20 transition-all hover:from-violet-500 hover:to-violet-600 active:scale-[.97]"
                    >
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-3.5 w-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                            <line x1="12" y1="5" x2="12" y2="19"/>
                            <line x1="5" y1="12" x2="19" y2="12"/>
                        </svg>
                        Tambah Kategori
                    </button>
                </div>

                <!-- Kategori Empty -->
                <div id="catEmptyState" class="hidden flex-1 animate-fade-in rounded-2xl border border-dashed border-slate-300 bg-white/50 p-16 text-center backdrop-blur dark:border-ink-700 dark:bg-ink-850/40">
                    <div class="mx-auto mb-4 grid h-16 w-16 place-items-center rounded-2xl bg-slate-100 text-3xl dark:bg-ink-800">📁</div>
                    <h3 class="text-base font-semibold text-slate-900 dark:text-white">Belum ada kategori</h3>
                    <p class="mx-auto mt-2 max-w-md text-sm text-slate-500 dark:text-slate-400">
                        Klik <strong>Tambah Kategori</strong> untuk mulai mengelompokkan video.
                    </p>
                </div>

                <!-- Kategori Table -->
                <div id="catTableContainer" class="hidden flex-1 animate-fade-in overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-sm dark:border-ink-700 dark:bg-ink-850">
                    <div class="h-full overflow-auto">
                        <table class="w-full text-left">
                            <thead class="sticky top-0 z-10 border-b border-slate-200 bg-slate-50/95 backdrop-blur dark:border-ink-700 dark:bg-ink-800/95">
                                <tr>
                                    <th class="w-12 px-4 py-3 text-[10px] font-bold uppercase tracking-wider text-slate-400 dark:text-slate-500">#</th>
                                    <th class="w-14 px-4 py-3 text-[10px] font-bold uppercase tracking-wider text-slate-400 dark:text-slate-500">Warna</th>
                                    <th class="px-4 py-3 text-[10px] font-bold uppercase tracking-wider text-slate-400 dark:text-slate-500">Nama Kategori</th>
                                    <th class="w-36 px-4 py-3 text-[10px] font-bold uppercase tracking-wider text-slate-400 dark:text-slate-500">Jumlah Video</th>
                                    <th class="w-44 px-4 py-3 text-right text-[10px] font-bold uppercase tracking-wider text-slate-400 dark:text-slate-500">Aksi</th>
                                </tr>
                            </thead>
                            <tbody id="catTable" class="divide-y divide-slate-100 dark:divide-ink-700/60"></tbody>
                        </table>
                    </div>
                </div>
            </div>

        </main>

        <footer class="border-t border-slate-200/70 bg-white/40 px-6 py-3 backdrop-blur dark:border-ink-700/60 dark:bg-ink-900/40 lg:px-8">
            <div class="flex items-center justify-between text-[11px] font-medium text-slate-400 dark:text-slate-500">
                <span>Ternak Dolar</span>
                <span class="flex items-center gap-1.5">
                    <span id="footerDot" class="h-1.5 w-1.5 rounded-full bg-slate-400 transition-colors"></span>
                    <span id="footerStatus">Checking...</span>
                </span>
            </div>
        </footer>
    </div>

    <!-- Toast -->
    <div id="toast" class="fixed bottom-6 left-1/2 z-50 hidden -translate-x-1/2 items-center gap-2 rounded-xl bg-slate-900 px-4 py-2.5 text-xs font-semibold text-white shadow-2xl shadow-slate-900/30 dark:bg-white dark:text-ink-900 dark:shadow-white/10">
        Link berhasil disalin
    </div>

    <!-- Schedule Modal -->
    <div id="scheduleModal" class="hidden fixed inset-0 z-[60] items-center justify-center p-4">
        <div class="modal-backdrop absolute inset-0 bg-slate-900/50 backdrop-blur-sm" onclick="closeScheduleModal()"></div>

        <div class="modal-content relative w-full max-w-md overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-2xl dark:border-ink-700 dark:bg-ink-850">
            <div class="flex items-center justify-between border-b border-slate-200 px-5 py-4 dark:border-ink-700">
                <div class="flex items-center gap-3">
                    <div class="grid h-9 w-9 place-items-center rounded-lg bg-gradient-to-br from-blue-500 to-indigo-600 text-white shadow-lg shadow-blue-500/20">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                            <rect x="3" y="4" width="18" height="18" rx="2" ry="2"/>
                            <line x1="16" y1="2" x2="16" y2="6"/>
                            <line x1="8" y1="2" x2="8" y2="6"/>
                            <line x1="3" y1="10" x2="21" y2="10"/>
                        </svg>
                    </div>
                    <div>
                        <h3 class="text-sm font-bold text-slate-900 dark:text-white">Jadwal Upload</h3>
                        <p class="text-[11px] text-slate-500 dark:text-slate-400">Atur kapan video akan di-upload</p>
                    </div>
                </div>

                <button onclick="closeScheduleModal()" class="grid h-8 w-8 place-items-center rounded-lg text-slate-400 transition hover:bg-slate-100 hover:text-slate-600 dark:hover:bg-ink-800 dark:hover:text-slate-200">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                        <line x1="18" y1="6" x2="6" y2="18"/>
                        <line x1="6" y1="6" x2="18" y2="18"/>
                    </svg>
                </button>
            </div>

            <div class="p-5">
                <div class="mb-4 rounded-xl bg-slate-50 p-3 dark:bg-ink-800">
                    <p class="text-[10px] font-bold uppercase tracking-wider text-slate-400 dark:text-slate-500">Video</p>
                    <p id="modalVideoTitle" class="mt-1 line-clamp-2 text-xs font-medium text-slate-800 dark:text-slate-200">-</p>
                    <code id="modalVideoId" class="mt-1 inline-block rounded bg-slate-200 px-1.5 py-0.5 text-[10px] font-mono text-slate-600 dark:bg-ink-700 dark:text-slate-400">-</code>
                </div>

                <div class="mb-4">
                    <label class="mb-2 block text-[11px] font-semibold uppercase tracking-wider text-slate-500 dark:text-slate-400">
                        Tanggal & Jam
                    </label>
                    <input
                        type="datetime-local"
                        id="scheduleInput"
                        class="w-full rounded-xl border border-slate-200 bg-white px-3 py-2.5 text-sm outline-none transition-all focus:border-blue-400 focus:ring-4 focus:ring-blue-500/10 dark:border-ink-700 dark:bg-ink-800 dark:text-slate-200 dark:focus:border-blue-500/60 dark:focus:ring-blue-500/10"
                    >
                </div>

                <div class="mb-4">
                    <label class="mb-2 block text-[11px] font-semibold uppercase tracking-wider text-slate-500 dark:text-slate-400">
                        Cepat
                    </label>
                    <div class="grid grid-cols-3 gap-2">
                        <button onclick="quickSchedule(1)" class="rounded-lg border border-slate-200 bg-white py-1.5 text-[11px] font-semibold text-slate-600 transition hover:border-blue-300 hover:bg-blue-50 hover:text-blue-600 dark:border-ink-700 dark:bg-ink-800 dark:text-slate-300 dark:hover:border-blue-800 dark:hover:bg-blue-950/40 dark:hover:text-blue-400">
                            +1 jam
                        </button>
                        <button onclick="quickSchedule(24)" class="rounded-lg border border-slate-200 bg-white py-1.5 text-[11px] font-semibold text-slate-600 transition hover:border-blue-300 hover:bg-blue-50 hover:text-blue-600 dark:border-ink-700 dark:bg-ink-800 dark:text-slate-300 dark:hover:border-blue-800 dark:hover:bg-blue-950/40 dark:hover:text-blue-400">
                            +1 hari
                        </button>
                        <button onclick="quickSchedule(168)" class="rounded-lg border border-slate-200 bg-white py-1.5 text-[11px] font-semibold text-slate-600 transition hover:border-blue-300 hover:bg-blue-50 hover:text-blue-600 dark:border-ink-700 dark:bg-ink-800 dark:text-slate-300 dark:hover:border-blue-800 dark:hover:bg-blue-950/40 dark:hover:text-blue-400">
                            +1 minggu
                        </button>
                    </div>
                </div>
            </div>

            <div class="flex items-center justify-between gap-2 border-t border-slate-200 px-5 py-4 dark:border-ink-700">
                <button
                    id="deleteScheduleBtn"
                    onclick="deleteSchedule()"
                    class="hidden items-center gap-1.5 rounded-lg border border-red-200 bg-white px-3 py-2 text-xs font-semibold text-red-600 transition hover:bg-red-50 dark:border-red-900/40 dark:bg-ink-850 dark:text-red-400 dark:hover:bg-red-950/40"
                >
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-3.5 w-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round">
                        <polyline points="3 6 5 6 21 6"/>
                        <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/>
                    </svg>
                    Hapus Jadwal
                </button>

                <div class="ml-auto flex items-center gap-2">
                    <button onclick="closeScheduleModal()" class="rounded-lg px-4 py-2 text-xs font-semibold text-slate-600 transition hover:bg-slate-100 dark:text-slate-400 dark:hover:bg-ink-800">
                        Batal
                    </button>
                    <button
                        onclick="saveSchedule()"
                        class="flex items-center gap-1.5 rounded-lg bg-gradient-to-b from-blue-500 to-blue-600 px-4 py-2 text-xs font-semibold text-white shadow-lg shadow-blue-500/20 transition hover:from-blue-600 hover:to-blue-700 active:scale-[.97]"
                    >
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-3.5 w-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                            <polyline points="20 6 9 17 4 12"/>
                        </svg>
                        Simpan
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Day Detail Modal -->
    <div id="dayModal" class="hidden fixed inset-0 z-[60] items-center justify-center p-4">
        <div class="modal-backdrop absolute inset-0 bg-slate-900/50 backdrop-blur-sm" onclick="closeDayModal()"></div>

        <div class="modal-content relative w-full max-w-lg overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-2xl dark:border-ink-700 dark:bg-ink-850">
            <div class="flex items-center justify-between border-b border-slate-200 px-5 py-4 dark:border-ink-700">
                <div class="flex items-center gap-3">
                    <div class="grid h-10 w-10 place-items-center rounded-xl bg-gradient-to-br from-blue-500 to-indigo-600 text-white shadow-lg shadow-blue-500/20">
                        <span id="dayModalDate" class="text-sm font-bold">15</span>
                    </div>
                    <div>
                        <h3 id="dayModalFullDate" class="text-sm font-bold text-slate-900 dark:text-white">Senin, 15 Jan 2026</h3>
                        <p id="dayModalCount" class="text-[11px] text-slate-500 dark:text-slate-400">0 konten terjadwal</p>
                    </div>
                </div>

                <button onclick="closeDayModal()" class="grid h-8 w-8 place-items-center rounded-lg text-slate-400 transition hover:bg-slate-100 hover:text-slate-600 dark:hover:bg-ink-800 dark:hover:text-slate-200">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                        <line x1="18" y1="6" x2="6" y2="18"/>
                        <line x1="6" y1="6" x2="18" y2="18"/>
                    </svg>
                </button>
            </div>

            <div id="dayModalList" class="max-h-[60vh] overflow-y-auto p-5 space-y-2"></div>

            <div class="border-t border-slate-200 px-5 py-3 dark:border-ink-700">
                <button onclick="closeDayModal()" class="w-full rounded-lg border border-slate-200 bg-white py-2 text-xs font-semibold text-slate-600 transition hover:bg-slate-50 dark:border-ink-700 dark:bg-ink-850 dark:text-slate-300 dark:hover:bg-ink-800">
                    Tutup
                </button>
            </div>
        </div>
    </div>




    <!-- Import Modal (dengan pilih kategori) -->
    <div id="importModal" class="hidden fixed inset-0 z-[60] items-center justify-center p-4">
        <div class="modal-backdrop absolute inset-0 bg-slate-900/50 backdrop-blur-sm" onclick="closeImportModal()"></div>

        <div class="modal-content relative w-full max-w-md overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-2xl dark:border-ink-700 dark:bg-ink-850">
            <div class="flex items-center justify-between border-b border-slate-200 px-5 py-4 dark:border-ink-700">
                <div class="flex items-center gap-3">
                    <div class="grid h-9 w-9 place-items-center rounded-lg bg-gradient-to-br from-slate-800 to-slate-900 text-white shadow-lg dark:from-white dark:to-slate-100 dark:text-ink-900">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                            <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
                            <polyline points="17 8 12 3 7 8"/>
                            <line x1="12" y1="3" x2="12" y2="15"/>
                        </svg>
                    </div>
                    <div>
                        <h3 class="text-sm font-bold text-slate-900 dark:text-white">Import Data</h3>
                        <p class="text-[11px] text-slate-500 dark:text-slate-400">Pilih kategori untuk data yang diimport</p>
                    </div>
                </div>

                <button onclick="closeImportModal()" class="grid h-8 w-8 place-items-center rounded-lg text-slate-400 transition hover:bg-slate-100 hover:text-slate-600 dark:hover:bg-ink-800 dark:hover:text-slate-200">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                        <line x1="18" y1="6" x2="6" y2="18"/>
                        <line x1="6" y1="6" x2="18" y2="18"/>
                    </svg>
                </button>
            </div>

            <div class="p-5">
                <div class="mb-4 rounded-xl bg-slate-50 p-3 dark:bg-ink-800">
                    <p class="text-[10px] font-bold uppercase tracking-wider text-slate-400 dark:text-slate-500">File</p>
                    <p id="importFileName" class="mt-1 text-xs font-medium text-slate-800 dark:text-slate-200">-</p>
                    <p id="importFileCount" class="mt-1 text-[11px] text-slate-500 dark:text-slate-400">0 video ditemukan</p>
                </div>

                <div class="mb-4">
                    <label class="mb-2 block text-[11px] font-semibold uppercase tracking-wider text-slate-500 dark:text-slate-400">
                        Kategori
                    </label>
                    <select id="importCategorySelect"
                        class="w-full cursor-pointer appearance-none rounded-xl border border-slate-200 bg-white px-3 py-2.5 text-sm outline-none transition-all focus:border-violet-400 focus:ring-4 focus:ring-violet-500/10 dark:border-ink-700 dark:bg-ink-800 dark:text-slate-200 dark:focus:border-violet-500/60 dark:focus:ring-violet-500/10">
                        <option value="">Tanpa Kategori</option>
                    </select>
                    <button onclick="quickAddCategoryFromImport()" class="mt-2 flex items-center gap-1.5 text-[11px] font-semibold text-violet-600 transition hover:text-violet-700 dark:text-violet-400 dark:hover:text-violet-300">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-3 w-3" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                            <line x1="12" y1="5" x2="12" y2="19"/>
                            <line x1="5" y1="12" x2="19" y2="12"/>
                        </svg>
                        Buat Kategori Baru
                    </button>
                </div>
            </div>

            <div class="flex items-center justify-end gap-2 border-t border-slate-200 px-5 py-4 dark:border-ink-700">
                <button onclick="closeImportModal()" class="rounded-lg px-4 py-2 text-xs font-semibold text-slate-600 transition hover:bg-slate-100 dark:text-slate-400 dark:hover:bg-ink-800">
                    Batal
                </button>
                <button
                    onclick="confirmImport()"
                    class="flex items-center gap-1.5 rounded-lg bg-gradient-to-b from-slate-900 to-slate-800 px-4 py-2 text-xs font-semibold text-white shadow-lg shadow-slate-900/20 transition hover:from-slate-800 hover:to-slate-700 active:scale-[.97] dark:from-white dark:to-slate-100 dark:text-ink-900"
                >
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-3.5 w-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                        <polyline points="20 6 9 17 4 12"/>
                    </svg>
                    Import
                </button>
            </div>
        </div>
    </div>

    <!-- Category Add/Edit Modal -->
    <div id="categoryModal" class="hidden fixed inset-0 z-[60] items-center justify-center p-4">
        <div class="modal-backdrop absolute inset-0 bg-slate-900/50 backdrop-blur-sm" onclick="closeCategoryModal()"></div>

        <div class="modal-content relative w-full max-w-sm overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-2xl dark:border-ink-700 dark:bg-ink-850">
            <div class="flex items-center justify-between border-b border-slate-200 px-5 py-4 dark:border-ink-700">
                <div class="flex items-center gap-3">
                    <div class="grid h-9 w-9 place-items-center rounded-lg bg-gradient-to-br from-violet-500 to-purple-600 text-white shadow-lg shadow-violet-500/20">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                            <path d="M4 20h16a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.93a2 2 0 0 1-1.66-.9l-.82-1.2A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13c0 1.1.9 2 2 2Z"/>
                        </svg>
                    </div>
                    <h3 id="catModalTitle" class="text-sm font-bold text-slate-900 dark:text-white">Tambah Kategori</h3>
                </div>

                <button onclick="closeCategoryModal()" class="grid h-8 w-8 place-items-center rounded-lg text-slate-400 transition hover:bg-slate-100 hover:text-slate-600 dark:hover:bg-ink-800 dark:hover:text-slate-200">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                        <line x1="18" y1="6" x2="6" y2="18"/>
                        <line x1="6" y1="6" x2="18" y2="18"/>
                    </svg>
                </button>
            </div>

            <div class="p-5 space-y-4">
                <div>
                    <label class="mb-2 block text-[11px] font-semibold uppercase tracking-wider text-slate-500 dark:text-slate-400">Nama Kategori</label>
                    <input type="text" id="catNameInput" placeholder="Contoh: Motivasi"
                        class="w-full rounded-xl border border-slate-200 bg-white px-3 py-2.5 text-sm outline-none transition-all placeholder:text-slate-400 focus:border-violet-400 focus:ring-4 focus:ring-violet-500/10 dark:border-ink-700 dark:bg-ink-800 dark:text-slate-200 dark:placeholder:text-slate-500 dark:focus:border-violet-500/60 dark:focus:ring-violet-500/10">
                </div>

                <div>
                    <label class="mb-2 block text-[11px] font-semibold uppercase tracking-wider text-slate-500 dark:text-slate-400">Warna</label>
                    <div class="flex items-center gap-3">
                        <input type="color" id="catColorInput" value="#3b82f6"
                            class="h-10 w-10 cursor-pointer rounded-lg border border-slate-200 bg-white p-0.5 dark:border-ink-700 dark:bg-ink-800">
                        <div class="flex flex-wrap gap-1.5">
                            <button onclick="setCatColor('#3b82f6')" class="h-7 w-7 rounded-lg bg-blue-500 transition hover:scale-110 active:scale-95"></button>
                            <button onclick="setCatColor('#ef4444')" class="h-7 w-7 rounded-lg bg-red-500 transition hover:scale-110 active:scale-95"></button>
                            <button onclick="setCatColor('#10b981')" class="h-7 w-7 rounded-lg bg-emerald-500 transition hover:scale-110 active:scale-95"></button>
                            <button onclick="setCatColor('#f59e0b')" class="h-7 w-7 rounded-lg bg-amber-500 transition hover:scale-110 active:scale-95"></button>
                            <button onclick="setCatColor('#8b5cf6')" class="h-7 w-7 rounded-lg bg-violet-500 transition hover:scale-110 active:scale-95"></button>
                            <button onclick="setCatColor('#ec4899')" class="h-7 w-7 rounded-lg bg-pink-500 transition hover:scale-110 active:scale-95"></button>
                            <button onclick="setCatColor('#06b6d4')" class="h-7 w-7 rounded-lg bg-cyan-500 transition hover:scale-110 active:scale-95"></button>
                            <button onclick="setCatColor('#6366f1')" class="h-7 w-7 rounded-lg bg-indigo-500 transition hover:scale-110 active:scale-95"></button>
                        </div>
                    </div>
                </div>

                <input type="hidden" id="catEditId" value="">
            </div>

            <div class="flex items-center justify-end gap-2 border-t border-slate-200 px-5 py-4 dark:border-ink-700">
                <button onclick="closeCategoryModal()" class="rounded-lg px-4 py-2 text-xs font-semibold text-slate-600 transition hover:bg-slate-100 dark:text-slate-400 dark:hover:bg-ink-800">
                    Batal
                </button>
                <button
                    onclick="saveCategory()"
                    class="flex items-center gap-1.5 rounded-lg bg-gradient-to-b from-violet-500 to-violet-600 px-4 py-2 text-xs font-semibold text-white shadow-lg shadow-violet-500/20 transition hover:from-violet-600 hover:to-violet-700 active:scale-[.97]"
                >
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-3.5 w-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                        <polyline points="20 6 9 17 4 12"/>
                    </svg>
                    Simpan
                </button>
            </div>
        </div>
    </div>


<script>

    const API_BASE = 'api.php';


    /* ============================================================
       API HELPER
    ============================================================ */

    async function apiRequest(action, method = 'GET', body = null) {
        const url = `${API_BASE}?action=${action}`;
        const options = { method };

        if (body !== null) {
            options.headers = { 'Content-Type': 'application/json' };
            options.body = JSON.stringify(body);
        }

        const res = await fetch(url, options);
        const data = await res.json();

        if (!res.ok || !data.success) {
            throw new Error(data.error || `HTTP ${res.status}`);
        }

        return data;
    }


    /* ============================================================
       THEME
    ============================================================ */

    function applyTheme(theme) {
        document.documentElement.classList.toggle('dark', theme === 'dark');
        localStorage.setItem('shorts_theme', theme);
    }

    function toggleTheme() {
        const isDark = document.documentElement.classList.contains('dark');
        applyTheme(isDark ? 'light' : 'dark');
    }

    (function initTheme() {
        applyTheme(localStorage.getItem('shorts_theme') || 'dark');
    })();


    /* ============================================================
       STATE
    ============================================================ */

    let videos = [];
    let categories = [];
    let copiedMap = new Map();
    let modalVideoId = null;
    let currentDate = new Date();
    let currentTab = 'list';
    let pendingImportData = null;
    let currentPage = 1;
    let totalPages = 1;
    let totalVideos = 0;
    let globalStats = { total_all: 0, total_copied: 0, total_scheduled: 0 };
    let randomSeed = Math.floor(Math.random() * 1000000);
    const perPage = 50;


    /* ============================================================
       TAB SWITCHING
    ============================================================ */

    function switchTab(tab) {
        currentTab = tab;

        const tabList = document.getElementById('tab-list');
        const tabCalendar = document.getElementById('tab-calendar');
        const tabReferensi = document.getElementById('tab-referensi');
        const viewList = document.getElementById('view-list');
        const viewCalendar = document.getElementById('view-calendar');
        const viewReferensi = document.getElementById('view-referensi');

        [tabList, tabCalendar, tabReferensi].forEach(t => t.classList.remove('active'));
        [viewList, viewCalendar, viewReferensi].forEach(v => { v.classList.add('hidden'); v.classList.remove('flex'); });

        if (tab === 'list') {
            tabList.classList.add('active');
            viewList.classList.remove('hidden');
            viewList.classList.add('flex');
        } else if (tab === 'calendar') {
            tabCalendar.classList.add('active');
            viewCalendar.classList.remove('hidden');
            viewCalendar.classList.add('flex');
            renderCalendar();
        } else if (tab === 'referensi') {
            tabReferensi.classList.add('active');
            viewReferensi.classList.remove('hidden');
            viewReferensi.classList.add('flex');
            loadCategories().then(() => renderCategories());
        }
    }


    /* ============================================================
       CONNECTION STATUS
    ============================================================ */

    function setConnectionStatus(status, message) {
        const colors = { online: 'bg-emerald-500', offline: 'bg-red-500', connecting: 'bg-amber-500' };
        const dot = colors[status] || 'bg-slate-400';
        const pulse = status === 'connecting' ? 'animate-pulse-soft' : '';

        ['statusDot', 'footerDot'].forEach(id => {
            const el = document.getElementById(id);
            if (!el) return;
            el.className = el.className.replace(/bg-(emerald|red|amber|slate)-\d+/g, '').replace(/animate-pulse-soft/g, '').trim();
            el.classList.add(...dot.split(' '));
            if (pulse) el.classList.add(pulse);
        });

        const dbStatus = document.getElementById('dbStatus');
        const footerStatus = document.getElementById('footerStatus');
        if (footerStatus) footerStatus.textContent = message;

        if (dbStatus) {
            dbStatus.classList.remove('hidden');
            dbStatus.classList.add('flex');
            dbStatus.querySelector('span:last-child').textContent = message;
            const indicator = dbStatus.querySelector('span:first-child');
            indicator.className = `h-1.5 w-1.5 rounded-full ${dot} ${pulse}`;
        }
    }


    /* ============================================================
       SEARCH DEBOUNCE
    ============================================================ */

    let searchTimer = null;
    function debouncedSearch() {
        clearTimeout(searchTimer);
        searchTimer = setTimeout(() => {
            currentPage = 1;
            loadVideos();
        }, 400);
    }

    function shuffleVideos() {
        randomSeed = Math.floor(Math.random() * 1000000);
        currentPage = 1;
        loadVideos();
        showToast('Urutan video diacak ulang');
    }


    /* ============================================================
       LOAD DATA
    ============================================================ */

    async function loadVideos() {

        document.getElementById('loadingState').classList.remove('hidden');
        document.getElementById('tableContainer').classList.add('hidden');
        document.getElementById('emptyState').classList.add('hidden');

        setConnectionStatus('connecting', 'Connecting...');

        try {
            const search = document.getElementById("searchInput").value.trim();
            const filter = document.getElementById("statusFilter").value;
            const catFilter = document.getElementById("categoryFilter").value;

            const params = new URLSearchParams({
                page: currentPage,
                per_page: perPage,
                seed: randomSeed,
            });
            if (search) params.set('search', search);
            if (filter && filter !== 'all') params.set('status', filter);
            if (catFilter && catFilter !== 'all') params.set('category_id', catFilter);

            const result = await apiRequest('list&' + params.toString());

            videos = (result.data || []).map(row => ({
                "Video ID": row.video_id,
                "Title": row.title,
                "Link Shorts": row.link_shorts,
                "is_copied": row.is_copied,
                "copied_at": row.copied_at,
                "schedule_at": row.schedule_at,
                "category_id": row.category_id,
                "category_name": row.category_name,
                "category_color": row.category_color
            }));

            totalVideos = result.total || 0;
            totalPages = result.total_pages || 1;
            currentPage = result.page || 1;
            globalStats = result.stats || { total_all: 0, total_copied: 0, total_scheduled: 0 };

            copiedMap = new Map();
            videos.forEach(v => {
                if (v.is_copied) copiedMap.set(v["Video ID"], true);
            });

            setConnectionStatus('online', 'MySQL Connected');

            // Load categories
            await loadCategories();

            document.getElementById('loadingState').classList.add('hidden');
            renderVideos();
            updateCalendarBadge();

            if (currentTab === 'calendar') {
                renderCalendar();
            }

        } catch (err) {
            console.error('Load failed:', err);
            document.getElementById('loadingState').innerHTML = `
                <div class="flex flex-col items-center gap-3 px-6 text-center">
                    <div class="grid h-14 w-14 place-items-center rounded-2xl bg-red-50 text-red-500 dark:bg-red-950/50 dark:text-red-400">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                            <circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/>
                        </svg>
                    </div>
                    <p class="text-sm font-semibold text-slate-800 dark:text-slate-200">Gagal terhubung ke Database</p>
                    <p class="max-w-md text-xs text-slate-500 dark:text-slate-400">${escapeHTML(err.message)}</p>
                    <p class="max-w-md text-[10px] text-slate-400 dark:text-slate-500">Pastikan MySQL dan tabel videos sudah disiapkan.</p>
                    <button onclick="loadVideos()" class="mt-2 rounded-lg bg-slate-900 px-4 py-2 text-xs font-semibold text-white hover:bg-slate-700 dark:bg-white dark:text-ink-900">
                        Coba Lagi
                    </button>
                </div>
            `;
            document.getElementById('emptyState').classList.remove('hidden');
        }
    }


    /* ============================================================
       IMPORT JSON
    ============================================================ */

    function importJSON(event) {

        const file = event.target.files[0];
        if (!file) return;

        const reader = new FileReader();

        reader.onload = async function(e) {

            try {
                const data = JSON.parse(e.target.result);

                if (!Array.isArray(data)) {
                    alert("Format JSON harus berupa array.");
                    return;
                }

                const seenInFile = new Set();
                const normalized = [];

                data.forEach(item => {
                    const title = item.Title || item.title || "Tanpa Judul";
                    const videoId = item["Video ID"] || item.video_id || item.id || "";
                    const link = item["Link Shorts"] || item.link || item.url || "";

                    if (!videoId) return;
                    if (seenInFile.has(videoId)) return;
                    seenInFile.add(videoId);

                    normalized.push({
                        video_id: videoId,
                        title: title,
                        link_shorts: link || `https://www.youtube.com/shorts/${videoId}`
                    });
                });

                if (normalized.length === 0) {
                    alert("Tidak ada data valid untuk diimport.");
                    return;
                }

                pendingImportData = { normalized, fileName: file.name };
                openImportModal(file.name, normalized.length);

            } catch (error) {
                alert("Gagal parse JSON: " + error.message);
                console.error(error);
            }
        };

        reader.readAsText(file);
        event.target.value = "";
    }


    /* ============================================================
       IMPORT MODAL
    ============================================================ */

    function openImportModal(fileName, count) {
        document.getElementById('importFileName').textContent = fileName;
        document.getElementById('importFileCount').textContent = `${count} video ditemukan`;

        const select = document.getElementById('importCategorySelect');
        select.innerHTML = '<option value="">Tanpa Kategori</option>';
        categories.forEach(cat => {
            select.innerHTML += `<option value="${cat.id}">${escapeHTML(cat.name)}</option>`;
        });

        const modal = document.getElementById('importModal');
        modal.classList.remove('hidden');
        modal.classList.add('flex');
    }

    function closeImportModal() {
        const modal = document.getElementById('importModal');
        modal.classList.add('hidden');
        modal.classList.remove('flex');
    }

    async function quickAddCategoryFromImport() {
        const name = prompt('Nama kategori baru:');
        if (!name || !name.trim()) return;

        try {
            const result = await apiRequest('category_add', 'POST', { name: name.trim(), color: '#3b82f6' });
            await loadCategories();
            showToast('Kategori "' + name.trim() + '" ditambahkan');

            // Refresh dropdown dan auto-select kategori baru
            const select = document.getElementById('importCategorySelect');
            select.innerHTML = '<option value="">Tanpa Kategori</option>';
            categories.forEach(cat => {
                select.innerHTML += `<option value="${cat.id}">${escapeHTML(cat.name)}</option>`;
            });
            select.value = result.id;
        } catch (err) {
            alert('Gagal: ' + err.message);
        }
    }

    async function confirmImport() {
        if (!pendingImportData) return;

        const { normalized } = pendingImportData;
        const categoryId = document.getElementById('importCategorySelect').value || null;

        closeImportModal();
        setConnectionStatus('connecting', 'Importing...');
        showToast(`Mengirim ${normalized.length} data...`);

        try {
            const existingIds = new Set(videos.map(v => v["Video ID"]));
            const duplicateInDb = normalized.filter(v => existingIds.has(v.video_id)).length;
            const toInsert = normalized.filter(v => !existingIds.has(v.video_id));

            let inserted = 0;

            if (toInsert.length > 0) {
                const body = { items: toInsert };
                if (categoryId) body.category_id = categoryId;
                const result = await apiRequest('import', 'POST', body);
                inserted = result.inserted || 0;
            }

            showToast(`\u2713 ${inserted} video ditambahkan`);

            setTimeout(() => {
                alert(
                    `Import selesai!\n\n` +
                    `Video baru   : ${inserted}\n` +
                    `Duplikat     : ${duplicateInDb}\n` +
                    `Total di DB  : ${videos.length + inserted}`
                );
            }, 300);

            await loadVideos();

        } catch (error) {
            alert("Gagal import: " + error.message);
            console.error(error);
            setConnectionStatus('online', 'MySQL Connected');
        }

        pendingImportData = null;
    }


    /* ============================================================
       RENDER LIST VIEW
    ============================================================ */

    function renderVideos() {

        const table = document.getElementById("videoTable");

        table.innerHTML = "";

        if (videos.length === 0) {
            document.getElementById("emptyState").classList.remove("hidden");
            document.getElementById("tableContainer").classList.add("hidden");
        } else {
            document.getElementById("emptyState").classList.add("hidden");
            document.getElementById("tableContainer").classList.remove("hidden");
        }

        const startIndex = (currentPage - 1) * perPage;

        videos.forEach((video, index) => {

            const id = video["Video ID"];
            const isCopied = copiedMap.has(id);

            let statusCellHTML = '';
            if (isCopied) {
                const t = formatCopiedAt(video.copied_at);
                statusCellHTML = `
                    <div class="flex flex-col gap-1">
                        <span class="inline-flex w-fit items-center gap-1.5 rounded-full bg-emerald-50 px-2.5 py-1 text-[11px] font-semibold text-emerald-700 dark:bg-emerald-950/50 dark:text-emerald-400">
                            <span class="h-1.5 w-1.5 rounded-full bg-emerald-500"></span>
                            Sudah Disalin
                        </span>
                        ${t ? `
                        <div class="flex items-center gap-1 text-[10px] font-medium text-slate-500 dark:text-slate-400" title="${escapeHTML(t.full)}">
                            <svg xmlns="http://www.w3.org/2000/svg" class="h-2.5 w-2.5 shrink-0" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                                <circle cx="12" cy="12" r="10"/>
                                <polyline points="12 6 12 12 16 14"/>
                            </svg>
                            <span class="truncate">${escapeHTML(t.time)} · ${escapeHTML(t.relative)}</span>
                        </div>
                        ` : ''}
                    </div>
                `;
            } else {
                statusCellHTML = `
                    <span class="inline-flex items-center gap-1.5 rounded-full bg-orange-50 px-2.5 py-1 text-[11px] font-semibold text-orange-700 dark:bg-orange-950/50 dark:text-orange-400">
                        <span class="h-1.5 w-1.5 rounded-full bg-orange-500"></span>
                        Belum Disalin
                    </span>
                `;
            }

            const scheduleCellHTML = renderScheduleCell(video);

            const row = document.createElement("tr");
            row.className = "group transition-colors hover:bg-slate-50/80 dark:hover:bg-ink-800/60";

            row.innerHTML = `
                <td class="px-4 py-3 text-xs font-medium text-slate-400 dark:text-slate-500 align-top">${startIndex + index + 1}</td>
                <td class="max-w-md px-4 py-3 align-top">
                    <div class="flex items-start gap-2">
                        <div class="flex-1 truncate text-sm font-medium text-slate-800 dark:text-slate-200">${escapeHTML(video.Title)}</div>
                        <button onclick="copyTitle('${escapeJS(video.Title)}')"
                            class="mt-0.5 shrink-0 grid h-6 w-6 place-items-center rounded-md border border-slate-200 bg-white text-slate-400 transition hover:border-violet-300 hover:bg-violet-50 hover:text-violet-600 dark:border-ink-700 dark:bg-ink-850 dark:text-slate-500 dark:hover:border-violet-800 dark:hover:bg-violet-950/40 dark:hover:text-violet-400"
                            title="Salin Title">
                            <svg xmlns="http://www.w3.org/2000/svg" class="h-3 w-3" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
                        </button>
                    </div>
                </td>
                <td class="px-4 py-3 align-top">
                    <code class="rounded-md bg-slate-100 px-2 py-1 text-[11px] font-mono text-slate-600 dark:bg-ink-800 dark:text-slate-400">${escapeHTML(id)}</code>
                </td>
                <td class="px-4 py-3 align-top">
                    ${video.category_name
                        ? `<span class="inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 text-[11px] font-semibold text-white" style="background:${video.category_color || '#3b82f6'}">
                            <span class="h-1.5 w-1.5 rounded-full bg-white/40"></span>
                            ${escapeHTML(video.category_name)}
                           </span>`
                        : `<span class="text-[11px] text-slate-400 dark:text-slate-500">—</span>`
                    }
                </td>
                <td class="px-4 py-3 align-top">
                    ${statusCellHTML}
                </td>
                <td class="px-4 py-3 align-top">
                    ${scheduleCellHTML}
                </td>
                <td class="px-4 py-3 text-right align-top">
                    <div class="flex flex-col items-end gap-1.5">
                        <button onclick="copyLink('${escapeJS(video["Link Shorts"])}', '${escapeJS(id)}')"
                            class="btn-copy inline-flex items-center gap-1.5 ${
                                isCopied
                                    ? "bg-emerald-50 text-emerald-700 hover:bg-emerald-100 dark:bg-emerald-950/50 dark:text-emerald-400 dark:hover:bg-emerald-950/80"
                                    : "bg-slate-900 text-white hover:bg-slate-700 dark:bg-white dark:text-ink-900 dark:hover:bg-slate-200"
                            } rounded-lg px-3 py-1.5 text-[11px] font-semibold">
                            ${isCopied
                                ? `<svg xmlns="http://www.w3.org/2000/svg" class="h-3 w-3" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>Disalin`
                                : `<svg xmlns="http://www.w3.org/2000/svg" class="h-3 w-3" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>Copy Link`
                            }
                        </button>
                    </div>
                </td>
            `;

            table.appendChild(row);
        });

        renderPagination();
        updateStatistics();
    }


    /* ============================================================
       PAGINATION
    ============================================================ */

    function renderPagination() {
        const container = document.getElementById('paginationContainer');
        const buttons = document.getElementById('pagButtons');

        if (totalPages <= 1 && totalVideos <= perPage) {
            container.classList.add('hidden');
            return;
        }

        container.classList.remove('hidden');

        const start = (currentPage - 1) * perPage + 1;
        const end = Math.min(currentPage * perPage, totalVideos);
        document.getElementById('pagStart').textContent = start;
        document.getElementById('pagEnd').textContent = end;
        document.getElementById('pagTotal').textContent = totalVideos;

        buttons.innerHTML = '';

        // Prev button
        const prevBtn = document.createElement('button');
        prevBtn.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" class="h-3.5 w-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 18 9 12 15 6"/></svg>`;
        prevBtn.className = `grid h-8 w-8 place-items-center rounded-lg border transition ${
            currentPage <= 1
                ? 'border-slate-100 bg-slate-50 text-slate-300 cursor-not-allowed dark:border-ink-700/50 dark:bg-ink-850 dark:text-ink-600'
                : 'border-slate-200 bg-white text-slate-600 hover:bg-slate-50 dark:border-ink-700 dark:bg-ink-850 dark:text-slate-300 dark:hover:bg-ink-800'
        }`;
        if (currentPage > 1) prevBtn.onclick = () => goToPage(currentPage - 1);
        buttons.appendChild(prevBtn);

        // Page numbers
        const pages = getPageNumbers(currentPage, totalPages);
        pages.forEach(p => {
            if (p === '...') {
                const dots = document.createElement('span');
                dots.textContent = '...';
                dots.className = 'px-1 text-xs text-slate-400 dark:text-slate-500';
                buttons.appendChild(dots);
            } else {
                const btn = document.createElement('button');
                btn.textContent = p;
                btn.className = `grid h-8 min-w-[2rem] place-items-center rounded-lg border text-xs font-semibold transition ${
                    p === currentPage
                        ? 'border-violet-300 bg-violet-600 text-white shadow-sm dark:border-violet-700 dark:bg-violet-600'
                        : 'border-slate-200 bg-white text-slate-600 hover:bg-slate-50 dark:border-ink-700 dark:bg-ink-850 dark:text-slate-300 dark:hover:bg-ink-800'
                }`;
                if (p !== currentPage) btn.onclick = () => goToPage(p);
                buttons.appendChild(btn);
            }
        });

        // Next button
        const nextBtn = document.createElement('button');
        nextBtn.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" class="h-3.5 w-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 18 15 12 9 6"/></svg>`;
        nextBtn.className = `grid h-8 w-8 place-items-center rounded-lg border transition ${
            currentPage >= totalPages
                ? 'border-slate-100 bg-slate-50 text-slate-300 cursor-not-allowed dark:border-ink-700/50 dark:bg-ink-850 dark:text-ink-600'
                : 'border-slate-200 bg-white text-slate-600 hover:bg-slate-50 dark:border-ink-700 dark:bg-ink-850 dark:text-slate-300 dark:hover:bg-ink-800'
        }`;
        if (currentPage < totalPages) nextBtn.onclick = () => goToPage(currentPage + 1);
        buttons.appendChild(nextBtn);
    }

    function getPageNumbers(current, total) {
        if (total <= 7) return Array.from({ length: total }, (_, i) => i + 1);

        const pages = [];
        pages.push(1);
        if (current > 3) pages.push('...');
        for (let i = Math.max(2, current - 1); i <= Math.min(total - 1, current + 1); i++) {
            pages.push(i);
        }
        if (current < total - 2) pages.push('...');
        pages.push(total);
        return pages;
    }

    function goToPage(page) {
        currentPage = page;
        loadVideos();
        // Scroll ke atas tabel
        document.getElementById('tableContainer').scrollIntoView({ behavior: 'smooth', block: 'start' });
    }


    function renderScheduleCell(video) {
        const id = video["Video ID"] || video.video_id || "";
        const isCopied = video.is_copied;

        if (!video.schedule_at) {
            return `
                <div class="flex items-center gap-2">
                    <span class="inline-flex items-center gap-1.5 text-[11px] font-medium text-slate-400 dark:text-slate-500">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-3 w-3" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                            <line x1="5" y1="12" x2="19" y2="12"/>
                        </svg>
                        Belum dijadwalkan
                    </span>
                    ${isCopied ? `<button onclick="openScheduleModal('${escapeJS(id)}')"
                        class="shrink-0 inline-flex items-center gap-1 rounded-md border border-blue-200 bg-white px-2 py-1 text-[10px] font-semibold text-blue-600 transition hover:border-blue-300 hover:bg-blue-50 dark:border-blue-900/40 dark:bg-ink-850 dark:text-blue-400 dark:hover:border-blue-800/60 dark:hover:bg-blue-950/40">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-2.5 w-2.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                            <line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/>
                        </svg>Set
                    </button>` : ''}
                </div>
            `;
        }

        const s = formatScheduleAt(video.schedule_at);
        if (!s) return '<span class="text-xs text-slate-400">-</span>';

        let badgeClass, dotClass, label;
        if (s.isPast) {
            badgeClass = "bg-slate-100 text-slate-600 dark:bg-ink-800 dark:text-slate-400";
            dotClass = "bg-slate-400";
            label = "Sudah lewat";
        } else if (s.isToday) {
            badgeClass = "bg-red-50 text-red-700 dark:bg-red-950/50 dark:text-red-400";
            dotClass = "bg-red-500 animate-pulse-soft";
            label = "Hari ini";
        } else if (s.daysUntil <= 3) {
            badgeClass = "bg-amber-50 text-amber-700 dark:bg-amber-950/50 dark:text-amber-400";
            dotClass = "bg-amber-500";
            label = `${s.relative}`;
        } else {
            badgeClass = "bg-blue-50 text-blue-700 dark:bg-blue-950/50 dark:text-blue-400";
            dotClass = "bg-blue-500";
            label = s.relative;
        }

        return `
            <div class="flex flex-col gap-1">
                <div class="flex items-center gap-2">
                    <span class="inline-flex w-fit items-center gap-1.5 rounded-full ${badgeClass} px-2.5 py-1 text-[11px] font-semibold">
                        <span class="h-1.5 w-1.5 rounded-full ${dotClass}"></span>
                        ${escapeHTML(label)}
                    </span>
                    <button onclick="openScheduleModal('${escapeJS(id)}')"
                        class="shrink-0 grid h-5 w-5 place-items-center rounded-md border border-slate-200 bg-white text-slate-400 transition hover:border-blue-300 hover:bg-blue-50 hover:text-blue-600 dark:border-ink-700 dark:bg-ink-850 dark:text-slate-500 dark:hover:border-blue-800 dark:hover:bg-blue-950/40 dark:hover:text-blue-400"
                        title="Edit Jadwal">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-2.5 w-2.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                            <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/>
                            <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/>
                        </svg>
                    </button>
                </div>
                <div class="flex items-center gap-1 text-[10px] font-medium text-slate-500 dark:text-slate-400" title="${escapeHTML(s.full)}">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-2.5 w-2.5 shrink-0" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                        <circle cx="12" cy="12" r="10"/>
                        <polyline points="12 6 12 12 16 14"/>
                    </svg>
                    <span class="truncate">${escapeHTML(s.time)}</span>
                </div>
                <div class="pl-3.5 text-[10px] font-medium text-slate-400 dark:text-slate-500">
                    ${escapeHTML(s.date)}
                </div>
            </div>
        `;
    }


    /* ============================================================
       RENDER CALENDAR VIEW (DENGAN BADGE JUMLAH YANG JELAS)
    ============================================================ */

    function updateCalendarBadge() {
        const totalScheduled = videos.filter(v => v.schedule_at).length;
        const badge = document.getElementById('calBadge');
        if (totalScheduled > 0) {
            badge.textContent = totalScheduled;
            badge.classList.remove('hidden');
        } else {
            badge.classList.add('hidden');
        }
    }

    function changeMonth(delta) {
        currentDate.setMonth(currentDate.getMonth() + delta);
        renderCalendar();
    }

    function goToToday() {
        currentDate = new Date();
        renderCalendar();
    }

    function renderCalendar() {

        const year = currentDate.getFullYear();
        const month = currentDate.getMonth();

        const monthNames = ['Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni',
                            'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'];
        document.getElementById('calMonthLabel').textContent = `${monthNames[month]} ${year}`;

        const firstDay = new Date(year, month, 1);
        const lastDay = new Date(year, month + 1, 0);
        const daysInMonth = lastDay.getDate();
        const startingDayOfWeek = firstDay.getDay();

        const prevLastDay = new Date(year, month, 0).getDate();

        // Group videos by date
        const videosByDate = {};
        videos.forEach(v => {
            if (!v.schedule_at) return;
            const d = new Date(v.schedule_at);
            if (isNaN(d.getTime())) return;
            const key = `${d.getFullYear()}-${d.getMonth()}-${d.getDate()}`;
            if (!videosByDate[key]) videosByDate[key] = [];
            videosByDate[key].push(v);
        });

        // Total scheduled bulan ini
        let monthTotal = 0;
        let busiestDay = { day: 0, count: 0 };
        for (let day = 1; day <= daysInMonth; day++) {
            const key = `${year}-${month}-${day}`;
            const count = (videosByDate[key] || []).length;
            monthTotal += count;
            if (count > busiestDay.count) {
                busiestDay = { day, count };
            }
        }

        document.getElementById('calTotalInfo').innerHTML =
            monthTotal > 0
                ? `<span class="font-semibold text-slate-700 dark:text-slate-300">${monthTotal} konten</span> di bulan ini · <span class="font-semibold text-slate-700 dark:text-slate-300">${busiestDay.count}</span> di tanggal ${busiestDay.day}`
                : 'Belum ada konten di bulan ini';

        const today = new Date();
        const todayKey = `${today.getFullYear()}-${today.getMonth()}-${today.getDate()}`;

        const grid = document.getElementById('calendarGrid');
        grid.innerHTML = '';

        const totalCells = 42;

        for (let i = 0; i < totalCells; i++) {

            let cellDay, cellMonth, cellYear, isOtherMonth = false;

            if (i < startingDayOfWeek) {
                cellDay = prevLastDay - startingDayOfWeek + i + 1;
                cellMonth = month - 1;
                cellYear = year;
                if (cellMonth < 0) { cellMonth = 11; cellYear = year - 1; }
                isOtherMonth = true;
            } else if (i < startingDayOfWeek + daysInMonth) {
                cellDay = i - startingDayOfWeek + 1;
                cellMonth = month;
                cellYear = year;
            } else {
                cellDay = i - startingDayOfWeek - daysInMonth + 1;
                cellMonth = month + 1;
                cellYear = year;
                if (cellMonth > 11) { cellMonth = 0; cellYear = year + 1; }
                isOtherMonth = true;
            }

            const key = `${cellYear}-${cellMonth}-${cellDay}`;
            const events = videosByDate[key] || [];
            const isToday = key === todayKey && !isOtherMonth;
            const eventCount = events.length;
            const hasEvents = eventCount > 0;

            const cell = document.createElement('div');
            cell.className = `cal-day relative p-2 ${isOtherMonth ? 'other-month' : ''} ${isToday ? 'today' : ''}`;

            // Nomor tanggal
            let dayNumberClass = "text-xs font-semibold text-slate-600 dark:text-slate-300";
            if (isToday) {
                dayNumberClass = "inline-flex h-6 w-6 items-center justify-center rounded-full bg-blue-500 text-xs font-bold text-white shadow-lg shadow-blue-500/30";
            }

            // =============================================
            // BADGE JUMLAH KONTEN (BARU - LEBIH JELAS)
            // =============================================
            let countBadgeHTML = '';
            if (hasEvents && !isOtherMonth) {
                let badgeClass = 'low';
                if (eventCount >= 5) badgeClass = 'high';
                else if (eventCount >= 3) badgeClass = 'medium';

                countBadgeHTML = `
                    <span class="cal-count-badge ${badgeClass}">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-2.5 w-2.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round">
                            <polygon points="23 7 16 12 23 17 23 7"/>
                            <rect x="1" y="5" width="15" height="14" rx="2" ry="2"/>
                        </svg>
                        ${eventCount}
                    </span>
                `;
            }

            // Events HTML (list kecil)
            let eventsHTML = '';
            const maxVisible = 2;
            events.slice(0, maxVisible).forEach(v => {
                const t = new Date(v.schedule_at);
                const pad = n => String(n).padStart(2, '0');
                const timeStr = `${pad(t.getHours())}:${pad(t.getMinutes())}`;
                const isPast = t.getTime() < Date.now();

                const colorClass = isPast
                    ? "bg-emerald-50 text-emerald-700 border-emerald-200 dark:bg-emerald-950/40 dark:text-emerald-400 dark:border-emerald-900/50"
                    : "bg-blue-50 text-blue-700 border-blue-200 dark:bg-blue-950/40 dark:text-blue-400 dark:border-blue-900/50";

                eventsHTML += `
                    <div
                        onclick="event.stopPropagation(); showDayDetail(${cellYear}, ${cellMonth}, ${cellDay});"
                        class="cal-event mt-1 truncate rounded border ${colorClass} px-1.5 py-0.5 text-[9px] font-semibold"
                        title="${escapeHTML(v.Title || 'Tanpa Judul')}"
                    >
                        ${escapeHTML(timeStr)} ${escapeHTML((v.Title || 'Tanpa Judul').slice(0, 18))}${(v.Title || '').length > 18 ? '...' : ''}
                    </div>
                `;
            });

            if (eventCount > maxVisible) {
                eventsHTML += `
                    <button
                        onclick="event.stopPropagation(); showDayDetail(${cellYear}, ${cellMonth}, ${cellDay});"
                        class="mt-1 w-full rounded border border-dashed border-slate-300 bg-white/50 py-0.5 text-center text-[9px] font-bold text-slate-500 transition hover:border-blue-400 hover:bg-blue-50 hover:text-blue-600 dark:border-ink-600 dark:bg-ink-800/50 dark:text-slate-400 dark:hover:border-blue-800 dark:hover:bg-blue-950/40 dark:hover:text-blue-400"
                    >
                        +${eventCount - maxVisible} lagi
                    </button>
                `;
            }

            // =============================================
            // CELL CONTENT
            // =============================================
            cell.innerHTML = `
                <div class="flex items-start justify-between gap-1">
                    <div class="${dayNumberClass}">${cellDay}</div>
                    ${countBadgeHTML}
                </div>
                <div class="mt-1">
                    ${eventsHTML}
                </div>
            `;

            if (hasEvents && !isOtherMonth) {
                cell.classList.add('cursor-pointer');
                cell.onclick = () => showDayDetail(cellYear, cellMonth, cellDay);
            }

            grid.appendChild(cell);
        }
    }


    /* ============================================================
       DAY DETAIL MODAL
    ============================================================ */

    function showDayDetail(year, month, day) {

        const dayNames = ['Minggu', 'Senin', 'Selasa', 'Rabu', 'Kamis', 'Jumat', 'Sabtu'];
        const monthNames = ['Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni',
                            'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'];

        const date = new Date(year, month, day);

        const dayEvents = videos.filter(v => {
            if (!v.schedule_at) return false;
            const d = new Date(v.schedule_at);
            return d.getFullYear() === year && d.getMonth() === month && d.getDate() === day;
        }).sort((a, b) => new Date(a.schedule_at) - new Date(b.schedule_at));

        document.getElementById('dayModalDate').textContent = day;
        document.getElementById('dayModalFullDate').textContent =
            `${dayNames[date.getDay()]}, ${day} ${monthNames[month]} ${year}`;
        document.getElementById('dayModalCount').textContent =
            `${dayEvents.length} konten terjadwal`;

        const list = document.getElementById('dayModalList');
        list.innerHTML = '';

        if (dayEvents.length === 0) {
            list.innerHTML = `
                <div class="py-8 text-center">
                    <div class="mx-auto mb-2 grid h-12 w-12 place-items-center rounded-2xl bg-slate-100 text-2xl dark:bg-ink-800">📭</div>
                    <p class="text-xs text-slate-500 dark:text-slate-400">Tidak ada konten di tanggal ini.</p>
                </div>
            `;
        } else {
            dayEvents.forEach(v => {
                const t = new Date(v.schedule_at);
                const pad = n => String(n).padStart(2, '0');
                const timeStr = `${pad(t.getHours())}:${pad(t.getMinutes())}`;
                const isPast = t.getTime() < Date.now();
                const isCopied = copiedMap.has(v["Video ID"]);

                const item = document.createElement('div');
                item.className = "rounded-xl border border-slate-200 bg-white p-3 transition hover:border-blue-300 dark:border-ink-700 dark:bg-ink-800 dark:hover:border-blue-800";
                item.innerHTML = `
                    <div class="flex items-start gap-3">
                        <div class="grid h-10 w-10 shrink-0 place-items-center rounded-lg ${
                            isPast
                                ? 'bg-emerald-50 text-emerald-600 dark:bg-emerald-950/50 dark:text-emerald-400'
                                : 'bg-blue-50 text-blue-600 dark:bg-blue-950/50 dark:text-blue-400'
                        }">
                            <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                                <circle cx="12" cy="12" r="10"/>
                                <polyline points="12 6 12 12 16 14"/>
                            </svg>
                        </div>

                        <div class="min-w-0 flex-1">
                            <div class="flex items-center gap-2">
                                <span class="text-xs font-bold ${
                                    isPast ? 'text-emerald-600 dark:text-emerald-400' : 'text-blue-600 dark:text-blue-400'
                                }">${timeStr}</span>
                                ${isPast
                                    ? '<span class="rounded-full bg-emerald-100 px-1.5 py-0.5 text-[9px] font-bold text-emerald-700 dark:bg-emerald-950/50 dark:text-emerald-400">DONE</span>'
                                    : '<span class="rounded-full bg-blue-100 px-1.5 py-0.5 text-[9px] font-bold text-blue-700 dark:bg-blue-950/50 dark:text-blue-400">UPCOMING</span>'
                                }
                            </div>
                            <p class="mt-1 line-clamp-2 text-xs font-medium text-slate-800 dark:text-slate-200">
                                ${escapeHTML(v.Title || 'Tanpa Judul')}
                            </p>
                            <div class="mt-1 flex items-center gap-2">
                                <code class="rounded bg-slate-100 px-1.5 py-0.5 text-[10px] font-mono text-slate-600 dark:bg-ink-700 dark:text-slate-400">
                                    ${escapeHTML(v["Video ID"])}
                                </code>
                                ${isCopied
                                    ? '<span class="text-[10px] font-semibold text-emerald-600 dark:text-emerald-400">✓ Disalin</span>'
                                    : ''
                                }
                            </div>
                        </div>

                        <div class="flex flex-col gap-1">
                            <button
                                onclick="openScheduleModal('${escapeJS(v["Video ID"])}'); closeDayModal();"
                                class="grid h-7 w-7 place-items-center rounded-lg border border-slate-200 bg-white text-slate-500 transition hover:border-blue-300 hover:bg-blue-50 hover:text-blue-600 dark:border-ink-700 dark:bg-ink-850 dark:text-slate-400 dark:hover:border-blue-800 dark:hover:bg-blue-950/40 dark:hover:text-blue-400"
                                title="Edit jadwal"
                            >
                                <svg xmlns="http://www.w3.org/2000/svg" class="h-3 w-3" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                                    <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/>
                                    <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/>
                                </svg>
                            </button>
                            <button
                                onclick="copyLink('${escapeJS(v["Link Shorts"])}', '${escapeJS(v["Video ID"])}')"
                                class="grid h-7 w-7 place-items-center rounded-lg border border-slate-200 bg-white text-slate-500 transition hover:border-emerald-300 hover:bg-emerald-50 hover:text-emerald-600 dark:border-ink-700 dark:bg-ink-850 dark:text-slate-400 dark:hover:border-emerald-800 dark:hover:bg-emerald-950/40 dark:hover:text-emerald-400"
                                title="Copy link"
                            >
                                <svg xmlns="http://www.w3.org/2000/svg" class="h-3 w-3" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round">
                                    <rect x="9" y="9" width="13" height="13" rx="2" ry="2"/>
                                    <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>
                                </svg>
                            </button>
                        </div>
                    </div>
                `;
                list.appendChild(item);
            });
        }

        document.getElementById('dayModal').classList.remove('hidden');
        document.getElementById('dayModal').classList.add('flex');
    }

    function closeDayModal() {
        document.getElementById('dayModal').classList.add('hidden');
        document.getElementById('dayModal').classList.remove('flex');
    }


    /* ============================================================
       COPY TITLE
    ============================================================ */

    async function copyTitle(title) {
        try {
            await navigator.clipboard.writeText(title);
        } catch (error) {
            const textarea = document.createElement("textarea");
            textarea.value = title;
            document.body.appendChild(textarea);
            textarea.select();
            document.execCommand("copy");
            textarea.remove();
        }
        showToast('Title disalin ke clipboard');
    }


    /* ============================================================
       COPY LINK
    ============================================================ */

    async function copyLink(link, id) {

        try {
            await navigator.clipboard.writeText(link);
        } catch (error) {
            const textarea = document.createElement("textarea");
            textarea.value = link;
            document.body.appendChild(textarea);
            textarea.select();
            document.execCommand("copy");
            textarea.remove();
        }

        if (!copiedMap.has(id)) {
            copiedMap.set(id, true);

            const v = videos.find(x => x["Video ID"] === id);
            if (v) {
                v.is_copied = true;
                v.copied_at = new Date().toISOString();
            }

            renderVideos();
        }

        showToast("✓ Link berhasil disalin");

        try {
            await apiRequest('copy', 'PATCH', { video_id: id });
        } catch (err) {
            console.error('Gagal update ke MySQL:', err);
            showToast("âš  Gagal simpan ke database");
            copiedMap.delete(id);
            const v = videos.find(x => x["Video ID"] === id);
            if (v) {
                v.is_copied = false;
                v.copied_at = null;
            }
            renderVideos();
        }
    }


    /* ============================================================
       SCHEDULE MODAL
    ============================================================ */

    function openScheduleModal(videoId) {
        const video = videos.find(v => v["Video ID"] === videoId);
        if (!video) return;

        modalVideoId = videoId;

        document.getElementById('modalVideoTitle').textContent = video.Title || 'Tanpa Judul';
        document.getElementById('modalVideoId').textContent = videoId;

        const input = document.getElementById('scheduleInput');
        const deleteBtn = document.getElementById('deleteScheduleBtn');

        if (video.schedule_at) {
            const d = new Date(video.schedule_at);
            input.value = toDatetimeLocalValue(d);
            deleteBtn.classList.remove('hidden');
            deleteBtn.classList.add('flex');
        } else {
            const d = new Date(Date.now() + 60 * 60 * 1000);
            input.value = toDatetimeLocalValue(d);
            deleteBtn.classList.add('hidden');
            deleteBtn.classList.remove('flex');
        }

        const modal = document.getElementById('scheduleModal');
        modal.classList.remove('hidden');
        modal.classList.add('flex');
    }

    function closeScheduleModal() {
        const modal = document.getElementById('scheduleModal');
        modal.classList.add('hidden');
        modal.classList.remove('flex');
        modalVideoId = null;
    }

    function quickSchedule(hoursFromNow) {
        const d = new Date(Date.now() + hoursFromNow * 60 * 60 * 1000);
        document.getElementById('scheduleInput').value = toDatetimeLocalValue(d);
    }

    function toDatetimeLocalValue(date) {
        const pad = n => String(n).padStart(2, '0');
        const yyyy = date.getFullYear();
        const mm = pad(date.getMonth() + 1);
        const dd = pad(date.getDate());
        const hh = pad(date.getHours());
        const mi = pad(date.getMinutes());
        return `${yyyy}-${mm}-${dd}T${hh}:${mi}`;
    }

    async function saveSchedule() {
        if (!modalVideoId) return;

        const input = document.getElementById('scheduleInput');
        const localValue = input.value;

        if (!localValue) {
            alert('Pilih tanggal & jam dulu.');
            return;
        }

        const date = new Date(localValue);
        if (isNaN(date.getTime())) {
            alert('Format tanggal tidak valid.');
            return;
        }

        const isoString = date.toISOString();
        const videoId = modalVideoId;

        const video = videos.find(v => v["Video ID"] === videoId);
        if (video) video.schedule_at = isoString;

        closeScheduleModal();
        renderVideos();
        updateCalendarBadge();
        if (currentTab === 'calendar') renderCalendar();
        showToast("✓ Jadwal disimpan");

        try {
            await apiRequest('schedule', 'PATCH', { video_id: videoId, schedule_at: isoString });
        } catch (err) {
            console.error('Gagal simpan jadwal:', err);
            showToast("âš  Gagal simpan jadwal");
            if (video) video.schedule_at = null;
            renderVideos();
        }
    }

    async function deleteSchedule() {
        if (!modalVideoId) return;
        if (!confirm('Hapus jadwal untuk video ini?')) return;

        const videoId = modalVideoId;
        const video = videos.find(v => v["Video ID"] === videoId);
        if (video) video.schedule_at = null;

        closeScheduleModal();
        renderVideos();
        updateCalendarBadge();
        if (currentTab === 'calendar') renderCalendar();
        showToast("Jadwal dihapus");

        try {
            await apiRequest('delete_schedule', 'PATCH', { video_id: videoId });
        } catch (err) {
            console.error('Gagal hapus jadwal:', err);
            showToast("âš  Gagal hapus jadwal");
            if (video) video.schedule_at = null;
            renderVideos();
        }
    }


    /* ============================================================
       STATISTICS
    ============================================================ */

    function updateStatistics() {

        const total = globalStats.total_all;
        const copied = globalStats.total_copied;
        const remaining = total - copied;
        const percentage = total > 0 ? Math.round((copied / total) * 100) : 0;
        const scheduled = globalStats.total_scheduled;

        document.getElementById("totalCount").textContent = total;
        document.getElementById("copiedCount").textContent = copied;
        document.getElementById("remainingCount").textContent = remaining;
        document.getElementById("progressText").textContent = `${percentage}%`;
        document.getElementById("progressBar").style.width = `${percentage}%`;

        const detail = document.getElementById("progressDetail");
        if (detail) detail.textContent = `${copied} dari ${total}`;

        const scheduledEl = document.getElementById("scheduledCount");
        if (scheduledEl) scheduledEl.textContent = `${scheduled} terjadwal`;
    }


    /* ============================================================
       RESET STATUS
    ============================================================ */

    async function resetCopiedStatus() {

        if (copiedMap.size === 0) {
            alert("Belum ada link yang disalin.");
            return;
        }

        if (!confirm("Reset semua status copy? Jadwal upload tetap tersimpan.")) return;

        setConnectionStatus('connecting', 'Resetting...');

        try {
            await apiRequest('reset', 'PATCH');

            copiedMap.clear();
            videos.forEach(v => {
                v.is_copied = false;
                v.copied_at = null;
            });

            renderVideos();
            updateCalendarBadge();
            showToast("Status berhasil direset");
            setConnectionStatus('online', 'MySQL Connected');

        } catch (err) {
            alert("Gagal reset: " + err.message);
            setConnectionStatus('online', 'MySQL Connected');
        }
    }


    /* ============================================================
       TOAST
    ============================================================ */

    let toastTimeout;

    function showToast(message) {
        const toast = document.getElementById("toast");
        toast.textContent = message;
        toast.classList.remove("hidden");
        toast.classList.add("flex");
        clearTimeout(toastTimeout);
        toastTimeout = setTimeout(() => {
            toast.classList.add("hidden");
            toast.classList.remove("flex");
        }, 2000);
    }


    /* ============================================================
       TIME FORMATTERS
    ============================================================ */

    function formatCopiedAt(isoString) {
        if (!isoString) return null;
        const date = new Date(isoString);
        if (isNaN(date.getTime())) return null;

        const diffSec = Math.floor((Date.now() - date.getTime()) / 1000);
        const diffMin = Math.floor(diffSec / 60);
        const diffHour = Math.floor(diffMin / 60);
        const diffDay = Math.floor(diffHour / 24);

        let relative;
        if (diffSec < 30) relative = 'baru saja';
        else if (diffSec < 60) relative = `${diffSec} detik lalu`;
        else if (diffMin < 60) relative = `${diffMin} menit lalu`;
        else if (diffHour < 24) relative = `${diffHour} jam lalu`;
        else if (diffDay < 7) relative = `${diffDay} hari lalu`;
        else if (diffDay < 30) relative = `${Math.floor(diffDay / 7)} minggu lalu`;
        else if (diffDay < 365) relative = `${Math.floor(diffDay / 30)} bulan lalu`;
        else relative = `${Math.floor(diffDay / 365)} tahun lalu`;

        const pad = n => String(n).padStart(2, '0');
        const timeStr = `${pad(date.getHours())}:${pad(date.getMinutes())}`;
        const dayNames = ['Min', 'Sen', 'Sel', 'Rab', 'Kam', 'Jum', 'Sab'];
        const monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'Mei', 'Jun', 'Jul', 'Agu', 'Sep', 'Okt', 'Nov', 'Des'];
        const dateStr = `${dayNames[date.getDay()]}, ${date.getDate()} ${monthNames[date.getMonth()]} ${date.getFullYear()}`;

        return { relative, time: timeStr, date: dateStr, full: `${dateStr} ${timeStr}`, iso: isoString };
    }

    function formatScheduleAt(isoString) {
        if (!isoString) return null;
        const date = new Date(isoString);
        if (isNaN(date.getTime())) return null;

        const now = new Date();
        const diffMs = date.getTime() - now.getTime();
        const isPast = diffMs < 0;

        const absDiffMs = Math.abs(diffMs);
        const diffSec = Math.floor(absDiffMs / 1000);
        const diffMin = Math.floor(diffSec / 60);
        const diffHour = Math.floor(diffMin / 60);
        const diffDay = Math.floor(diffHour / 24);

        let relative;
        if (isPast) {
            if (diffSec < 60) relative = 'baru saja';
            else if (diffMin < 60) relative = `${diffMin} menit lalu`;
            else if (diffHour < 24) relative = `${diffHour} jam lalu`;
            else if (diffDay < 7) relative = `${diffDay} hari lalu`;
            else if (diffDay < 30) relative = `${Math.floor(diffDay / 7)} minggu lalu`;
            else relative = `${Math.floor(diffDay / 30)} bulan lalu`;
        } else {
            if (diffSec < 60) relative = 'dalam beberapa detik';
            else if (diffMin < 60) relative = `${diffMin} menit lagi`;
            else if (diffHour < 24) relative = `${diffHour} jam lagi`;
            else if (diffDay === 1) relative = 'besok';
            else if (diffDay < 7) relative = `${diffDay} hari lagi`;
            else if (diffDay < 30) relative = `${Math.floor(diffDay / 7)} minggu lagi`;
            else relative = `${Math.floor(diffDay / 30)} bulan lagi`;
        }

        const pad = n => String(n).padStart(2, '0');
        const timeStr = `${pad(date.getHours())}:${pad(date.getMinutes())}`;
        const dayNames = ['Min', 'Sen', 'Sel', 'Rab', 'Kam', 'Jum', 'Sab'];
        const monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'Mei', 'Jun', 'Jul', 'Agu', 'Sep', 'Okt', 'Nov', 'Des'];
        const dateStr = `${dayNames[date.getDay()]}, ${date.getDate()} ${monthNames[date.getMonth()]} ${date.getFullYear()}`;

        const isToday = date.toDateString() === now.toDateString();

        return {
            relative, time: timeStr, date: dateStr,
            full: `${dateStr} ${timeStr}`,
            iso: isoString,
            isPast, isToday,
            daysUntil: diffDay
        };
    }


    /* ============================================================
       ESCAPE HELPERS
    ============================================================ */

    function escapeHTML(value) {
        return String(value || "")
            .replace(/&/g, "&amp;")
            .replace(/</g, "&lt;")
            .replace(/>/g, "&gt;")
            .replace(/"/g, "&quot;")
            .replace(/'/g, "&#039;");
    }

    function escapeJS(value) {
        return String(value || "")
            .replace(/\\/g, "\\\\")
            .replace(/'/g, "\\'")
            .replace(/\n/g, "\\n")
            .replace(/\r/g, "\\r");
    }


    /* ============================================================
       CATEGORIES MANAGEMENT
    ============================================================ */

    async function loadCategories() {
        try {
            const result = await apiRequest('categories');
            categories = result.data || [];
            updateCategoryFilter();
            updateCategoryBadge();
        } catch (err) {
            console.error('Load categories failed:', err);
            categories = [];
        }
    }

    function updateCategoryFilter() {
        const select = document.getElementById('categoryFilter');
        const current = select.value;
        select.innerHTML = '<option value="all">Semua Kategori</option><option value="none">Tanpa Kategori</option>';
        categories.forEach(cat => {
            const opt = document.createElement('option');
            opt.value = cat.id;
            opt.textContent = cat.name;
            select.appendChild(opt);
        });
        select.value = current;
    }

    function updateCategoryBadge() {
        const badge = document.getElementById('catBadge');
        if (categories.length > 0) {
            badge.textContent = categories.length;
            badge.classList.remove('hidden');
        } else {
            badge.classList.add('hidden');
        }
    }

    function renderCategories() {
        const table = document.getElementById('catTable');
        const emptyState = document.getElementById('catEmptyState');
        const container = document.getElementById('catTableContainer');

        if (categories.length === 0) {
            emptyState.classList.remove('hidden');
            container.classList.add('hidden');
            return;
        }

        emptyState.classList.add('hidden');
        container.classList.remove('hidden');

        table.innerHTML = '';
        categories.forEach((cat, i) => {
            const row = document.createElement('tr');
            row.className = 'group transition-colors hover:bg-slate-50/80 dark:hover:bg-ink-800/60';
            row.innerHTML = `
                <td class="px-4 py-3 text-xs font-medium text-slate-400 dark:text-slate-500">${i + 1}</td>
                <td class="px-4 py-3">
                    <span class="inline-block h-6 w-6 rounded-lg shadow-sm" style="background:${escapeHTML(cat.color)}"></span>
                </td>
                <td class="px-4 py-3">
                    <span class="inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 text-[11px] font-semibold text-white" style="background:${escapeHTML(cat.color)}">
                        ${escapeHTML(cat.name)}
                    </span>
                </td>
                <td class="px-4 py-3">
                    <span class="rounded-md bg-slate-100 px-2 py-0.5 text-xs font-bold text-slate-700 dark:bg-ink-800 dark:text-slate-300">${cat.video_count}</span>
                    <span class="ml-1 text-[11px] text-slate-400 dark:text-slate-500">video</span>
                </td>
                <td class="px-4 py-3 text-right">
                    <div class="flex items-center justify-end gap-1.5">
                        <button onclick="openCategoryModal(${cat.id})"
                            class="grid h-8 w-8 place-items-center rounded-lg border border-slate-200 bg-white text-slate-500 transition hover:border-violet-300 hover:bg-violet-50 hover:text-violet-600 dark:border-ink-700 dark:bg-ink-850 dark:text-slate-400 dark:hover:border-violet-800 dark:hover:bg-violet-950/40 dark:hover:text-violet-400"
                            title="Edit">
                            <svg xmlns="http://www.w3.org/2000/svg" class="h-3.5 w-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                                <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/>
                                <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/>
                            </svg>
                        </button>
                        <button onclick="deleteCategory(${cat.id}, '${escapeJS(cat.name)}')"
                            class="grid h-8 w-8 place-items-center rounded-lg border border-red-200 bg-white text-red-500 transition hover:border-red-300 hover:bg-red-50 hover:text-red-600 dark:border-red-900/40 dark:bg-ink-850 dark:text-red-400 dark:hover:border-red-800/60 dark:hover:bg-red-950/40"
                            title="Hapus">
                            <svg xmlns="http://www.w3.org/2000/svg" class="h-3.5 w-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round">
                                <polyline points="3 6 5 6 21 6"/>
                                <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/>
                            </svg>
                        </button>
                    </div>
                </td>
            `;
            table.appendChild(row);
        });
    }

    function setCatColor(color) {
        document.getElementById('catColorInput').value = color;
    }

    function openCategoryModal(editId) {
        const titleEl = document.getElementById('catModalTitle');
        const nameInput = document.getElementById('catNameInput');
        const colorInput = document.getElementById('catColorInput');
        const editIdInput = document.getElementById('catEditId');

        if (editId) {
            const cat = categories.find(c => c.id === editId);
            if (!cat) return;
            titleEl.textContent = 'Edit Kategori';
            nameInput.value = cat.name;
            colorInput.value = cat.color;
            editIdInput.value = cat.id;
        } else {
            titleEl.textContent = 'Tambah Kategori';
            nameInput.value = '';
            colorInput.value = '#3b82f6';
            editIdInput.value = '';
        }

        const modal = document.getElementById('categoryModal');
        modal.classList.remove('hidden');
        modal.classList.add('flex');
        nameInput.focus();
    }

    function closeCategoryModal() {
        const modal = document.getElementById('categoryModal');
        modal.classList.add('hidden');
        modal.classList.remove('flex');
    }

    async function saveCategory() {
        const name = document.getElementById('catNameInput').value.trim();
        const color = document.getElementById('catColorInput').value;
        const editId = document.getElementById('catEditId').value;

        if (!name) { alert('Nama kategori wajib diisi.'); return; }

        closeCategoryModal();

        try {
            if (editId) {
                await apiRequest('category_edit', 'PATCH', { id: parseInt(editId), name, color });
                showToast('Kategori diperbarui');
            } else {
                await apiRequest('category_add', 'POST', { name, color });
                showToast('Kategori ditambahkan');
            }
            await loadCategories();
            await loadVideos();
            if (currentTab === 'referensi') renderCategories();
        } catch (err) {
            alert('Gagal: ' + err.message);
        }
    }

    async function deleteCategory(id, name) {
        if (!confirm(`Hapus kategori "${name}"?\nVideo di kategori ini tidak akan terhapus.`)) return;

        try {
            await apiRequest('category_delete', 'POST', { id });
            showToast('Kategori dihapus');
            await loadCategories();
            await loadVideos();
            if (currentTab === 'referensi') renderCategories();
        } catch (err) {
            alert('Gagal hapus: ' + err.message);
        }
    }


    /* ============================================================
       KEYBOARD SHORTCUTS
    ============================================================ */

    document.addEventListener('keydown', (e) => {
        if (e.key === 'Escape') {
            const scheduleModal = document.getElementById('scheduleModal');
            const dayModal = document.getElementById('dayModal');
            const importModal = document.getElementById('importModal');
            const categoryModal = document.getElementById('categoryModal');

            if (!categoryModal.classList.contains('hidden')) {
                closeCategoryModal();
            } else if (!importModal.classList.contains('hidden')) {
                closeImportModal();
            } else if (!scheduleModal.classList.contains('hidden')) {
                closeScheduleModal();
            } else if (!dayModal.classList.contains('hidden')) {
                closeDayModal();
            }
        }
    });


    /* ============================================================
       INIT
    ============================================================ */

    loadVideos();

</script>

</body>
</html>

Zerion Mini Shell 1.0