File size: 24,437 Bytes
36d488d
 
 
 
 
fa5cb75
36d488d
 
 
 
baba0aa
36d488d
 
fa5cb75
 
36d488d
fa5cb75
36d488d
 
 
 
fa5cb75
36d488d
 
fa5cb75
36d488d
fa5cb75
59ea1b6
 
 
 
fa5cb75
36d488d
 
fa5cb75
6a5e9da
60d5ca5
d816aa5
 
fa5cb75
 
 
d816aa5
36d488d
59ea1b6
fa5cb75
 
9bcbd91
 
fa5cb75
 
 
9bcbd91
fa5cb75
59ea1b6
9bcbd91
baba0aa
fa5cb75
 
 
 
 
9bcbd91
6a5e9da
9bcbd91
 
 
6a5e9da
fa5cb75
9bcbd91
fa5cb75
 
9bcbd91
 
fa5cb75
36d488d
fa5cb75
 
 
 
36d488d
fa5cb75
9bcbd91
36d488d
fa5cb75
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9bcbd91
fa5cb75
baba0aa
fa5cb75
 
d816aa5
fa5cb75
d816aa5
9bcbd91
59ea1b6
fa5cb75
 
baba0aa
fa5cb75
 
c4dff8a
9bcbd91
fa5cb75
 
6a5e9da
fa5cb75
36d488d
 
ce9d84e
36d488d
ce9d84e
d816aa5
36d488d
fa5cb75
9bcbd91
 
fa5cb75
 
59ea1b6
 
fa5cb75
59ea1b6
 
 
fa5cb75
36d488d
 
 
 
 
baba0aa
fa5cb75
 
9bcbd91
36d488d
fa5cb75
c3aa225
c2ee016
a981822
fa5cb75
baba0aa
 
 
36d488d
9bcbd91
fa5cb75
 
 
36d488d
 
 
ce9d84e
baba0aa
fa5cb75
9229566
fa5cb75
 
36d488d
9229566
fa5cb75
d816aa5
fa5cb75
 
 
d816aa5
fa5cb75
 
 
d348ff5
 
59ea1b6
fa5cb75
59ea1b6
36d488d
 
ce9d84e
baba0aa
fa5cb75
baba0aa
2cb7484
36d488d
 
 
 
fa5cb75
 
c3aa225
a981822
fa5cb75
 
 
36d488d
60d5ca5
6a5e9da
 
59ea1b6
6a5e9da
59ea1b6
 
 
 
 
 
 
 
 
 
36d488d
 
 
59ea1b6
 
 
 
 
 
 
 
c4dff8a
59ea1b6
 
 
 
 
 
36d488d
59ea1b6
36d488d
 
 
 
59ea1b6
60d5ca5
59ea1b6
 
 
 
 
baba0aa
 
59ea1b6
 
 
 
 
 
 
9bcbd91
 
fa5cb75
59ea1b6
 
 
36d488d
 
 
59ea1b6
 
 
 
b76e90a
 
59ea1b6
 
 
 
 
36d488d
59ea1b6
 
 
 
 
daa009b
7a3b8d2
 
 
daa009b
 
 
 
7a3b8d2
 
 
 
daa009b
 
 
f6fe3a9
 
daa009b
9bcbd91
7a3b8d2
 
 
 
 
81c1665
 
 
 
 
 
 
9bcbd91
 
 
81c1665
 
 
 
9bcbd91
fa5cb75
59ea1b6
 
6a5e9da
4913893
59ea1b6
9bcbd91
 
fa5cb75
9bcbd91
 
59ea1b6
60d5ca5
6a5e9da
59ea1b6
 
 
 
fa5cb75
59ea1b6
 
9229566
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60d5ca5
36d488d
59ea1b6
 
 
 
 
 
 
fa5cb75
 
c3aa225
10e0463
c3aa225
 
10e0463
 
 
 
a981822
 
 
 
c3aa225
 
59ea1b6
 
 
 
 
 
