Spaces:
Running
Running
π³ 14/04 - 17:39 - Build a trending algorithm.Tracks rank higher based on:- Number of plays- Number of unlocks- Recent activity (last 24β48 hours)Add:- βTrending Nowβ section- βRising BeatsβUpdate ran
6b2c51b verified Download app.js from Onttraders/BeatFridge: direct link, hf CLI and curl.
- Browser
- Download file 132 kB
-
https://huggingface.co/spaces/Onttraders/BeatFridge/resolve/main/app.js
- Command line
-
hf download hf://spaces/Onttraders/BeatFridge/app.js
-
curl -L -o app.js https://huggingface.co/spaces/Onttraders/BeatFridge/resolve/main/app.js
132 kB
// BeatFridge - Core Application Logic
const BF = (() => {
// ===== DEFAULT DATA =====
const defaultTracks = [
{ id: 1, title: "Neon Horizons", artist: "Aurora Void", artistId: "aurora-void", duration: "4:32", image: "http://static.photos/technology/400x400/1", plays: "12.5K", genre: "techno", date: "2 days ago" },
{ id: 2, title: "Digital Rain", artist: "Aurora Void", artistId: "aurora-void", duration: "3:45", image: "http://static.photos/technology/400x400/2", plays: "8.2K", genre: "ambient", date: "5 days ago" },
{ id: 3, title: "Cybernetic Dreams", artist: "Aurora Void", artistId: "aurora-void", duration: "5:18", image: "http://static.photos/technology/400x400/3", plays: "24.1K", genre: "techno", date: "1 week ago" },
{ id: 4, title: "Analog Heart", artist: "Aurora Void", artistId: "aurora-void", duration: "3:22", image: "http://static.photos/technology/400x400/4", plays: "15.3K", genre: "synthwave", date: "2 weeks ago" },
{ id: 5, title: "Midnight Synthesis", artist: "Aurora Void", artistId: "aurora-void", duration: "4:08", image: "http://static.photos/technology/400x400/5", plays: "32.7K", genre: "techno", date: "3 weeks ago" },
{ id: 6, title: "Void Walker", artist: "Aurora Void", artistId: "aurora-void", duration: "6:14", image: "http://static.photos/technology/400x400/6", plays: "9.8K", genre: "ambient", date: "1 month ago" },
{ id: 7, title: "Electric Soul", artist: "Neon Prophet", artistId: "neon-prophet", duration: "3:55", image: "http://static.photos/technology/400x400/7", plays: "18.4K", genre: "house", date: "3 days ago" },
{ id: 8, title: "Digital Horizon", artist: "Cyber Dreamer", artistId: "cyber-dreamer", duration: "4:15", image: "http://static.photos/technology/400x400/8", plays: "11.2K", genre: "synthwave", date: "1 week ago" },
{ id: 9, title: "Deep Pulse", artist: "Deep Frequencies", artistId: "deep-freq", duration: "6:18", image: "http://static.photos/technology/400x400/9", plays: "7.6K", genre: "techno", date: "4 days ago" },
{ id: 10, title: "Neon City", artist: "Neon Prophet", artistId: "neon-prophet", duration: "4:22", image: "http://static.photos/technology/400x400/10", plays: "14.1K", genre: "synthwave", date: "6 days ago" },
{ id: 11, title: "Binary Sunset", artist: "Synth Wanderer", artistId: "synth-wanderer", duration: "5:02", image: "http://static.photos/technology/400x400/11", plays: "6.3K", genre: "ambient", date: "2 weeks ago" },
{ id: 12, title: "Crystal Waves", artist: "Cyber Dreamer", artistId: "cyber-dreamer", duration: "3:38", image: "http://static.photos/technology/400x400/12", plays: "19.7K", genre: "house", date: "1 day ago" }
];
const defaultArtists = [
{ id: "aurora-void", name: "Aurora Void", followers: "128.5K", image: "http://static.photos/people/200x200/77", genre: "Electronic", verified: true },
{ id: "neon-prophet", name: "Neon Prophet", followers: "45.2K", image: "http://static.photos/people/200x200/10", genre: "Techno", verified: false },
{ id: "cyber-dreamer", name: "Cyber Dreamer", followers: "32.8K", image: "http://static.photos/people/200x200/11", genre: "Synthwave", verified: false },
{ id: "synth-wanderer", name: "Synth Wanderer", followers: "28.1K", image: "http://static.photos/people/200x200/12", genre: "Ambient", verified: false },
{ id: "deep-freq", name: "Deep Frequencies", followers: "15.7K", image: "http://static.photos/people/200x200/13", genre: "Techno", verified: false },
{ id: "bass-architect", name: "Bass Architect", followers: "22.4K", image: "http://static.photos/people/200x200/14", genre: "Drum & Bass", verified: true }
];
const genres = [
{ name: "Techno", icon: "waves", color: "cyan" },
{ name: "Ambient", icon: "cloud", color: "purple" },
{ name: "House", icon: "flame", color: "orange" },
{ name: "Synthwave", icon: "zap", color: "pink" },
{ name: "Lo-Fi", icon: "leaf", color: "green" },
{ name: "Drum & Bass", icon: "activity", color: "red" }
];
// ===== AUTH =====
const isLoggedIn = () => localStorage.getItem('isLoggedIn') === 'true';
const isProducer = () => {
try {
const user = JSON.parse(localStorage.getItem('beatfridge_current_user'));
return user && (user.role === 'producer' || (!user.role && user.isArtist));
} catch { return false; }
};
const isFan = () => {
try {
const user = JSON.parse(localStorage.getItem('beatfridge_current_user'));
return user && user.role === 'fan';
} catch { return false; }
};
const getCurrentUser = () => {
try {
return JSON.parse(localStorage.getItem('beatfridge_current_user')) || null;
} catch { return null; }
};
const signIn = (identifier, password) => {
try {
const users = JSON.parse(localStorage.getItem('beatfridge_users') || '[]');
const user = users.find(u => (u.username === identifier || u.email === identifier) && u.password === password);
if (user) {
localStorage.setItem('beatfridge_current_user', JSON.stringify(user));
localStorage.setItem('isLoggedIn', 'true');
localStorage.setItem('currentUserId', user.id);
return { success: true, user };
}
return { success: false, error: 'Invalid username or password' };
} catch {
return { success: false, error: 'Sign in failed' };
}
};
const signOut = () => {
localStorage.removeItem('beatfridge_current_user');
localStorage.removeItem('isLoggedIn');
localStorage.removeItem('currentUserId');
window.location.href = 'index.html';
};
const signUp = (userData) => {
try {
const users = JSON.parse(localStorage.getItem('beatfridge_users') || '[]');
if (users.find(u => u.username.toLowerCase() === userData.username.toLowerCase())) {
return { success: false, error: 'Username is already taken' };
}
if (users.find(u => u.email.toLowerCase() === userData.email.toLowerCase())) {
return { success: false, error: 'Email is already registered' };
}
const role = userData.role || 'fan';
const newUser = {
id: (role === 'producer' ? 'producer_' : 'fan_') + Date.now(),
username: userData.username,
email: userData.email,
password: userData.password,
displayName: userData.displayName || userData.username,
avatar: userData.avatar || 'http://static.photos/people/200x200/' + Math.floor(Math.random() * 100),
role: role,
isArtist: role === 'producer',
createdAt: new Date().toISOString(),
bio: '',
location: '',
followers: 0,
following: [],
tracks: [],
likes: 0,
reposts: 0
};
users.push(newUser);
localStorage.setItem('beatfridge_users', JSON.stringify(users));
localStorage.setItem('beatfridge_current_user', JSON.stringify(newUser));
localStorage.setItem('isLoggedIn', 'true');
localStorage.setItem('currentUserId', newUser.id);
// Record referral if applicable
try {
const pendingRef = sessionStorage.getItem('bf_pending_referral');
if (pendingRef) { recordReferralSignup(pendingRef); sessionStorage.removeItem('bf_pending_referral'); }
} catch {}
return { success: true, user: newUser };
} catch (e) {
return { success: false, error: 'Sign up failed: ' + e.message };
}
};
// ===== TRACKS =====
const getAllTracks = () => {
try {
const userTracks = JSON.parse(localStorage.getItem('userTracks') || '[]');
const bfTracks = JSON.parse(localStorage.getItem('beatfridge_tracks') || '[]');
const seen = new Set();
const all = [...defaultTracks, ...userTracks, ...bfTracks];
return all.filter(t => {
if (seen.has(t.id)) return false;
seen.add(t.id);
return true;
});
} catch { return [...defaultTracks]; }
};
const getArtists = () => {
try {
const user = getCurrentUser();
if (user && (user.role === 'producer' || (!user.role && user.isArtist))) {
const exists = defaultArtists.find(a => a.id === user.id);
if (!exists) {
return [{ id: user.id, name: user.displayName || user.username, followers: user.followers || "0", image: user.avatar || 'http://static.photos/people/200x200/42', genre: "Electronic", verified: false, isUser: true }, ...defaultArtists];
}
}
} catch (e) { console.error('getArtists error:', e); }
return [...defaultArtists];
};
const getGenres = () => [...genres];
const getTrendingTracks = () => {
const shareCounts = {};
try { Object.assign(shareCounts, JSON.parse(localStorage.getItem('bf_track_shares') || '{}')); } catch {}
const unlockCounts = {};
try { JSON.parse(localStorage.getItem('bf_download_states') || '[]').forEach(s => { if (s.unlocked) unlockCounts[s.trackId] = (unlockCounts[s.trackId] || 0) + 1; }); } catch {}
const recentActivity = {};
try { Object.assign(recentActivity, JSON.parse(localStorage.getItem('bf_recent_activity') || '{}')); } catch {}
const now = Date.now();
const HOUR = 3600000;
let prevRankings = {};
try { prevRankings = JSON.parse(localStorage.getItem('bf_prev_rankings') || '{}'); } catch {}
const ranked = getAllTracks().map(t => {
const p = parseFloat(t.plays || '0');
const plays = (t.plays || '').includes('K') ? p * 1000 : p;
const shares = shareCounts[t.id] || 0;
const unlocks = unlockCounts[t.id] || 0;
// Base score
const baseScore = plays + (unlocks * 10) + (shares * 5);
// Recency boost: recent activity gets exponential weight
const act = recentActivity[t.id] || { lastPlay: 0, lastUnlock: 0, recentPlays: 0, recentUnlocks: 0 };
const hoursSincePlay = act.lastPlay ? (now - act.lastPlay) / HOUR : Infinity;
const hoursSinceUnlock = act.lastUnlock ? (now - act.lastUnlock) / HOUR : Infinity;
let recencyBoost = 1;
if (hoursSincePlay < 24) recencyBoost *= 3;
else if (hoursSincePlay < 48) recencyBoost *= 2;
else if (hoursSincePlay < 72) recencyBoost *= 1.5;
if (hoursSinceUnlock < 24) recencyBoost *= 2.5;
else if (hoursSinceUnlock < 48) recencyBoost *= 1.8;
// Recent volume boost
const recentVolumeBoost = Math.min((act.recentPlays || 0) / 100, 5) + Math.min((act.recentUnlocks || 0) / 5, 3);
// New upload bonus
let uploadBonus = 0;
if (t.publishedAt) {
const hoursSinceUpload = (now - new Date(t.publishedAt).getTime()) / HOUR;
if (hoursSinceUpload < 24) uploadBonus = 500;
else if (hoursSinceUpload < 48) uploadBonus = 300;
else if (hoursSinceUpload < 72) uploadBonus = 100;
}
const trendScore = (baseScore * recencyBoost) + (recentVolumeBoost * 100) + uploadBonus;
const prevRank = prevRankings[t.id] || null;
return { ...t, _trendScore: trendScore, _recencyBoost: recencyBoost, _recentPlays: act.recentPlays || 0, _recentUnlocks: act.recentUnlocks || 0, _prevRank: prevRank };
}).sort((a, b) => b._trendScore - a._trendScore);
// Save current rankings for position-change tracking
const newRankings = {};
ranked.forEach((t, i) => { newRankings[t.id] = i + 1; });
try { localStorage.setItem('bf_current_rankings', JSON.stringify(newRankings)); } catch {}
return ranked.map((t, i) => ({
...t,
_rank: i + 1,
_rankChange: t._prevRank ? (t._prevRank - (i + 1)) : 0
}));
};
// ===== RISING BEATS =====
const getRisingBeats = () => {
const recentActivity = {};
try { Object.assign(recentActivity, JSON.parse(localStorage.getItem('bf_recent_activity') || '{}')); } catch {}
const shareCounts = {};
try { Object.assign(shareCounts, JSON.parse(localStorage.getItem('bf_track_shares') || '{}')); } catch {}
const unlockCounts = {};
try { JSON.parse(localStorage.getItem('bf_download_states') || '[]').forEach(s => { if (s.unlocked) unlockCounts[s.trackId] = (unlockCounts[s.trackId] || 0) + 1; }); } catch {}
const now = Date.now();
const HOUR = 3600000;
return getAllTracks().map(t => {
const p = parseFloat(t.plays || '0');
const totalPlays = (t.plays || '').includes('K') ? p * 1000 : p;
const shares = shareCounts[t.id] || 0;
const unlocks = unlockCounts[t.id] || 0;
const act = recentActivity[t.id] || { recentPlays: 0, recentUnlocks: 0, recentShares: 0 };
const recentScore = ((act.recentPlays || 0) * 1) + ((act.recentUnlocks || 0) * 10) + ((act.recentShares || 0) * 5);
// Velocity: how fast is it growing relative to total
const velocityScore = totalPlays > 0 ? (recentScore / totalPlays) * 1000 : (recentScore > 0 ? 500 : 0);
// New upload bonus β fresh tracks get a big boost
let uploadBonus = 0;
if (t.publishedAt) {
const hoursSinceUpload = (now - new Date(t.publishedAt).getTime()) / HOUR;
if (hoursSinceUpload < 12) uploadBonus = 800;
else if (hoursSinceUpload < 24) uploadBonus = 500;
else if (hoursSinceUpload < 48) uploadBonus = 300;
else if (hoursSinceUpload < 72) uploadBonus = 100;
}
// Also check date field for older tracks
if (!t.publishedAt && t.date) {
const d = t.date.toLowerCase();
if (d.includes('just') || d.includes('minute') || d.includes('hour')) uploadBonus = Math.max(uploadBonus, 400);
else if (d.includes('1 day') || d.includes('2 day')) uploadBonus = Math.max(uploadBonus, 200);
}
const risingScore = (recentScore * 3) + velocityScore + uploadBonus;
return {
...t,
_risingScore: risingScore,
_recentPlays: act.recentPlays || 0,
_recentUnlocks: act.recentUnlocks || 0,
_recentShares: act.recentShares || 0,
_velocity: velocityScore
};
})
.filter(t => t._risingScore > 10)
.sort((a, b) => b._risingScore - a._risingScore);
};
// ===== TREND INDICATOR =====
const getTrackTrendIndicator = (trackId) => {
try {
const prev = JSON.parse(localStorage.getItem('bf_prev_rankings') || '{}');
const cur = JSON.parse(localStorage.getItem('bf_current_rankings') || '{}');
const prevPos = prev[trackId];
const curPos = cur[trackId];
if (!prevPos && !curPos) return { direction: 'new', arrow: 'π', label: 'New', cssClass: 'text-gray-400' };
if (!prevPos) return { direction: 'new', arrow: 'π', label: 'New', cssClass: 'text-cyan-400' };
const change = prevPos - curPos;
if (change > 2) return { direction: 'up', arrow: 'β', label: '+' + change, cssClass: 'text-green-400' };
if (change > 0) return { direction: 'up', arrow: 'β', label: '+' + change, cssClass: 'text-green-400' };
if (change < -2) return { direction: 'down', arrow: 'β', label: '' + change, cssClass: 'text-red-400' };
if (change < 0) return { direction: 'down', arrow: 'β', label: '' + change, cssClass: 'text-red-400' };
return { direction: 'stable', arrow: 'β', label: 'β', cssClass: 'text-gray-600' };
} catch {
return { direction: 'stable', arrow: 'β', label: 'β', cssClass: 'text-gray-600' };
}
};
// ===== ACTIVITY RECORDING =====
const recordActivity = (trackId, type) => {
try {
let activity = JSON.parse(localStorage.getItem('bf_recent_activity') || '{}');
if (!activity[trackId]) activity[trackId] = { lastPlay: 0, lastUnlock: 0, lastShare: 0, recentPlays: 0, recentUnlocks: 0, recentShares: 0 };
const now = Date.now();
const cutoff = now - (48 * 3600000); // 48h window
// Reset counters if data is stale
if ((activity[trackId]._lastReset || 0) < cutoff) {
activity[trackId].recentPlays = 0;
activity[trackId].recentUnlocks = 0;
activity[trackId].recentShares = 0;
activity[trackId]._lastReset = now;
}
if (type === 'play') { activity[trackId].lastPlay = now; activity[trackId].recentPlays = (activity[trackId].recentPlays || 0) + 1; }
else if (type === 'unlock') { activity[trackId].lastUnlock = now; activity[trackId].recentUnlocks = (activity[trackId].recentUnlocks || 0) + 1; }
else if (type === 'share') { activity[trackId].lastShare = now; activity[trackId].recentShares = (activity[trackId].recentShares || 0) + 1; }
localStorage.setItem('bf_recent_activity', JSON.stringify(activity));
} catch {}
};
// ===== SIMULATE RECENT ACTIVITY (demo data) =====
const simulateRecentActivity = () => {
try {
let activity = JSON.parse(localStorage.getItem('bf_recent_activity') || '{}');
const allTracks = getAllTracks();
const now = Date.now();
const HOUR = 3600000;
// Generate plausible recent activity for top tracks
allTracks.forEach((t, i) => {
if (!activity[t.id]) activity[t.id] = { lastPlay: 0, lastUnlock: 0, lastShare: 0, recentPlays: 0, recentUnlocks: 0, recentShares: 0, _lastReset: now };
const p = parseFloat(t.plays || '0');
const totalPlays = (t.plays || '').includes('K') ? p * 1000 : p;
// Top tracks get more recent activity
if (i < 3) {
activity[t.id].recentPlays = Math.floor(200 + Math.random() * 400);
activity[t.id].recentUnlocks = Math.floor(10 + Math.random() * 25);
activity[t.id].recentShares = Math.floor(5 + Math.random() * 15);
activity[t.id].lastPlay = now - (Math.random() * 12 * HOUR);
activity[t.id].lastUnlock = now - (Math.random() * 24 * HOUR);
} else if (i < 6) {
activity[t.id].recentPlays = Math.floor(80 + Math.random() * 200);
activity[t.id].recentUnlocks = Math.floor(3 + Math.random() * 12);
activity[t.id].recentShares = Math.floor(2 + Math.random() * 8);
activity[t.id].lastPlay = now - (Math.random() * 24 * HOUR);
} else {
activity[t.id].recentPlays = Math.floor(10 + Math.random() * 80);
activity[t.id].recentUnlocks = Math.floor(Math.random() * 5);
activity[t.id].recentShares = Math.floor(Math.random() * 3);
}
// Freshly uploaded tracks get extra boost
if (t.date && (t.date.includes('Just') || t.date.includes('hour') || t.date.includes('minute'))) {
activity[t.id].recentPlays += Math.floor(100 + Math.random() * 300);
activity[t.id].recentUnlocks += Math.floor(5 + Math.random() * 15);
activity[t.id].lastPlay = now - (Math.random() * 4 * HOUR);
}
});
activity._simulated = true;
localStorage.setItem('bf_recent_activity', JSON.stringify(activity));
} catch {}
};
// ===== SAVE RANKINGS SNAPSHOT =====
const saveRankingSnapshot = () => {
try {
const current = JSON.parse(localStorage.getItem('bf_current_rankings') || '{}');
localStorage.setItem('bf_prev_rankings', JSON.stringify(current));
} catch {}
};
// ===== SHARE TRACKING =====
const trackShare = (trackId) => {
try {
let shares = JSON.parse(localStorage.getItem('bf_track_shares') || '{}');
shares[trackId] = (shares[trackId] || 0) + 1;
localStorage.setItem('bf_track_shares', JSON.stringify(shares));
recordActivity(trackId, 'share');
} catch {}
};
const getShareCount = (trackId) => {
try { return (JSON.parse(localStorage.getItem('bf_track_shares') || '{}'))[trackId] || 0; }
catch { return 0; }
};
const getUnlockCount = (trackId) => {
try { return JSON.parse(localStorage.getItem('bf_download_states') || '[]').filter(s => s.trackId === trackId && s.unlocked).length; }
catch { return 0; }
};
// ===== REFERRAL SYSTEM =====
const getReferralCode = () => {
const user = getCurrentUser();
if (!user) return null;
try {
let refs = JSON.parse(localStorage.getItem('bf_referral_codes') || '{}');
const uid = user.id;
if (refs[uid]) return refs[uid];
const prefix = (user.username || 'usr').substring(0, 3).toUpperCase();
const code = prefix + Math.floor(1000 + Math.random() * 9000);
refs[uid] = code;
localStorage.setItem('bf_referral_codes', JSON.stringify(refs));
return code;
} catch { return null; }
};
const recordReferralSignup = (referralCode) => {
if (!referralCode) return;
try {
let referrals = JSON.parse(localStorage.getItem('bf_referrals') || '[]');
referrals.push({ code: referralCode, newUserId: getCurrentUser()?.id, date: new Date().toISOString(), status: 'pending' });
localStorage.setItem('bf_referrals', JSON.stringify(referrals));
} catch {}
};
const getReferralStats = () => {
const user = getCurrentUser();
if (!user) return { code: null, clicks: 0, signups: 0, earnings: 0 };
const code = getReferralCode();
try {
const referrals = JSON.parse(localStorage.getItem('bf_referrals') || '[]');
const clicks = JSON.parse(localStorage.getItem('bf_referral_clicks') || '{}');
const userRefs = referrals.filter(r => r.code === code);
return { code, clicks: clicks[code] || 0, signups: userRefs.length, earnings: userRefs.filter(r => r.status === 'confirmed').length * 5, pendingEarnings: userRefs.filter(r => r.status === 'pending').length * 5 };
} catch { return { code, clicks: 0, signups: 0, earnings: 0 }; }
};
const trackReferralClick = (referralCode) => {
if (!referralCode) return;
try {
let clicks = JSON.parse(localStorage.getItem('bf_referral_clicks') || '{}');
clicks[referralCode] = (clicks[referralCode] || 0) + 1;
localStorage.setItem('bf_referral_clicks', JSON.stringify(clicks));
sessionStorage.setItem('bf_pending_referral', referralCode);
} catch {}
};
// ===== SHARE MODAL =====
const showShareModal = (trackTitle, artistName, trackId) => {
if (document.getElementById('bfShareModal')) return;
const baseUrl = window.location.origin;
let url = baseUrl + '/track.html?id=' + trackId;
if (isLoggedIn()) { const rc = getReferralCode(); if (rc) url += '&ref=' + rc; }
const shareText = 'Check out this beat on BeatFridge: ' + trackTitle + ' by ' + artistName;
const safeT = String(trackTitle).replace(/'/g, "\\'").replace(/"/g, '"');
const safeA = String(artistName).replace(/'/g, "\\'").replace(/"/g, '"');
const modal = document.createElement('div');
modal.id = 'bfShareModal';
modal.innerHTML = `
<div class="bf-signin-overlay" onclick="BF.closeShareModal()"></div>
<div class="bf-signin-modal">
<div class="bf-signin-card" style="max-width:380px">
<div class="flex items-center justify-between mb-5">
<h3 class="text-lg font-bold text-white flex items-center gap-2"><i data-lucide="share-2" class="w-5 h-5 text-purple-400"></i>Share This Beat</h3>
<button onclick="BF.closeShareModal()" class="text-gray-400 hover:text-white transition"><i data-lucide="x" class="w-5 h-5"></i></button>
</div>
<div class="flex items-center gap-3 mb-4 p-3 rounded-xl bg-white/5">
<i data-lucide="music" class="w-5 h-5 text-cyan-400 flex-shrink-0"></i>
<div class="min-w-0"><p class="text-sm font-medium text-white truncate">${trackTitle}</p><p class="text-xs text-gray-500">${artistName}</p></div>
</div>
<p class="text-xs text-gray-500 mb-4 px-1">"${shareText}"</p>
<div class="space-y-2 mb-4">
<button onclick="BF.shareViaWhatsApp(${trackId},'${safeT}','${safeA}')" class="bf-share-platform bg-green-500/5 border-green-500/20 hover:bg-green-500/10 hover:border-green-500/40">
<div class="w-10 h-10 rounded-full bg-green-500/15 flex items-center justify-center flex-shrink-0"><svg viewBox="0 0 24 24" class="w-5 h-5 text-green-400" fill="currentColor"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.981.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.88 11.88 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/></svg></div>
<div><p class="text-sm font-semibold text-green-400">WhatsApp</p><p class="text-xs text-gray-500">Share via WhatsApp</p></div>
</button>
<button onclick="BF.shareViaFacebook(${trackId},'${safeT}','${safeA}')" class="bf-share-platform bg-blue-500/5 border-blue-500/20 hover:bg-blue-500/10 hover:border-blue-500/40">
<div class="w-10 h-10 rounded-full bg-blue-500/15 flex items-center justify-center flex-shrink-0"><i data-lucide="facebook" class="w-5 h-5 text-blue-400"></i></div>
<div><p class="text-sm font-semibold text-blue-400">Facebook</p><p class="text-xs text-gray-500">Share on your timeline</p></div>
</button>
<button onclick="BF.shareViaTwitter(${trackId},'${safeT}','${safeA}')" class="bf-share-platform bg-sky-500/5 border-sky-500/20 hover:bg-sky-500/10 hover:border-sky-500/40">
<div class="w-10 h-10 rounded-full bg-sky-500/15 flex items-center justify-center flex-shrink-0"><i data-lucide="twitter" class="w-5 h-5 text-sky-400"></i></div>
<div><p class="text-sm font-semibold text-sky-400">Twitter / X</p><p class="text-xs text-gray-500">Tweet this beat</p></div>
</button>
<button onclick="BF.copyTrackLink(${trackId},'${safeT}','${safeA}')" class="bf-share-platform bg-white/[0.03] border-white/10 hover:bg-white/[0.06] hover:border-white/20">
<div class="w-10 h-10 rounded-full bg-white/10 flex items-center justify-center flex-shrink-0"><i data-lucide="link" class="w-5 h-5 text-gray-400"></i></div>
<div><p class="text-sm font-semibold text-white">Copy Link</p><p class="text-xs text-gray-500">Copy track URL to clipboard</p></div>
</button>
</div>
${isLoggedIn() ? `<div class="p-3 rounded-xl bg-orange-500/5 border border-orange-500/15"><div class="flex items-center gap-2 mb-1"><i data-lucide="gift" class="w-4 h-4 text-orange-400"></i><p class="text-xs font-semibold text-orange-400">Share & Earn</p></div><p class="text-[11px] text-gray-500">Your link includes your referral code. Earn rewards when new users sign up through your shares.</p></div>` : ''}
</div>
</div>
`;
document.body.appendChild(modal);
if (window.lucide) lucide.createIcons();
};
const closeShareModal = () => { document.getElementById('bfShareModal')?.remove(); };
const shareViaWhatsApp = (trackId, trackTitle, artistName) => {
trackShare(trackId);
let url = window.location.origin + '/track.html?id=' + trackId;
if (isLoggedIn()) { const rc = getReferralCode(); if (rc) url += '&ref=' + rc; }
const text = 'Check out this beat on BeatFridge: ' + trackTitle + ' by ' + artistName + ' ' + url;
window.open('https://wa.me/?text=' + encodeURIComponent(text), '_blank');
closeShareModal();
showToast('Shared via WhatsApp π±');
};
const shareViaFacebook = (trackId, trackTitle, artistName) => {
trackShare(trackId);
let url = window.location.origin + '/track.html?id=' + trackId;
if (isLoggedIn()) { const rc = getReferralCode(); if (rc) url += '&ref=' + rc; }
window.open('https://www.facebook.com/sharer/sharer.php?u=' + encodeURIComponent(url), '_blank');
closeShareModal();
showToast('Shared on Facebook π');
};
const shareViaTwitter = (trackId, trackTitle, artistName) => {
trackShare(trackId);
let url = window.location.origin + '/track.html?id=' + trackId;
if (isLoggedIn()) { const rc = getReferralCode(); if (rc) url += '&ref=' + rc; }
const text = 'Check out this beat on BeatFridge: ' + trackTitle + ' by ' + artistName + ' π΅ ' + url;
window.open('https://twitter.com/intent/tweet?text=' + encodeURIComponent(text), '_blank');
closeShareModal();
showToast('Shared on Twitter π¦');
};
const copyTrackLink = (trackId, trackTitle, artistName) => {
trackShare(trackId);
let url = window.location.origin + '/track.html?id=' + trackId;
if (isLoggedIn()) { const rc = getReferralCode(); if (rc) url += '&ref=' + rc; }
navigator.clipboard.writeText(url).then(() => {
closeShareModal();
showToast('Link copied! Share it anywhere π');
}).catch(() => {
const input = document.createElement('input');
input.value = url;
document.body.appendChild(input);
input.select();
document.execCommand('copy');
input.remove();
closeShareModal();
showToast('Link copied! π');
});
};
// ===== RENDER SHARE BUTTON =====
const renderShare = (trackId, trackTitle, artistName) => {
const safeTitle = String(trackTitle).replace(/'/g, "\\'").replace(/"/g, '"');
const safeArtist = String(artistName).replace(/'/g, "\\'").replace(/"/g, '"');
return `<button class="bf-share-btn" onclick="event.stopPropagation(); BF.showShareModal('${safeTitle}', '${safeArtist}', ${trackId})"><i data-lucide="share-2" class="w-3 h-3"></i>Share</button>`;
};
const getFreshUploads = () => {
return getAllTracks().filter(t => t.date && (t.date.includes('day') || t.date.includes('hour') || t.date.includes('Just') || t.date.includes('minute')));
};
const searchTracks = (query) => {
const q = query.toLowerCase().trim();
if (!q) return [];
return getAllTracks().filter(t => t.title.toLowerCase().includes(q) || t.artist.toLowerCase().includes(q) || (t.genre && t.genre.toLowerCase().includes(q)));
};
const searchArtists = (query) => {
const q = query.toLowerCase().trim();
if (!q) return [];
return getArtists().filter(a => a.name.toLowerCase().includes(q) || (a.genre && a.genre.toLowerCase().includes(q)));
};
// ===== UI: STYLES =====
const injectStyles = () => {
if (document.getElementById('bf-app-styles')) return;
const style = document.createElement('style');
style.id = 'bf-app-styles';
style.textContent = `
.bottom-tab-bar {
position: fixed; bottom: 0; left: 0; right: 0; z-index: 60;
display: flex; align-items: center; justify-content: space-around;
height: 56px; background: rgba(15,15,15,0.95); backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px); border-top: 1px solid rgba(255,255,255,0.08);
padding: 0 8px; padding-bottom: env(safe-area-inset-bottom, 0px);
}
.bottom-tab {
display: flex; flex-direction: column; align-items: center; justify-content: center;
flex: 1; height: 100%; text-decoration: none; color: #6b7280;
transition: color 0.2s; font-size: 10px; gap: 2px; position: relative;
}
.bottom-tab i, .bottom-tab svg { width: 20px; height: 20px; }
.bottom-tab.active { color: #00d4ff; }
.bottom-tab:hover { color: #9ca3af; }
.bottom-tab.active:hover { color: #00d4ff; }
.bottom-tab-center {
position: relative; top: -10px;
background: linear-gradient(135deg, #00d4ff, #7c3aed);
border-radius: 50%; width: 48px; height: 48px; flex: none;
display: flex; align-items: center; justify-content: center;
box-shadow: 0 0 20px rgba(0,212,255,0.3); margin: 0 4px;
}
.bottom-tab-center i, .bottom-tab-center svg { width: 24px; height: 24px; color: #000; }
.bottom-tab-center span { display: none; }
.bottom-tab-center.active { box-shadow: 0 0 30px rgba(0,212,255,0.5); }
@media (min-width: 768px) {
.bottom-tab-bar { display: none; }
}
.bf-signin-overlay { position: fixed; inset: 0; background: rgba(0,0,0,0.8); backdrop-filter: blur(8px); z-index: 70; }
.bf-signin-modal { position: fixed; top: 50%; left: 50%; transform: translate(-50%,-50%); z-index: 71; width: 100%; max-width: 420px; padding: 0 1rem; }
.bf-signin-card { background: #111; border: 1px solid rgba(255,255,255,0.1); border-radius: 1rem; padding: 1.5rem; }
.bf-content-shift { padding-bottom: 0 !important; }
@media (max-width: 767px) {
.sticky-player { bottom: 56px !important; }
body { padding-bottom: 120px !important; }
}
.bf-locked-overlay { position: absolute; inset: 0; background: rgba(0,0,0,0.6); backdrop-filter: blur(3px); display: flex; flex-direction: column; align-items: center; justify-content: center; border-radius: inherit; z-index: 10; pointer-events: none; }
.bf-superfan-badge { background: linear-gradient(135deg, #f97316, #ef4444); color: white; font-size: 10px; font-weight: 600; padding: 3px 10px; border-radius: 9999px; display: inline-flex; align-items: center; gap: 4px; white-space: nowrap; }
.bf-superfan-btn { transition: all 0.2s ease; }
.bf-superfan-btn:hover { transform: scale(1.02); }
.bf-payment-input {
width: 100%; background: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.1);
border-radius: 0.75rem; padding: 0.75rem 1rem; font-size: 0.875rem;
color: white; outline: none; transition: border-color 0.2s, background 0.2s;
}
.bf-payment-input:focus { border-color: rgba(249,115,22,0.5); background: rgba(255,255,255,0.07); }
.bf-payment-input::placeholder { color: #4b5563; }
.bf-payment-input.error { border-color: rgba(239,68,68,0.5); }
@keyframes bf-spin { to { transform: rotate(360deg); } }
.bf-download-btn {
display: inline-flex; align-items: center; gap: 4px;
font-size: 11px; font-weight: 500; color: #9ca3af;
background: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.1);
cursor: pointer; padding: 4px 10px; border-radius: 6px;
transition: all 0.2s;
}
.bf-download-btn:hover { color: #00d4ff; border-color: rgba(0,212,255,0.3); background: rgba(0,212,255,0.05); }
.bf-download-btn.bf-dl-free { color: #f97316; border-color: rgba(249,115,22,0.3); background: rgba(249,115,22,0.08); }
.bf-download-btn.bf-dl-free:hover { color: #fb923c; border-color: rgba(249,115,22,0.5); background: rgba(249,115,22,0.12); }
.bf-download-btn.bf-dl-unlocked { color: #22c55e; border-color: rgba(34,197,94,0.3); background: rgba(34,197,94,0.08); }
.bf-download-btn.bf-dl-unlocked:hover { color: #4ade80; border-color: rgba(34,197,94,0.5); background: rgba(34,197,94,0.12); }
.bf-unlock-btn {
display: inline-flex; align-items: center; gap: 4px;
font-size: 11px; font-weight: 600; color: #f97316;
background: linear-gradient(135deg, rgba(249,115,22,0.12), rgba(239,68,68,0.08));
border: 1px solid rgba(249,115,22,0.3);
cursor: pointer; padding: 5px 12px; border-radius: 8px;
transition: all 0.2s;
box-shadow: 0 0 10px rgba(249,115,22,0.08);
}
.bf-unlock-btn:hover {
background: linear-gradient(135deg, rgba(249,115,22,0.2), rgba(239,68,68,0.12));
border-color: rgba(249,115,22,0.5);
box-shadow: 0 0 16px rgba(249,115,22,0.15);
transform: translateY(-1px);
}
.bf-sf-free-label {
display: inline-flex; align-items: center; gap: 3px;
font-size: 9px; color: #f97316; font-weight: 600; margin-top: 2px;
background: rgba(249,115,22,0.08); padding: 2px 8px; border-radius: 4px;
border: 1px solid rgba(249,115,22,0.15);
}
.bf-quick-amount {
flex: 1; padding: 10px 0; border-radius: 10px;
background: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.1);
color: #d1d5db; font-size: 14px; font-weight: 600;
cursor: pointer; transition: all 0.2s; text-align: center;
}
.bf-quick-amount:hover { background: rgba(0,212,255,0.1); border-color: rgba(0,212,255,0.3); color: #00d4ff; }
.bf-quick-amount.active { background: rgba(0,212,255,0.15); border-color: rgba(0,212,255,0.5); color: #00d4ff; box-shadow: 0 0 12px rgba(0,212,255,0.1); }
@keyframes bfSuccessPulse { 0% { transform: scale(0.5); opacity: 0; } 50% { transform: scale(1.15); } 100% { transform: scale(1); opacity: 1; } }
@keyframes bfSuccessFade { 0% { opacity: 0; transform: translateY(8px); } 100% { opacity: 1; transform: translateY(0); } }
.bf-success-pulse { animation: bfSuccessPulse 0.4s cubic-bezier(0.34, 1.56, 0.64, 1) forwards; }
.bf-pay-success h3, .bf-pay-success p, .bf-pay-success div:not(.bf-success-pulse) { animation: bfSuccessFade 0.35s ease forwards; }
.bf-pay-success h3 { animation-delay: 0.1s; opacity: 0; }
.bf-pay-success p { animation-delay: 0.2s; opacity: 0; }
.bf-pay-success .bf-success-pulse + div { animation-delay: 0.3s; opacity: 0; }
.bf-share-btn {
display: inline-flex; align-items: center; gap: 4px;
font-size: 11px; font-weight: 500; color: #9ca3af;
background: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.1);
cursor: pointer; padding: 4px 10px; border-radius: 6px;
transition: all 0.2s;
}
.bf-share-btn:hover { color: #a78bfa; border-color: rgba(167,139,250,0.3); background: rgba(167,139,250,0.08); }
.bf-share-platform { width: 100%; padding: 12px 16px; border-radius: 12px; display: flex; align-items: center; gap: 12px; cursor: pointer; transition: all 0.2s; border: 1px solid transparent; }
.bf-share-platform:hover { transform: translateX(2px); }
.bf-social-proof { display: flex; align-items: center; gap: 6px; font-size: 11px; color: #f97316; font-weight: 600; background: rgba(249,115,22,0.08); padding: 4px 10px; border-radius: 6px; border: 1px solid rgba(249,115,22,0.15); }
.bf-urgency-badge { display: inline-flex; align-items: center; gap: 4px; font-size: 10px; color: #f97316; font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px; background: rgba(249,115,22,0.06); padding: 3px 8px; border-radius: 4px; animation: bfUrgencyPulse 2s ease-in-out infinite; }
@keyframes bfUrgencyPulse { 0%,100% { opacity: 1; } 50% { opacity: 0.7; } }
.bf-preview-snippet { position: relative; height: 52px; background: rgba(255,255,255,0.03); border-radius: 10px; overflow: hidden; cursor: pointer; border: 1px solid rgba(255,255,255,0.06); transition: border-color 0.2s; }
.bf-preview-snippet:hover { border-color: rgba(0,212,255,0.3); }
.bf-preview-highlight { position: absolute; top: 0; bottom: 0; background: rgba(0,212,255,0.06); border-left: 2px solid rgba(0,212,255,0.4); border-right: 2px solid rgba(0,212,255,0.4); pointer-events: none; }
.bf-preview-play { position: absolute; left: 10px; top: 50%; transform: translateY(-50%); width: 30px; height: 30px; border-radius: 50%; background: rgba(0,212,255,0.9); display: flex; align-items: center; justify-content: center; cursor: pointer; z-index: 2; transition: transform 0.15s, box-shadow 0.15s; box-shadow: 0 0 12px rgba(0,212,255,0.25); }
.bf-preview-play:hover { transform: translateY(-50%) scale(1.1); box-shadow: 0 0 20px rgba(0,212,255,0.4); }
.bf-preview-wave { display: flex; align-items: center; gap: 1.5px; height: 100%; padding: 0 12px 0 50px; }
.bf-preview-wave span { width: 2px; border-radius: 1px; flex-shrink: 0; background: rgba(255,255,255,0.1); transition: background 0.3s; }
.bf-preview-snippet.bf-preview-active .bf-preview-wave span { animation: bfPreviewWave 0.35s ease-in-out infinite alternate; }
.bf-preview-snippet.bf-preview-active .bf-preview-highlight + .bf-preview-wave span { background: rgba(255,255,255,0.12); }
@keyframes bfPreviewWave { 0% { transform: scaleY(0.3); } 100% { transform: scaleY(1); } }
@keyframes bfUnlockCelebrate { 0% { transform: scale(0) rotate(-10deg); opacity: 0; } 60% { transform: scale(1.15) rotate(3deg); opacity: 1; } 100% { transform: scale(1) rotate(0); opacity: 1; } }
@keyframes bfDownloadProgress { 0% { width: 0; } 100% { width: 100%; } }
@keyframes bfConfettiDrop { 0% { transform: translateY(0) rotate(0deg); opacity: 1; } 100% { transform: translateY(60px) rotate(360deg); opacity: 0; } }
.bf-unlock-success-icon { animation: bfUnlockCelebrate 0.5s cubic-bezier(0.34, 1.56, 0.64, 1) forwards; }
.bf-download-progress { height: 4px; background: rgba(255,255,255,0.08); border-radius: 3px; overflow: hidden; margin-top: 16px; width: 80%; margin-left: auto; margin-right: auto; }
.bf-download-progress-bar { height: 100%; background: linear-gradient(90deg, #22c55e, #4ade80); border-radius: 3px; animation: bfDownloadProgress 1.8s ease forwards; }
.bf-confetti-particle { position: absolute; width: 6px; height: 6px; border-radius: 50%; animation: bfConfettiDrop 1.2s ease forwards; pointer-events: none; }
.bf-support-cta { font-size: 12px; color: #9ca3af; display: flex; align-items: center; gap: 6px; margin-bottom: 12px; }
.bf-support-cta strong { color: #f97316; }
.bf-like-btn { display: inline-flex; align-items: center; gap: 4px; font-size: 11px; font-weight: 500; color: #9ca3af; background: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.1); cursor: pointer; padding: 4px 10px; border-radius: 6px; transition: all 0.2s; }
.bf-like-btn:hover { color: #f97316; border-color: rgba(249,115,22,0.3); background: rgba(249,115,22,0.08); }
.bf-like-btn.bf-liked { color: #f97316; border-color: rgba(249,115,22,0.3); background: rgba(249,115,22,0.1); }
.bf-replay-btn { display: inline-flex; align-items: center; justify-content: center; width: 28px; height: 28px; border-radius: 50%; background: rgba(255,255,255,0.06); border: 1px solid rgba(255,255,255,0.1); cursor: pointer; transition: all 0.2s; color: #9ca3af; }
.bf-replay-btn:hover { background: rgba(0,212,255,0.15); border-color: rgba(0,212,255,0.4); color: #00d4ff; transform: scale(1.08); }
.bf-rec-card { transition: all 0.3s cubic-bezier(0.4,0,0.2,1); cursor: pointer; }
.bf-rec-card:hover { transform: translateY(-3px); box-shadow: 0 12px 24px -6px rgba(0,212,255,0.12); }
.bf-player-ctrl { width: 32px; height: 32px; border-radius: 50%; display: flex; align-items: center; justify-content: center; cursor: pointer; transition: all 0.15s; border: none; color: #9ca3af; background: transparent; }
.bf-player-ctrl:hover { color: #ffffff; background: rgba(255,255,255,0.08); }
.bf-player-ctrl:active { transform: scale(0.9); }
`;
document.head.appendChild(style);
};
// ===== UI: BOTTOM NAV =====
const injectBottomNav = (activeTab) => {
if (document.getElementById('bottomTabBar')) return;
const loggedIn = isLoggedIn();
const user = getCurrentUser();
const role = user ? (user.role || (user.isArtist ? 'producer' : null)) : null;
let tabs;
if (role === 'fan') {
tabs = [
{ id: 'home', icon: 'home', label: 'Home', href: 'index.html' },
{ id: 'search', icon: 'search', label: 'Search', href: 'search.html' },
{ id: 'library', icon: 'library', label: 'Library', href: 'library.html' },
{ id: 'profile', icon: 'user', label: 'Profile', href: 'profile.html' }
];
} else if (role === 'producer') {
tabs = [
{ id: 'home', icon: 'home', label: 'Home', href: 'index.html' },
{ id: 'search', icon: 'search', label: 'Search', href: 'search.html' },
{ id: 'upload', icon: 'plus', label: 'Upload', href: 'upload.html', center: true },
{ id: 'profile', icon: 'user', label: 'Profile', href: 'profile.html' }
];
} else {
tabs = [
{ id: 'home', icon: 'home', label: 'Home', href: 'index.html' },
{ id: 'search', icon: 'search', label: 'Search', href: 'search.html' },
{ id: 'upload', icon: 'plus', label: 'Upload', href: '#', center: true, action: 'BF.showSignInModal(); return false;' },
{ id: 'signin', icon: 'log-in', label: 'Sign In', href: '#', action: 'BF.showSignInModal(); return false;' }
];
}
const nav = document.createElement('nav');
nav.className = 'bottom-tab-bar';
nav.id = 'bottomTabBar';
nav.innerHTML = tabs.map(tab => {
const isActive = activeTab === tab.id;
const isCenter = tab.center;
const action = tab.action ? `onclick="${tab.action}"` : '';
return `<a href="${tab.href}" class="bottom-tab${isCenter ? ' bottom-tab-center' : ''}${isActive ? ' active' : ''}" ${action}>
<i data-lucide="${tab.icon}"></i><span>${tab.label}</span>
</a>`;
}).join('');
document.body.appendChild(nav);
};
// ===== UI: SIGN IN / SIGN UP MODAL =====
let _signUpRole = 'producer';
const showSignInModal = () => {
if (document.getElementById('bfSignInModal')) return;
const modal = document.createElement('div');
modal.id = 'bfSignInModal';
modal.innerHTML = `
<div class="bf-signin-overlay" onclick="BF.closeSignInModal()"></div>
<div class="bf-signin-modal">
<div class="bf-signin-card">
<div class="flex items-center justify-between mb-6">
<h3 class="text-xl font-bold text-white" id="bfModalTitle">Welcome to BeatFridge</h3>
<button onclick="BF.closeSignInModal()" class="text-gray-400 hover:text-white transition"><i data-lucide="x" class="w-6 h-6"></i></button>
</div>
<!-- Step 1: Choose Account Type -->
<div id="bfStepChooseType">
<p class="text-gray-400 text-sm mb-6">What would you like to do?</p>
<div class="space-y-3 mb-6">
<button onclick="BF.showSignUpForm('producer')" class="w-full p-4 rounded-xl bg-white/5 border border-white/10 hover:border-cyan-500/50 hover:bg-cyan-500/5 transition text-left group">
<div class="flex items-center gap-3">
<div class="w-12 h-12 rounded-full bg-cyan-500/20 flex items-center justify-center flex-shrink-0">
<i data-lucide="music" class="w-6 h-6 text-cyan-400"></i>
</div>
<div>
<p class="font-semibold text-white group-hover:text-cyan-400 transition">I want to upload music</p>
<p class="text-xs text-gray-500 mt-1">Create a Producer account to share your tracks</p>
</div>
</div>
</button>
<button onclick="BF.showSignUpForm('fan')" class="w-full p-4 rounded-xl bg-white/5 border border-white/10 hover:border-purple-500/50 hover:bg-purple-500/5 transition text-left group">
<div class="flex items-center gap-3">
<div class="w-12 h-12 rounded-full bg-purple-500/20 flex items-center justify-center flex-shrink-0">
<i data-lucide="headphones" class="w-6 h-6 text-purple-400"></i>
</div>
<div>
<p class="font-semibold text-white group-hover:text-purple-400 transition">I just want to listen</p>
<p class="text-xs text-gray-500 mt-1">Create a Fan account to discover and enjoy music</p>
</div>
</div>
</button>
</div>
<div class="text-center">
<p class="text-sm text-gray-500">Already have an account? <button onclick="BF.showSignInForm()" class="text-cyan-400 hover:underline">Sign In</button></p>
</div>
</div>
<!-- Step 2: Sign Up Form -->
<div id="bfStepSignUp" class="hidden">
<div class="flex items-center gap-2 mb-4">
<span class="px-3 py-1 rounded-full text-xs font-medium" id="bfRoleBadge"></span>
</div>
<div class="space-y-4">
<div>
<label class="block text-xs font-medium text-gray-500 uppercase tracking-wider mb-2">Display Name</label>
<input type="text" id="bfSignupName" placeholder="Your display name" class="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-sm focus:outline-none focus:border-cyan-500/50 text-white">
</div>
<div>
<label class="block text-xs font-medium text-gray-500 uppercase tracking-wider mb-2">Username</label>
<input type="text" id="bfSignupUsername" placeholder="Choose a username" class="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-sm focus:outline-none focus:border-cyan-500/50 text-white">
</div>
<div>
<label class="block text-xs font-medium text-gray-500 uppercase tracking-wider mb-2">Email</label>
<input type="email" id="bfSignupEmail" placeholder="your@email.com" class="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-sm focus:outline-none focus:border-cyan-500/50 text-white">
</div>
<div>
<label class="block text-xs font-medium text-gray-500 uppercase tracking-wider mb-2">Password</label>
<input type="password" id="bfSignupPassword" placeholder="Create a password (min 8 chars)" class="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-sm focus:outline-none focus:border-cyan-500/50 text-white" onkeydown="if(event.key==='Enter')BF.handleSignUp()">
</div>
<div id="bfSignupError" class="hidden text-red-400 text-sm"></div>
<button onclick="BF.handleSignUp()" class="w-full py-3 bg-cyan-500 hover:bg-cyan-400 text-black font-semibold rounded-xl transition" id="bfSignupBtn">Create Account</button>
<button onclick="BF.showChooseType()" class="w-full py-2 text-sm text-gray-500 hover:text-white transition">β Back</button>
</div>
</div>
<!-- Step 3: Sign In Form -->
<div id="bfStepSignIn" class="hidden">
<div class="space-y-4">
<div>
<label class="block text-xs font-medium text-gray-500 uppercase tracking-wider mb-2">Username or Email</label>
<input type="text" id="bfSigninId" placeholder="Enter username or email" class="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-sm focus:outline-none focus:border-cyan-500/50 text-white">
</div>
<div>
<label class="block text-xs font-medium text-gray-500 uppercase tracking-wider mb-2">Password</label>
<input type="password" id="bfSigninPw" placeholder="Enter password" class="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-sm focus:outline-none focus:border-cyan-500/50 text-white" onkeydown="if(event.key==='Enter')BF.handleSignIn()">
</div>
<div id="bfSigninError" class="hidden text-red-400 text-sm"></div>
<button onclick="BF.handleSignIn()" class="w-full py-3 bg-cyan-500 hover:bg-cyan-400 text-black font-semibold rounded-xl transition">Sign In</button>
<p class="text-sm text-gray-500 text-center">No account? <button onclick="BF.showChooseType()" class="text-cyan-400 hover:underline">Create one</button></p>
</div>
</div>
</div>
</div>
`;
document.body.appendChild(modal);
if (window.lucide) lucide.createIcons();
};
const showSignUpForm = (role) => {
_signUpRole = role;
document.getElementById('bfStepChooseType').classList.add('hidden');
document.getElementById('bfStepSignUp').classList.remove('hidden');
document.getElementById('bfStepSignIn').classList.add('hidden');
document.getElementById('bfModalTitle').textContent = role === 'producer' ? 'Create Producer Account' : 'Create Fan Account';
const badge = document.getElementById('bfRoleBadge');
if (role === 'producer') {
badge.textContent = 'π΅ Producer';
badge.className = 'px-3 py-1 rounded-full text-xs font-medium bg-cyan-500/20 text-cyan-400 border border-cyan-500/30';
document.getElementById('bfSignupBtn').textContent = 'Create Producer Account';
document.getElementById('bfSignupBtn').className = 'w-full py-3 bg-cyan-500 hover:bg-cyan-400 text-black font-semibold rounded-xl transition';
} else {
badge.textContent = 'π§ Fan';
badge.className = 'px-3 py-1 rounded-full text-xs font-medium bg-purple-500/20 text-purple-400 border border-purple-500/30';
document.getElementById('bfSignupBtn').textContent = 'Create Fan Account';
document.getElementById('bfSignupBtn').className = 'w-full py-3 bg-purple-500 hover:bg-purple-400 text-black font-semibold rounded-xl transition';
}
document.getElementById('bfSignupName')?.focus();
if (window.lucide) lucide.createIcons();
};
const showSignInForm = () => {
document.getElementById('bfStepChooseType').classList.add('hidden');
document.getElementById('bfStepSignUp').classList.add('hidden');
document.getElementById('bfStepSignIn').classList.remove('hidden');
document.getElementById('bfModalTitle').textContent = 'Sign In to BeatFridge';
document.getElementById('bfSigninId')?.focus();
};
const showChooseType = () => {
document.getElementById('bfStepChooseType').classList.remove('hidden');
document.getElementById('bfStepSignUp').classList.add('hidden');
document.getElementById('bfStepSignIn').classList.add('hidden');
document.getElementById('bfModalTitle').textContent = 'Welcome to BeatFridge';
};
const handleSignUp = () => {
const name = document.getElementById('bfSignupName')?.value.trim();
const username = document.getElementById('bfSignupUsername')?.value.trim();
const email = document.getElementById('bfSignupEmail')?.value.trim();
const password = document.getElementById('bfSignupPassword')?.value;
const err = document.getElementById('bfSignupError');
if (!username || !email || !password) { err.textContent = 'Please fill in all fields'; err.classList.remove('hidden'); return; }
if (username.length < 3) { err.textContent = 'Username must be at least 3 characters'; err.classList.remove('hidden'); return; }
if (!/^[a-zA-Z0-9_]+$/.test(username)) { err.textContent = 'Username can only contain letters, numbers, and underscores'; err.classList.remove('hidden'); return; }
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) { err.textContent = 'Please enter a valid email'; err.classList.remove('hidden'); return; }
if (password.length < 8) { err.textContent = 'Password must be at least 8 characters'; err.classList.remove('hidden'); return; }
const result = signUp({ username, email, password, role: _signUpRole, displayName: name || username });
if (result.success) {
closeSignInModal();
const isProd = result.user.role === 'producer';
showToast(`Welcome, ${result.user.username}! π ${isProd ? 'Start uploading your tracks!' : 'Discover amazing music!'}`);
setTimeout(() => window.location.reload(), 500);
} else {
err.textContent = result.error;
err.classList.remove('hidden');
}
};
const closeSignInModal = () => {
document.getElementById('bfSignInModal')?.remove();
};
const handleSignIn = () => {
const id = document.getElementById('bfSigninId')?.value.trim();
const pw = document.getElementById('bfSigninPw')?.value;
const err = document.getElementById('bfSigninError');
if (!id || !pw) { err.textContent = 'Please fill in all fields'; err.classList.remove('hidden'); return; }
const result = signIn(id, pw);
if (result.success) {
closeSignInModal();
showToast('Welcome back, ' + result.user.username + '!');
setTimeout(() => window.location.reload(), 500);
} else {
err.textContent = result.error;
err.classList.remove('hidden');
}
};
// ===== UI: TOAST =====
const showToast = (message) => {
const toast = document.createElement('div');
toast.className = 'fixed bottom-24 left-1/2 -translate-x-1/2 bg-cyan-500 text-black px-4 py-2 rounded-full text-sm font-medium z-[80] whitespace-nowrap';
toast.style.boxShadow = '0 0 20px rgba(0,212,255,0.3)';
toast.textContent = message;
document.body.appendChild(toast);
setTimeout(() => { toast.style.opacity = '0'; toast.style.transition = 'opacity 0.3s'; setTimeout(() => toast.remove(), 300); }, 2500);
};
// ===== PLAYER SYNC =====
const syncPlayer = () => {
try {
const track = JSON.parse(localStorage.getItem('currentTrack'));
const playing = localStorage.getItem('isPlaying') === 'true';
const t = document.getElementById('playerTitle');
const a = document.getElementById('playerArtist');
const i = document.getElementById('playerArt');
const p = document.getElementById('playIcon');
if (track && t) t.textContent = track.title;
if (track && a) a.textContent = track.artist;
if (track && i) i.src = track.image;
if (p) { p.setAttribute('data-lucide', playing ? 'pause' : 'play'); if (window.lucide) lucide.createIcons(); }
} catch {}
};
// ===== PLAYER CONTROLS =====
const playTrack = (track, fromQueue) => {
localStorage.setItem('currentTrack', JSON.stringify(track));
localStorage.setItem('isPlaying', 'true');
recordActivity(track.id, 'play');
syncPlayer();
// Update queue context if track is in queue
if (!fromQueue) {
try {
const queue = JSON.parse(localStorage.getItem('bf_play_queue') || '[]');
const idx = queue.findIndex(t => t.id === track.id);
if (idx > -1) {
_queueIndex = idx;
localStorage.setItem('bf_queue_index', String(idx));
}
} catch {}
}
// Add to recently played
try {
let rp = JSON.parse(localStorage.getItem('recentlyPlayed') || '[]');
rp = rp.filter(t => t.id !== track.id);
rp.unshift({ ...track, playedAt: new Date().toISOString() });
if (rp.length > 50) rp.pop();
localStorage.setItem('recentlyPlayed', JSON.stringify(rp));
} catch {}
// Dispatch track change event for UI updates
try { window.dispatchEvent(new CustomEvent('bf:trackChange', { detail: track })); } catch {}
};
const togglePlay = () => {
const current = localStorage.getItem('isPlaying') === 'true';
localStorage.setItem('isPlaying', current ? 'false' : 'true');
syncPlayer();
};
// ===== TOP NAV AUTH UPDATE =====
const updateTopNav = () => {
const user = getCurrentUser();
const avatarEl = document.getElementById('topNavAvatar');
if (avatarEl && user) {
avatarEl.src = user.avatar || `http://static.photos/people/200x200/42`;
avatarEl.onclick = () => { window.location.href = 'profile.html'; };
}
};
// ===== TOP NAV ROLE ADJUSTMENT =====
const adjustTopNav = () => {
const user = getCurrentUser();
const role = user ? (user.role || (user.isArtist ? 'producer' : null)) : null;
if (role === 'fan') {
document.querySelectorAll('a[href="upload.html"]').forEach(el => el.style.display = 'none');
document.querySelectorAll('a[href="analytics.html"]').forEach(el => el.style.display = 'none');
}
};
// ===== SUPER FAN STATE =====
const migrateSuperFanData = () => {
const key = 'bf_superfan';
try {
let subs = JSON.parse(localStorage.getItem(key) || '[]');
if (subs.length && typeof subs[0] === 'string') {
const migrated = subs.map(slug => ({
slug: slug,
name: slug.split('-').map(w => w.charAt(0).toUpperCase() + w.slice(1)).join(' '),
image: '',
date: new Date().toISOString(),
active: true
}));
localStorage.setItem(key, JSON.stringify(migrated));
}
} catch (e) { console.error('Super Fan migration error:', e); }
};
const getSuperFanSubscriptions = () => {
try {
migrateSuperFanData();
const subs = JSON.parse(localStorage.getItem('bf_superfan') || '[]');
return subs.filter(s => typeof s !== 'string' && s.active !== false);
} catch { return []; }
};
const cancelSuperFanSubscription = (artistSlug) => {
const key = 'bf_superfan';
migrateSuperFanData();
let subs = [];
try { subs = JSON.parse(localStorage.getItem(key) || '[]'); } catch { subs = []; }
const index = subs.findIndex(s => typeof s === 'string' ? s === artistSlug : s.slug === artistSlug);
if (index > -1) {
const name = typeof subs[index] === 'string' ? artistSlug : subs[index].name;
subs.splice(index, 1);
localStorage.setItem(key, JSON.stringify(subs));
updateSuperFanButtons();
showToast('Super Fan subscription cancelled for ' + name);
return true;
}
return false;
};
// ===== SUPER FAN UI =====
let _sfArtistName = '';
let _sfArtistImage = '';
let _sfRetryAttempt = 0;
let _dlTrackTitle = '';
let _dlArtistName = '';
let _dlTrackId = null;
let _dlAmount = null;
const showSuperFanModal = (artistName, artistImage) => {
if (document.getElementById('bfSuperFanModal')) return;
if (isSuperFanOf(artistName)) {
showToast('You are already a Super Fan of ' + artistName + ' \ud83c\udfa7');
return;
}
_sfArtistName = artistName;
_sfArtistImage = artistImage;
const modal = document.createElement('div');
modal.id = 'bfSuperFanModal';
modal.innerHTML = `
<div class="bf-signin-overlay" onclick="BF.closeSuperFanModal()"></div>
<div class="bf-signin-modal">
<div class="bf-signin-card" style="max-width:420px">
<div class="flex items-center justify-between mb-6">
<h3 class="text-xl font-bold text-white">Become a Super Fan</h3>
<button onclick="BF.closeSuperFanModal()" class="text-gray-400 hover:text-white transition"><i data-lucide="x" class="w-6 h-6"></i></button>
</div>
<!-- Step 1: Summary -->
<div id="bfSfStep1">
<div class="flex items-center gap-4 mb-6">
<div class="w-16 h-16 rounded-full overflow-hidden border-2 border-orange-500/50 flex-shrink-0">
<img src="${artistImage}" class="w-full h-full object-cover">
</div>
<div class="min-w-0">
<p class="font-semibold text-white text-lg truncate">${artistName}</p>
<p class="text-sm text-gray-400">Support this artist and unlock exclusive content</p>
</div>
</div>
<div class="p-4 rounded-xl bg-gradient-to-r from-orange-500/10 to-red-500/10 border border-orange-500/20 mb-6">
<div class="flex items-center justify-between mb-4">
<span class="text-sm text-gray-300">Monthly subscription</span>
<span class="text-xl font-bold text-orange-400">$25<span class="text-sm text-gray-500 font-normal">/mo</span></span>
</div>
<div class="space-y-2.5">
<div class="flex items-center gap-2 text-sm text-gray-300">
<i data-lucide="unlock" class="w-4 h-4 text-orange-400 flex-shrink-0"></i>
<span>Early access to new music</span>
</div>
<div class="flex items-center gap-2 text-sm text-gray-300">
<i data-lucide="music" class="w-4 h-4 text-orange-400 flex-shrink-0"></i>
<span>Exclusive tracks & content</span>
</div>
<div class="flex items-center gap-2 text-sm text-gray-300">
<i data-lucide="headphones" class="w-4 h-4 text-orange-400 flex-shrink-0"></i>
<span>High-quality audio</span>
</div>
<div class="flex items-center gap-2 text-sm text-gray-300">
<i data-lucide="heart" class="w-4 h-4 text-orange-400 flex-shrink-0"></i>
<span>Direct support for the creator</span>
</div>
</div>
</div>
<button onclick="BF.showSuperFanPaymentStep()" class="w-full py-3 bg-gradient-to-r from-orange-500 to-red-500 hover:from-orange-400 hover:to-red-400 text-white font-semibold rounded-xl transition flex items-center justify-center gap-2" style="box-shadow: 0 0 20px rgba(249,115,22,0.3)">
<i data-lucide="credit-card" class="w-5 h-5"></i>
Continue to Payment
</button>
<p class="text-xs text-gray-600 text-center mt-3">Recurring monthly \u2022 Cancel anytime</p>
</div>
<!-- Step 2: Payment Form (shown directly for 2-click flow) -->
<div id="bfSfStep2" class="hidden">
<div class="flex items-center gap-3 mb-4 p-3 rounded-xl bg-white/5">
<div class="w-10 h-10 rounded-full overflow-hidden border border-orange-500/30 flex-shrink-0">
<img src="${artistImage}" class="w-full h-full object-cover">
</div>
<div class="flex-1 min-w-0">
<p class="text-sm font-semibold text-white truncate">${artistName}</p>
<p class="text-xs text-orange-400 font-medium">$25/mo</p>
</div>
</div>
<div class="flex flex-wrap items-center gap-x-3 gap-y-1 mb-4 px-1 text-xs text-gray-400">
<span class="flex items-center gap-1"><i data-lucide="download" class="w-3 h-3 text-orange-400"></i>Free downloads</span>
<span class="flex items-center gap-1"><i data-lucide="unlock" class="w-3 h-3 text-orange-400"></i>No paywalls</span>
<span class="flex items-center gap-1"><i data-lucide="music" class="w-3 h-3 text-orange-400"></i>Exclusive content</span>
</div>
<div class="space-y-4">
<div>
<label class="block text-xs font-medium text-gray-500 uppercase tracking-wider mb-2">Name on card</label>
<input type="text" id="bfSfCardName" placeholder="John Doe" class="bf-payment-input">
</div>
<div>
<label class="block text-xs font-medium text-gray-500 uppercase tracking-wider mb-2">Card number</label>
<div class="relative">
<input type="text" id="bfSfCardNumber" placeholder="4242 4242 4242 4242" class="bf-payment-input" style="padding-right:4.5rem" maxlength="19" oninput="BF.formatCardNumber(this)">
<div class="absolute right-3 top-1/2 -translate-y-1/2 flex items-center gap-1.5 text-gray-600">
<svg width="28" height="18" viewBox="0 0 28 18" fill="none"><rect width="28" height="18" rx="2" fill="#1A1F71"/><path d="M11 5.5L8.5 12.5h2l.5-1.5h2.5l.5 1.5h2L13 5.5h-2zm.8 4.5l1-3 1 3h-2z" fill="#fff"/></svg>
</div>
</div>
</div>
<div class="flex gap-3">
<div class="flex-1">
<label class="block text-xs font-medium text-gray-500 uppercase tracking-wider mb-2">Expiry</label>
<input type="text" id="bfSfCardExpiry" placeholder="MM/YY" class="bf-payment-input" maxlength="5" oninput="BF.formatCardExpiry(this)">
</div>
<div class="w-24">
<label class="block text-xs font-medium text-gray-500 uppercase tracking-wider mb-2">CVC</label>
<input type="text" id="bfSfCardCvc" placeholder="123" class="bf-payment-input" maxlength="4" oninput="this.value=this.value.replace(/[^0-9]/g,'')">
</div>
</div>
<div id="bfSfPaymentError" class="hidden text-red-400 text-sm"></div>
<button onclick="BF.confirmSuperFanPayment()" class="w-full py-3 bg-gradient-to-r from-orange-500 to-red-500 hover:from-orange-400 hover:to-red-400 text-white font-semibold rounded-xl transition flex items-center justify-center gap-2" style="box-shadow: 0 0 20px rgba(249,115,22,0.3)">
<i data-lucide="lock" class="w-5 h-5"></i>
Confirm Subscription \u2022 $25/mo
</button>
<button onclick="BF.showSuperFanSummaryStep()" class="w-full py-2 text-sm text-gray-500 hover:text-white transition">\u2190 Back</button>
</div>
<div class="flex items-center justify-center gap-4 mt-4 pt-4 border-t border-white/5">
<div class="flex items-center gap-1.5 text-xs text-gray-600">
<i data-lucide="shield-check" class="w-3.5 h-3.5"></i>
<span>Encrypted</span>
</div>
<div class="flex items-center gap-1.5 text-xs text-gray-600">
<i data-lucide="lock" class="w-3.5 h-3.5"></i>
<span>Secure</span>
</div>
<div class="flex items-center gap-1.5 text-xs text-gray-600">
<i data-lucide="credit-card" class="w-3.5 h-3.5"></i>
<span>PCI Compliant</span>
</div>
</div>
</div>
<!-- Step 3: Processing -->
<div id="bfSfStep3" class="hidden">
<div class="py-12 text-center">
<div class="w-16 h-16 rounded-full border-4 border-orange-500/20 border-t-orange-500 mx-auto mb-6" style="animation: bf-spin 1s linear infinite;"></div>
<h4 class="text-lg font-semibold text-white mb-2">Processing payment...</h4>
<p class="text-sm text-gray-500">Please wait while we confirm your subscription</p>
</div>
</div>
<!-- Step 4: Success -->
<div id="bfSfStep4" class="hidden">
<div class="py-8 text-center">
<div class="w-20 h-20 rounded-full bg-green-500/20 flex items-center justify-center mx-auto mb-6">
<i data-lucide="check-circle" class="w-10 h-10 text-green-400"></i>
</div>
<h4 class="text-xl font-bold text-white mb-2">You are now a Super Fan \ud83c\udfa7</h4>
<p class="text-sm text-gray-400 mb-1">Subscription to <span class="text-orange-400 font-medium">${artistName}</span> is active</p>
<p class="text-xs text-gray-600">Exclusive content has been unlocked</p>
</div>
</div>
</div>
</div>
`;
document.body.appendChild(modal);
if (window.lucide) lucide.createIcons();
// Auto-advance to payment form (2-click flow: open β pay)
_sfRetryAttempt = 0;
showSuperFanPaymentStep();
// Pre-fill saved card if available
try {
const savedCard = JSON.parse(localStorage.getItem('bf_saved_card') || 'null');
if (savedCard) {
const nameInput = document.getElementById('bfSfCardName');
const numberInput = document.getElementById('bfSfCardNumber');
const expiryInput = document.getElementById('bfSfCardExpiry');
if (nameInput && savedCard.name) nameInput.value = savedCard.name;
if (numberInput && savedCard.last4) numberInput.value = 'Β·Β·Β·Β· Β·Β·Β·Β· Β·Β·Β·Β· ' + savedCard.last4;
if (expiryInput && savedCard.expiry) expiryInput.value = savedCard.expiry;
}
} catch (e) {}
};
const closeSuperFanModal = () => {
document.getElementById('bfSuperFanModal')?.remove();
};
// ===== DOWNLOAD ACCESS CONTROL =====
const isDownloadUnlocked = (trackId, artistName) => {
if (isSuperFanOf(artistName)) return true;
try {
const states = JSON.parse(localStorage.getItem('bf_download_states') || '[]');
return states.some(s => s.trackId === trackId && s.unlocked);
} catch { return false; }
};
const unlockTrackDownload = (trackId, trackTitle, artistName, amount) => {
try {
let states = JSON.parse(localStorage.getItem('bf_download_states') || '[]');
const existing = states.findIndex(s => s.trackId === trackId);
const entry = { trackId, trackTitle, artistName, amount, unlocked: true, date: new Date().toISOString() };
if (existing > -1) { states[existing] = entry; } else { states.push(entry); }
localStorage.setItem('bf_download_states', JSON.stringify(states));
return true;
} catch { return false; }
};
const getDownloadStates = () => {
try { return JSON.parse(localStorage.getItem('bf_download_states') || '[]'); } catch { return []; }
};
const showDownloadModal = (trackTitle, artistName, trackId) => {
if (document.getElementById('bfDownloadModal')) return;
if (!isLoggedIn()) { showSignInModal(); return; }
_dlTrackTitle = trackTitle;
_dlArtistName = artistName;
_dlTrackId = trackId || 0;
const unlocked = isDownloadUnlocked(_dlTrackId, artistName);
const isSuperFan = isSuperFanOf(artistName);
const modal = document.createElement('div');
modal.id = 'bfDownloadModal';
let bodyContent;
if (unlocked) {
// Auto-download for unlocked tracks β 1-click experience
processMockDownload();
bodyContent = `
<div class="flex flex-col items-center justify-center py-8 text-center bf-pay-success">
<div class="w-16 h-16 rounded-full ${isSuperFan ? 'bg-orange-500/20' : 'bg-green-500/20'} flex items-center justify-center mx-auto mb-4 bf-success-pulse" style="box-shadow: 0 0 24px ${isSuperFan ? 'rgba(249,115,22,0.3)' : 'rgba(34,197,94,0.3)'}">
<i data-lucide="${isSuperFan ? 'zap' : 'check-circle'}" class="w-8 h-8 ${isSuperFan ? 'text-orange-400' : 'text-green-400'}"></i>
</div>
<h3 class="text-xl font-bold text-white mb-1">${isSuperFan ? 'Super Fan Download' : 'Unlocked β Downloading now'}</h3>
<p class="text-sm text-gray-400 mb-1">${trackTitle} Β· ${artistName}</p>
<p class="text-xs text-gray-600 mb-3">${isSuperFan ? 'Free with your Super Fan subscription' : 'Already unlocked'}</p>
<div class="bf-download-progress">
<div class="bf-download-progress-bar"></div>
</div>
<div class="mt-3 flex items-center gap-2 ${isSuperFan ? 'text-orange-400' : 'text-green-400'} text-sm font-medium">
<i data-lucide="download" class="w-4 h-4"></i>
<span>Downloading...</span>
</div>
</div>`;
// Auto-close after brief display
setTimeout(() => {
closeDownloadModal();
showToast('Beat unlocked successfully β');
}, 1500);
} else {
const unlockCount = getUnlockCount(_dlTrackId);
const socialProofHtml = unlockCount > 0
? `<div class="flex items-center justify-between mb-3"><div class="bf-social-proof"><i data-lucide="flame" class="w-3.5 h-3.5"></i>${unlockCount} people unlocked this</div><span class="bf-urgency-badge"><i data-lucide="clock" class="w-3 h-3"></i>Limited time</span></div>`
: `<div class="flex items-center justify-end mb-3"><span class="bf-urgency-badge"><i data-lucide="clock" class="w-3 h-3"></i>Limited time</span></div>`;
// Generate preview snippet waveform bars
let previewWaveBars = '';
const totalBars = 60;
const dropStart = Math.floor(totalBars * 0.35);
const dropEnd = dropStart + Math.floor(totalBars * 0.15); // ~8-12 sec of a ~4min track
for (let b = 0; b < totalBars; b++) {
let h;
if (b >= dropStart && b <= dropEnd) {
h = 50 + Math.random() * 50; // Drop section: taller bars
} else {
h = 15 + Math.random() * 40;
}
const inDrop = (b >= dropStart && b <= dropEnd) ? '1' : '0';
previewWaveBars += '<span style="height:' + h + '%;animation-delay:' + (b * 0.02).toFixed(2) + 's" data-in-drop="' + inDrop + '"></span>';
}
const highlightLeft = ((dropStart / totalBars) * 100).toFixed(1);
const highlightWidth = (((dropEnd - dropStart) / totalBars) * 100).toFixed(1);
bodyContent = `
${socialProofHtml}
<div class="flex items-center gap-4 mb-4">
<div class="w-12 h-12 rounded-lg bg-cyan-500/20 flex items-center justify-center flex-shrink-0">
<i data-lucide="music" class="w-6 h-6 text-cyan-400"></i>
</div>
<div class="min-w-0">
<p class="font-semibold text-white truncate">${trackTitle}</p>
<p class="text-sm text-gray-400 truncate">${artistName}</p>
</div>
</div>
<!-- Preview Snippet Hook -->
<div class="bf-preview-snippet mb-4" id="bfPreviewSnippet" onclick="BF.playPreviewSnippet()">
<div class="bf-preview-highlight" style="left:${highlightLeft}%;width:${highlightWidth}%"></div>
<button class="bf-preview-play" id="bfPreviewPlayBtn"><i data-lucide="play" class="w-3.5 h-3.5 text-black fill-current ml-0.5" id="bfPreviewPlayIcon"></i></button>
<div class="bf-preview-wave">${previewWaveBars}</div>
<div style="position:absolute;right:10px;top:50%;transform:translateY(-50%);display:flex;align-items:center;gap:6px;z-index:3">
<span style="font-size:10px;color:#6b7280" id="bfPreviewTime">Preview Β· 0:10</span>
<span style="font-size:9px;color:#00d4ff;font-weight:600;background:rgba(0,212,255,0.1);padding:2px 6px;border-radius:4px">DROP</span>
</div>
</div>
<div class="bf-support-cta">
<i data-lucide="heart-handshake" class="w-3.5 h-3.5 text-orange-400 flex-shrink-0"></i>
<span>Support this creator & <strong>download instantly</strong></span>
</div>
<div class="p-4 rounded-xl bg-gradient-to-r from-orange-500/10 to-cyan-500/10 border border-orange-500/20 mb-5">
<div class="flex items-center gap-2 mb-3">
<i data-lucide="zap" class="w-4 h-4 text-orange-400"></i>
<p class="text-sm font-semibold text-white">Unlock this beat instantly</p>
</div>
<p class="text-xs text-gray-400 mb-4">Pay what you want β minimum $0.50</p>
<div class="flex gap-2 mb-4">
<button class="bf-quick-amount active" onclick="BF.selectQuickAmount(0.50)">$0.50</button>
<button class="bf-quick-amount" onclick="BF.selectQuickAmount(1)">$1</button>
<button class="bf-quick-amount" onclick="BF.selectQuickAmount(5)">$5</button>
<button class="bf-quick-amount" onclick="BF.selectQuickAmount(0)">Custom</button>
</div>
<div>
<label class="block text-xs font-medium text-gray-500 uppercase tracking-wider mb-2">Custom amount</label>
<div class="relative">
<span class="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500 text-sm">$</span>
<input type="number" id="bfDownloadAmount" value="0.50" min="0.50" step="0.01" class="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 pl-7 text-sm focus:outline-none focus:border-orange-500/50 text-white" oninput="BF.onCustomAmountInput()" autofocus>
</div>
<p id="bfDownloadError" class="text-red-400 text-xs mt-2 hidden"></p>
</div>
</div>
<button id="bfDownloadCta" class="w-full py-3.5 bg-gradient-to-r from-orange-500 to-red-500 hover:from-orange-400 hover:to-red-400 text-white font-bold rounded-xl transition flex items-center justify-center gap-2 text-base" style="box-shadow: 0 0 24px rgba(249,115,22,0.25)" onclick="BF.handleDownloadUnlock()">
<i data-lucide="lock" class="w-5 h-5"></i>
Unlock & Download Β· $0.50
</button>
<div class="flex items-center justify-center gap-4 mt-3">
<div class="flex items-center gap-1.5 text-xs text-gray-600">
<i data-lucide="heart" class="w-3 h-3"></i>
<span>Artist gets 85%</span>
</div>
<div class="flex items-center gap-1.5 text-xs text-gray-600">
<i data-lucide="shield-check" class="w-3 h-3"></i>
<span>Secure</span>
</div>
</div>`;
}
modal.innerHTML = `
<div class="bf-signin-overlay" onclick="BF.closeDownloadModal()"></div>
<div class="bf-signin-modal">
<div class="bf-signin-card" style="max-width:400px">
<div class="flex items-center justify-between mb-6">
<h3 class="text-xl font-bold text-white flex items-center gap-2">
<i data-lucide="download" class="w-5 h-5 text-cyan-400"></i>
Download
</h3>
<button onclick="BF.closeDownloadModal()" class="text-gray-400 hover:text-white transition"><i data-lucide="x" class="w-6 h-6"></i></button>
</div>
${bodyContent}
</div>
</div>
`;
document.body.appendChild(modal);
if (window.lucide) lucide.createIcons();
};
const closeDownloadModal = () => {
document.getElementById('bfDownloadModal')?.remove();
};
const handleDownloadUnlock = () => {
const amountInput = document.getElementById('bfDownloadAmount');
const errorEl = document.getElementById('bfDownloadError');
if (!amountInput) return;
const amount = parseFloat(amountInput.value);
if (!amount || isNaN(amount)) {
if (errorEl) { errorEl.textContent = 'Please enter an amount'; errorEl.classList.remove('hidden'); }
amountInput.classList.add('border-red-500/50');
return;
}
if (amount < 0.50) {
if (errorEl) { errorEl.textContent = 'Minimum amount is $0.50'; errorEl.classList.remove('hidden'); }
amountInput.classList.add('border-red-500/50');
return;
}
if (errorEl) errorEl.classList.add('hidden');
amountInput.classList.remove('border-red-500/50');
// Store unlock state (mock payment)
unlockTrackDownload(_dlTrackId, _dlTrackTitle, _dlArtistName, amount);
// Store amount for flow continuity
_dlAmount = amount;
// Record transaction with full metadata
try {
const config = getMonetizationConfig();
const fee = +(amount * config.platformFeePercent / 100).toFixed(2);
const user = getCurrentUser();
const transactions = JSON.parse(localStorage.getItem('transactions') || '[]');
const tx = {
type: 'download',
amount: amount,
artist: _dlArtistName,
track: _dlTrackTitle,
trackId: _dlTrackId,
date: new Date().toISOString(),
fee: fee,
currency: config.currency,
paymentMethod: 'card',
cardLast4: '4242',
status: 'completed',
userId: user ? user.id : null
};
transactions.push(tx);
localStorage.setItem('transactions', JSON.stringify(transactions));
// Record creator earning
recordCreatorEarning(tx);
} catch {}
// Auto-download + instant success feedback
processMockDownload();
const card = document.querySelector('#bfDownloadModal .bf-signin-card');
if (card) {
// Generate confetti particles
const confettiColors = ['#22c55e', '#4ade80', '#00d4ff', '#f97316', '#a78bfa', '#facc15'];
let confettiHtml = '';
for (let i = 0; i < 18; i++) {
const color = confettiColors[Math.floor(Math.random() * confettiColors.length)];
const left = (5 + Math.random() * 90).toFixed(0);
const delay = (Math.random() * 0.5).toFixed(2);
const size = (4 + Math.random() * 4).toFixed(0);
confettiHtml += '<div class="bf-confetti-particle" style="left:' + left + '%;top:-8px;width:' + size + 'px;height:' + size + 'px;background:' + color + ';animation-delay:' + delay + 's;animation-duration:' + (0.8 + Math.random() * 0.6).toFixed(2) + 's"></div>';
}
card.innerHTML = `
<div class="flex flex-col items-center justify-center py-8 text-center bf-pay-success" style="position:relative;overflow:hidden">
${confettiHtml}
<div class="w-20 h-20 rounded-full bg-green-500/20 flex items-center justify-center mx-auto mb-5 bf-unlock-success-icon" style="box-shadow: 0 0 30px rgba(34,197,94,0.3)">
<i data-lucide="check-circle" class="w-10 h-10 text-green-400"></i>
</div>
<h3 class="text-xl font-bold text-white mb-1" style="animation-delay:0.1s">Unlocked β Downloading now</h3>
<p class="text-sm text-gray-400 mb-1" style="animation-delay:0.2s">${_dlTrackTitle} Β· ${_dlArtistName}</p>
<p class="text-xs text-green-400 font-medium mb-1" style="animation-delay:0.25s">Paid ${amount.toFixed(2)} Β· Creator receives ${(amount * 0.85).toFixed(2)}</p>
<div class="bf-download-progress" style="animation-delay:0.3s">
<div class="bf-download-progress-bar"></div>
</div>
<div class="mt-4 flex items-center gap-2 text-green-400 text-sm font-medium" style="animation-delay:0.35s">
<i data-lucide="download" class="w-4 h-4"></i>
<span>Download starting...</span>
</div>
</div>
`;
lucide.createIcons();
}
// Auto-close after brief success display
setTimeout(() => {
closeDownloadModal();
showToast('Unlocked β Downloading now β');
}, 2200);
};
const processMockDownload = () => {
showToast('β¬οΈ Downloading: ' + _dlTrackTitle + ' β ' + _dlArtistName);
};
const showSuperFanPaymentStep = () => {
const step1 = document.getElementById('bfSfStep1');
const step2 = document.getElementById('bfSfStep2');
if (step1) step1.classList.add('hidden');
if (step2) step2.classList.remove('hidden');
const nameInput = document.getElementById('bfSfCardName');
if (nameInput) nameInput.focus();
};
const showSuperFanSummaryStep = () => {
const step1 = document.getElementById('bfSfStep1');
const step2 = document.getElementById('bfSfStep2');
if (step2) step2.classList.add('hidden');
if (step1) step1.classList.remove('hidden');
};
const formatCardNumber = (input) => {
let v = input.value.replace(/\D/g, '').substring(0, 16);
let formatted = v.match(/.{1,4}/g);
input.value = formatted ? formatted.join(' ') : '';
};
const formatCardExpiry = (input) => {
let v = input.value.replace(/\D/g, '').substring(0, 4);
if (v.length >= 2) {
v = v.substring(0, 2) + '/' + v.substring(2);
}
input.value = v;
};
const confirmSuperFanPayment = () => {
const name = document.getElementById('bfSfCardName')?.value.trim();
const number = document.getElementById('bfSfCardNumber')?.value.replace(/\s/g, '');
const expiry = document.getElementById('bfSfCardExpiry')?.value.trim();
const cvc = document.getElementById('bfSfCardCvc')?.value.trim();
const errEl = document.getElementById('bfSfPaymentError');
// Validate fields
if (!name) {
if (errEl) { errEl.textContent = 'Please enter the name on your card'; errEl.classList.remove('hidden'); }
document.getElementById('bfSfCardName')?.classList.add('error');
return;
}
document.getElementById('bfSfCardName')?.classList.remove('error');
if (!number || number.length < 13) {
if (errEl) { errEl.textContent = 'Please enter a valid card number'; errEl.classList.remove('hidden'); }
document.getElementById('bfSfCardNumber')?.classList.add('error');
return;
}
document.getElementById('bfSfCardNumber')?.classList.remove('error');
if (!expiry || !/^\d{2}\/\d{2}$/.test(expiry)) {
if (errEl) { errEl.textContent = 'Please enter a valid expiry date (MM/YY)'; errEl.classList.remove('hidden'); }
document.getElementById('bfSfCardExpiry')?.classList.add('error');
return;
}
document.getElementById('bfSfCardExpiry')?.classList.remove('error');
if (!cvc || cvc.length < 3) {
if (errEl) { errEl.textContent = 'Please enter a valid CVC'; errEl.classList.remove('hidden'); }
document.getElementById('bfSfCardCvc')?.classList.add('error');
return;
}
document.getElementById('bfSfCardCvc')?.classList.remove('error');
// Hide error, show processing
if (errEl) errEl.classList.add('hidden');
document.getElementById('bfSfStep2')?.classList.add('hidden');
document.getElementById('bfSfStep3')?.classList.remove('hidden');
// Simulate payment processing (1.5s delay for speed)
const last4 = number.replace(/\s/g, '').slice(-4);
// Save card for quick re-use
try {
localStorage.setItem('bf_saved_card', JSON.stringify({
name: name,
last4: last4,
expiry: expiry
}));
} catch (e) {}
setTimeout(() => {
// Simulate random payment failure (~15% on first attempt, 0% on retry)
if (_sfRetryAttempt === 0 && Math.random() < 0.15) {
_sfRetryAttempt++;
document.getElementById('bfSfStep3')?.classList.add('hidden');
const step2 = document.getElementById('bfSfStep2');
if (step2) {
step2.classList.remove('hidden');
const errEl = document.getElementById('bfSfPaymentError');
if (errEl) {
errEl.textContent = 'Payment declined β please try again or use a different card';
errEl.classList.remove('hidden');
}
// Show retry button
const existingBtn = step2.querySelector('.bf-retry-btn');
if (!existingBtn) {
const retryBtn = document.createElement('button');
retryBtn.className = 'bf-retry-btn w-full py-3 bg-gradient-to-r from-orange-500 to-red-500 hover:from-orange-400 hover:to-red-400 text-white font-semibold rounded-xl transition flex items-center justify-center gap-2 mt-3';
retryBtn.style.boxShadow = '0 0 20px rgba(249,115,22,0.3)';
retryBtn.innerHTML = '<i data-lucide="refresh-cw" class="w-5 h-5"></i> Retry Payment Β· $25/mo';
retryBtn.onclick = () => confirmSuperFanPayment();
const confirmBtn = step2.querySelector('button[onclick="BF.confirmSuperFanPayment()"]');
if (confirmBtn) confirmBtn.parentElement.insertBefore(retryBtn, confirmBtn.nextSibling);
lucide.createIcons();
}
}
return;
}
// Activate subscription with rich data
const key = 'bf_superfan';
let subs = [];
try { subs = JSON.parse(localStorage.getItem(key) || '[]'); } catch { subs = []; }
migrateSuperFanData();
const slug = _sfArtistName.toLowerCase().replace(/\s+/g, '-');
const existing = subs.find(s => typeof s === 'string' ? s === slug : s.slug === slug);
if (!existing) {
subs.push({
slug: slug,
name: _sfArtistName,
image: _sfArtistImage,
date: new Date().toISOString(),
active: true,
payment: { last4: last4, amount: 25, currency: 'USD' }
});
localStorage.setItem(key, JSON.stringify(subs));
}
// Record transaction
try {
const transactions = JSON.parse(localStorage.getItem('transactions') || '[]');
transactions.push({
type: 'subscription',
amount: 25,
artist: _sfArtistName,
tier: 'Super Fan',
date: new Date().toISOString(),
fee: 3.75,
currency: 'USD',
paymentMethod: 'card',
cardLast4: last4,
status: 'completed',
userId: getCurrentUser()?.id || null
});
localStorage.setItem('transactions', JSON.stringify(transactions));
} catch {}
// Record creator earning
recordCreatorEarning({
type: 'subscription',
amount: 25,
artist: _sfArtistName,
track: null,
trackId: null,
fee: 3.75,
currency: 'USD',
paymentMethod: 'card',
cardLast4: last4,
status: 'completed',
date: new Date().toISOString()
});
// Show success step
document.getElementById('bfSfStep3')?.classList.add('hidden');
document.getElementById('bfSfStep4')?.classList.remove('hidden');
if (window.lucide) lucide.createIcons();
// Update all Super Fan buttons on page
updateSuperFanButtons();
// Auto-close modal after 1.8s and show toast
setTimeout(() => {
closeSuperFanModal();
showToast('You are now a Super Fan of ' + _sfArtistName + ' \ud83c\udfa7');
if (window.lucide) lucide.createIcons();
}, 1800);
}, 2000);
};
const isSuperFanOf = (artistName) => {
try {
migrateSuperFanData();
const subs = JSON.parse(localStorage.getItem('bf_superfan') || '[]');
const slug = artistName.toLowerCase().replace(/\s+/g, '-');
return subs.some(s => {
if (typeof s === 'string') return s === slug;
return s.slug === slug && s.active !== false;
});
} catch { return false; }
};
const updateSuperFanButtons = () => {
document.querySelectorAll('[data-superfan-artist]').forEach(btn => {
const artist = btn.getAttribute('data-superfan-artist');
const isActive = isSuperFanOf(artist);
const isSmall = btn.getAttribute('data-superfan-size') === 'small';
if (isActive) {
if (isSmall) {
btn.innerHTML = '<i data-lucide="check-circle" class="w-3.5 h-3.5"></i><span>Super Fan Active \u2713</span>';
} else {
btn.innerHTML = '<i data-lucide="check-circle" class="w-4 h-4"></i><span>Super Fan Active \u2713</span>';
}
btn.className = btn.className.replace(/bg-gradient-to-r from-orange-500 to-red-500 hover:from-orange-400 hover:to-red-400 text-white/g, '');
btn.classList.remove('bg-gradient-to-r', 'from-orange-500', 'to-red-500', 'hover:from-orange-400', 'hover:to-red-400', 'text-white', 'bf-superfan-btn');
btn.classList.add('bg-green-500/20', 'text-green-400', 'border', 'border-green-500/30');
if (!isSmall) btn.style.boxShadow = '0 0 20px rgba(34,197,94,0.2)';
else btn.style.boxShadow = '';
} else {
if (isSmall) {
btn.innerHTML = '<i data-lucide="zap" class="w-3.5 h-3.5"></i><span>Super Fan</span>';
} else {
btn.innerHTML = '<i data-lucide="zap" class="w-4 h-4"></i><span>Become Super Fan</span>';
}
btn.classList.remove('bg-green-500/20', 'text-green-400', 'border', 'border-green-500/30');
btn.classList.add('bg-gradient-to-r', 'from-orange-500', 'to-red-500', 'hover:from-orange-400', 'hover:to-red-400', 'text-white', 'bf-superfan-btn');
if (!isSmall) btn.style.boxShadow = '0 0 20px rgba(249,115,22,0.3)';
else btn.style.boxShadow = '';
}
});
};
// ===== ROLE SYSTEM =====
const ROLES = { GUEST: 'guest', USER: 'user', CREATOR: 'creator', SUPERFAN: 'superfan' };
const getUserRole = () => {
if (!isLoggedIn()) return ROLES.GUEST;
const user = getCurrentUser();
if (!user) return ROLES.GUEST;
if (getSuperFanSubscriptions().length > 0) return ROLES.SUPERFAN;
if (user.role === 'producer' || user.isArtist) return ROLES.CREATOR;
return ROLES.USER;
};
const canBrowse = () => true;
const canDownload = () => isLoggedIn();
const canUpload = () => { const r = getUserRole(); return r === ROLES.CREATOR || r === ROLES.SUPERFAN; };
const canEarn = () => getUserRole() === ROLES.CREATOR;
const hasFreeDownloads = (artistName) => isSuperFanOf(artistName);
// ===== MONETIZATION CONFIG =====
const MONETIZATION_DEFAULTS = {
minimumPrice: 0.50,
platformFeePercent: 15,
creatorPayoutPercent: 85,
currency: 'USD',
superFanMonthlyPrice: 25
};
const getMonetizationConfig = () => {
try { return JSON.parse(localStorage.getItem('bf_monetization_config')) || { ...MONETIZATION_DEFAULTS }; }
catch { return { ...MONETIZATION_DEFAULTS }; }
};
// ===== TRACK MONETIZATION =====
const getTrackMonetization = (trackId) => {
try {
const states = JSON.parse(localStorage.getItem('bf_track_monetization') || '[]');
return states.find(s => s.trackId === trackId) || null;
} catch { return null; }
};
const setTrackMonetization = (trackId, config) => {
try {
let states = JSON.parse(localStorage.getItem('bf_track_monetization') || '[]');
const idx = states.findIndex(s => s.trackId === trackId);
const entry = {
trackId,
isMonetized: config.isMonetized !== false,
minimumPrice: config.minimumPrice || MONETIZATION_DEFAULTS.minimumPrice,
suggestedPrice: config.suggestedPrice || 2.99,
isLocked: config.isLocked !== false,
superFanFree: config.superFanFree !== false,
currency: config.currency || MONETIZATION_DEFAULTS.currency,
updatedAt: new Date().toISOString()
};
if (idx > -1) states[idx] = entry; else states.push(entry);
localStorage.setItem('bf_track_monetization', JSON.stringify(states));
return entry;
} catch (e) { return null; }
};
const isTrackLocked = (trackId, artistName) => {
if (isSuperFanOf(artistName)) return false;
if (isDownloadUnlocked(trackId, artistName)) return false;
const m = getTrackMonetization(trackId);
return m ? m.isLocked : false;
};
// ===== CREATOR EARNINGS =====
const getCreatorEarnings = (creatorId) => {
try {
const earnings = JSON.parse(localStorage.getItem('bf_creator_earnings') || '[]');
return creatorId ? earnings.filter(e => e.creatorId === creatorId) : earnings;
} catch { return []; }
};
const recordCreatorEarning = (tx) => {
try {
let earnings = JSON.parse(localStorage.getItem('bf_creator_earnings') || '[]');
const config = getMonetizationConfig();
const fee = tx.fee || +(tx.amount * config.platformFeePercent / 100).toFixed(2);
const user = getCurrentUser();
const earning = {
id: 'earn_' + Date.now(),
creatorId: tx.creatorId || tx.artist,
creatorName: tx.artist,
source: tx.type,
grossAmount: tx.amount,
platformFee: fee,
netAmount: +(tx.amount - fee).toFixed(2),
currency: tx.currency || config.currency,
trackId: tx.trackId || null,
trackTitle: tx.track || null,
userId: user ? user.id : null,
date: tx.date || new Date().toISOString(),
status: 'completed',
paymentMethod: tx.paymentMethod || 'card',
cardLast4: tx.cardLast4 || null
};
earnings.push(earning);
localStorage.setItem('bf_creator_earnings', JSON.stringify(earnings));
return earning;
} catch (e) { return null; }
};
const getCreatorEarningsSummary = (creatorId) => {
const earnings = getCreatorEarnings(creatorId);
const summary = {
totalGross: 0,
totalNet: 0,
totalFees: 0,
bySource: {},
byMonth: {},
transactionCount: earnings.length
};
earnings.forEach(e => {
summary.totalGross += e.grossAmount;
summary.totalNet += e.netAmount;
summary.totalFees += e.platformFee;
summary.bySource[e.source] = (summary.bySource[e.source] || 0) + e.grossAmount;
const month = e.date.substring(0, 7);
summary.byMonth[month] = (summary.byMonth[month] || 0) + e.grossAmount;
});
summary.totalGross = +summary.totalGross.toFixed(2);
summary.totalNet = +summary.totalNet.toFixed(2);
summary.totalFees = +summary.totalFees.toFixed(2);
return summary;
};
// ===== ENHANCED TRANSACTIONS =====
const getTransactionHistory = (filters) => {
try {
let transactions = JSON.parse(localStorage.getItem('transactions') || '[]');
if (filters) {
if (filters.type) transactions = transactions.filter(t => t.type === filters.type);
if (filters.artist) transactions = transactions.filter(t => t.artist === filters.artist);
if (filters.status) transactions = transactions.filter(t => t.status === filters.status);
if (filters.userId) transactions = transactions.filter(t => t.userId === filters.userId);
}
return transactions.sort((a, b) => new Date(b.date) - new Date(a.date));
} catch { return []; }
};
// ===== MONETIZATION PRESETS =====
const MonetizationPresets = {
free: { isMonetized: false, isLocked: false, minimumPrice: 0, suggestedPrice: 0, superFanFree: true },
payWhatYouWant: { isMonetized: true, isLocked: true, minimumPrice: 0.50, suggestedPrice: 0, superFanFree: true },
fixedPrice: { isMonetized: true, isLocked: true, minimumPrice: 0.99, suggestedPrice: 2.99, superFanFree: true },
superFanExclusive: { isMonetized: true, isLocked: true, minimumPrice: 0, suggestedPrice: 0, superFanFree: false },
premium: { isMonetized: true, isLocked: true, minimumPrice: 4.99, suggestedPrice: 9.99, superFanFree: true }
};
// ===== UNIFIED PAYMENT PROCESSING =====
const processTip = (artistName, amount, options = {}) => {
if (!isLoggedIn()) return { success: false, error: 'Must be logged in to tip' };
if (!amount || isNaN(amount) || amount < MONETIZATION_DEFAULTS.minimumPrice) {
return { success: false, error: 'Minimum tip is
const init = (activeTab) => {
injectStyles();
injectBottomNav(activeTab);
migrateSuperFanData();
syncPlayer();
updateTopNav();
adjustTopNav();
updateSuperFanButtons();
if (window.lucide) lucide.createIcons();
// Check for referral parameter in URL
try {
const urlParams = new URLSearchParams(window.location.search);
const refCode = urlParams.get('ref');
if (refCode) trackReferralClick(refCode);
} catch {}
// Re-sync player every 2 seconds
setInterval(syncPlayer, 2000);
};
return {
isLoggedIn, isProducer, isFan, getCurrentUser, signIn, signOut, signUp,
getAllTracks, getArtists, getGenres, getTrendingTracks, getFreshUploads,
searchTracks, searchArtists,
init, showSignInModal, closeSignInModal, handleSignIn,
showSignUpForm, showSignInForm, showChooseType, handleSignUp,
adjustTopNav, showToast, syncPlayer, playTrack, togglePlay,
showSuperFanModal, closeSuperFanModal, confirmSuperFanPayment, showSuperFanPaymentStep, showSuperFanSummaryStep, formatCardNumber, formatCardExpiry, isSuperFanOf, updateSuperFanButtons,
getSuperFanSubscriptions, cancelSuperFanSubscription,
showDownloadModal, closeDownloadModal, isDownloadUnlocked, unlockTrackDownload, getDownloadStates, handleDownloadUnlock, processMockDownload,
// Role system
ROLES, getUserRole, canBrowse, canDownload, canUpload, canEarn, hasFreeDownloads,
// Monetization
MONETIZATION_DEFAULTS, getMonetizationConfig,
getTrackMonetization, setTrackMonetization, isTrackLocked,
// Creator earnings
getCreatorEarnings, recordCreatorEarning, getCreatorEarningsSummary,
// Enhanced transactions
getTransactionHistory,
// Monetization presets
MonetizationPresets,
// Unified payment processing
processTip, processSubscription,
// User capabilities
getUserCapabilities,
// Track publishing with monetization
publishTrackWithMonetization,
// Creator dashboard
getCreatorDashboard,
// Download button renderer
renderDL,
// Share button renderer
renderShare,
// Share system
showShareModal, closeShareModal,
shareViaWhatsApp, shareViaFacebook, shareViaTwitter, copyTrackLink,
trackShare, getShareCount, getUnlockCount,
// Referral system
getReferralCode, recordReferralSignup, getReferralStats, trackReferralClick,
// Quick amount selector
selectQuickAmount, onCustomAmountInput,
// Preview snippet
playPreviewSnippet,
// Like system
toggleLike, isLiked, getLikedTracks, renderLikeBtn, handleLikeClick,
// Recommendations
getRecommendations,
// Queue / continuous playback
setPlayQueue, getPlayQueue, playNext, playPrevious, replayTrack,
// Creator onboarding & incentives
isFirstTimeCreator, getOnboardingState, getCreatorBadges,
getTopCreatorsThisWeek, getMotivationalPrompt,
dismissOnboarding, isOnboardingDismissed,
// Trending algorithm
getRisingBeats, getTrackTrendIndicator, recordActivity,
simulateRecentActivity, saveRankingSnapshot
};
})(); + MONETIZATION_DEFAULTS.minimumPrice };
}
try {
const config = getMonetizationConfig();
const fee = +(amount * config.platformFeePercent / 100).toFixed(2);
const user = getCurrentUser();
const last4 = options.cardLast4 || '4242';
const tx = {
type: 'tip',
amount: amount,
artist: artistName,
date: new Date().toISOString(),
fee: fee,
currency: options.currency || config.currency,
paymentMethod: options.paymentMethod || 'card',
cardLast4: last4,
status: 'completed',
userId: user ? user.id : null,
message: options.message || null
};
const transactions = JSON.parse(localStorage.getItem('transactions') || '[]');
transactions.push(tx);
localStorage.setItem('transactions', JSON.stringify(transactions));
recordCreatorEarning(tx);
if (options.deductFromWallet !== false) {
const balance = parseFloat(localStorage.getItem('walletBalance') || '0');
if (balance >= amount) {
localStorage.setItem('walletBalance', (balance - amount).toFixed(2));
}
}
return { success: true, transaction: tx };
} catch (e) {
return { success: false, error: 'Tip processing failed' };
}
};
const processSubscription = (artistName, amount, tier, options = {}) => {
if (!isLoggedIn()) return { success: false, error: 'Must be logged in to subscribe' };
try {
const config = getMonetizationConfig();
const fee = +(amount * config.platformFeePercent / 100).toFixed(2);
const user = getCurrentUser();
const last4 = options.cardLast4 || '4242';
const tx = {
type: 'subscription',
amount: amount,
artist: artistName,
tier: tier,
date: new Date().toISOString(),
fee: fee,
currency: options.currency || config.currency,
paymentMethod: options.paymentMethod || 'card',
cardLast4: last4,
status: 'completed',
userId: user ? user.id : null
};
const transactions = JSON.parse(localStorage.getItem('transactions') || '[]');
transactions.push(tx);
localStorage.setItem('transactions', JSON.stringify(transactions));
recordCreatorEarning(tx);
return { success: true, transaction: tx };
} catch (e) {
return { success: false, error: 'Subscription processing failed' };
}
};
// ===== USER CAPABILITIES =====
const getUserCapabilities = () => {
const role = getUserRole();
const user = getCurrentUser();
const isCreatorRole = user && (user.role === 'producer' || user.isArtist);
const isSuperFanRole = role === ROLES.SUPERFAN;
const isCreator = isCreatorRole || isSuperFanRole;
const isGuest = role === ROLES.GUEST;
const compositeRoles = [];
if (isCreatorRole) compositeRoles.push(ROLES.CREATOR);
if (isSuperFanRole) compositeRoles.push(ROLES.SUPERFAN);
if (!isCreatorRole && !isSuperFanRole && !isGuest) compositeRoles.push(ROLES.USER);
if (isGuest) compositeRoles.push(ROLES.GUEST);
return {
role: role,
roles: compositeRoles,
canBrowse: true,
canPlay: true,
canDownload: !isGuest,
canUpload: isCreator,
canEarn: isCreatorRole,
canMonetize: isCreatorRole,
hasFreeDownloads: isSuperFanRole,
canComment: !isGuest,
canFollow: !isGuest,
canLike: !isGuest,
canCreatePlaylist: !isGuest,
canViewAnalytics: isCreatorRole,
canSetPricing: isCreatorRole,
canManageTracks: isCreatorRole,
canUpgradeRole: !isGuest,
maxUploadSize: isCreator ? 500 : 0,
maxTracks: isCreator ? (localStorage.getItem('isPro') === 'true' ? Infinity : 10) : 0
};
};
// ===== PUBLISH TRACK WITH MONETIZATION =====
const publishTrackWithMonetization = (trackData, monetizationConfig = null) => {
try {
let allTracks = JSON.parse(localStorage.getItem('beatfridge_tracks') || '[]');
allTracks.push(trackData);
localStorage.setItem('beatfridge_tracks', JSON.stringify(allTracks));
let userTracks = JSON.parse(localStorage.getItem('userTracks') || '[]');
userTracks.push(trackData);
localStorage.setItem('userTracks', JSON.stringify(userTracks));
if (monetizationConfig && monetizationConfig.isMonetized) {
setTrackMonetization(trackData.id, monetizationConfig);
} else if (monetizationConfig) {
setTrackMonetization(trackData.id, {
isMonetized: false,
isLocked: false,
superFanFree: true,
...monetizationConfig
});
}
return { success: true, track: trackData };
} catch (e) {
return { success: false, error: 'Publish failed: ' + e.message };
}
};
// ===== CREATOR DASHBOARD DATA =====
const getCreatorDashboard = (creatorId) => {
const earnings = getCreatorEarnings(creatorId);
const summary = getCreatorEarningsSummary(creatorId);
const allTransactions = getTransactionHistory({});
const creatorTransactions = allTransactions.filter(t => t.artist === creatorId || t.artistId === creatorId);
const tracks = getAllTracks().filter(t => t.artistId === creatorId || t.artist === creatorId);
const config = getMonetizationConfig();
const trackStats = tracks.map(track => {
const monetization = getTrackMonetization(track.id);
const trackEarnings = earnings.filter(e => e.trackId === track.id);
const trackRevenue = trackEarnings.reduce((sum, e) => sum + e.netAmount, 0);
return {
trackId: track.id,
title: track.title,
plays: track.plays,
revenue: +trackRevenue.toFixed(2),
monetization: monetization,
isLocked: monetization ? monetization.isLocked : false,
downloadCount: trackEarnings.filter(e => e.source === 'download').length,
tipCount: trackEarnings.filter(e => e.source === 'tip').length
};
});
return {
summary,
tracks: trackStats,
recentTransactions: creatorTransactions.slice(0, 20),
monetizationConfig: config,
payoutRate: config.creatorPayoutPercent + '%',
pendingPayout: summary.totalNet,
lastUpdated: new Date().toISOString()
};
};
// ===== RENDER DOWNLOAD BUTTON =====
const renderDL = (trackId, trackTitle, artistName) => {
const safeTitle = String(trackTitle).replace(/'/g, "\\'").replace(/"/g, '"');
const safeArtist = String(artistName).replace(/'/g, "\\'").replace(/"/g, '"');
const unlockCount = getUnlockCount(trackId);
if (isSuperFanOf(artistName)) {
return `<button class="bf-download-btn bf-dl-free" onclick="event.stopPropagation(); BF.showDownloadModal('${safeTitle}', '${safeArtist}', ${trackId})"><i data-lucide="download" class="w-3 h-3"></i>Free</button>`;
}
if (isDownloadUnlocked(trackId, artistName)) {
return `<button class="bf-download-btn bf-dl-unlocked" onclick="event.stopPropagation(); BF.showDownloadModal('${safeTitle}', '${safeArtist}', ${trackId})"><i data-lucide="download" class="w-3 h-3"></i>Download</button>`;
}
const proofHtml = unlockCount > 0 ? `<span class="bf-social-proof" style="margin-top:3px"><i data-lucide="users" class="w-3 h-3"></i>${unlockCount} unlocked</span>` : '';
return `<div style="display:inline-flex;flex-direction:column;align-items:flex-end;gap:2px"><button class="bf-unlock-btn" onclick="event.stopPropagation(); BF.showDownloadModal('${safeTitle}', '${safeArtist}', ${trackId})"><i data-lucide="lock" class="w-3 h-3"></i>Unlock from $0.50</button>${proofHtml}</div>`;
};
// ===== LIKE SYSTEM =====
const toggleLike = (trackId, trackTitle, trackArtist) => {
try {
let liked = JSON.parse(localStorage.getItem('bf_liked_tracks') || '[]');
const idx = liked.findIndex(t => t.id === trackId);
if (idx > -1) {
liked.splice(idx, 1);
localStorage.setItem('bf_liked_tracks', JSON.stringify(liked));
return { liked: false, count: liked.length };
}
liked.unshift({ id: trackId, title: trackTitle, artist: trackArtist, likedAt: new Date().toISOString() });
if (liked.length > 200) liked.pop();
localStorage.setItem('bf_liked_tracks', JSON.stringify(liked));
return { liked: true, count: liked.length };
} catch { return { liked: false, count: 0 }; }
};
const isLiked = (trackId) => {
try { return JSON.parse(localStorage.getItem('bf_liked_tracks') || '[]').some(t => t.id === trackId); }
catch { return false; }
};
const getLikedTracks = () => {
try { return JSON.parse(localStorage.getItem('bf_liked_tracks') || '[]'); }
catch { return []; }
};
const renderLikeBtn = (trackId, trackTitle, trackArtist) => {
const liked = isLiked(trackId);
const sT = String(trackTitle).replace(/'/g, "\\'").replace(/"/g, '"');
const sA = String(trackArtist).replace(/'/g, "\\'").replace(/"/g, '"');
return '<button class="bf-like-btn' + (liked ? ' bf-liked' : '') + '" onclick="event.stopPropagation();BF.handleLikeClick(' + trackId + ',\'' + sT + '\',\'' + sA + '\',this)"><i data-lucide="heart" class="w-3 h-3' + (liked ? ' fill-current' : '') + '"></i>' + (liked ? 'Liked' : 'Like') + '</button>';
};
const handleLikeClick = (trackId, trackTitle, trackArtist, btn) => {
const result = toggleLike(trackId, trackTitle, trackArtist);
if (btn) {
if (result.liked) {
btn.classList.add('bf-liked');
btn.innerHTML = '<i data-lucide="heart" class="w-3 h-3 fill-current"></i>Liked';
showToast('Added to your likes β€οΈ');
} else {
btn.classList.remove('bf-liked');
btn.innerHTML = '<i data-lucide="heart" class="w-3 h-3"></i>Like';
showToast('Removed from likes');
}
if (window.lucide) lucide.createIcons();
}
return result;
};
// ===== RECOMMENDATIONS =====
const getRecommendations = (track, limit) => {
limit = limit || 6;
const allTracks = getAllTracks();
if (!track) return allTracks.slice(0, limit);
return allTracks
.filter(t => t.id !== track.id)
.map(t => {
let score = 0;
if (t.genre && track.genre && t.genre.toLowerCase() === track.genre.toLowerCase()) score += 50;
if (t.artist && track.artist && t.artist.toLowerCase() === track.artist.toLowerCase()) score += 25;
if (t.artistId && track.artistId && t.artistId === track.artistId) score += 20;
const tp = parseFloat((t.plays || '0').replace('K', '')) * ((t.plays || '').includes('K') ? 1000 : 1);
score += Math.min(tp / 1000, 10);
score += Math.random() * 8;
return { ...t, _recScore: score };
})
.sort((a, b) => b._recScore - a._recScore)
.slice(0, limit);
};
// ===== QUEUE / CONTINUOUS PLAYBACK =====
let _playQueue = [];
let _queueIndex = -1;
const setPlayQueue = (tracks, startIndex) => {
startIndex = startIndex || 0;
_playQueue = tracks.map(t => ({ ...t }));
_queueIndex = startIndex;
try {
localStorage.setItem('bf_play_queue', JSON.stringify(_playQueue));
localStorage.setItem('bf_queue_index', String(_queueIndex));
} catch {}
};
const getPlayQueue = () => {
try {
if (!_playQueue.length) {
_playQueue = JSON.parse(localStorage.getItem('bf_play_queue') || '[]');
_queueIndex = parseInt(localStorage.getItem('bf_queue_index') || '-1');
}
return { queue: _playQueue, index: _queueIndex };
} catch { return { queue: [], index: -1 }; }
};
const playNext = () => {
const { queue, index } = getPlayQueue();
if (!queue.length) return false;
const repeat = localStorage.getItem('bf_repeat') === 'true';
let nextIdx = index + 1;
if (nextIdx >= queue.length) {
if (!repeat) return false;
nextIdx = 0;
}
_queueIndex = nextIdx;
try { localStorage.setItem('bf_queue_index', String(_queueIndex)); } catch {}
playTrack(queue[nextIdx], true);
return true;
};
const playPrevious = () => {
const { queue, index } = getPlayQueue();
if (!queue.length) return false;
let prevIdx = index - 1;
if (prevIdx < 0) prevIdx = queue.length - 1;
_queueIndex = prevIdx;
try { localStorage.setItem('bf_queue_index', String(_queueIndex)); } catch {}
playTrack(queue[prevIdx], true);
return true;
};
const replayTrack = () => {
try {
const track = JSON.parse(localStorage.getItem('currentTrack'));
if (track) { playTrack(track); return true; }
} catch {}
return false;
};
// ===== PREVIEW SNIPPET =====
let _previewTimer = null;
let _previewPlaying = false;
const playPreviewSnippet = () => {
const snippet = document.getElementById('bfPreviewSnippet');
const playIcon = document.getElementById('bfPreviewPlayIcon');
const timeLabel = document.getElementById('bfPreviewTime');
if (!snippet) return;
if (_previewPlaying) {
// Stop preview
_previewPlaying = false;
snippet.classList.remove('bf-preview-active');
if (playIcon) { playIcon.setAttribute('data-lucide', 'play'); playIcon.classList.add('ml-0.5'); }
if (timeLabel) timeLabel.textContent = 'Preview Β· 0:10';
if (_previewTimer) { clearTimeout(_previewTimer); _previewTimer = null; }
lucide.createIcons();
return;
}
// Start preview β simulate 10-second snippet
_previewPlaying = true;
snippet.classList.add('bf-preview-active');
if (playIcon) { playIcon.setAttribute('data-lucide', 'pause'); playIcon.classList.remove('ml-0.5'); }
let secondsLeft = 10;
if (timeLabel) timeLabel.textContent = 'Playing Β· 0:' + String(secondsLeft).padStart(2, '0');
lucide.createIcons();
_previewTimer = setInterval(() => {
secondsLeft--;
if (secondsLeft <= 0) {
// Auto-stop after 10 seconds
_previewPlaying = false;
snippet.classList.remove('bf-preview-active');
if (playIcon) { playIcon.setAttribute('data-lucide', 'play'); playIcon.classList.add('ml-0.5'); }
if (timeLabel) timeLabel.textContent = 'Preview Β· 0:10';
clearInterval(_previewTimer);
_previewTimer = null;
lucide.createIcons();
return;
}
if (timeLabel) timeLabel.textContent = 'Playing Β· 0:' + String(secondsLeft).padStart(2, '0');
}, 1000);
};
// ===== QUICK AMOUNT SELECTOR =====
const selectQuickAmount = (amount) => {
const input = document.getElementById('bfDownloadAmount');
if (input) input.value = amount > 0 ? amount.toFixed(2) : '';
document.querySelectorAll('.bf-quick-amount').forEach(btn => {
const btnVal = parseFloat(btn.textContent.replace('
injectStyles();
injectBottomNav(activeTab);
migrateSuperFanData();
syncPlayer();
updateTopNav();
adjustTopNav();
updateSuperFanButtons();
if (window.lucide) lucide.createIcons();
// Re-sync player every 2 seconds
setInterval(syncPlayer, 2000);
};
return {
isLoggedIn, isProducer, isFan, getCurrentUser, signIn, signOut, signUp,
getAllTracks, getArtists, getGenres, getTrendingTracks, getFreshUploads,
searchTracks, searchArtists,
init, showSignInModal, closeSignInModal, handleSignIn,
showSignUpForm, showSignInForm, showChooseType, handleSignUp,
adjustTopNav, showToast, syncPlayer, playTrack, togglePlay,
showSuperFanModal, closeSuperFanModal, confirmSuperFanPayment, showSuperFanPaymentStep, showSuperFanSummaryStep, formatCardNumber, formatCardExpiry, isSuperFanOf, updateSuperFanButtons,
getSuperFanSubscriptions, cancelSuperFanSubscription,
showDownloadModal, closeDownloadModal, isDownloadUnlocked, unlockTrackDownload, getDownloadStates, handleDownloadUnlock, processMockDownload,
// Role system
ROLES, getUserRole, canBrowse, canDownload, canUpload, canEarn, hasFreeDownloads,
// Monetization
MONETIZATION_DEFAULTS, getMonetizationConfig,
getTrackMonetization, setTrackMonetization, isTrackLocked,
// Creator earnings
getCreatorEarnings, recordCreatorEarning, getCreatorEarningsSummary,
// Enhanced transactions
getTransactionHistory
};
})();, ''));
btn.classList.toggle('active', amount > 0 && btnVal === amount);
});
const cta = document.getElementById('bfDownloadCta');
if (cta) {
if (amount > 0) {
cta.innerHTML = '<i data-lucide="lock" class="w-5 h-5"></i> Unlock & Download Β·
injectStyles();
injectBottomNav(activeTab);
migrateSuperFanData();
syncPlayer();
updateTopNav();
adjustTopNav();
updateSuperFanButtons();
if (window.lucide) lucide.createIcons();
// Re-sync player every 2 seconds
setInterval(syncPlayer, 2000);
};
return {
isLoggedIn, isProducer, isFan, getCurrentUser, signIn, signOut, signUp,
getAllTracks, getArtists, getGenres, getTrendingTracks, getFreshUploads,
searchTracks, searchArtists,
init, showSignInModal, closeSignInModal, handleSignIn,
showSignUpForm, showSignInForm, showChooseType, handleSignUp,
adjustTopNav, showToast, syncPlayer, playTrack, togglePlay,
showSuperFanModal, closeSuperFanModal, confirmSuperFanPayment, showSuperFanPaymentStep, showSuperFanSummaryStep, formatCardNumber, formatCardExpiry, isSuperFanOf, updateSuperFanButtons,
getSuperFanSubscriptions, cancelSuperFanSubscription,
showDownloadModal, closeDownloadModal, isDownloadUnlocked, unlockTrackDownload, getDownloadStates, handleDownloadUnlock, processMockDownload,
// Role system
ROLES, getUserRole, canBrowse, canDownload, canUpload, canEarn, hasFreeDownloads,
// Monetization
MONETIZATION_DEFAULTS, getMonetizationConfig,
getTrackMonetization, setTrackMonetization, isTrackLocked,
// Creator earnings
getCreatorEarnings, recordCreatorEarning, getCreatorEarningsSummary,
// Enhanced transactions
getTransactionHistory
};
})(); + amount.toFixed(2);
} else {
cta.innerHTML = '<i data-lucide="lock" class="w-5 h-5"></i> Unlock & Download';
}
if (window.lucide) lucide.createIcons();
}
if (amount === 0 && input) input.focus();
};
const onCustomAmountInput = () => {
const input = document.getElementById('bfDownloadAmount');
const val = parseFloat(input?.value);
document.querySelectorAll('.bf-quick-amount').forEach(btn => btn.classList.remove('active'));
const cta = document.getElementById('bfDownloadCta');
if (cta) {
if (val && val >= 0.50) {
cta.innerHTML = '<i data-lucide="lock" class="w-5 h-5"></i> Unlock & Download Β·
injectStyles();
injectBottomNav(activeTab);
migrateSuperFanData();
syncPlayer();
updateTopNav();
adjustTopNav();
updateSuperFanButtons();
if (window.lucide) lucide.createIcons();
// Re-sync player every 2 seconds
setInterval(syncPlayer, 2000);
};
return {
isLoggedIn, isProducer, isFan, getCurrentUser, signIn, signOut, signUp,
getAllTracks, getArtists, getGenres, getTrendingTracks, getFreshUploads,
searchTracks, searchArtists,
init, showSignInModal, closeSignInModal, handleSignIn,
showSignUpForm, showSignInForm, showChooseType, handleSignUp,
adjustTopNav, showToast, syncPlayer, playTrack, togglePlay,
showSuperFanModal, closeSuperFanModal, confirmSuperFanPayment, showSuperFanPaymentStep, showSuperFanSummaryStep, formatCardNumber, formatCardExpiry, isSuperFanOf, updateSuperFanButtons,
getSuperFanSubscriptions, cancelSuperFanSubscription,
showDownloadModal, closeDownloadModal, isDownloadUnlocked, unlockTrackDownload, getDownloadStates, handleDownloadUnlock, processMockDownload,
// Role system
ROLES, getUserRole, canBrowse, canDownload, canUpload, canEarn, hasFreeDownloads,
// Monetization
MONETIZATION_DEFAULTS, getMonetizationConfig,
getTrackMonetization, setTrackMonetization, isTrackLocked,
// Creator earnings
getCreatorEarnings, recordCreatorEarning, getCreatorEarningsSummary,
// Enhanced transactions
getTransactionHistory
};
})(); + val.toFixed(2);
} else {
cta.innerHTML = '<i data-lucide="lock" class="w-5 h-5"></i> Unlock & Download';
}
if (window.lucide) lucide.createIcons();
}
};
// ===== CREATOR ONBOARDING =====
const isFirstTimeCreator = () => {
const user = getCurrentUser();
if (!user || (user.role !== 'producer' && !user.isArtist)) return false;
const userTracks = getAllTracks().filter(t => t.artistId === user.id || t.artist === (user.displayName || user.username));
return userTracks.length === 0;
};
const getOnboardingState = () => {
const user = getCurrentUser();
if (!user) return { isOnboarding: false, steps: [], completedCount: 0, totalCount: 4 };
const userTracks = getAllTracks().filter(t => t.artistId === user.id || t.artist === (user.displayName || user.username));
const earnings = getCreatorEarningsSummary(user.id || (user.displayName || user.username));
const totalPlays = userTracks.reduce((s, t) => { const p = parseFloat(t.plays || '0'); return s + ((t.plays || '').includes('K') ? p * 1000 : p); }, 0);
const steps = [
{ id: 'signup', label: 'Create Producer account', icon: 'user-plus', completed: true },
{ id: 'first_upload', label: 'Upload your first beat', icon: 'upload-cloud', completed: userTracks.length > 0 },
{ id: 'earn_10', label: 'Earn your first $10', icon: 'dollar-sign', completed: earnings.totalNet >= 10 },
{ id: 'get_plays', label: 'Get 100 plays', icon: 'play-circle', completed: totalPlays >= 100 }
];
return { isOnboarding: !steps.every(s => s.completed), steps, completedCount: steps.filter(s => s.completed).length, totalCount: steps.length };
};
const getCreatorBadges = () => {
const user = getCurrentUser();
if (!user) return [];
const userTracks = getAllTracks().filter(t => t.artistId === user.id || t.artist === (user.displayName || user.username));
const earnings = getCreatorEarningsSummary(user.id || (user.displayName || user.username));
const totalPlays = userTracks.reduce((s, t) => { const p = parseFloat(t.plays || '0'); return s + ((t.plays || '').includes('K') ? p * 1000 : p); }, 0);
const badges = [];
if (userTracks.length >= 1) badges.push({ id: 'first_upload', icon: 'π΅', label: 'First Upload', description: 'Uploaded your first track', earned: true });
if (earnings.totalNet >= 10) badges.push({ id: 'earn_10', icon: 'π°', label: 'First $10', description: 'Earned your first $10', earned: true });
if (earnings.totalNet >= 50) badges.push({ id: 'earn_50', icon: 'π₯', label: '$50 Club', description: 'Earned $50 on the platform', earned: true });
if (earnings.totalNet >= 100) badges.push({ id: 'earn_100', icon: 'π', label: '$100 Club', description: 'Earned $100 on the platform', earned: true });
if (userTracks.length >= 5) badges.push({ id: '5_tracks', icon: 'πΉ', label: '5 Tracks', description: 'Uploaded 5 tracks', earned: true });
if (userTracks.length >= 10) badges.push({ id: '10_tracks', icon: 'ποΈ', label: '10 Tracks', description: 'Uploaded 10 tracks', earned: true });
if (totalPlays >= 1000) badges.push({ id: '1k_plays', icon: 'π§', label: '1K Plays', description: 'Reached 1,000 total plays', earned: true });
if (totalPlays >= 10000) badges.push({ id: '10k_plays', icon: 'π', label: '10K Plays', description: 'Reached 10,000 total plays', earned: true });
if (!badges.find(b => b.id === 'earn_10')) badges.push({ id: 'earn_10', icon: 'π°', label: 'First $10', description: 'Earn your first $10', earned: false });
if (!badges.find(b => b.id === '5_tracks')) badges.push({ id: '5_tracks', icon: 'πΉ', label: '5 Tracks', description: 'Upload 5 tracks', earned: false });
if (!badges.find(b => b.id === '1k_plays')) badges.push({ id: '1k_plays', icon: 'π§', label: '1K Plays', description: 'Reach 1,000 total plays', earned: false });
return badges;
};
const getTopCreatorsThisWeek = () => {
return [
{ name: 'Aurora Void', image: 'http://static.photos/people/200x200/77', tracks: 247, earnings: '$1,247', genre: 'Techno', change: '+23%', rank: 1 },
{ name: 'Neon Prophet', image: 'http://static.photos/people/200x200/10', tracks: 89, earnings: '$834', genre: 'Techno', change: '+18%', rank: 2 },
{ name: 'Cyber Dreamer', image: 'http://static.photos/people/200x200/11', tracks: 56, earnings: '$612', genre: 'Synthwave', change: '+31%', rank: 3 },
{ name: 'Deep Frequencies', image: 'http://static.photos/people/200x200/13', tracks: 34, earnings: '$428', genre: 'Ambient', change: '+12%', rank: 4 },
{ name: 'Bass Architect', image: 'http://static.photos/people/200x200/14', tracks: 67, earnings: '$389', genre: 'D&B', change: '+9%', rank: 5 }
];
};
const getMotivationalPrompt = () => {
const prompts = [
'Your beat could be someone\'s next hit π΅',
'Every upload brings you closer to your first $10 π°',
'Top creators started with just one track π',
'Share your sound β the world is listening π§',
'One upload today could change everything β¨',
'Your music deserves to be heard πΆ',
'The next chart-topper starts with you π',
'Don\'t let your beats stay on your hard drive π€'
];
return prompts[Math.floor(Math.random() * prompts.length)];
};
const dismissOnboarding = () => {
localStorage.setItem('bf_onboarding_dismissed', 'true');
};
const isOnboardingDismissed = () => {
return localStorage.getItem('bf_onboarding_dismissed') === 'true';
};
// ===== INIT =====
const init = (activeTab) => {
injectStyles();
injectBottomNav(activeTab);
migrateSuperFanData();
syncPlayer();
updateTopNav();
adjustTopNav();
updateSuperFanButtons();
if (window.lucide) lucide.createIcons();
// Re-sync player every 2 seconds
setInterval(syncPlayer, 2000);
};
return {
isLoggedIn, isProducer, isFan, getCurrentUser, signIn, signOut, signUp,
getAllTracks, getArtists, getGenres, getTrendingTracks, getFreshUploads,
searchTracks, searchArtists,
init, showSignInModal, closeSignInModal, handleSignIn,
showSignUpForm, showSignInForm, showChooseType, handleSignUp,
adjustTopNav, showToast, syncPlayer, playTrack, togglePlay,
showSuperFanModal, closeSuperFanModal, confirmSuperFanPayment, showSuperFanPaymentStep, showSuperFanSummaryStep, formatCardNumber, formatCardExpiry, isSuperFanOf, updateSuperFanButtons,
getSuperFanSubscriptions, cancelSuperFanSubscription,
showDownloadModal, closeDownloadModal, isDownloadUnlocked, unlockTrackDownload, getDownloadStates, handleDownloadUnlock, processMockDownload,
// Role system
ROLES, getUserRole, canBrowse, canDownload, canUpload, canEarn, hasFreeDownloads,
// Monetization
MONETIZATION_DEFAULTS, getMonetizationConfig,
getTrackMonetization, setTrackMonetization, isTrackLocked,
// Creator earnings
getCreatorEarnings, recordCreatorEarning, getCreatorEarningsSummary,
// Enhanced transactions
getTransactionHistory
};
})();
// BeatFridge - Core Application Logic
const BF = (() => {
// ===== DEFAULT DATA =====
const defaultTracks = [
{ id: 1, title: "Neon Horizons", artist: "Aurora Void", artistId: "aurora-void", duration: "4:32", image: "http://static.photos/technology/400x400/1", plays: "12.5K", genre: "techno", date: "2 days ago" },
{ id: 2, title: "Digital Rain", artist: "Aurora Void", artistId: "aurora-void", duration: "3:45", image: "http://static.photos/technology/400x400/2", plays: "8.2K", genre: "ambient", date: "5 days ago" },
{ id: 3, title: "Cybernetic Dreams", artist: "Aurora Void", artistId: "aurora-void", duration: "5:18", image: "http://static.photos/technology/400x400/3", plays: "24.1K", genre: "techno", date: "1 week ago" },
{ id: 4, title: "Analog Heart", artist: "Aurora Void", artistId: "aurora-void", duration: "3:22", image: "http://static.photos/technology/400x400/4", plays: "15.3K", genre: "synthwave", date: "2 weeks ago" },
{ id: 5, title: "Midnight Synthesis", artist: "Aurora Void", artistId: "aurora-void", duration: "4:08", image: "http://static.photos/technology/400x400/5", plays: "32.7K", genre: "techno", date: "3 weeks ago" },
{ id: 6, title: "Void Walker", artist: "Aurora Void", artistId: "aurora-void", duration: "6:14", image: "http://static.photos/technology/400x400/6", plays: "9.8K", genre: "ambient", date: "1 month ago" },
{ id: 7, title: "Electric Soul", artist: "Neon Prophet", artistId: "neon-prophet", duration: "3:55", image: "http://static.photos/technology/400x400/7", plays: "18.4K", genre: "house", date: "3 days ago" },
{ id: 8, title: "Digital Horizon", artist: "Cyber Dreamer", artistId: "cyber-dreamer", duration: "4:15", image: "http://static.photos/technology/400x400/8", plays: "11.2K", genre: "synthwave", date: "1 week ago" },
{ id: 9, title: "Deep Pulse", artist: "Deep Frequencies", artistId: "deep-freq", duration: "6:18", image: "http://static.photos/technology/400x400/9", plays: "7.6K", genre: "techno", date: "4 days ago" },
{ id: 10, title: "Neon City", artist: "Neon Prophet", artistId: "neon-prophet", duration: "4:22", image: "http://static.photos/technology/400x400/10", plays: "14.1K", genre: "synthwave", date: "6 days ago" },
{ id: 11, title: "Binary Sunset", artist: "Synth Wanderer", artistId: "synth-wanderer", duration: "5:02", image: "http://static.photos/technology/400x400/11", plays: "6.3K", genre: "ambient", date: "2 weeks ago" },
{ id: 12, title: "Crystal Waves", artist: "Cyber Dreamer", artistId: "cyber-dreamer", duration: "3:38", image: "http://static.photos/technology/400x400/12", plays: "19.7K", genre: "house", date: "1 day ago" }
];
const defaultArtists = [
{ id: "aurora-void", name: "Aurora Void", followers: "128.5K", image: "http://static.photos/people/200x200/77", genre: "Electronic", verified: true },
{ id: "neon-prophet", name: "Neon Prophet", followers: "45.2K", image: "http://static.photos/people/200x200/10", genre: "Techno", verified: false },
{ id: "cyber-dreamer", name: "Cyber Dreamer", followers: "32.8K", image: "http://static.photos/people/200x200/11", genre: "Synthwave", verified: false },
{ id: "synth-wanderer", name: "Synth Wanderer", followers: "28.1K", image: "http://static.photos/people/200x200/12", genre: "Ambient", verified: false },
{ id: "deep-freq", name: "Deep Frequencies", followers: "15.7K", image: "http://static.photos/people/200x200/13", genre: "Techno", verified: false },
{ id: "bass-architect", name: "Bass Architect", followers: "22.4K", image: "http://static.photos/people/200x200/14", genre: "Drum & Bass", verified: true }
];
const genres = [
{ name: "Techno", icon: "waves", color: "cyan" },
{ name: "Ambient", icon: "cloud", color: "purple" },
{ name: "House", icon: "flame", color: "orange" },
{ name: "Synthwave", icon: "zap", color: "pink" },
{ name: "Lo-Fi", icon: "leaf", color: "green" },
{ name: "Drum & Bass", icon: "activity", color: "red" }
];
// ===== AUTH =====
const isLoggedIn = () => localStorage.getItem('isLoggedIn') === 'true';
const isProducer = () => {
try {
const user = JSON.parse(localStorage.getItem('beatfridge_current_user'));
return user && (user.role === 'producer' || (!user.role && user.isArtist));
} catch { return false; }
};
const isFan = () => {
try {
const user = JSON.parse(localStorage.getItem('beatfridge_current_user'));
return user && user.role === 'fan';
} catch { return false; }
};
const getCurrentUser = () => {
try {
return JSON.parse(localStorage.getItem('beatfridge_current_user')) || null;
} catch { return null; }
};
const signIn = (identifier, password) => {
try {
const users = JSON.parse(localStorage.getItem('beatfridge_users') || '[]');
const user = users.find(u => (u.username === identifier || u.email === identifier) && u.password === password);
if (user) {
localStorage.setItem('beatfridge_current_user', JSON.stringify(user));
localStorage.setItem('isLoggedIn', 'true');
localStorage.setItem('currentUserId', user.id);
return { success: true, user };
}
return { success: false, error: 'Invalid username or password' };
} catch {
return { success: false, error: 'Sign in failed' };
}
};
const signOut = () => {
localStorage.removeItem('beatfridge_current_user');
localStorage.removeItem('isLoggedIn');
localStorage.removeItem('currentUserId');
window.location.href = 'index.html';
};
const signUp = (userData) => {
try {
const users = JSON.parse(localStorage.getItem('beatfridge_users') || '[]');
if (users.find(u => u.username.toLowerCase() === userData.username.toLowerCase())) {
return { success: false, error: 'Username is already taken' };
}
if (users.find(u => u.email.toLowerCase() === userData.email.toLowerCase())) {
return { success: false, error: 'Email is already registered' };
}
const role = userData.role || 'fan';
const newUser = {
id: (role === 'producer' ? 'producer_' : 'fan_') + Date.now(),
username: userData.username,
email: userData.email,
password: userData.password,
displayName: userData.displayName || userData.username,
avatar: userData.avatar || 'http://static.photos/people/200x200/' + Math.floor(Math.random() * 100),
role: role,