-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscout_app.html
More file actions
675 lines (561 loc) · 32.6 KB
/
scout_app.html
File metadata and controls
675 lines (561 loc) · 32.6 KB
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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Scout App - SIM Scouting</title>
<script src="https://cdn.tailwindcss.com"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; }
</style>
</head>
<body class="bg-[#111111] min-h-screen flex flex-col items-center justify-center p-4">
<!-- Card -->
<div class="bg-[#1a1a1a] p-8 rounded-2xl shadow-2xl shadow-black/50 max-w-sm w-full text-center border border-gray-800 transform transition-all hover:scale-[1.01]">
<!-- VIEW: DASHBOARD (Sharing) -->
<div id="view-dashboard" class="hidden">
<!-- Header / Greeting -->
<h1 class="text-2xl font-bold text-white mb-3">Hi <span id="scout-name" class="text-[#00b4d8]">Scout</span>, <br>trainiere nicht allein!</h1>
<!-- Subline -->
<p class="text-gray-400 mb-8 font-medium leading-relaxed">
Schenk deinen Freunden Fitness! <br>
<span class="text-sm opacity-60">Dein Code ist wertvoll. Teile ihn jetzt.</span>
</p>
<!-- STATS CARD (New Feature) -->
<!-- STATS CARD (New Feature) -->
<!-- STATS CARD (New Feature) -->
<!-- Reward Banner Container -->
<div id="reward-container" class="mb-6 hidden"></div>
<!-- Action Buttons -->
<div class="flex flex-col gap-4">
<!-- WhatsApp Button -->
<a id="whatsapp-btn" href="#" target="_blank" class="bg-[#25D366] hover:bg-[#20bd5a] text-white font-bold py-4 px-6 rounded-xl flex items-center justify-center transition-all shadow-lg hover:shadow-green-900/50 group">
<i class="fab fa-whatsapp text-3xl mr-3 group-hover:scale-110 transition-transform"></i>
<span class="text-lg">Per WhatsApp teilen</span>
</a>
<!-- Email Button -->
<a id="email-btn" href="#" class="bg-blue-600 hover:bg-blue-500 text-white font-bold py-4 px-6 rounded-xl flex items-center justify-center transition-all shadow-lg hover:shadow-blue-900/50 group">
<i class="fa-solid fa-envelope text-3xl mr-3 group-hover:scale-110 transition-transform"></i>
<span class="text-lg">Per E-Mail teilen ✉️</span>
</a>
<!-- Copy Link Button -->
<button id="copy-btn" class="bg-gray-800 hover:bg-gray-700 text-white font-bold py-4 px-6 rounded-xl flex items-center justify-center transition-all shadow-lg border border-gray-700 hover:border-gray-600 group">
<i id="copy-icon" class="fas fa-copy text-xl mr-3 text-[#00b4d8] group-hover:text-white transition-colors"></i>
<span id="copy-text" class="text-lg">Link kopieren</span>
</button>
<!-- Save Link Button (Sticky Feature) -->
<a id="save-btn" href="#" target="_blank" class="mt-2 text-gray-500 hover:text-gray-300 border-2 border-gray-800 hover:border-gray-700 hover:bg-white/5 font-semibold py-3 px-6 rounded-xl flex items-center justify-center transition-all group">
<i class="fas fa-save text-lg mr-3 group-hover:scale-110 transition-transform"></i>
<span>Link für mich sichern 💾</span>
</a>
</div>
<!-- STATS (Moved to bottom) -->
<div class="mt-8 pt-6 border-t border-gray-800">
<div id="stats-loader" class="mb-4 text-center text-gray-500 animate-pulse text-sm">
<i class="fas fa-spinner fa-spin mr-2"></i> Lade Statistik...
</div>
<div id="stats-container" class="mb-4 hidden scale-90 origin-top">
<div class="grid grid-cols-2 gap-4">
<!-- Count -->
<div class="bg-[#111] p-3 rounded-xl border border-gray-800 flex flex-col items-center justify-center">
<span class="text-2xl font-bold text-white" id="stats-count">-</span>
<span class="text-[10px] text-gray-500 uppercase tracking-wider mt-1">Leads</span>
</div>
<!-- Rank -->
<div class="bg-[#111] p-3 rounded-xl border border-gray-800 flex flex-col items-center justify-center">
<span class="text-lg font-bold text-gray-400" id="stats-rank">-</span>
<span class="text-[10px] text-gray-500 uppercase tracking-wider mt-1">Status</span>
</div>
</div>
</div>
<!-- EMPTY STATE (No leads yet) -->
<div id="stats-empty" class="mb-4 hidden text-center">
<div class="bg-gray-800/30 p-3 rounded-xl border border-gray-800 text-gray-400 text-xs inline-block">
Noch keine Leads. <span class="text-white font-bold">Teile deinen Link! 🚀</span>
</div>
</div>
</div>
<!-- Link Display (Optional) -->
<div class="mt-4 text-xs text-gray-600 break-all select-all font-mono" id="debug-link"></div>
</div>
<!-- VIEW: REGISTER (Onboarding) -->
<div id="view-register" class="hidden">
<h1 class="text-2xl font-bold text-white mb-3">Werde <span class="text-[#00b4d8]">Scout</span>!</h1>
<p class="text-gray-400 mb-6 font-medium">
Registriere dich jetzt und erhalte deinen persönlichen Code zum Teilen.
</p>
<form id="register-form" class="text-left flex flex-col gap-4">
<div class="flex gap-2">
<div class="w-1/2">
<label class="block text-gray-500 text-sm font-bold mb-1 ml-1">Vorname</label>
<input type="text" id="reg-first-name" required placeholder="Max"
class="w-full p-3 bg-[#111111] border border-gray-700 rounded-xl text-white focus:outline-none focus:border-[#00b4d8] focus:ring-1 focus:ring-[#00b4d8] transition-all">
</div>
<div class="w-1/2">
<label class="block text-gray-500 text-sm font-bold mb-1 ml-1">Nachname</label>
<input type="text" id="reg-last-name" required placeholder="Mustermann"
class="w-full p-3 bg-[#111111] border border-gray-700 rounded-xl text-white focus:outline-none focus:border-[#00b4d8] focus:ring-1 focus:ring-[#00b4d8] transition-all">
</div>
</div>
<div>
<label class="block text-gray-500 text-sm font-bold mb-1 ml-1">E-Mail</label>
<input type="email" id="reg-email" required placeholder="deine@mail.de"
class="w-full p-3 bg-[#111111] border border-gray-700 rounded-xl text-white focus:outline-none focus:border-[#00b4d8] focus:ring-1 focus:ring-[#00b4d8] transition-all">
</div>
<div id="reg-error" class="text-red-500 text-sm hidden text-center">Fehler beim Erstellen.</div>
<button type="submit" id="reg-btn"
class="mt-2 bg-gradient-to-r from-[#00b4d8] to-[#0096b4] hover:from-[#00c4e8] hover:to-[#00a6c4] text-white font-bold py-4 px-6 rounded-xl flex items-center justify-center transition-all shadow-lg shadow-cyan-900/20 transform hover:-translate-y-0.5">
Jetzt Scout werden 🚀
</button>
</form>
</div>
<!-- Toast (Hidden by default) -->
<div id="toast" class="fixed bottom-6 left-1/2 transform -translate-x-1/2 bg-[#00b4d8] text-white px-6 py-3 rounded-full shadow-[0_0_20px_rgba(0,180,216,0.5)] opacity-0 transition-opacity duration-300 pointer-events-none flex items-center font-bold z-50">
<i class="fas fa-check-circle text-white mr-2"></i> Link kopiert!
</div>
</div>
<!-- Achievements Section -->
<div id="achievements-container" class="mb-8 w-full max-w-sm hidden"></div>
<div class="mt-8 opacity-30">
<img src="https://www.studios-in-motion.de/images/logo_studiosinmotion_2021_rahmen.svg" alt="Studios in Motion" class="h-6 mx-auto invert grayscale" onerror="this.style.display='none'">
</div>
<!-- SUPABASE & APP LOGIC -->
<script type="module">
// import { createClient } from 'https://esm.sh/@supabase/supabase-js@2';
import { createClient } from 'https://cdn.jsdelivr.net/npm/@supabase/supabase-js@2/+esm';
// CONFIG
const FALLBACK_LANDING_PAGE_URL = 'https://simscouting.studios-in-motion.de/test_page.html';
const SUPABASE_URL = 'https://rmtyebyzitzgkplxvzxg.supabase.co';
const SUPABASE_KEY = 'sb_publishable_2qDg3Jssg_fTPdXl_3Ku-g_1yOkdJ3i';
const TENANT_ID = '79a37c78-7bdf-45e4-a631-fb47926d054d';
// Debug Logger
const debugArea = document.getElementById('debug-link');
function logDebug(msg) {
console.log(msg);
// debugArea.innerHTML += `<div>${msg}</div>`; // Uncomment for extreme debugging
}
// Global Campaign State
let currentCampaign = null;
// Init Supabase
let supabase;
try {
supabase = createClient(SUPABASE_URL, SUPABASE_KEY);
logDebug('Supabase Client Initialized');
} catch (e) {
logDebug('Supabase Init Error: ' + e.message);
document.getElementById('stats-loader').textContent = 'Fehler: Supabase Konfiguration';
}
// Determine Campaign on Load
document.addEventListener('DOMContentLoaded', () => {
const urlParams = new URLSearchParams(window.location.search);
const hashParams = new URLSearchParams(window.location.hash.replace(/^#\/?/, ''));
const getParam = (key) => urlParams.get(key) || hashParams.get(key);
// Robust check
currentCampaign = getParam('campaign') || getParam('utm_campaign') || getParam('Campaign');
if (currentCampaign) {
console.log('Campaign detected:', currentCampaign);
}
});
// Tracking Helper
async function trackEvent(type, scoutId, meta = {}) {
if (!scoutId) return;
// Enrich with Campaign Data if available
if (currentCampaign) {
meta.campaign = currentCampaign;
}
try {
await supabase.from('tracking_events').insert({
scout_id: scoutId,
event_type: type,
meta_data: meta
});
logDebug('Tracked: ' + type);
} catch (e) {
console.warn('Tracking failed:', e);
}
}
async function initApp() {
// Get Scout ID from URL
const urlParams = new URLSearchParams(window.location.search);
let scoutId = urlParams.get('id');
// View Elements
const viewDashboard = document.getElementById('view-dashboard');
const viewRegister = document.getElementById('view-register');
const scoutNameEl = document.getElementById('scout-name');
// Routing Logic
if (scoutId) {
// SHOW DASHBOARD
viewDashboard.classList.remove('hidden');
// NEW: Load Stats (Parallel not waiting for Dashboard)
// We need rewardConfig from initDashboard to be available or passed.
// Refactor: initDashboard now returns rewardConfig or we make it global.
// For now, let's just make initDashboard return the config and we wait for it.
const config = await initDashboard(scoutId);
// Optional: Fetch Scout Name (Restored)
fetchScoutName(scoutId);
loadStats(scoutId, config);
} else {
// SHOW REGISTRATION
viewRegister.classList.remove('hidden');
initRegistration();
}
}
async function fetchScoutName(id) {
try {
// logDebug('Fetching name for ' + id);
// V2: Fetch first_name instead of name
const { data, error } = await supabase
.from('scouts')
.select('first_name')
.eq('id', id)
.single();
if (error) throw error;
if (data && data.first_name) {
document.getElementById('scout-name').textContent = data.first_name;
// logDebug('Name loaded: ' + data.first_name);
}
} catch (e) {
console.log('Could not fetch name', e);
// document.getElementById('scout-name').textContent = 'Fehler: ' + e.message;
}
}
async function initDashboard(scoutId) {
// Base URL for invite link - Default to fallback
let landingPageUrl = FALLBACK_LANDING_PAGE_URL;
let whatsappTextTemplate = `Hey, ich lade dich zu 7 Tagen Training ein! Hol dir hier deinen Pass: {{link}}`;
let rewardConfig = {};
// Fetch dynamic configuration from Campaign
try {
const { data: campaigns, error } = await supabase
.from('campaigns')
.select('scouting_text, landingpage_url, reward_config')
.eq('tenant_id', TENANT_ID)
.eq('status', 'active')
.limit(1);
if (campaigns && campaigns.length > 0) {
const campaign = campaigns[0];
if (campaign.scouting_text) {
// Fix: Handle literal "\n" from DB text fields as actual newlines for WhatsApp
whatsappTextTemplate = campaign.scouting_text.replace(/\\n/g, '\n');
}
if (campaign.landingpage_url) {
landingPageUrl = campaign.landingpage_url;
}
// Handle Reward Config
rewardConfig = campaign.reward_config || {};
console.log('Campaign Reward Config:', rewardConfig);
// Render Rewards
renderRewardBanner(rewardConfig);
}
} catch (err) {
console.warn('Could not load dynamic campaign settings', err);
}
let referralLink = `${landingPageUrl}?ref=${scoutId}`;
// NEW: Append campaign if available
if (currentCampaign) {
referralLink += `&campaign=${currentCampaign}`;
}
// 1. WhatsApp Link
const whatsappRefLink = `${referralLink}&source=wa`;
// Note: whatsappTextTemplate is defined above
const whatsappText = whatsappTextTemplate.replace('{{link}}', whatsappRefLink);
const whatsappUrl = `https://wa.me/?text=${encodeURIComponent(whatsappText)}`;
// 2. Email Link
const emailRefLink = `${referralLink}&source=em`;
const emailSubject = encodeURIComponent('Ich habe ein tolles Angebot für dich gefunden! 🎁');
const emailBody = encodeURIComponent('Hallo,\n\nich bin gerade auf dieses Angebot gestoßen und musste sofort an dich denken.\n\nSchau dir das mal an: ' + emailRefLink + '\n\nLiebe Grüße!');
const emailUrl = `mailto:?subject=${emailSubject}&body=${emailBody}`;
// Setup Buttons
const whatsappBtn = document.getElementById('whatsapp-btn');
whatsappBtn.href = whatsappUrl;
whatsappBtn.onclick = () => trackEvent('share_whatsapp', scoutId, { source: 'wa' });
// New: Email Button Logic
const emailBtn = document.getElementById('email-btn');
emailBtn.href = emailUrl;
emailBtn.onclick = () => trackEvent('share_email', scoutId, { source: 'em' });
// document.getElementById('debug-link').textContent = referralLink; // Optional Debug
const copyBtn = document.getElementById('copy-btn');
const copyText = document.getElementById('copy-text');
const copyIcon = document.getElementById('copy-icon');
copyBtn.onclick = () => {
trackEvent('share_copy', scoutId, { source: 'cp' });
// Copy Link with Source
const copyRefLink = `${referralLink}&source=cp`;
navigator.clipboard.writeText(copyRefLink).then(() => {
showToast();
// Button Animation
const originalText = copyText.innerText;
copyText.innerText = 'Kopiert!';
copyIcon.classList.remove('fa-copy', 'text-[#00b4d8]');
copyIcon.classList.add('fa-check', 'text-green-400');
setTimeout(() => {
copyText.innerText = originalText;
copyIcon.classList.remove('fa-check', 'text-green-400');
copyIcon.classList.add('fa-copy', 'text-[#00b4d8]');
}, 2000);
}).catch(err => {
console.error('Copy failed', err);
alert('Konnte Link nicht kopieren: ' + referralLink);
alert('Falls das Kopieren nicht geht (z.B. in In-App Browsern), kopiere den Link bitte manuell:\n' + referralLink);
});
};
// NEW: Save Link Logic (Sticky Feature)
// Save the Dashboard URL (this page) so the Scout can return later
let dashboardLink = window.location.origin + window.location.pathname + '?id=' + scoutId;
if (currentCampaign) {
dashboardLink += `&campaign=${currentCampaign}`;
}
const saveText = `Mein Link zum Scout-Dashboard (hier klicken zum Teilen): ${dashboardLink} \n(Am besten diese Nachricht an dich selbst schicken/speichern!)`;
const saveUrl = `https://wa.me/?text=${encodeURIComponent(saveText)}`;
const saveBtn = document.getElementById('save-btn');
saveBtn.href = saveUrl;
saveBtn.onclick = () => trackEvent('save_link', scoutId, { source: 'save' });
return rewardConfig;
}
// NEW: Load Live Stats & Achievements
async function loadStats(scoutId, rewardConfig) {
const loader = document.getElementById('stats-loader');
const container = document.getElementById('stats-container');
const emptyState = document.getElementById('stats-empty');
// const debugLog = document.getElementById('debug-link'); // reuse debug area
try {
// console.log('Loading stats for', scoutId);
// Fetch full invites to list them
const { data: invites, count, error } = await supabase
.from('invites')
.select('id, status, created_at, lead_data', { count: 'exact' })
.eq('scout_id', scoutId);
if (error) {
// check for potential RLS 403 or network error
logDebug(error.message);
throw error;
}
console.log('Stats loaded:', count);
// Hide loader
loader.classList.add('hidden');
// Elements
const countEl = document.getElementById('stats-count');
const rankEl = document.getElementById('stats-rank');
// Logic
if (count === null || count === 0) {
container.classList.add('hidden');
emptyState.classList.remove('hidden');
} else {
container.classList.remove('hidden');
emptyState.classList.add('hidden');
countEl.textContent = count;
// Determine Rank
let rankText = 'Rookie 🌱';
let rankClass = 'text-gray-400';
if (count >= 10) {
rankText = 'Legende 👑';
rankClass = 'text-yellow-400';
} else if (count >= 3) {
rankText = 'Influencer 🚀';
rankClass = 'text-indigo-400';
}
rankEl.textContent = rankText;
rankEl.className = `text-xl font-bold ${rankClass}`;
}
// Render Achievements List
if (rewardConfig && (rewardConfig.instant_reward?.active || rewardConfig.lottery?.active)) {
console.log('Rendering Achievements...', invites?.count); // Use matches or length? invites is data.
// Wait, invites is 'data'. count is 'count'.
// If invites is array.
renderAchievements(invites || [], rewardConfig);
}
} catch (err) {
console.error('Error loading stats:', err);
// Show Empty State on Error as fallback, but log it
loader.classList.add('hidden');
emptyState.classList.remove('hidden');
// Optional: Show error in debug area
// debugLog.innerText = 'Stats Error: ' + err.message;
}
}
function initRegistration() {
const form = document.getElementById('register-form');
const btn = document.getElementById('reg-btn');
const errorMsg = document.getElementById('reg-error');
form.addEventListener('submit', async (e) => {
e.preventDefault();
btn.disabled = true;
btn.textContent = 'Erstelle Account...';
errorMsg.classList.add('hidden');
const firstName = document.getElementById('reg-first-name').value;
const lastName = document.getElementById('reg-last-name').value;
const email = document.getElementById('reg-email').value;
try {
// Insert into Supabase
const { data, error } = await supabase
.from('scouts')
.insert({
tenant_id: TENANT_ID,
first_name: firstName,
last_name: lastName,
email: email,
stats: {} // Empty JSONB
})
.select(); // Return inserted record to get ID
if (error) throw error;
if (data && data.length > 0) {
const newScoutId = data[0].id;
console.log('Registered!', newScoutId);
// Redirect to self with new ID
window.location.href = `?id=${newScoutId}`;
} else {
throw new Error('No data returned');
}
} catch (err) {
console.error('Registration error:', err);
errorMsg.textContent = 'Fehler: ' + (err.message || 'Unbekannter Fehler');
errorMsg.classList.remove('hidden');
btn.disabled = false;
btn.textContent = 'Jetzt Scout werden 🚀';
}
});
}
function showToast() {
const toast = document.getElementById('toast');
toast.classList.remove('opacity-0');
setTimeout(() => {
toast.classList.add('opacity-0');
}, 2000);
}
// NEW: Render Reward Banner
function renderRewardBanner(config) {
if (!config) return;
const container = document.getElementById('reward-container');
container.innerHTML = '';
let hasContent = false;
// 1. Instant Reward
if (config.instant_reward && config.instant_reward.active) {
hasContent = true;
const r = config.instant_reward;
const card = document.createElement('div');
card.className = 'bg-yellow-900/20 border border-yellow-500/50 p-4 rounded-xl flex items-center gap-4 relative overflow-hidden mb-3';
card.innerHTML = `
<div class="absolute top-0 right-0 bg-yellow-500 text-black text-[10px] uppercase font-bold px-2 py-0.5 rounded-bl-lg">
Sofort-Belohnung
</div>
<div class="text-4xl filter drop-shadow-[0_0_10px_rgba(234,179,8,0.5)]">
${r.icon || '🎁'}
</div>
<div class="text-left">
<h3 class="text-yellow-400 font-bold leading-tight">${r.title || 'Belohnung'}</h3>
<p class="text-yellow-100/80 text-xs mt-1 leading-snug">${r.description || ''}</p>
${r.valid_until ? `<div class="mt-1 text-[10px] text-yellow-500/80">Aktion bis: ${new Date(r.valid_until).toLocaleDateString('de-DE')}</div>` : ''}
</div>
`;
container.appendChild(card);
}
// 2. Lottery
if (config.lottery && config.lottery.active) {
hasContent = true;
const l = config.lottery;
const card = document.createElement('div');
card.className = 'bg-indigo-900/20 border border-indigo-500/50 p-4 rounded-xl flex items-center gap-4 relative overflow-hidden';
card.innerHTML = `
<div class="absolute top-0 right-0 bg-indigo-500 text-white text-[10px] uppercase font-bold px-2 py-0.5 rounded-bl-lg">
Gewinnspiel
</div>
<div class="text-4xl filter drop-shadow-[0_0_10px_rgba(99,102,241,0.5)]">
${l.icon || '🎟️'}
</div>
<div class="text-left">
<h3 class="text-indigo-400 font-bold leading-tight">${l.title || 'Verlosung'}</h3>
<p class="text-indigo-100/80 text-xs mt-1 leading-snug">${l.description || ''}</p>
${l.draw_date ? `<div class="mt-1.5 text-[10px] text-indigo-300 bg-indigo-900/40 inline-block px-1.5 py-0.5 rounded border border-indigo-500/20">📅 Auslosung: ${new Date(l.draw_date).toLocaleDateString('de-DE')}</div>` : ''}
${l.valid_until ? `<div class="mt-1.5 ml-1 text-[10px] text-indigo-300 bg-indigo-900/40 inline-block px-1.5 py-0.5 rounded border border-indigo-500/20">⏳ Bis: ${new Date(l.valid_until).toLocaleDateString('de-DE')}</div>` : ''}
</div>
`;
container.appendChild(card);
}
if (hasContent) {
container.classList.remove('hidden');
}
}
// NEW: Render Achievements List
function renderAchievements(invites, config) {
const container = document.getElementById('achievements-container');
container.innerHTML = '';
container.classList.remove('hidden');
// NEW: Helper for Date Checks
const isDateInScope = (dateStr, validFrom, validUntil) => {
const d = new Date(dateStr);
if (validFrom && new Date(validFrom) > d) return false;
if (validUntil && new Date(validUntil) < d) return false;
return true;
};
// Filter relevant invites (e.g. lead_captured or completed)
// For now assuming all invites that are not 'clicked' (so actual leads)
const allLeads = invites.filter(i => i.status && i.status !== 'clicked' && i.status !== 'viewed');
// Log for debugging
console.log('Total Leads (All Time):', allLeads.length);
// if (leads.length === 0) return; // Removed early return to show "0 Tickets" if desired
// 1. Lottery Logic
if (config.lottery && config.lottery.active) {
// Filter leads by lottery date scope
const validLeads = allLeads.filter(l => isDateInScope(l.created_at, config.lottery.valid_from, config.lottery.valid_until));
const tickets = validLeads.length;
const lotus = document.createElement('div');
lotus.className = 'bg-gradient-to-r from-indigo-900/40 to-purple-900/40 border border-indigo-500/30 p-4 rounded-xl mb-6 text-center shadow-lg';
lotus.innerHTML = `
<div class="text-3xl mb-1">🎟️ <span class="text-white font-bold">${tickets}</span> <span class="text-indigo-200 text-lg">Lose</span></div>
<div class="text-xs text-indigo-300 uppercase tracking-wide">Im Lostopf für ${config.lottery.title || 'das Gewinnspiel'}</div>
${tickets < allLeads.length ? `<div class="text-[10px] text-gray-500 mt-1">(${allLeads.length - tickets} abgelaufen/außerhalb Zeitraum)</div>` : ''}
`;
container.appendChild(lotus);
}
// 2. Instant Rewards List
if (config.instant_reward && config.instant_reward.active && allLeads.length > 0) {
// Title
const title = document.createElement('h3');
title.className = 'text-gray-400 text-sm font-bold uppercase tracking-wider mb-3 pl-1';
title.innerHTML = `Deine Prämien & Erfolge`;
container.appendChild(title);
const list = document.createElement('div');
list.className = 'flex flex-col gap-2';
allLeads.forEach(lead => {
// Check validity
const isValid = isDateInScope(lead.created_at, config.instant_reward.valid_from, config.instant_reward.valid_until);
// Try to parse lead_name
let name = 'Ein Freund';
if (lead.lead_data) {
if (typeof lead.lead_data === 'string') {
try { const d = JSON.parse(lead.lead_data); name = d.first_name || name; } catch(e){}
} else {
name = lead.lead_data.first_name || name;
}
}
// Item
const item = document.createElement('div');
item.className = `bg-[#1a1a1a] border ${isValid ? 'border-gray-800' : 'border-red-900/30'} p-3 rounded-lg flex items-center justify-between ${isValid ? '' : 'opacity-50 grayscale'}`;
// Simple logic: If lead exists -> Status "Verdient" (green)
// In future we could check "reward_claimed" flag.
const isEarned = true;
item.innerHTML = `
<div class="flex items-center gap-3">
<div class="bg-gray-800 h-8 w-8 rounded-full flex items-center justify-center text-lg">
${isEarned ? (isValid ? '✅' : '🕰️') : '⏳'}
</div>
<div class="text-left">
<div class="text-sm text-white font-bold">${name}</div>
<div class="text-xs text-yellow-500">${config.instant_reward.title}</div>
</div>
</div>
<div class="text-xs ${isValid ? 'bg-green-500/20 text-green-400 border-green-500/30' : 'bg-gray-700/50 text-gray-500 border-gray-600'} border px-2 py-0.5 rounded font-medium">
${isValid ? 'Verdient' : 'Abgelaufen'}
</div>
`;
list.appendChild(item);
});
container.appendChild(list);
}
}
// Run
initApp();
</script>
</body>
</html>