60d5ca5
ce9d84e
36d488d
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>ViralFlow AI — Luxury Command Center</title>
    <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=Outfit:wght@400;600;800;900&family=Plus+Jakarta+Sans:wght@300;400;600;700&display=swap" rel="stylesheet">
    <script src="https://unpkg.com/lucide@latest"></script>
    <script src="https://cdn.jsdelivr.net/npm/@supabase/supabase-js@2"></script>
    <style>
        :root {
            --bg: #030712;
            --surface: rgba(17, 24, 39, 0.7);
            --accent: #6366f1;
            --accent-glow: rgba(99, 102, 241, 0.5);
            --success: #10b981;
            --danger: #ef4444;
            --text: #f8fafc;
            --text-dim: #94a3b8;
            --glass-border: rgba(255, 255, 255, 0.1);
        }

        * { box-sizing: border-box; transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1); }
        body {
            background: radial-gradient(circle at 50% -20%, #1e1b4b 0%, var(--bg) 80%);
            color: var(--text);
            font-family: 'Plus Jakarta Sans', sans-serif;
            margin: 0; min-height: 100vh;
            overflow-x: hidden;
            padding-bottom: 80px; /* Space for mobile nav */
        }

        .container { width: 100%; max-width: 1400px; margin: 0 auto; padding: 15px; display: none; }
        html.is-authed .container { display: block !important; }
        html.is-authed .auth-overlay { display: none !important; }

        .glass-panel {
            background: var(--surface); backdrop-filter: blur(40px);
            border-radius: 28px; border: 1px solid var(--glass-border);
            box-shadow: 0 20px 50px rgba(0,0,0,0.5);
        }

        header {
            display: flex; justify-content: space-between; align-items: center;
            padding: 20px; margin-bottom: 25px;
        }

        .logo-text { font-family: 'Outfit', sans-serif; font-size: 1.8rem; font-weight: 900; letter-spacing: -1.5px; }
        
        /* Stats Widgets */
        .stats-grid { 
            display: grid; grid-template-columns: repeat(2, 1fr); gap: 12px; margin-bottom: 25px; 
        }
        @media (min-width: 1024px) { .stats-grid { grid-template-columns: repeat(4, 1fr); } }

        .stat-card { 
            padding: 20px; text-align: center; position: relative;
            background: linear-gradient(135deg, rgba(255,255,255,0.05) 0%, rgba(255,255,255,0) 100%);
        }
        .stat-label { font-size: 0.65rem; font-weight: 900; color: var(--text-dim); text-transform: uppercase; letter-spacing: 2px; }
        .stat-value { font-size: 1.8rem; font-weight: 900; font-family: 'Outfit', sans-serif; margin-top: 5px; }

        /* Main Layout */
        .main-grid { display: grid; grid-template-columns: 1fr; gap: 20px; }
        @media (min-width: 1024px) { .main-grid { grid-template-columns: 1fr 1.6fr; } }

        .panel { padding: 30px; }
        .panel-title { 
            font-family: 'Outfit', sans-serif; font-size: 1.4rem; font-weight: 800; 
            margin-bottom: 25px; display: flex; align-items: center; gap: 12px; 
        }

        /* Premium Buttons */
        .btn-primary {
            cursor: pointer; border: none; padding: 16px 30px; border-radius: 20px;
            background: var(--accent); color: #fff; font-weight: 800; font-size: 1rem;
            display: inline-flex; align-items: center; justify-content: center; gap: 12px;
            box-shadow: 0 10px 30px var(--accent-glow);
        }
        .btn-primary:active { transform: scale(0.95); }
        .btn-full { width: 100%; }

        .btn-upgrade {
            background: linear-gradient(90deg, #f59e0b, #ef4444);
            box-shadow: 0 10px 30px rgba(239, 68, 68, 0.3);
        }

        /* Mobile Bottom Nav */
        .mobile-nav {
            position: fixed; bottom: 0; left: 0; right: 0;
            background: rgba(3, 7, 18, 0.8); backdrop-filter: blur(20px);
            border-top: 1px solid var(--glass-border);
            display: flex; justify-content: space-around; padding: 15px; z-index: 1000;
        }
        @media (min-width: 1024px) { .mobile-nav { display: none; } }
        
        .nav-item { color: var(--text-dim); text-decoration: none; display: flex; flex-direction: column; align-items: center; font-size: 0.6rem; font-weight: 800; gap: 5px; }
        .nav-item.active { color: var(--accent); }

        /* Input Luxury */
        .input-group { margin-bottom: 20px; }
        label { display: block; margin-bottom: 10px; font-size: 0.75rem; font-weight: 900; color: var(--text-dim); text-transform: uppercase; letter-spacing: 1px; }
        input {
            width: 100%; background: rgba(0,0,0,0.4); border: 1px solid var(--glass-border);
            padding: 18px; border-radius: 20px; color: #fff; font-size: 1rem; outline: none;
        }
        input:focus { border-color: var(--accent); box-shadow: 0 0 20px var(--accent-glow); }

        /* Logs */
        .log-container { 
            background: rgba(0,0,0,0.5); border-radius: 24px; padding: 20px; 
            height: 500px; overflow-y: auto; border: 1px solid var(--glass-border);
        }
        .log-item { padding: 12px; border-bottom: 1px solid rgba(255,255,255,0.02); display: flex; gap: 15px; font-size: 0.85rem; }
        .log-time { color: var(--accent); font-weight: 900; }

        /* Auth */
        .auth-overlay { position: fixed; inset: 0; background: var(--bg); display: flex; align-items: center; justify-content: center; z-index: 2000; padding: 20px; }
        .auth-card { padding: 40px; width: 100%; max-width: 450px; text-align: center; }

        .tag { background: rgba(99, 102, 241, 0.1); color: var(--accent); padding: 6px 14px; border-radius: 12px; font-size: 0.7rem; font-weight: 900; border: 1px solid var(--accent); }
    </style>
</head>
<body>

    <div class="auth-overlay" id="auth-overlay">
        <div class="auth-card glass-panel">
            <div id="login-form">
                <h1 style="font-family: 'Outfit', sans-serif; font-size: 2.2rem; margin-bottom: 30px;">ViralFlow</h1>
                <div class="input-group"><label>Email</label><input type="email" id="login-email" placeholder="agent@viralflow.ai"></div>
                <div class="input-group"><label>Password</label><input type="password" id="login-pass" placeholder="••••••••"></div>
                <button class="btn-primary btn-full" onclick="login()">Access Dashboard</button>
                <p onclick="toggleAuth()" style="cursor:pointer; margin-top:25px; color:var(--text-dim); font-size: 0.9rem;">New here? <span style="color:var(--accent)">Join Now</span></p>
            </div>
            <div id="signup-form" style="display:none;">
                <h1 style="font-family: 'Outfit', sans-serif; font-size: 2.2rem; margin-bottom: 30px;">Get Started</h1>
                <div class="input-group"><label>Email</label><input type="email" id="signup-email"></div>
                <div class="input-group"><label>Password</label><input type="password" id="signup-pass"></div>
                <button class="btn-primary btn-full" onclick="signup()">Create Account</button>
                <p onclick="toggleAuth()" style="cursor:pointer; margin-top:25px; color:var(--text-dim);">Already a member? <span style="color:var(--accent)">Login</span></p>
            </div>
        </div>
    </div>

    <div class="container" id="dashboard-container">
        <header class="glass-panel">
            <div class="logo-group" style="display: flex; align-items: center; gap: 15px;">
                <div class="logo-text">ViralFlow</div>
                <div class="tag" id="user-plan">🛡️ FREE</div>
            </div>
            <div style="display:flex; gap:15px; align-items:center;">
                <a href="/admin.html" id="admin-btn" class="btn-primary" style="display:none; background: rgba(139, 92, 246, 0.15); color: #a78bfa; border: 1px solid #8b5cf6; padding: 10px 20px; font-size: 0.8rem;"><i data-lucide="shield"></i> ADMIN</a>
                <a href="/tutorial.html" class="btn-primary" style="background: rgba(255,255,255,0.05); color: #fff; border: 1px solid var(--glass-border); padding: 10px 20px; font-size: 0.8rem;"><i data-lucide="help-circle"></i> HELP</a>
                <a href="/plans.html" id="upgrade-btn" class="btn-primary btn-upgrade" style="padding: 10px 20px; font-size: 0.8rem;"><i data-lucide="zap"></i> UPGRADE</a>
                <button class="btn-primary" style="background: rgba(239, 68, 68, 0.1); color: var(--danger); box-shadow: none; padding: 10px;" onclick="logout()"><i data-lucide="log-out"></i></button>
            </div>
        </header>

        <div class="stats-grid">
            <div class="stat-card glass-panel"><div class="stat-label">Videos</div><div class="stat-value" id="stat-generated">0</div></div>
            <div class="stat-card glass-panel"><div class="stat-label">Views</div><div class="stat-value" id="stat-views" style="color:var(--accent);">0</div></div>
            <div class="stat-card glass-panel"><div class="stat-label">Subs</div><div class="stat-value" id="stat-subs" style="color:var(--success);">0</div></div>
            <div class="stat-card glass-panel"><div class="stat-label">IST Time</div><div class="stat-value" id="server-time" style="font-size: 1.2rem; margin-top: 10px;">00:00:00</div></div>
        </div>

        <div class="main-grid">
            <div class="left-col">
                <div class="panel glass-panel">
                    <h3 class="panel-title"><i data-lucide="shield-check"></i> Command Center</h3>
                    <div style="display:flex; gap:12px; margin-bottom:15px;">
                        <button class="btn-primary" style="flex:1;" onclick="saveSettings(this)">Sync Settings</button>
                        <button class="btn-primary" style="flex:1.5; background:var(--success);" onclick="generateNow()"><i data-lucide="play"></i> Create Video</button>
                    </div>
                    <button class="btn-primary btn-full btn-sm" onclick="resetProduction(this)" style="background: rgba(239, 68, 68, 0.1); color: var(--danger); border: 1px solid rgba(239, 68, 68, 0.1); margin-bottom: 30px;"><i data-lucide="refresh-cw"></i> Emergency: Reset Production Lock</button>
                    <div class="input-group"><label>Target Niche</label><input type="text" id="setting-niche"></div>
                    <div class="input-group">
                        <label>Post Schedule</label>
                        <div id="schedule-list" style="display:flex; flex-wrap:wrap; gap:10px; margin-bottom:15px;"></div>
                        <div style="display:flex; gap:10px;"><input type="time" id="new-time" style="flex:1;"><button class="btn-primary" onclick="addTimeSlot()" style="padding:10px 20px;">+</button></div>
                    </div>
                    <div style="padding:25px; background:rgba(0,0,0,0.3); border-radius:24px; margin-bottom:20px; border:1px solid var(--glass-border);">
                        <label>Google Cloud Keys</label>
                        <input type="text" id="setting-client-id" placeholder="Client ID" style="margin-bottom:10px; font-size: 0.85rem;">
                        <input type="password" id="setting-client-secret" placeholder="Secret Key" style="margin-bottom:15px; font-size: 0.85rem;">
                        <button class="btn-primary btn-full btn-sm" onclick="saveSettings(this)" style="background: rgba(255,255,255,0.05); border: 1px solid var(--glass-border);">Update Vault Keys</button>
                    </div>
                    <button id="connect-btn" class="btn-primary btn-full" onclick="connectYouTube()" style="background:#ef4444;">Connect Channel</button>
                    <div id="channel-list" style="margin-top:20px;"></div>
                </div>
            </div>
            <div class="right-col">
                <div class="panel glass-panel">
                    <h3 class="panel-title"><i data-lucide="activity"></i> Real-time Activity</h3>
                    <div class="log-container" id="activity-log"></div>
                </div>
            </div>
        </div>
    </div>

    <nav class="mobile-nav">
        <a href="/" class="nav-item active"><i data-lucide="layout-dashboard"></i> Home</a>
        <a href="/admin.html" id="admin-nav" class="nav-item" style="display:none;"><i data-lucide="shield"></i> Admin</a>
        <a href="/plans.html" id="upgrade-nav" class="nav-item"><i data-lucide="zap"></i> Plans</a>
        <a href="/tutorial.html" class="nav-item"><i data-lucide="help-circle"></i> Help</a>
    </nav>

    <script>
        let authToken = localStorage.getItem('saas_token');
        let preferredHours = [];
        let userPlan = 'free';
        let supabaseClient = null;

        if (authToken) {
            document.documentElement.classList.add('is-authed');
            checkAuth();
        }

        function toggleAuth() {
            const l = document.getElementById('login-form'), s = document.getElementById('signup-form');
            l.style.display = l.style.display === 'none' ? 'block' : 'none';
            s.style.display = s.style.display === 'none' ? 'block' : 'none';
        }

        async function login() {
            const email = document.getElementById('login-email').value, pass = document.getElementById('login-pass').value;
            try {
                const res = await fetch('/api/auth/login', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ email, password: pass })});
                const d = await res.json();
                if (d.token) { 
                    localStorage.setItem('saas_token', d.token); 
                    authToken = d.token;
                    document.documentElement.classList.add('is-authed');
                    await checkAuth();
                } else { alert("Login Error: " + (d.error || "Invalid Credentials")); }
            } catch(e) { alert("Network Error"); }
        }

        async function signup() {
            const email = document.getElementById('signup-email').value, pass = document.getElementById('signup-pass').value;
            const res = await fetch('/api/auth/signup', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ email, password: pass })});
            const d = await res.json();
            if (d.token) { localStorage.setItem('saas_token', d.token); location.reload(); } else alert("Signup Failed");
        }

        function logout() { localStorage.removeItem('saas_token'); location.reload(); }

        async function initRealtime() {
            try {
                const configRes = await fetch('/api/config');
                const config = await configRes.json();
                supabaseClient = supabase.createClient(config.supabaseUrl, config.supabaseKey);
                supabaseClient.channel('activity-updates').on('postgres_changes', { event: 'INSERT', schema: 'public', table: 'activity' }, () => { updateLogs(); initDashboard(); }).subscribe();
            } catch(e) { console.error("Realtime Init Failed", e); }
        }

        async function updateLogs() {
            try {
                const res = await fetch('/api/logs', { headers: { 'Authorization': `Bearer ${authToken}` } });
                const logs = await res.json();
                const logList = document.getElementById('activity-log');
                logList.innerHTML = logs.map(l => `
                    <div class="log-item">
                        <span class="log-time">${new Date(l.time).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'})}</span>
                        <span style="flex:1;">${l.msg}</span>
                        ${l.metadata?.url ? `<a href="${l.metadata.url}" target="_blank" style="color:var(--success); font-weight:800; font-size:0.75rem; text-decoration:none;">WATCH ↗</a>` : ''}
                    </div>
                `).join('');
            } catch (e) { console.error(e); }
        }

        async function initDashboard() {
            try {
                const res = await fetch('/api/stats', { headers: { 'Authorization': `Bearer ${authToken}` } });
                const d = await res.json();
                document.getElementById('stat-generated').innerText = d.videosProduced || 0;
                document.getElementById('stat-views').innerText = d.totalViews?.toLocaleString() || 0;
                document.getElementById('stat-subs').innerText = d.subscribers?.toLocaleString() || 0;
                document.getElementById('setting-niche').value = d.niche || '';
                document.getElementById('setting-client-id').value = d.custom_client_id || '';
                document.getElementById('setting-client-secret').value = d.custom_client_secret || '';
                preferredHours = d.preferred_hours || [];
                updateScheduleUI();

                const ytRes = await fetch('/api/youtube', { headers: { 'Authorization': `Bearer ${authToken}` } });
                const yt = await ytRes.json();
                const list = document.getElementById('channel-list');
                const connectBtn = document.getElementById('connect-btn');
                list.innerHTML = '';
                
                let totalViews = 0;
                let totalSubs = 0;

                const channelsToShow = yt.channels || [];
                if (channelsToShow.length > 0) {
                    channelsToShow.forEach(c => { 
                        const isLive = c.connected || c.channel_id;
                        if (isLive) {
                            totalViews += (c.totalViews || 0);
                            totalSubs += (c.subscribers || 0);
                        }
                        list.innerHTML += `
                            <div style="background:rgba(16, 185, 129, 0.05); color:${isLive ? 'var(--success)' : 'var(--text-dim)'}; padding:15px; border-radius:18px; border:1px solid ${isLive ? 'rgba(16, 185, 129, 0.2)' : 'var(--glass-border)'}; font-weight:800; margin-bottom:10px; font-size:0.85rem; display:flex; align-items:center; gap:10px;">
                                <i data-lucide="${isLive ? 'check-circle' : 'alert-circle'}" style="width:16px;"></i> 
                                ${c.channel_name || 'Ready for Connection'}
                                ${isLive ? '' : '<span style="font-size:0.6rem; background:rgba(239,68,68,0.2); color:var(--text-dim); padding:4px 10px; border-radius:20px; margin-left:auto; border:1px solid rgba(255,255,255,0.1);">UNLINKED</span>'}
                            </div>`; 
                    });

                    // Update Top Stats with Live Summed Data
                    document.getElementById('stat-views').innerText = totalViews.toLocaleString();
                    document.getElementById('stat-subs').innerText = totalSubs.toLocaleString();

                    // --- Unlimited Slots for Admins ---
                    const isAdmin = (userPlan === 'ultra'); // Existing plan check
                    // Note: We will use the role from the global d variable in a better way
                    
                    const slotLimit = (userPlan === 'ultra' || document.getElementById('admin-btn').style.display === 'flex') ? 999 : 1;

                    if (channelsToShow.length >= slotLimit) { 
                        connectBtn.innerHTML = `Slot Occupied`; 
                        connectBtn.disabled = true; 
                        connectBtn.style.opacity = '0.5'; 
                    } else {
                        connectBtn.innerHTML = `Connect Channel`;
                        connectBtn.disabled = false;
                        connectBtn.style.opacity = '1';
                    }
                    lucide.createIcons();
                }
            } catch(e) { console.error(e); }
        }

        function updateScheduleUI() {
            document.getElementById('schedule-list').innerHTML = preferredHours.map((t, i) => `
                <div class="tag" style="background:rgba(255,255,255,0.05); border-color:var(--glass-border); color:#fff; display:flex; align-items:center; gap:8px;">
                    ${t} <span style="cursor:pointer; color:var(--danger); font-size:1.2rem;" onclick="removeTime(${i})">×</span>
                </div>
            `).join('');
        }
        function addTimeSlot() { const t = document.getElementById('new-time').value; if (t && !preferredHours.includes(t)) { preferredHours.push(t); updateScheduleUI(); } }
        function removeTime(i) { preferredHours.splice(i, 1); updateScheduleUI(); }

        async function saveSettings(btn) {
            const orig = btn.innerHTML; btn.innerHTML = 'Syncing...';
            await fetch('/api/settings', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${authToken}` }, body: JSON.stringify({ niche: document.getElementById('setting-niche').value, preferred_hours: preferredHours, custom_client_id: document.getElementById('setting-client-id').value, custom_client_secret: document.getElementById('setting-client-secret').value }) });
            btn.innerHTML = 'Synced!'; setTimeout(() => { btn.innerHTML = orig; }, 2000);
        }

        async function generateNow() { 
            if(!confirm("Initialize Production?")) return; 
            const res = await fetch('/api/generate', { method: 'POST', headers: { 'Authorization': `Bearer ${authToken}` } }); 
            const d = await res.json();
            if (res.ok) alert("Production Started! Check logs below. 🎬🚀");
            else alert("Error: " + d.error);
        }

        async function resetProduction(btn) {
            if(!confirm("Are you sure? Only use this if production is stuck.")) return;
            const res = await fetch('/api/generate/reset', { method: 'POST', headers: { 'Authorization': `Bearer ${authToken}` } });
            const d = await res.json();
            alert(d.message);
            location.reload();
        }
        async function connectYouTube() { const res = await fetch('/api/auth/url', { headers: { 'Authorization': `Bearer ${authToken}` } }); const d = await res.json(); if (d.url) window.open(d.url, '_blank'); }

        async function checkAuth() {
            if (!authToken) return;
            try {
                const res = await fetch('/api/auth/me', { headers: { 'Authorization': `Bearer ${authToken}` } });
                const d = await res.json();
                if (d.loggedIn) {
                    userPlan = d.plan || 'free';
                    const p = document.getElementById('user-plan');
                    if (p) p.innerText = userPlan === 'ultra' ? '☢️ GOD MODE' : (userPlan === 'pro' ? '⚡ PRO' : '🛡️ FREE');
                    
                    if (d.role === 'admin') {
                        document.getElementById('admin-btn').style.display = 'flex';
                        document.getElementById('admin-nav').style.display = 'flex';
                    }

                    // --- Hide Upgrade for Admins & Ultra Users ---
                    if (d.role === 'admin' || userPlan === 'ultra') {
                        const upBtn = document.getElementById('upgrade-btn');
                        const upNav = document.getElementById('upgrade-nav');
                        if (upBtn) upBtn.style.display = 'none';
                        if (upNav) upNav.style.display = 'none';
                    }

                    document.documentElement.classList.add('is-authed');
                    initDashboard(); updateLogs(); initRealtime();
                } else { localStorage.removeItem('saas_token'); document.documentElement.classList.remove('is-authed'); }
            } catch (e) { document.documentElement.classList.add('is-authed'); }
        }

        setInterval(() => { document.getElementById('server-time').innerText = new Date().toLocaleTimeString('en-IN', { timeZone: 'Asia/Kolkata', hour: '2-digit', minute: '2-digit', second: '2-digit' }); }, 1000);
        lucide.createIcons();
    </script>
</body>
</html>