T.ME/BIBIL_0DAY
CasperSecurity


Server : Apache/2
System : Linux server-15-235-50-60 5.15.0-164-generic #174-Ubuntu SMP Fri Nov 14 20:25:16 UTC 2025 x86_64
User : gositeme ( 1004)
PHP Version : 8.2.29
Disable Function : exec,system,passthru,shell_exec,proc_close,proc_open,dl,popen,show_source,posix_kill,posix_mkfifo,posix_getpwuid,posix_setpgid,posix_setsid,posix_setuid,posix_setgid,posix_seteuid,posix_setegid,posix_uname
Directory :  /home/gositeme/domains/soundstudiopro.com/public_html/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : /home/gositeme/domains/soundstudiopro.com/public_html/library copy.php
<?php
// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

session_start();

// ALWAYS check if user is logged in - no exceptions
if (!isset($_SESSION['user_id'])) {
    header('Location: /auth/login.php');
    exit;
}

// Include database configuration
require_once 'config/database.php';

// Include shared music creation modal
include_once 'includes/create_music_modal.php';

$user = getUserById($_SESSION['user_id']);
$user_name = $user['name'] ?? 'User';
$credits = $_SESSION['credits'] ?? 5;

// Get user stats
$pdo = getDBConnection();
$stmt = $pdo->prepare("
    SELECT 
        COUNT(*) as total_tracks,
        COUNT(CASE WHEN status = 'complete' THEN 1 END) as completed_tracks,
        COUNT(CASE WHEN status = 'processing' THEN 1 END) as processing_tracks,
        COUNT(CASE WHEN status = 'failed' THEN 1 END) as failed_tracks,
        AVG(CASE WHEN status = 'complete' THEN duration END) as avg_duration,
        SUM(CASE WHEN status = 'complete' THEN duration END) as total_duration
    FROM music_tracks 
    WHERE user_id = ?
");
$stmt->execute([$_SESSION['user_id']]);
$user_stats = $stmt->fetch();

// Get user's music tracks with enhanced data and variations
$status_filter = $_GET['status'] ?? 'all';
$sort_filter = $_GET['sort'] ?? 'latest';

// Build WHERE clause for status filtering
$where_clause = "WHERE mt.user_id = ?";
$params = [$_SESSION['user_id']];

if ($status_filter !== 'all') {
    $where_clause .= " AND mt.status = ?";
    $params[] = $status_filter;
}

// Build ORDER BY clause for sorting
$order_clause = "ORDER BY ";
switch ($sort_filter) {
    case 'oldest':
        $order_clause .= "mt.created_at ASC";
        break;
    case 'popular':
        $order_clause = "LEFT JOIN (SELECT track_id, COUNT(*) as like_count FROM track_likes GROUP BY track_id) likes ON mt.id = likes.track_id ORDER BY likes.like_count DESC, mt.created_at DESC";
        break;
    case 'most-played':
        $order_clause = "LEFT JOIN (SELECT track_id, COUNT(*) as play_count FROM track_plays GROUP BY track_id) plays ON mt.id = plays.track_id ORDER BY plays.play_count DESC, mt.created_at DESC";
        break;
    case 'latest':
    default:
        $order_clause .= "mt.created_at DESC";
        break;
}

// Get tracks
$stmt = $pdo->prepare("
    SELECT 
        mt.*,
        COALESCE(vars.variation_count, 0) as variation_count,
        CASE 
            WHEN mt.created_at >= DATE_SUB(NOW(), INTERVAL 1 HOUR) THEN '🔥 Hot'
            WHEN mt.created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR) THEN '⭐ New'
            ELSE ''
        END as badge
    FROM music_tracks mt
    LEFT JOIN (
        SELECT track_id, COUNT(*) as variation_count 
        FROM audio_variations 
        GROUP BY track_id
    ) vars ON mt.id = vars.track_id
    $where_clause
    $order_clause
");
$stmt->execute($params);
$user_tracks = $stmt->fetchAll();

// Get variations for each track
$tracks_with_variations = [];
foreach ($user_tracks as $track) {
    $track['variations'] = [];
    
    // Get variations for this track
    $var_stmt = $pdo->prepare("SELECT * FROM audio_variations WHERE track_id = ? ORDER BY created_at ASC");
    $var_stmt->execute([$track['id']]);
    $track['variations'] = $var_stmt->fetchAll();
    
    $tracks_with_variations[] = $track;
}

// Include header
include 'includes/header.php';
?>

<div class="container" id="pageContainer">
    <div class="main-content">
        <!-- Library Header -->
        <div class="library-header">
            <div class="library-header-content">
                <h1>🎵 My Music Library</h1>
                <p>Manage and organize your AI-generated music tracks</p>
                
                <div class="library-stats">
                    <div class="stat-item">
                        <i class="fas fa-music"></i>
                        <span class="stat-number"><?= $user_stats['total_tracks'] ?? 0 ?></span>
                        <span class="stat-label">Total Tracks</span>
                    </div>
                    <div class="stat-item">
                        <i class="fas fa-check-circle"></i>
                        <span class="stat-number"><?= $user_stats['completed_tracks'] ?? 0 ?></span>
                        <span class="stat-label">Completed</span>
                    </div>
                    <div class="stat-item">
                        <i class="fas fa-clock"></i>
                        <span class="stat-number"><?= $user_stats['processing_tracks'] ?? 0 ?></span>
                        <span class="stat-label">Processing</span>
                    </div>
                    <div class="stat-item">
                        <i class="fas fa-coins"></i>
                        <span class="stat-number"><?= $credits ?></span>
                        <span class="stat-label">Credits Left</span>
                    </div>
                </div>
            </div>
        </div>

        <!-- Library Controls -->
        <div class="library-controls">
            <div class="controls-left">
                <button class="btn btn-primary" onclick="showCreateMusicModal()">
                    <i class="fas fa-plus"></i> Create New Music
                </button>
            </div>
            
            <div class="controls-right">
                <div class="filter-group">
                    <label for="statusFilter">Status:</label>
                    <select id="statusFilter" onchange="filterTracks()">
                        <option value="all" <?= $status_filter === 'all' ? 'selected' : '' ?>>All Tracks</option>
                        <option value="complete" <?= $status_filter === 'complete' ? 'selected' : '' ?>>Completed</option>
                        <option value="processing" <?= $status_filter === 'processing' ? 'selected' : '' ?>>Processing</option>
                        <option value="failed" <?= $status_filter === 'failed' ? 'selected' : '' ?>>Failed</option>
                    </select>
                </div>
                
                <div class="filter-group">
                    <label for="sortFilter">Sort by:</label>
                    <select id="sortFilter" onchange="filterTracks()">
                        <option value="latest" <?= $sort_filter === 'latest' ? 'selected' : '' ?>>Latest</option>
                        <option value="oldest" <?= $sort_filter === 'oldest' ? 'selected' : '' ?>>Oldest</option>
                        <option value="popular" <?= $sort_filter === 'popular' ? 'selected' : '' ?>>Most Popular</option>
                        <option value="most-played" <?= $sort_filter === 'most-played' ? 'selected' : '' ?>>Most Played</option>
                    </select>
                </div>
            </div>
        </div>

        <!-- Tracks Grid -->
        <div class="tracks-grid" id="tracksGrid">
            <?php if (empty($tracks_with_variations)): ?>
                <div class="empty-state">
                    <div class="empty-state-content">
                        <i class="fas fa-music"></i>
                        <h3>No tracks yet</h3>
                        <p>Create your first AI-generated music track to get started!</p>
                        <button class="btn btn-primary" onclick="showCreateMusicModal()">
                            <i class="fas fa-plus"></i> Create Your First Track
                        </button>
                    </div>
                </div>
            <?php else: ?>
                <?php foreach ($tracks_with_variations as $track): ?>
                    <div class="track-card" data-track-id="<?= $track['id'] ?>" data-status="<?= $track['status'] ?>">
                        <div class="track-card-header">
                            <div class="track-info">
                                <h3><?= htmlspecialchars($track['title'] ?? 'Untitled Track') ?></h3>
                                <p class="track-prompt"><?= htmlspecialchars($track['prompt'] ?? 'No description') ?></p>
                            </div>
                            <div class="track-badge">
                                <?php if ($track['badge']): ?>
                                    <span class="badge <?= strtolower(str_replace(' ', '-', $track['badge'])) ?>"><?= $track['badge'] ?></span>
                                <?php endif; ?>
                            </div>
                        </div>
                        
                        <div class="track-card-body">
                            <div class="track-status">
                                <?php if ($track['status'] === 'complete'): ?>
                                    <i class="fas fa-check-circle status-complete"></i>
                                    <span>Complete</span>
                                <?php elseif ($track['status'] === 'processing'): ?>
                                    <i class="fas fa-spinner fa-spin status-processing"></i>
                                    <span>Processing...</span>
                                <?php elseif ($track['status'] === 'failed'): ?>
                                    <i class="fas fa-exclamation-circle status-failed"></i>
                                    <span>Failed</span>
                                <?php endif; ?>
                            </div>
                            
                            <div class="track-meta">
                                <span><i class="fas fa-clock"></i> <?= $track['duration'] ?? 30 ?>s</span>
                                <span><i class="fas fa-calendar"></i> <?= date('M j, Y', strtotime($track['created_at'])) ?></span>
                                <?php if ($track['variation_count'] > 0): ?>
                                    <span><i class="fas fa-layer-group"></i> <?= $track['variation_count'] ?> variations</span>
                                <?php endif; ?>
                            </div>
                        </div>
                        
                        <div class="track-card-actions">
                            <?php if ($track['status'] === 'complete'): ?>
                                <button class="btn btn-primary" onclick="playTrack(<?= $track['id'] ?>)">
                                    <i class="fas fa-play"></i> Play
                                </button>
                                <button class="btn btn-secondary" onclick="downloadTrack(<?= $track['id'] ?>)">
                                    <i class="fas fa-download"></i> Download
                                </button>
                            <?php elseif ($track['status'] === 'processing'): ?>
                                <button class="btn btn-secondary" onclick="checkStatus(<?= $track['id'] ?>)">
                                    <i class="fas fa-sync"></i> Check Status
                                </button>
                            <?php else: ?>
                                <button class="btn btn-danger" onclick="retryTrack(<?= $track['id'] ?>)">
                                    <i class="fas fa-redo"></i> Retry
                                </button>
                            <?php endif; ?>
                            
                            <button class="btn btn-outline" onclick="deleteTrack(<?= $track['id'] ?>)">
                                <i class="fas fa-trash"></i>
                            </button>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>
</div>

<style>
/* Library Styles */
.library-header {
    background: linear-gradient(135deg, #667eea, #764ba2);
    color: white;
    padding: 4rem 0;
    margin-bottom: 3rem;
    border-radius: 20px;
}

.library-header-content {
    text-align: center;
}

.library-header h1 {
    font-size: 4rem;
    margin-bottom: 1rem;
}

.library-header p {
    font-size: 1.8rem;
    opacity: 0.9;
    margin-bottom: 3rem;
}

.library-stats {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 2rem;
    max-width: 800px;
    margin: 0 auto;
}

.stat-item {
    text-align: center;
    padding: 2rem;
    background: rgba(255, 255, 255, 0.1);
    border-radius: 15px;
    backdrop-filter: blur(10px);
}

.stat-item i {
    font-size: 3rem;
    margin-bottom: 1rem;
    opacity: 0.8;
}

.stat-number {
    display: block;
    font-size: 3rem;
    font-weight: 700;
    margin-bottom: 0.5rem;
}

.stat-label {
    font-size: 1.4rem;
    opacity: 0.8;
}

.library-controls {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 3rem;
    padding: 2rem;
    background: rgba(255, 255, 255, 0.05);
    border-radius: 15px;
}

.controls-left, .controls-right {
    display: flex;
    gap: 2rem;
    align-items: center;
}

.filter-group {
    display: flex;
    align-items: center;
    gap: 1rem;
}

.filter-group label {
    color: white;
    font-size: 1.4rem;
}

.filter-group select {
    padding: 0.8rem 1.5rem;
    border: 1px solid rgba(255, 255, 255, 0.2);
    border-radius: 10px;
    background: rgba(255, 255, 255, 0.1);
    color: white;
    font-size: 1.4rem;
}

.tracks-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
    gap: 2rem;
}

.track-card {
    background: rgba(255, 255, 255, 0.05);
    border-radius: 15px;
    padding: 2rem;
    border: 1px solid rgba(255, 255, 255, 0.1);
    transition: all 0.3s ease;
}

.track-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
    border-color: rgba(102, 126, 234, 0.3);
}

.track-card-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 1.5rem;
}

.track-info h3 {
    font-size: 1.8rem;
    margin-bottom: 0.5rem;
    color: white;
}

.track-prompt {
    font-size: 1.3rem;
    color: rgba(255, 255, 255, 0.7);
    line-height: 1.4;
}

.track-badge .badge {
    padding: 0.5rem 1rem;
    border-radius: 20px;
    font-size: 1.2rem;
    font-weight: 600;
}

.badge.hot {
    background: linear-gradient(135deg, #ff6b6b, #ee5a24);
    color: white;
}

.badge.new {
    background: linear-gradient(135deg, #48bb78, #38a169);
    color: white;
}

.track-card-body {
    margin-bottom: 2rem;
}

.track-status {
    display: flex;
    align-items: center;
    gap: 1rem;
    margin-bottom: 1rem;
    font-size: 1.4rem;
}

.status-complete {
    color: #48bb78;
}

.status-processing {
    color: #ed8936;
}

.status-failed {
    color: #e53e3e;
}

.track-meta {
    display: flex;
    flex-wrap: wrap;
    gap: 1.5rem;
    font-size: 1.3rem;
    color: rgba(255, 255, 255, 0.6);
}

.track-meta span {
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.track-card-actions {
    display: flex;
    gap: 1rem;
    flex-wrap: wrap;
}

.btn {
    padding: 0.8rem 1.5rem;
    border: none;
    border-radius: 10px;
    font-size: 1.4rem;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s ease;
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    text-decoration: none;
}

.btn-primary {
    background: linear-gradient(135deg, #667eea, #764ba2);
    color: white;
}

.btn-primary:hover {
    transform: translateY(-2px);
    box-shadow: 0 10px 20px rgba(102, 126, 234, 0.3);
}

.btn-secondary {
    background: rgba(255, 255, 255, 0.1);
    color: white;
    border: 1px solid rgba(255, 255, 255, 0.2);
}

.btn-secondary:hover {
    background: rgba(255, 255, 255, 0.2);
}

.btn-danger {
    background: linear-gradient(135deg, #e53e3e, #c53030);
    color: white;
}

.btn-outline {
    background: transparent;
    color: rgba(255, 255, 255, 0.6);
    border: 1px solid rgba(255, 255, 255, 0.2);
}

.btn-outline:hover {
    color: white;
    border-color: rgba(255, 255, 255, 0.4);
}

.empty-state {
    grid-column: 1 / -1;
    text-align: center;
    padding: 6rem 2rem;
}

.empty-state-content i {
    font-size: 8rem;
    color: rgba(255, 255, 255, 0.3);
    margin-bottom: 2rem;
}

.empty-state-content h3 {
    font-size: 2.4rem;
    color: white;
    margin-bottom: 1rem;
}

.empty-state-content p {
    font-size: 1.6rem;
    color: rgba(255, 255, 255, 0.7);
    margin-bottom: 3rem;
}
</style>

<script>
// Library JavaScript functions
function filterTracks() {
    const statusFilter = document.getElementById('statusFilter').value;
    const sortFilter = document.getElementById('sortFilter').value;
    
    window.location.href = `library.php?status=${statusFilter}&sort=${sortFilter}`;
}

function playTrack(trackId) {
    // Implementation for playing track
    console.log('Playing track:', trackId);
}

function downloadTrack(trackId) {
    // Implementation for downloading track
    console.log('Downloading track:', trackId);
}

function checkStatus(trackId) {
    // Implementation for checking track status
    console.log('Checking status for track:', trackId);
}

function retryTrack(trackId) {
    // Implementation for retrying failed track
    console.log('Retrying track:', trackId);
}

function deleteTrack(trackId) {
    if (confirm('Are you sure you want to delete this track?')) {
        // Implementation for deleting track
        console.log('Deleting track:', trackId);
    }
}
</script>
    
    if ($track['variation_count'] > 0) {
        $stmt = $pdo->prepare("
            SELECT 
                variation_index,
                audio_url,
                duration,
                title,
                tags,
                image_url,
                source_audio_url,
                stream_audio_url
            FROM audio_variations 
            WHERE track_id = ?
            ORDER BY variation_index
        ");
        $stmt->execute([$track['id']]);
        $track['variations'] = $stmt->fetchAll();
    }
    
    $tracks_with_variations[] = $track;
}
$user_tracks = $tracks_with_variations;

// Set page variables for header
$page_title = 'My Music Library - SoundStudioPro';
$page_description = 'View and manage all your AI-generated music tracks. Play, download, and organize your music collection.';
$current_page = 'library_new';

// Include header
include 'includes/header.php';
?>

<!-- Modern Library Design -->
<div class="modern-library">
    <!-- Hero Section -->
    <div class="library-hero">
        <div class="hero-content">
            <div class="hero-badge">
                <i class="fas fa-music"></i>
                My Library
            </div>
            <h1 class="hero-title">Your Music Collection</h1>
            <p class="hero-subtitle">Manage, play, and organize all your AI-generated music tracks. Your creative journey starts here.</p>
            <div class="hero-actions">
                <button class="btn btn-primary hero-create-btn" onclick="showCreateMusicModal()">
                    <i class="fas fa-plus"></i> Create New Music
                </button>
            </div>
        </div>
        <div class="hero-visual">
            <div class="floating-elements">
                <div class="floating-note">♪</div>
                <div class="floating-note">♫</div>
                <div class="floating-note">♬</div>
            </div>
        </div>
    </div>

    <!-- Stats Dashboard -->
    <div class="stats-dashboard">
        <div class="stat-card">
            <div class="stat-icon">
                <i class="fas fa-music"></i>
            </div>
            <div class="stat-content">
                <div class="stat-number"><?= $user_stats['total_tracks'] ?></div>
                <div class="stat-label">Total Tracks</div>
            </div>
        </div>
        
        <div class="stat-card">
            <div class="stat-icon success">
                <i class="fas fa-check-circle"></i>
            </div>
            <div class="stat-content">
                <div class="stat-number"><?= $user_stats['completed_tracks'] ?></div>
                <div class="stat-label">Completed</div>
            </div>
        </div>
        
        <div class="stat-card">
            <div class="stat-icon warning">
                <i class="fas fa-clock"></i>
            </div>
            <div class="stat-content">
                <div class="stat-number"><?= $user_stats['processing_tracks'] ?></div>
                <div class="stat-label">Processing</div>
            </div>
        </div>
        
        <div class="stat-card">
            <div class="stat-icon error">
                <i class="fas fa-exclamation-triangle"></i>
            </div>
            <div class="stat-content">
                <div class="stat-number"><?= $user_stats['failed_tracks'] ?></div>
                <div class="stat-label">Failed</div>
            </div>
        </div>
    </div>

    <!-- Main Content -->
    <div class="library-content">
        <div class="content-header">
            <div class="header-left">
                <h2 class="section-title">Your Music Tracks</h2>
                <p class="section-subtitle">All your AI-generated music in one place</p>
            </div>
            
            <div class="header-controls">
                <div class="filter-group">
                    <select class="modern-select" onchange="window.location.href='?status=' + this.value + '&sort=<?= $sort_filter ?>'">
                        <option value="all" <?= $status_filter === 'all' ? 'selected' : '' ?>>All Status</option>
                        <option value="complete" <?= $status_filter === 'complete' ? 'selected' : '' ?>>✅ Complete</option>
                        <option value="processing" <?= $status_filter === 'processing' ? 'selected' : '' ?>>⏳ Processing</option>
                        <option value="failed" <?= $status_filter === 'failed' ? 'selected' : '' ?>>❌ Failed</option>
                    </select>
                    
                    <select class="modern-select" onchange="window.location.href='?status=<?= $status_filter ?>&sort=' + this.value">
                        <option value="latest" <?= $sort_filter === 'latest' ? 'selected' : '' ?>>Latest</option>
                        <option value="oldest" <?= $sort_filter === 'oldest' ? 'selected' : '' ?>>Oldest</option>
                        <option value="popular" <?= $sort_filter === 'popular' ? 'selected' : '' ?>>Most Popular</option>
                        <option value="most-played" <?= $sort_filter === 'most-played' ? 'selected' : '' ?>>Most Played</option>
                    </select>
                </div>
            </div>
        </div>

        <!-- Tracks Grid -->
        <div class="tracks-grid">
            <?php if (empty($user_tracks)): ?>
                <div class="empty-state">
                    <div class="empty-icon">
                        <i class="fas fa-music"></i>
                    </div>
                    <h3 class="empty-title">No tracks yet</h3>
                    <p class="empty-description">Start creating your first AI-generated music track!</p>
                    <a href="/create_music.php" class="btn btn-primary">
                        <i class="fas fa-plus"></i>
                        Create Your First Track
                    </a>
                </div>
            <?php else: ?>
                <?php 
                $track_number = 1;
                foreach ($user_tracks as $track): 
                ?>
                    <div class="track-card-modern <?= !empty($track['badge']) ? 'has-badge' : '' ?>" 
                         data-track-id="<?= $track['id'] ?>" 
                         data-status="<?= $track['status'] ?>"
                         data-selected-variation="<?= $track['selected_variation'] ?? 0 ?>"
                         data-variations="<?= htmlspecialchars(json_encode($track['variations'] ?? [])) ?>">
                        
                        <!-- Track Number -->
                        <div class="track-number-modern">#<?= $track_number ?></div>
                        
                        <?php if (!empty($track['badge'])): ?>
                            <div class="track-badge-modern"><?= $track['badge'] ?></div>
                        <?php endif; ?>

                        <!-- Track Header -->
                        <div class="track-header-modern">
                            <div class="artist-avatar-modern">
                                <?php if (!empty($user['profile_image'])): ?>
                                    <img src="<?= htmlspecialchars($user['profile_image']) ?>" 
                                         alt="<?= htmlspecialchars($user_name) ?>" 
                                         class="avatar-image"
                                         onerror="this.parentElement.innerHTML='<div class=\'avatar-fallback\'><?= substr(htmlspecialchars(ucwords(strtolower($user_name))), 0, 1) ?></div>'">
                                <?php else: ?>
                                    <div class="avatar-fallback"><?= substr(htmlspecialchars(ucwords(strtolower($user_name))), 0, 1) ?></div>
                                <?php endif; ?>
                            </div>
                            
                            <div class="track-info-modern">
                                <h3 class="track-title-modern">
                                    <?php 
                                    $displayTitle = $track['title'];
                                    if (empty($displayTitle)) {
                                        if (!empty($track['prompt'])) {
                                            $displayTitle = substr($track['prompt'], 0, 50);
                                            if (strlen($track['prompt']) > 50) {
                                                $displayTitle .= '...';
                                            }
                                        } else {
                                            $displayTitle = 'Untitled Track';
                                        }
                                    }
                                    ?>
                                    <?= htmlspecialchars($displayTitle) ?>
                                </h3>
                                <p class="track-artist-modern">by <?= htmlspecialchars($user_name) ?></p>
                                
                                <div class="track-meta-modern">
                                    <span class="meta-item">
                                        <i class="fas fa-clock"></i>
                                        <?= floor($track['duration'] / 60) ?>m <?= $track['duration'] % 60 ?>s
                                    </span>
                                    <span class="meta-item">
                                        <i class="fas fa-calendar"></i>
                                        <?= date('M j, Y', strtotime($track['created_at'])) ?>
                                    </span>
                                </div>
                            </div>
                        </div>

                        <!-- Track Prompt -->
                        <div class="track-prompt-modern">
                            <div class="prompt-label">Original Prompt:</div>
                            <div class="prompt-text"><?= htmlspecialchars(substr($track['prompt'], 0, 150)) ?>...</div>
                        </div>

                        <!-- Track Status -->
                        <div class="track-status-modern">
                            <?php if ($track['status'] === 'complete'): ?>
                                <div class="status-complete">
                                    <i class="fas fa-check-circle"></i>
                                    Complete
                                </div>
                            <?php elseif ($track['status'] === 'processing'): ?>
                                <div class="status-processing">
                                    <div class="processing-spinner"></div>
                                    Processing
                                    <button onclick="checkTrackStatus(<?= $track['id'] ?>)" class="refresh-btn-modern" title="Check Status">
                                        <i class="fas fa-sync-alt"></i>
                                    </button>
                                </div>
                            <?php elseif ($track['status'] === 'failed'): ?>
                                <?php
                                // Extract error message from metadata
                                $error_message = '';
                                $error_type = '';
                                if (!empty($track['metadata'])) {
                                    $metadata = json_decode($track['metadata'], true);
                                    if ($metadata && isset($metadata['msg'])) {
                                        $error_message = $metadata['msg'];
                                    }
                                    if ($metadata && isset($metadata['code'])) {
                                        $error_type = $metadata['code'] == 400 ? 'content_violation' : 'technical_error';
                                    }
                                }
                                ?>
                                <div class="status-failed">
                                    <i class="fas fa-exclamation-triangle"></i>
                                    Failed
                                </div>
                                <?php if ($error_message): ?>
                                    <div class="error-message-modern">
                                        <div class="error-header">
                                            <i class="fas fa-exclamation-triangle"></i>
                                            <strong>Error Details:</strong>
                                        </div>
                                        <div class="error-content">
                                            <?= htmlspecialchars($error_message) ?>
                                        </div>
                                        <div class="error-tip">
                                            <i class="fas fa-lightbulb"></i>
                                            <strong>Quick Fix:</strong> 
                                            <?php if (stripos($error_message, 'artist name') !== false): ?>
                                                Avoid mentioning existing artists or bands. Use music genres and styles instead.
                                            <?php elseif (stripos($error_message, 'copyright') !== false): ?>
                                                Don't reference existing songs, lyrics, or copyrighted material.
                                            <?php elseif (stripos($error_message, 'inappropriate') !== false): ?>
                                                Keep content family-friendly and appropriate.
                                            <?php else: ?>
                                                Try modifying your prompt to be more generic and avoid specific names.
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                <?php endif; ?>
                            <?php endif; ?>
                        </div>

                        <!-- Track Actions -->
                        <div class="track-actions-modern">
                            <?php if ($track['status'] === 'complete'): ?>
                                <button class="action-btn primary" onclick="playTrackFromButton(this)" 
                                        data-audio-url="<?= htmlspecialchars($track['audio_url']) ?>" 
                                        data-title="<?= htmlspecialchars($displayTitle) ?>" 
                                        data-artist="<?= htmlspecialchars($user_name) ?>"
                                        title="Play Track">
                                    <i class="fas fa-play"></i>
                                    Play
                                </button>
                                
                                <button class="action-btn secondary" onclick="downloadTrack(<?= $track['id'] ?>)" title="Download Track">
                                    <i class="fas fa-download"></i>
                                    Download
                                </button>
                                
                                <?php if ($track['variation_count'] > 0): ?>
                                    <button class="action-btn secondary" onclick="showVariations(<?= $track['id'] ?>)" title="View Variations">
                                        <i class="fas fa-layer-group"></i>
                                        Variations
                                    </button>
                                <?php endif; ?>
                                
                                <button class="action-btn secondary" onclick="showLyrics(<?= $track['id'] ?>)" title="View Lyrics">
                                    <i class="fas fa-music"></i>
                                    Lyrics
                                </button>
                                
                            <?php elseif ($track['status'] === 'processing'): ?>
                                <div class="processing-actions">
                                    <button class="action-btn secondary" onclick="checkTrackStatus(<?= $track['id'] ?>)" title="Check Status">
                                        <i class="fas fa-sync-alt"></i>
                                        Check Status
                                    </button>
                                </div>
                                
                            <?php elseif ($track['status'] === 'failed'): ?>
                                <div class="failed-actions-modern">
                                    <button class="action-btn primary" onclick="retryTrack(<?= $track['id'] ?>)" title="Create a new version with the same prompt">
                                        <i class="fas fa-redo"></i>
                                        Retry
                                    </button>
                                    <button class="action-btn secondary" onclick="showFailureHelp(<?= $track['id'] ?>)" title="Why did this fail?">
                                        <i class="fas fa-question-circle"></i>
                                        Help
                                    </button>
                                    <button class="action-btn danger" onclick="deleteFailedTrack(<?= $track['id'] ?>)" title="Delete this failed track">
                                        <i class="fas fa-trash"></i>
                                        Delete
                                    </button>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php 
                $track_number++;
                endforeach; 
                ?>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Modern CSS Styles -->
<style>
/* Modern Library Design */
.modern-library {
    min-height: 100vh;
    background: linear-gradient(135deg, #0a0a0a 0%, #1a1a1a 50%, #0a0a0a 100%);
    position: relative;
    overflow-x: hidden;
}

/* Shared Modal Styles */
.create-music-modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.8);
    display: none;
    align-items: center;
    justify-content: center;
    z-index: 10000;
    backdrop-filter: blur(10px);
}

.create-music-modal {
    background: #1a1a1a;
    border: 1px solid rgba(255, 255, 255, 0.1);
    border-radius: 16px;
    padding: 0;
    max-width: 1200px;
    width: 95%;
    max-height: 95vh;
    overflow-y: auto;
    color: white;
    box-shadow: 0 20px 40px rgba(0, 0, 0, 0.5);
}

.create-music-modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 2.5rem 3rem 1.5rem;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.create-music-modal-header h3 {
    color: #667eea;
    margin: 0;
    font-size: 2rem;
}

.close-create-music-modal {
    background: none;
    border: none;
    color: #cccccc;
    font-size: 2rem;
    cursor: pointer;
    padding: 0.5rem;
    border-radius: 8px;
    transition: all 0.3s ease;
}

.close-create-music-modal:hover {
    color: #ffffff;
    background: rgba(255, 255, 255, 0.1);
}

.create-music-modal-body {
    padding: 2rem 3rem;
    max-height: 70vh;
    overflow-y: auto;
}

.mode-selector {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 1.5rem;
    margin-bottom: 3rem;
}

.mode-option {
    background: rgba(255, 255, 255, 0.05);
    border: 2px solid rgba(255, 255, 255, 0.1);
    border-radius: 12px;
    padding: 2rem;
    text-align: center;
    cursor: pointer;
    transition: all 0.3s ease;
    position: relative;
}

.mode-option:hover {
    border-color: #667eea;
    background: rgba(102, 126, 234, 0.1);
}

.mode-option.active {
    border-color: #667eea;
    background: rgba(102, 126, 234, 0.2);
}

.mode-option i {
    font-size: 2rem;
    color: #667eea;
    margin-bottom: 1rem;
}

.mode-option span {
    display: block;
    font-size: 1.4rem;
    font-weight: 600;
    color: #ffffff;
    margin-bottom: 0.5rem;
}

.mode-option small {
    display: block;
    font-size: 1rem;
    color: #a0aec0;
    margin-bottom: 1rem;
}

.mode-cost {
    background: #667eea;
    color: white;
    padding: 0.5rem 1rem;
    border-radius: 20px;
    font-size: 0.9rem;
    font-weight: 600;
}

.form-mode {
    display: none;
}

.form-mode.active {
    display: block;
}

.form-row {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 1.5rem;
    margin-bottom: 1.5rem;
}

.form-group {
    margin-bottom: 1.5rem;
}

.form-group label {
    display: block;
    margin-bottom: 0.5rem;
    color: #ffffff;
    font-weight: 500;
}

.form-input {
    width: 100%;
    padding: 1rem;
    border: 1px solid rgba(255, 255, 255, 0.2);
    border-radius: 8px;
    background: rgba(255, 255, 255, 0.05);
    color: #ffffff;
    font-size: 1rem;
    transition: all 0.3s ease;
}

.form-input:focus {
    outline: none;
    border-color: #667eea;
    background: rgba(255, 255, 255, 0.1);
}

.slider-container {
    margin-top: 0.5rem;
}

.slider {
    width: 100%;
    height: 6px;
    border-radius: 3px;
    background: rgba(255, 255, 255, 0.2);
    outline: none;
    -webkit-appearance: none;
}

.slider::-webkit-slider-thumb {
    -webkit-appearance: none;
    appearance: none;
    width: 20px;
    height: 20px;
    border-radius: 50%;
    background: #667eea;
    cursor: pointer;
}

.slider::-moz-range-thumb {
    width: 20px;
    height: 20px;
    border-radius: 50%;
    background: #667eea;
    cursor: pointer;
    border: none;
}

.slider-labels {
    display: flex;
    justify-content: space-between;
    margin-top: 0.5rem;
    font-size: 0.9rem;
    color: #a0aec0;
}

.radio-group {
    display: flex;
    gap: 1rem;
}

.radio-option {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    cursor: pointer;
}

.radio-option input[type="radio"] {
    margin: 0;
}

.char-count {
    text-align: right;
    font-size: 0.9rem;
    color: #a0aec0;
    margin-top: 0.5rem;
}

.pro-mode-header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    padding: 2rem;
    border-radius: 12px;
    margin-bottom: 2rem;
    text-align: center;
}

.pro-mode-header h3 {
    color: white;
    margin: 0 0 0.5rem 0;
    font-size: 1.8rem;
}

.pro-mode-header p {
    color: rgba(255, 255, 255, 0.8);
    margin: 0;
    font-size: 1.1rem;
}

.pro-section {
    margin-bottom: 2rem;
}

.pro-section h4 {
    color: #667eea;
    font-size: 1.4rem;
    margin-bottom: 1rem;
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.form-actions {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 2rem 3rem;
    border-top: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.2);
}

.credits-info {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    color: #a0aec0;
    font-size: 1rem;
}

.credits-info.low-credits {
    color: #f56565;
}

.credit-warning {
    color: #f56565;
    font-weight: 600;
}

.btn {
    padding: 1rem 2rem;
    border: none;
    border-radius: 8px;
    font-size: 1rem;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s ease;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
}

.btn-primary {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
}

.btn-primary:hover {
    transform: translateY(-2px);
    box-shadow: 0 10px 20px rgba(102, 126, 234, 0.3);
}

.btn-secondary {
    background: rgba(255, 255, 255, 0.1);
    color: #ffffff;
    border: 1px solid rgba(255, 255, 255, 0.2);
}

.btn-secondary:hover {
    background: rgba(255, 255, 255, 0.2);
}

@media (max-width: 768px) {
    .create-music-modal {
        width: 98%;
        max-height: 98vh;
    }
    .create-music-modal-header {
        padding: 1.5rem 2rem 1rem;
    }
    .create-music-modal-body {
        padding: 1.5rem 2rem;
    }
    .form-actions {
        padding: 1.5rem 2rem;
        flex-direction: column;
        gap: 1rem;
    }
    .mode-selector {
        grid-template-columns: 1fr;
    }
    .form-row {
        grid-template-columns: 1fr;
    }
}

/* Hero Section */
.library-hero {
    position: relative;
    padding: 6rem 0 4rem;
    text-align: center;
    background: linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%);
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);
    overflow: hidden;
}

.hero-content {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 2rem;
    position: relative;
    z-index: 2;
}

.hero-badge {
    display: inline-block;
    background: linear-gradient(135deg, #667eea, #764ba2);
    color: white;
    padding: 1rem 2rem;
    border-radius: 50px;
    font-size: 1.2rem;
    font-weight: 600;
    margin-bottom: 2rem;
    backdrop-filter: blur(10px);
    border: 1px solid rgba(255, 255, 255, 0.2);
    box-shadow: 0 8px 32px rgba(102, 126, 234, 0.3);
}

.hero-title {
    font-size: 4rem;
    font-weight: 900;
    line-height: 1.1;
    margin-bottom: 1.5rem;
    background: linear-gradient(135deg, #667eea, #764ba2);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
}

.hero-subtitle {
    font-size: 1.5rem;
    color: #a0aec0;
    max-width: 600px;
    margin: 0 auto 2rem;
    line-height: 1.6;
}

.hero-actions {
    display: flex;
    justify-content: center;
    gap: 2rem;
    margin-bottom: 2rem;
}

.hero-create-btn {
    background: linear-gradient(135deg, #667eea, #764ba2);
    color: white;
    padding: 1.5rem 3rem;
    border: none;
    border-radius: 50px;
    font-size: 1.6rem;
    font-weight: 700;
    cursor: pointer;
    transition: all 0.3s ease;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    gap: 1rem;
    box-shadow: 0 10px 30px rgba(102, 126, 234, 0.3);
}

.hero-create-btn:hover {
    transform: translateY(-3px);
    box-shadow: 0 15px 40px rgba(102, 126, 234, 0.4);
}

.hero-visual {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    pointer-events: none;
}

.floating-elements {
    position: relative;
    height: 100%;
}

.floating-note {
    position: absolute;
    font-size: 3rem;
    color: rgba(102, 126, 234, 0.3);
    animation: float 6s ease-in-out infinite;
}

.floating-note:nth-child(1) {
    top: 20%;
    left: 10%;
    animation-delay: 0s;
}

.floating-note:nth-child(2) {
    top: 60%;
    right: 15%;
    animation-delay: 2s;
}

.floating-note:nth-child(3) {
    bottom: 30%;
    left: 20%;
    animation-delay: 4s;
}

@keyframes float {
    0%, 100% { transform: translateY(0px) rotate(0deg); }
    50% { transform: translateY(-20px) rotate(10deg); }
}

/* Stats Dashboard */
.stats-dashboard {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 2rem;
    max-width: 1200px;
    margin: -2rem auto 4rem;
    padding: 0 2rem;
    position: relative;
    z-index: 3;
}

.stat-card {
    background: rgba(255, 255, 255, 0.05);
    border: 1px solid rgba(255, 255, 255, 0.1);
    border-radius: 20px;
    padding: 2rem;
    backdrop-filter: blur(20px);
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    gap: 1.5rem;
}

.stat-card:hover {
    transform: translateY(-5px);
    border-color: rgba(102, 126, 234, 0.3);
    box-shadow: 0 20px 60px rgba(102, 126, 234, 0.1);
}

.stat-icon {
    width: 60px;
    height: 60px;
    border-radius: 15px;
    background: linear-gradient(135deg, #667eea, #764ba2);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.5rem;
    color: white;
}

.stat-icon.success {
    background: linear-gradient(135deg, #48bb78, #38a169);
}

.stat-icon.warning {
    background: linear-gradient(135deg, #ed8936, #dd6b20);
}

.stat-icon.error {
    background: linear-gradient(135deg, #f56565, #e53e3e);
}

.stat-content {
    flex: 1;
}

.stat-number {
    font-size: 2.5rem;
    font-weight: 900;
    color: white;
    margin-bottom: 0.5rem;
}

.stat-label {
    font-size: 1rem;
    color: #a0aec0;
    font-weight: 500;
}

/* Library Content */
.library-content {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 2rem 4rem;
}

.content-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 3rem;
    gap: 2rem;
}

.header-left {
    flex: 1;
}

.section-title {
    font-size: 3rem;
    font-weight: 700;
    color: white;
    margin-bottom: 0.5rem;
}

.section-subtitle {
    font-size: 1.2rem;
    color: #a0aec0;
}

.header-controls {
    display: flex;
    gap: 1rem;
}

.filter-group {
    display: flex;
    gap: 1rem;
}

.modern-select {
    background: rgba(255, 255, 255, 0.05);
    border: 1px solid rgba(255, 255, 255, 0.1);
    border-radius: 12px;
    padding: 0.8rem 1.2rem;
    color: white;
    font-size: 1rem;
    cursor: pointer;
    transition: all 0.3s ease;
    backdrop-filter: blur(10px);
}

.modern-select:hover {
    border-color: rgba(102, 126, 234, 0.3);
    background: rgba(255, 255, 255, 0.08);
}

.modern-select:focus {
    outline: none;
    border-color: #667eea;
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.modern-select option {
    background: #1a1a1a;
    color: white;
}

/* Tracks Grid */
.tracks-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
    gap: 2rem;
}

.track-card-modern {
    background: rgba(255, 255, 255, 0.03);
    border: 1px solid rgba(255, 255, 255, 0.1);
    border-radius: 20px;
    padding: 2rem;
    backdrop-filter: blur(20px);
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;
}

.track-card-modern:hover {
    transform: translateY(-5px);
    border-color: rgba(102, 126, 234, 0.3);
    box-shadow: 0 20px 60px rgba(102, 126, 234, 0.1);
}

.track-card-modern.has-badge {
    border-color: rgba(102, 126, 234, 0.3);
}

.track-badge-modern {
    position: absolute;
    top: 1rem;
    right: 1rem;
    background: linear-gradient(135deg, #667eea, #764ba2);
    color: white;
    padding: 0.5rem 1rem;
    border-radius: 20px;
    font-size: 0.8rem;
    font-weight: 600;
    z-index: 2;
}

.track-number-modern {
    position: absolute;
    top: 1rem;
    right: 1rem;
    background: linear-gradient(135deg, #667eea, #764ba2);
    color: white;
    padding: 0.8rem 1.2rem;
    border-radius: 25px;
    font-size: 1.4rem;
    font-weight: 900;
    z-index: 1;
    border: 2px solid rgba(255, 255, 255, 0.3);
    backdrop-filter: blur(10px);
    box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4);
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
    animation: pulse-glow 2s ease-in-out infinite alternate;
}

@keyframes pulse-glow {
    0% {
        box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4);
        transform: scale(1);
    }
    100% {
        box-shadow: 0 12px 35px rgba(102, 126, 234, 0.6);
        transform: scale(1.05);
    }
}

/* Track Header */
.track-header-modern {
    display: flex;
    align-items: center;
    gap: 1rem;
    margin-bottom: 1.5rem;
}

.artist-avatar-modern {
    width: 60px;
    height: 60px;
    border-radius: 15px;
    overflow: hidden;
    flex-shrink: 0;
}

.avatar-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.avatar-fallback {
    width: 100%;
    height: 100%;
    background: linear-gradient(135deg, #667eea, #764ba2);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.5rem;
    font-weight: 700;
    color: white;
}

.track-info-modern {
    flex: 1;
    min-width: 0;
}

.track-title-modern {
    font-size: 1.3rem;
    font-weight: 700;
    color: white;
    margin-bottom: 0.3rem;
    line-height: 1.3;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.track-artist-modern {
    font-size: 1rem;
    color: #a0aec0;
    margin-bottom: 0.8rem;
}

.track-meta-modern {
    display: flex;
    gap: 1rem;
    flex-wrap: wrap;
}

.meta-item {
    display: flex;
    align-items: center;
    gap: 0.3rem;
    font-size: 0.9rem;
    color: #718096;
}

.meta-item i {
    font-size: 0.8rem;
}

/* Track Prompt */
.track-prompt-modern {
    background: rgba(255, 255, 255, 0.02);
    border: 1px solid rgba(255, 255, 255, 0.05);
    border-radius: 12px;
    padding: 1rem;
    margin-bottom: 1.5rem;
}

.prompt-label {
    font-size: 0.9rem;
    color: #a0aec0;
    margin-bottom: 0.5rem;
    font-weight: 600;
}

.prompt-text {
    font-size: 0.9rem;
    color: #cbd5e0;
    line-height: 1.5;
}

/* Track Status */
.track-status-modern {
    margin-bottom: 1.5rem;
}

.status-complete {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    color: #48bb78;
    font-weight: 600;
    font-size: 1rem;
}

.status-processing {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    color: #ed8936;
    font-weight: 600;
    font-size: 1rem;
}

.processing-spinner {
    width: 16px;
    height: 16px;
    border: 2px solid rgba(237, 137, 54, 0.3);
    border-top: 2px solid #ed8936;
    border-radius: 50%;
    animation: spin 1s linear infinite;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

.status-failed {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    color: #f56565;
    font-weight: 600;
    font-size: 1rem;
    margin-bottom: 0.5rem;
}

.error-message-modern {
    background: rgba(245, 101, 101, 0.1);
    border: 1px solid rgba(245, 101, 101, 0.3);
    border-radius: 8px;
    padding: 1.5rem;
    font-size: 1.4rem;
    color: #f56565;
    line-height: 1.4;
}

.error-header {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    margin-bottom: 0.8rem;
    font-weight: 600;
}

.error-content {
    background: rgba(0, 0, 0, 0.2);
    padding: 0.8rem;
    border-radius: 6px;
    margin-bottom: 0.8rem;
    font-family: 'Courier New', monospace;
    font-size: 1.3rem;
}

.error-tip {
    display: flex;
    align-items: flex-start;
    gap: 0.5rem;
    background: rgba(255, 193, 7, 0.1);
    border: 1px solid rgba(255, 193, 7, 0.3);
    border-radius: 6px;
    padding: 0.8rem;
    color: #ffc107;
    font-size: 1.3rem;
    line-height: 1.4;
}

.error-tip i {
    margin-top: 0.2rem;
    flex-shrink: 0;
}

.refresh-btn-modern {
    background: none;
    border: none;
    color: #ed8936;
    cursor: pointer;
    padding: 0.3rem;
    border-radius: 6px;
    transition: all 0.3s ease;
}

.refresh-btn-modern:hover {
    background: rgba(237, 137, 54, 0.1);
    color: #ed8936;
}

/* Track Actions */
.track-actions-modern {
    display: flex;
    gap: 0.8rem;
    flex-wrap: wrap;
}

.action-btn {
    padding: 0.8rem 1.2rem;
    border: none;
    border-radius: 10px;
    font-size: 0.9rem;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    gap: 0.5rem;
    text-decoration: none;
    flex: 1;
    min-width: 0;
    justify-content: center;
}

.action-btn.primary {
    background: linear-gradient(135deg, #667eea, #764ba2);
    color: white;
}

.action-btn.primary:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
}

.action-btn.secondary {
    background: rgba(255, 255, 255, 0.05);
    color: #a0aec0;
    border: 1px solid rgba(255, 255, 255, 0.1);
}

.action-btn.secondary:hover {
    background: rgba(255, 255, 255, 0.1);
    color: white;
    border-color: rgba(255, 255, 255, 0.2);
}

.action-btn.danger {
    background: rgba(245, 101, 101, 0.1);
    color: #f56565;
    border: 1px solid rgba(245, 101, 101, 0.3);
}

.action-btn.danger:hover {
    background: rgba(245, 101, 101, 0.2);
    color: #f56565;
    border-color: rgba(245, 101, 101, 0.5);
}

.processing-actions,
.failed-actions-modern {
    display: flex;
    gap: 0.8rem;
    width: 100%;
}

/* Empty State */
.empty-state {
    grid-column: 1 / -1;
    text-align: center;
    padding: 4rem 2rem;
}

.empty-icon {
    font-size: 4rem;
    color: #667eea;
    margin-bottom: 2rem;
}

.empty-title {
    font-size: 2rem;
    color: white;
    margin-bottom: 1rem;
}

.empty-description {
    font-size: 1.1rem;
    color: #a0aec0;
    margin-bottom: 2rem;
}

.btn {
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    padding: 1rem 2rem;
    border: none;
    border-radius: 12px;
    font-size: 1rem;
    font-weight: 600;
    text-decoration: none;
    cursor: pointer;
    transition: all 0.3s ease;
}

.btn-primary {
    background: linear-gradient(135deg, #667eea, #764ba2);
    color: white;
}

.btn-primary:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
}

/* Responsive Design */
@media (max-width: 768px) {
    .hero-title {
        font-size: 2.5rem;
    }
    
    .section-title {
        font-size: 2rem;
    }
    
    .content-header {
        flex-direction: column;
        align-items: stretch;
    }
    
    .filter-group {
        flex-direction: column;
    }
    
    .tracks-grid {
        grid-template-columns: 1fr;
    }
    
    .stats-dashboard {
        grid-template-columns: repeat(2, 1fr);
    }
    
    .track-actions-modern {
        flex-direction: column;
    }
    
    .action-btn {
        width: 100%;
    }
}

@media (max-width: 480px) {
    .stats-dashboard {
        grid-template-columns: 1fr;
    }
    
    .hero-badge {
        padding: 0.8rem 1.5rem;
        font-size: 1rem;
    }
    
    .hero-title {
        font-size: 2rem;
    }
    
    .hero-subtitle {
        font-size: 1.2rem;
    }
}

    /* Variations Modal */
    .variations-modal {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.8);
        z-index: 2000;
        backdrop-filter: blur(5px);
    }

    .variations-modal.active {
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .variations-content {
        background: #1a1a1a;
        border-radius: 16px;
        padding: 2rem;
        max-width: 800px;
        width: 90%;
        max-height: 80vh;
        overflow-y: auto;
        box-shadow: 0 20px 40px rgba(0, 0, 0, 0.5);
        border: 1px solid #333;
    }
    
    .variations-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 2rem;
        padding-bottom: 1rem;
        border-bottom: 1px solid var(--border-medium);
    }

    .variations-title {
        font-size: 2rem;
        font-weight: 700;
        color: #ffffff;
    }

    .close-variations {
        background: none;
        border: none;
        color: #cccccc;
        font-size: 2rem;
        cursor: pointer;
        padding: 0.5rem;
        border-radius: 8px;
        transition: all 0.3s ease;
    }

    .close-variations:hover {
        color: #ffffff;
        background: rgba(255, 255, 255, 0.1);
    }
    
    .variations-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
        gap: 1.5rem;
        margin-bottom: 2rem;
    }
    
    .variation-card {
        background: #2a2a2a;
        border: 2px solid #444;
        border-radius: 12px;
        padding: 1.5rem;
        transition: all 0.3s ease;
        cursor: pointer;
    }
    
    .variation-card:hover {
        border-color: #667eea;
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
    }

    .variation-card.selected {
        border-color: #667eea;
        background: rgba(102, 126, 234, 0.15);
        box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
    }
    
    .variation-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 1rem;
    }
    
    .variation-title {
        font-size: 1.4rem;
        font-weight: 600;
        color: #ffffff;
    }
    
    .variation-index {
        background: var(--primary-color);
        color: white;
        padding: 0.4rem 0.8rem;
        border-radius: 20px;
        font-size: 1.2rem;
        font-weight: 600;
    }
    
    .variation-duration {
        color: #cccccc;
        font-size: 1.2rem;
        margin-bottom: 1rem;
    }
    
    .variation-tags {
        display: flex;
        flex-wrap: wrap;
        gap: 0.5rem;
        margin-bottom: 1rem;
    }

    .variation-tag {
        background: #444;
        color: #cccccc;
        padding: 0.3rem 0.8rem;
        border-radius: 12px;
        font-size: 1.1rem;
        border: 1px solid #555;
    }

    .variation-actions {
        display: flex;
        gap: 0.8rem;
        flex-wrap: wrap;
    }

    .variation-btn {
        flex: 1;
        min-width: 80px;
        padding: 0.8rem;
        border: none;
        border-radius: 8px;
        font-size: 1.2rem;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.3s ease;
    }

    .variation-btn.play {
        background: #667eea;
        color: white;
        border: 1px solid #667eea;
        font-weight: 600;
    }

    .variation-btn.play:hover {
        transform: translateY(-2px);
        box-shadow: 0 5px 15px rgba(102, 126, 234, 0.3);
    }

    .variation-btn.download {
        background: rgba(245, 158, 11, 0.3);
        color: #fbbf24;
        border: 1px solid rgba(245, 158, 11, 0.5);
        font-weight: 600;
    }

    .variation-btn.download:hover {
        background: rgba(245, 158, 11, 0.4);
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(245, 158, 11, 0.3);
    }

    .variation-btn.select {
        background: rgba(72, 187, 120, 0.3);
        color: #68d391;
        border: 1px solid rgba(72, 187, 120, 0.5);
        font-weight: 600;
    }

    .variation-btn.select:hover {
        background: rgba(72, 187, 120, 0.4);
        box-shadow: 0 4px 12px rgba(72, 187, 120, 0.3);
    }

    .variation-btn.select.selected {
        background: #48bb78;
        color: white;
        font-weight: 700;
    }

    .variations-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding-top: 1rem;
        border-top: 1px solid #444;
    }

    .variations-info {
        color: #cccccc;
        font-size: 1.3rem;
    }

    .variations-actions {
        display: flex;
        gap: 1rem;
    }

    .variations-btn {
        padding: 1rem 2rem;
        border: none;
        border-radius: 8px;
        font-size: 1.4rem;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.3s ease;
    }
    
    .variations-btn.cancel {
        background: rgba(255, 255, 255, 0.15);
        color: #cccccc;
        border: 1px solid rgba(255, 255, 255, 0.2);
    }

    .variations-btn.cancel:hover {
        background: rgba(255, 255, 255, 0.25);
        color: #ffffff;
    }

    .variations-btn.save {
        background: #667eea;
        color: white;
        border: 1px solid #667eea;
    }

    .variations-btn.save:hover {
        transform: translateY(-2px);
        box-shadow: 0 5px 15px rgba(102, 126, 234, 0.3);
    }

    .variations-btn.save:disabled {
        opacity: 0.5;
        cursor: not-allowed;
        transform: none;
    }
</style>

    <!-- Variations Modal -->
    <div id="variationsModal" class="variations-modal">
        <div class="variations-content">
            <div class="variations-header">
                <h2 class="variations-title">Choose Your Track Variation</h2>
                <button class="close-variations" onclick="closeVariations()">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            
            <div id="variationsGrid" class="variations-grid">
                <!-- Variations will be loaded here -->
            </div>
            
            <div class="variations-footer">
                <div class="variations-info">
                    <i class="fas fa-info-circle"></i>
                    Select which variation will be your main track for sale and public display. You can also download individual variations or all versions at once.
                </div>
                <div class="variations-actions">
                    <button class="variations-btn cancel" onclick="closeVariations()">
                        Cancel
                    </button>
                    <button id="saveVariationBtn" class="variations-btn save" onclick="saveVariationSelection()" disabled>
                        Save Selection
                    </button>
                </div>
            </div>
        </div>
    </div>

<!-- Include the existing JavaScript -->
<script>
    // Global variables for variations
    let trackVariations = [];
    let currentTrackId = null;
    let selectedVariationIndex = null;
    
    // Check if global player is loaded
    window.addEventListener('load', function() {
        console.log('🎵 Modern library loaded');
        console.log('🎵 Global player status:', typeof window.globalPlayer !== 'undefined');
        console.log('🎵 Global player element exists:', !!document.getElementById('globalMusicPlayer'));
        console.log('🎵 playTrackWithGlobalPlayer function exists:', typeof window.playTrackWithGlobalPlayer === 'function');
        
        if (typeof window.globalPlayer === 'undefined') {
            console.error('🎵 Global player not loaded!');
            setTimeout(() => {
                if (typeof window.globalPlayer !== 'undefined') {
                    console.log('🎵 Global player loaded after delay');
                } else {
                    console.error('🎵 Global player still not available after delay');
                }
            }, 1000);
        } else {
            console.log('🎵 Global player loaded successfully');
            window.globalPlayer.showPlayer();
        }
        
        // Check if playTrackWithGlobalPlayer is available
        if (typeof window.playTrackWithGlobalPlayer === 'function') {
            console.log('🎵 playTrackWithGlobalPlayer function is available');
        } else {
            console.error('🎵 playTrackWithGlobalPlayer function is missing!');
        }
        
        // Start status checking for processing tracks
        checkProcessingTracks();
        
        // Test global player after a delay
        setTimeout(() => {
            testGlobalPlayer();
        }, 2000);
    });
    
    // Check processing tracks status periodically
    function checkProcessingTracks() {
        const processingTracks = document.querySelectorAll('.track-card-modern[data-status="processing"]');
        
        if (processingTracks.length > 0) {
            console.log('🎵 Found processing tracks, checking status...');
            
            // Show status indicator
            showStatusIndicator(`Checking ${processingTracks.length} processing track(s)...`);
            
            processingTracks.forEach(trackCard => {
                const trackId = trackCard.getAttribute('data-track-id');
                checkTrackStatus(trackId);
            });
            
            // Check again in 30 seconds
            setTimeout(checkProcessingTracks, 30000);
        } else {
            hideStatusIndicator();
        }
    }
    
    // Show status indicator
    function showStatusIndicator(message) {
        let indicator = document.getElementById('status-indicator');
        if (!indicator) {
            indicator = document.createElement('div');
            indicator.id = 'status-indicator';
            indicator.className = 'status-indicator';
            indicator.innerHTML = `
                <div class="status-indicator-content">
                    <i class="fas fa-spinner fa-spin"></i>
                    <span>${message}</span>
                </div>
            `;
            document.body.appendChild(indicator);
        } else {
            indicator.querySelector('span').textContent = message;
        }
        indicator.style.display = 'block';
    }
    
    // Hide status indicator
    function hideStatusIndicator() {
        const indicator = document.getElementById('status-indicator');
        if (indicator) {
            indicator.style.display = 'none';
        }
    }
    
    // Check individual track status
    async function checkTrackStatus(trackId) {
        try {
            console.log(`🎵 Checking status for track ${trackId}...`);
            
            // Show loading state on the refresh button
            const refreshBtn = document.querySelector(`[onclick="checkTrackStatus(${trackId})"]`);
            if (refreshBtn) {
                const originalContent = refreshBtn.innerHTML;
                refreshBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
                refreshBtn.disabled = true;
            }
            
            const response = await fetch(`/api/check_track_status.php?track_id=${trackId}`);
            const result = await response.json();
            
            if (result.success && result.data) {
                const status = result.data.status;
                const trackCard = document.querySelector(`[data-track-id="${trackId}"]`);
                
                console.log(`🎵 Track ${trackId} status: ${status}`);
                
                if (trackCard && status !== 'processing') {
                    console.log(`🎵 Track ${trackId} status changed to: ${status}`);
                    
                    // Update track card status
                    trackCard.setAttribute('data-status', status);
                    
                    // Show success notification
                    if (typeof window.showNotification === 'function') {
                        window.showNotification(`Track status updated: ${status}`, 'success');
                    }
                    
                    // Refresh the page to show updated status
                    setTimeout(() => {
                        window.location.reload();
                    }, 2000);
                } else if (status === 'processing') {
                    // Show notification that it's still processing
                    if (typeof window.showNotification === 'function') {
                        window.showNotification('Track is still processing...', 'info');
                    }
                }
            } else {
                console.error('🎵 Track status check failed:', result.message);
                if (typeof window.showNotification === 'function') {
                    window.showNotification('Failed to check track status', 'error');
                }
            }
        } catch (error) {
            console.error('🎵 Error checking track status:', error);
            
            // Show error notification if available
            if (typeof window.showNotification === 'function') {
                window.showNotification('Error checking track status', 'error');
            }
        } finally {
            // Restore refresh button
            if (refreshBtn) {
                refreshBtn.innerHTML = '<i class="fas fa-sync-alt"></i>';
                refreshBtn.disabled = false;
            }
        }
    }
    
    // Retry failed track
    async function retryTrack(trackId) {
        if (!confirm('🔄 Are you sure you want to retry this track? This will create a new version using your original prompt.')) {
            return;
        }
        
        try {
            console.log(`🎵 Retrying track ${trackId}...`);
            
            // Show loading state
            const retryBtn = document.querySelector(`[onclick="retryTrack(${trackId})"]`);
            if (retryBtn) {
                const originalContent = retryBtn.innerHTML;
                retryBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Retrying...';
                retryBtn.disabled = true;
            }
            
            const response = await fetch('/api_retry.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: JSON.stringify({ track_id: trackId })
            });
            
            const result = await response.json();
            
            if (result.success) {
                console.log('🎵 Track retry initiated successfully');
                
                if (typeof window.showNotification === 'function') {
                    window.showNotification('Track retry initiated! Check your library for the new version.', 'success');
                }
                
                // Refresh the page to show the new track
                setTimeout(() => {
                    window.location.reload();
                }, 2000);
                
            } else {
                console.error('🎵 Track retry failed:', result.error);
                
                if (typeof window.showNotification === 'function') {
                    window.showNotification('Failed to retry track: ' + (result.error || 'Unknown error'), 'error');
                } else {
                    alert('❌ Failed to retry track: ' + (result.error || 'Unknown error'));
                }
            }
            
        } catch (error) {
            console.error('🎵 Error retrying track:', error);
            
            if (typeof window.showNotification === 'function') {
                window.showNotification('Network error retrying track. Please try again.', 'error');
            } else {
                alert('❌ Network error retrying track. Please check your connection and try again.');
            }
        } finally {
            // Restore retry button
            if (retryBtn) {
                retryBtn.innerHTML = '<i class="fas fa-redo"></i> Retry';
                retryBtn.disabled = false;
            }
        }
    }
    
    // Delete failed track
    async function deleteFailedTrack(trackId) {
        if (!confirm('🗑️ Are you sure you want to delete this failed track? This action cannot be undone.')) {
            return;
        }
        
        try {
            console.log(`🎵 Deleting failed track ${trackId}...`);
            
            // Show loading state
            const deleteBtn = document.querySelector(`[onclick="deleteFailedTrack(${trackId})"]`);
            if (deleteBtn) {
                const originalContent = deleteBtn.innerHTML;
                deleteBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Deleting...';
                deleteBtn.disabled = true;
            }
            
            const response = await fetch('/api_delete_track.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: JSON.stringify({ track_id: trackId })
            });
            
            const result = await response.json();
            
            if (result.success) {
                console.log('🎵 Failed track deleted successfully');
                
                if (typeof window.showNotification === 'function') {
                    window.showNotification('Failed track deleted successfully!', 'success');
                }
                
                // Remove the track card from the DOM
                const trackCard = document.querySelector(`[data-track-id="${trackId}"]`);
                if (trackCard) {
                    trackCard.remove();
                } else {
                    // Fallback: refresh the page
                    setTimeout(() => {
                        window.location.reload();
                    }, 1000);
                }
                
            } else {
                console.error('🎵 Failed to delete track:', result.error);
                
                if (typeof window.showNotification === 'function') {
                    window.showNotification('Failed to delete track: ' + (result.error || 'Unknown error'), 'error');
                } else {
                    alert('❌ Failed to delete track: ' + (result.error || 'Unknown error'));
                }
            }
            
        } catch (error) {
            console.error('🎵 Error deleting track:', error);
            
            if (typeof window.showNotification === 'function') {
                window.showNotification('Network error deleting track. Please try again.', 'error');
            } else {
                alert('❌ Network error deleting track. Please check your connection and try again.');
            }
        } finally {
            // Restore delete button
            if (deleteBtn) {
                deleteBtn.innerHTML = '<i class="fas fa-trash"></i> Delete';
                deleteBtn.disabled = false;
            }
        }
    }
    
    // Show failure help modal
    function showFailureHelp(trackId) {
        const helpContent = `
            <div class="failure-help-modal">
                <h3>🤔 Why did my track fail?</h3>
                <p>Track generation can fail for several reasons. Here's what you need to know:</p>
                
                <div class="failure-section">
                    <h4>🔧 Technical Issues</h4>
                    <ul>
                        <li><strong>API Service:</strong> External service temporarily unavailable</li>
                        <li><strong>Generation Timeout:</strong> Track took too long to generate</li>
                        <li><strong>Audio Processing:</strong> Problems with audio file creation</li>
                        <li><strong>Server Issues:</strong> Temporary system problems</li>
                    </ul>
                </div>
                
                <div class="failure-section">
                    <h4>🚫 Content Restrictions</h4>
                    <p><strong>Your track was rejected because it contains restricted content:</strong></p>
                    <ul>
                        <li><strong>Artist/Band Names:</strong> "gorillaz", "beatles", "michael jackson", "taylor swift", etc.</li>
                        <li><strong>Copyrighted Material:</strong> Song titles, lyrics, or melodies from existing songs</li>
                        <li><strong>Explicit Content:</strong> Inappropriate, offensive, or adult content</li>
                        <li><strong>Trademarks:</strong> Brand names, company names, or product names</li>
                        <li><strong>Celebrity Names:</strong> Real person names in music context</li>
                    </ul>
                </div>
                
                <div class="failure-section">
                    <h4>💡 How to Fix It</h4>
                    <p><strong>Instead of specific names, use generic descriptions:</strong></p>
                    <ul>
                        <li>❌ "like gorillaz" → ✅ "electronic alternative rock band"</li>
                        <li>❌ "michael jackson style" → ✅ "pop dance music with soul influences"</li>
                        <li>❌ "beatles sound" → ✅ "classic rock with harmonies"</li>
                        <li>❌ "taylor swift song" → ✅ "pop country ballad"</li>
                    </ul>
                </div>
                
                <div class="failure-section">
                    <h4>🎵 Success Tips</h4>
                    <ul>
                        <li><strong>Be Creative:</strong> Describe the music style, not the artist</li>
                        <li><strong>Use Genres:</strong> "rock", "pop", "electronic", "jazz", "classical"</li>
                        <li><strong>Describe Mood:</strong> "upbeat", "melancholic", "energetic", "relaxing"</li>
                        <li><strong>Mention Instruments:</strong> "guitar-driven", "piano ballad", "electronic beats"</li>
                        <li><strong>Try Again:</strong> Use the retry button with a modified prompt</li>
                    </ul>
                </div>
                
                <div class="failure-section">
                    <h4>🔄 What You Can Do</h4>
                    <ul>
                        <li><strong>Retry:</strong> Create a new version with a modified prompt</li>
                        <li><strong>Delete:</strong> Remove this failed track and start fresh</li>
                        <li><strong>Learn:</strong> Check the error message for specific details</li>
                        <li><strong>Contact Support:</strong> If you're unsure why it failed</li>
                    </ul>
                </div>
                
                <div class="help-actions">
                    <button onclick="closeFailureHelp()" class="btn btn-primary">
                        <i class="fas fa-check"></i> Got it!
                    </button>
                    <button onclick="retryTrack(${trackId})" class="btn btn-secondary">
                        <i class="fas fa-redo"></i> Retry Track
                    </button>
                    <button onclick="deleteFailedTrack(${trackId})" class="btn btn-danger">
                        <i class="fas fa-trash"></i> Delete Track
                    </button>
                </div>
            </div>
        `;
        
        // Create modal
        const modal = document.createElement('div');
        modal.className = 'modal-overlay';
        modal.innerHTML = helpContent;
        document.body.appendChild(modal);
        
        // Add modal styles
        const style = document.createElement('style');
        style.textContent = `
            .modal-overlay {
                position: fixed;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                background: rgba(0, 0, 0, 0.8);
                display: flex;
                align-items: center;
                justify-content: center;
                z-index: 10000;
                backdrop-filter: blur(10px);
            }
            .failure-help-modal {
                background: #1a1a1a;
                border: 1px solid rgba(255, 255, 255, 0.1);
                border-radius: 12px;
                padding: 2rem;
                max-width: 600px;
                max-height: 80vh;
                overflow-y: auto;
                color: white;
                box-shadow: 0 20px 40px rgba(0, 0, 0, 0.5);
            }
            .failure-help-modal h3 {
                color: #ffc107;
                margin-bottom: 1.5rem;
                font-size: 2rem;
                text-align: center;
            }
            .failure-section {
                margin-bottom: 2rem;
                padding: 1.5rem;
                background: rgba(255, 255, 255, 0.05);
                border-radius: 8px;
                border-left: 3px solid #667eea;
            }
            .failure-section h4 {
                color: #667eea;
                margin-bottom: 1rem;
                font-size: 1.6rem;
                display: flex;
                align-items: center;
                gap: 0.5rem;
            }
            .failure-help-modal ul {
                margin: 1rem 0;
                padding-left: 1.5rem;
            }
            .failure-help-modal li {
                margin: 0.8rem 0;
                line-height: 1.5;
            }
            .failure-help-modal strong {
                color: #ffc107;
            }
            .help-actions {
                display: flex;
                gap: 1rem;
                margin-top: 2rem;
                justify-content: center;
                flex-wrap: wrap;
            }
            .help-actions .btn {
                min-width: 120px;
                padding: 1rem 1.5rem;
                font-size: 1.4rem;
            }
        `;
        document.head.appendChild(style);
    }
    
    // Close failure help modal
    function closeFailureHelp() {
        const modal = document.querySelector('.modal-overlay');
        if (modal) {
            modal.remove();
        }
    }

    // Use global player for track playback
    async function playTrack(audioUrl, title, artist) {
        console.log('🎵 Library playTrack called:', { audioUrl, title, artist });
        
        // Validate audio URL
        if (!audioUrl || audioUrl === 'NULL' || audioUrl === 'null') {
            console.error('🎵 INVALID AUDIO URL:', audioUrl);
            return;
        }
        
        // Use the global player function directly
        if (typeof window.playTrackWithGlobalPlayer === 'function') {
            console.log('🎵 Using playTrackWithGlobalPlayer function');
            try {
                window.playTrackWithGlobalPlayer(audioUrl, title, artist, <?= $_SESSION['user_id'] ?>);
                return;
            } catch (error) {
                console.error('🎵 playTrackWithGlobalPlayer failed:', error);
            }
        }
        
        // Fallback to direct global player
        if (typeof window.globalPlayer !== 'undefined' && typeof window.globalPlayer.playTrack === 'function') {
            console.log('🎵 Using direct global player fallback');
            try {
                window.globalPlayer.wasPlaying = true;
                window.globalPlayer.playTrack(audioUrl, title, artist, <?= $_SESSION['user_id'] ?>);
                return;
            } catch (error) {
                console.error('🎵 Direct global player failed:', error);
            }
        }
        
        console.error('🎵 No global player available for playback');
    }

    // Track play when play button is clicked
    function trackPlay(trackId) {
        fetch('/api_social.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ action: 'play', track_id: trackId })
        });
    }

    // Play track from button and record play
    async function playTrackFromButton(button) {
        const audioUrl = button.getAttribute('data-audio-url');
        const title = button.getAttribute('data-title');
        const artist = button.getAttribute('data-artist');
        const trackId = button.closest('.track-card-modern').getAttribute('data-track-id');
        
        console.log('🎵 Play button clicked:', { audioUrl, title, artist, trackId });
        
        // Validate audio URL
        if (!audioUrl || audioUrl === 'NULL' || audioUrl === 'null') {
            console.error('🎵 INVALID AUDIO URL:', audioUrl);
            return;
        }
        
        // Record the play
        trackPlay(trackId);
        
        // Wait for global player to be ready
        await waitForGlobalPlayer();
        
        // Play the track using the global player
        if (typeof window.playTrackWithGlobalPlayer === 'function') {
            console.log('🎵 Using window.playTrackWithGlobalPlayer function');
            window.playTrackWithGlobalPlayer(audioUrl, title, artist, <?= $_SESSION['user_id'] ?>);
        } else if (typeof window.globalPlayer !== 'undefined' && typeof window.globalPlayer.playTrack === 'function') {
            console.log('🎵 Using direct global player fallback');
            window.globalPlayer.wasPlaying = true;
            window.globalPlayer.playTrack(audioUrl, title, artist, <?= $_SESSION['user_id'] ?>);
        } else {
            console.error('🎵 No global player available for playback');
            alert('Audio player not available. Please refresh the page and try again.');
        }
    }

    // Wait for global player to be ready
    async function waitForGlobalPlayer() {
        return new Promise((resolve) => {
            // Check if already available
            if (typeof window.playTrackWithGlobalPlayer === 'function' || 
                (typeof window.globalPlayer !== 'undefined' && typeof window.globalPlayer.playTrack === 'function')) {
                console.log('🎵 Global player already available');
                resolve();
                return;
            }
            
            console.log('🎵 Waiting for global player to be ready...');
            
            // Wait for global player ready event
            const checkPlayer = () => {
                if (typeof window.playTrackWithGlobalPlayer === 'function' || 
                    (typeof window.globalPlayer !== 'undefined' && typeof window.globalPlayer.playTrack === 'function')) {
                    console.log('🎵 Global player is now ready');
                    resolve();
                } else {
                    setTimeout(checkPlayer, 100);
                }
            };
            
            // Start checking
            setTimeout(checkPlayer, 100);
            
            // Also listen for the global player ready event
            window.addEventListener('globalPlayerReady', () => {
                console.log('🎵 Global player ready event received');
                resolve();
            }, { once: true });
            
            // Timeout after 5 seconds
            setTimeout(() => {
                console.warn('🎵 Global player timeout - proceeding anyway');
                resolve();
            }, 5000);
        });
    }

    // Download track function
    function downloadTrack(trackId) {
        window.open(`/api_download_track.php?track_id=${trackId}`, '_blank');
    }

    // Show variations modal
    function showVariations(trackId) {
        console.log('🎵 Showing variations for track:', trackId);
        
        // Get track data from PHP
        const trackCard = document.querySelector(`[data-track-id="${trackId}"]`);
        if (!trackCard) {
            console.error('🎵 Track card not found for track ID:', trackId);
            alert('Track not found. Please refresh the page and try again.');
            return;
        }
        
        console.log('🎵 Track card found:', trackCard);
        
        // Get variations data from PHP
        const variationsData = trackCard.getAttribute('data-variations');
        console.log('🎵 Raw variations data:', variationsData);
        
        if (!variationsData || variationsData === '[]') {
            console.error('🎵 No variations data found');
            alert('No variations available for this track.');
            return;
        }
        
        try {
            trackVariations = JSON.parse(variationsData);
            console.log('🎵 Parsed variations:', trackVariations);
            
            if (!Array.isArray(trackVariations) || trackVariations.length === 0) {
                console.error('🎵 No variations in array');
                alert('No variations available for this track.');
                return;
            }
            
            currentTrackId = trackId;
            
            // Get current selection
            const currentSelection = trackCard.getAttribute('data-selected-variation') || '0';
            selectedVariationIndex = parseInt(currentSelection);
            
            console.log('🎵 About to populate variations grid');
            
            // Populate variations grid
            populateVariationsGrid();
            
            console.log('🎵 About to show modal');
            
            // Show modal
            const modal = document.getElementById('variationsModal');
            if (!modal) {
                console.error('🎵 Variations modal not found');
                alert('Modal not found. Please refresh the page and try again.');
                return;
            }
            
            modal.classList.add('active');
            console.log('🎵 Modal should now be visible');
            
        } catch (error) {
            console.error('🎵 Error parsing variations data:', error);
            alert('Error loading variations. Please refresh the page and try again.');
        }
    }

    // Show lyrics modal
    function showLyrics(trackId) {
        // This would need to be implemented based on your lyrics system
        alert('Lyrics feature coming soon!');
    }

    // Populate variations grid
    function populateVariationsGrid() {
        const grid = document.getElementById('variationsGrid');
        grid.innerHTML = '';
        
        trackVariations.forEach((variation, index) => {
            const card = document.createElement('div');
            card.className = `variation-card ${index === selectedVariationIndex ? 'selected' : ''}`;
            card.onclick = () => selectVariation(index);
            
            const duration = Math.floor(variation.duration / 60) + 'm ' + Math.floor(variation.duration % 60) + 's';
            const tags = variation.tags ? variation.tags.split(',').slice(0, 3) : [];
            
            card.innerHTML = `
                <div class="variation-header">
                    <div class="variation-title">${variation.title || 'Variation ' + (index + 1)}</div>
                    <div class="variation-index">${index + 1}</div>
                </div>
                <div class="variation-duration">
                    <i class="fas fa-clock"></i> ${duration}
                </div>
                ${tags.length > 0 ? `
                    <div class="variation-tags">
                        ${tags.map(tag => `<span class="variation-tag">${tag.trim()}</span>`).join('')}
                    </div>
                ` : ''}
                <div class="variation-actions">
                    <button class="variation-btn play" onclick="playVariation(${index})">
                        <i class="fas fa-play"></i> Play
                    </button>
                    <button class="variation-btn download" onclick="downloadVariation(${index})">
                        <i class="fas fa-download"></i> Download
                    </button>
                    <button class="variation-btn select ${index === selectedVariationIndex ? 'selected' : ''}" onclick="selectVariation(${index})">
                        <i class="fas fa-check"></i> ${index === selectedVariationIndex ? 'Selected' : 'Select'}
                    </button>
                </div>
            `;
            
            grid.appendChild(card);
        });
        
        // Update save button state
        updateSaveButton();
    }

    // Select variation
    function selectVariation(index) {
        selectedVariationIndex = index;
        
        // Update visual selection
        document.querySelectorAll('.variation-card').forEach((card, i) => {
            card.classList.toggle('selected', i === index);
        });
        
        document.querySelectorAll('.variation-btn.select').forEach((btn, i) => {
            btn.classList.toggle('selected', i === index);
            btn.innerHTML = `<i class="fas fa-check"></i> ${i === index ? 'Selected' : 'Select'}`;
        });
        
        updateSaveButton();
    }

    // Play variation
    async function playVariation(index) {
        const variation = trackVariations[index];
        if (!variation) return;
        
        console.log('🎵 Playing variation:', variation);
        
        // Wait for global player to be ready
        await waitForGlobalPlayer();
        
        // Use the global player
        if (typeof window.playTrackWithGlobalPlayer === 'function') {
            console.log('🎵 Using window.playTrackWithGlobalPlayer function for variation');
            window.playTrackWithGlobalPlayer(variation.audio_url, variation.title || 'Variation ' + (index + 1), '<?= htmlspecialchars($user_name) ?>', <?= $_SESSION['user_id'] ?>);
        } else if (typeof window.globalPlayer !== 'undefined' && typeof window.globalPlayer.playTrack === 'function') {
            console.log('🎵 Using direct global player fallback for variation');
            window.globalPlayer.wasPlaying = true;
            window.globalPlayer.playTrack(variation.audio_url, variation.title || 'Variation ' + (index + 1), '<?= htmlspecialchars($user_name) ?>', <?= $_SESSION['user_id'] ?>);
        } else {
            console.error('🎵 No global player available for variation playback');
            alert('Audio player not available. Please refresh the page and try again.');
        }
    }

    // Download variation
    function downloadVariation(index) {
        const variation = trackVariations[index];
        if (!variation) return;
        
        console.log('🎵 Downloading variation:', variation);
        
        // Create a temporary link element to trigger download
        const link = document.createElement('a');
        link.href = variation.audio_url;
        
        // Create a meaningful filename
        const trackTitle = variation.title || 'Variation ' + (index + 1);
        const artistName = '<?= htmlspecialchars($user_name) ?>';
        const filename = `${artistName} - ${trackTitle} (Variation ${index + 1}).mp3`;
        
        link.download = filename;
        link.target = '_blank';
        
        // Add to DOM, click, and remove
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        
        // Show success message
        const toast = document.createElement('div');
        toast.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            background: rgba(72, 187, 120, 0.9);
            color: white;
            padding: 1rem 2rem;
            border-radius: 8px;
            z-index: 3000;
            font-size: 1.4rem;
            font-weight: 600;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
        `;
        toast.textContent = `✅ Downloading: ${filename}`;
        document.body.appendChild(toast);
        
        // Remove toast after 3 seconds
        setTimeout(() => {
            if (toast.parentNode) {
                toast.parentNode.removeChild(toast);
            }
        }, 3000);
    }

    // Close variations modal
    function closeVariations() {
        const modal = document.getElementById('variationsModal');
        modal.classList.remove('active');
        
        // Reset variables
        trackVariations = [];
        currentTrackId = null;
        selectedVariationIndex = null;
    }

    // Update save button state
    function updateSaveButton() {
        const saveBtn = document.getElementById('saveVariationBtn');
        if (!saveBtn) {
            console.error('🎵 Save button not found');
            return;
        }
        
        if (currentTrackId === null) {
            saveBtn.disabled = true;
            saveBtn.textContent = 'No Track Selected';
            return;
        }
        
        const trackCard = document.querySelector(`[data-track-id="${currentTrackId}"]`);
        if (!trackCard) {
            saveBtn.disabled = true;
            saveBtn.textContent = 'Track Not Found';
            return;
        }
        
        const currentSelection = trackCard.getAttribute('data-selected-variation') || '0';
        
        if (selectedVariationIndex !== parseInt(currentSelection)) {
            saveBtn.disabled = false;
            saveBtn.textContent = 'Save Selection';
        } else {
            saveBtn.disabled = true;
            saveBtn.textContent = 'No Changes';
        }
    }

    // Save variation selection
    function saveVariationSelection() {
        if (selectedVariationIndex === null || currentTrackId === null) {
            console.error('🎵 No variation or track selected');
            return;
        }
        
        console.log('🎵 Saving variation selection:', { trackId: currentTrackId, variationIndex: selectedVariationIndex });
        
        // Disable save button during request
        const saveBtn = document.getElementById('saveVariationBtn');
        saveBtn.disabled = true;
        saveBtn.textContent = 'Saving...';
        
        fetch('/api_select_variation.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                track_id: currentTrackId,
                variation_index: selectedVariationIndex
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                console.log('🎵 Variation selection saved:', data);
                
                // Update the track card
                const trackCard = document.querySelector(`[data-track-id="${currentTrackId}"]`);
                if (trackCard) {
                    trackCard.setAttribute('data-selected-variation', selectedVariationIndex);
                    
                    // Update the main audio URL and duration
                    const variation = trackVariations[selectedVariationIndex];
                    if (variation) {
                        // Update play button
                        const playBtn = trackCard.querySelector('.play-track-btn');
                        if (playBtn) {
                            playBtn.setAttribute('data-audio-url', variation.audio_url);
                        }
                        
                        // Update duration display
                        const durationSpan = trackCard.querySelector('.track-details span:first-child');
                        if (durationSpan) {
                            const duration = Math.floor(variation.duration / 60) + 'm ' + Math.floor(variation.duration % 60) + 's';
                            durationSpan.innerHTML = `<i class="fas fa-clock"></i> ${duration}`;
                        }
                    }
                }
                
                // Show success message
                if (typeof window.showNotification === 'function') {
                    window.showNotification('Variation selection saved successfully!', 'success');
                } else {
                    alert('✅ Variation selection saved successfully!');
                }
                
                // Close modal
                closeVariations();
                
            } else {
                console.error('🎵 Failed to save variation selection:', data.error);
                
                if (typeof window.showNotification === 'function') {
                    window.showNotification('Failed to save variation selection: ' + (data.error || 'Unknown error'), 'error');
                } else {
                    alert('❌ Failed to save variation selection: ' + (data.error || 'Unknown error'));
                }
            }
        })
        .catch(error => {
            console.error('🎵 Error saving variation selection:', error);
            
            if (typeof window.showNotification === 'function') {
                window.showNotification('Network error saving variation selection. Please try again.', 'error');
            } else {
                alert('❌ Network error saving variation selection. Please check your connection and try again.');
            }
        })
        .finally(() => {
            // Restore save button
            saveBtn.disabled = false;
            saveBtn.textContent = 'Save Selection';
        });
    }

    // Close modal when clicking outside
    document.addEventListener('click', function(event) {
        const variationsModal = document.getElementById('variationsModal');
        
        if (variationsModal && variationsModal.classList.contains('active')) {
            if (event.target === variationsModal) {
                closeVariations();
            }
        }
    });

    // Close modal on escape key
    document.addEventListener('keydown', function(event) {
        if (event.key === 'Escape') {
            const variationsModal = document.getElementById('variationsModal');
            if (variationsModal && variationsModal.classList.contains('active')) {
                closeVariations();
            }
        }
    });

    // Test global player function
    function testGlobalPlayer() {
        console.log('🎵 Testing global player...');
        console.log('🎵 window.globalPlayer:', typeof window.globalPlayer);
        console.log('🎵 window.playTrackWithGlobalPlayer:', typeof window.playTrackWithGlobalPlayer);
        console.log('🎵 globalPlayer.playTrack:', typeof window.globalPlayer?.playTrack);
        
        if (typeof window.playTrackWithGlobalPlayer === 'function') {
            console.log('✅ playTrackWithGlobalPlayer is available');
        } else {
            console.log('❌ playTrackWithGlobalPlayer is NOT available');
        }
        
        if (typeof window.globalPlayer !== 'undefined' && typeof window.globalPlayer.playTrack === 'function') {
            console.log('✅ globalPlayer.playTrack is available');
        } else {
            console.log('❌ globalPlayer.playTrack is NOT available');
        }
    }

    // All other existing functions remain unchanged...
    // (Additional functions would be added here as needed)
    
    // Music Creation Modal Functions
    function showCreateMusicModal() {
        // Show the shared modal template
        const modal = document.getElementById('createMusicModalOverlay');
        if (modal) {
            modal.style.display = 'flex';
            
            // Setup event listeners for the shared modal
            setupSharedModalEvents();
            
            // Initialize character counters
            initializeCharacterCounters();
            
            // Initialize sliders
            initializeSliders();
            
            // Update credit cost
            updateCreditCost();
        }
    }
    
    // Setup event listeners for the shared modal
    function setupSharedModalEvents() {
        // Mode switching
        const modeOptions = document.querySelectorAll('.mode-option');
        const formModes = document.querySelectorAll('.form-mode');
        
        modeOptions.forEach(option => {
            option.addEventListener('click', function() {
                const mode = this.getAttribute('data-mode');
                
                // Update active mode option
                modeOptions.forEach(opt => opt.classList.remove('active'));
                this.classList.add('active');
                
                // Show corresponding form
                formModes.forEach(form => {
                    form.classList.remove('active');
                    if (form.id === mode + 'Form') {
                        form.classList.add('active');
                    }
                });
                
                // Update credit cost
                updateCreditCost();
            });
        });
        
        // Character counters
        const textareas = document.querySelectorAll('textarea');
        textareas.forEach(textarea => {
            textarea.addEventListener('input', function() {
                const counter = this.parentNode.querySelector('.char-count');
                if (counter) {
                    const maxLength = this.getAttribute('maxlength') || 400;
                    const currentLength = this.value.length;
                    counter.textContent = `${currentLength}/${maxLength}`;
                }
            });
        });
        
        // Slider updates
        const sliders = document.querySelectorAll('input[type="range"]');
        sliders.forEach(slider => {
            slider.addEventListener('input', function() {
                const valueDisplay = document.querySelector('#' + this.id + 'Value');
                if (valueDisplay) {
                    valueDisplay.textContent = this.value;
                }
            });
        });
        
        // Variations change
        const variationsSelects = document.querySelectorAll('#variations, #proVariations');
        variationsSelects.forEach(select => {
            select.addEventListener('change', updateCreditCost);
        });
        
        // Form submission
        const form = document.getElementById('musicFormModal');
        if (form) {
            form.addEventListener('submit', function(e) {
                e.preventDefault();
                submitCreateMusic();
            });
        }
    }
    
    // Close create music modal
    function closeCreateMusicModal() {
        const modal = document.getElementById('createMusicModalOverlay');
        if (modal) {
            modal.style.display = 'none';
        }
    }
    
    // Add click outside to close modal
    document.addEventListener('DOMContentLoaded', function() {
        const modalOverlay = document.getElementById('createMusicModalOverlay');
        if (modalOverlay) {
            modalOverlay.addEventListener('click', function(e) {
                // Only close if clicking on the overlay itself, not the modal content
                if (e.target === modalOverlay) {
                    closeCreateMusicModal();
                }
            });
        }
    });
    
    // Initialize character counters for all textareas and inputs
    function initializeCharacterCounters() {
        const textareas = document.querySelectorAll('textarea[maxlength]');
        textareas.forEach(textarea => {
            const counter = textarea.nextElementSibling;
            if (counter && counter.classList.contains('char-count')) {
                const maxLength = textarea.getAttribute('maxlength');
                const currentLength = textarea.value.length;
                counter.textContent = `${currentLength}/${maxLength}`;
            }
        });
        
        const inputs = document.querySelectorAll('input[maxlength]');
        inputs.forEach(input => {
            const counter = input.nextElementSibling;
            if (counter && counter.classList.contains('char-count')) {
                const maxLength = input.getAttribute('maxlength');
                const currentLength = input.value.length;
                counter.textContent = `${currentLength}/${maxLength}`;
            }
        });
    }
    
    // Initialize sliders for all range inputs
    function initializeSliders() {
        const sliders = document.querySelectorAll('input[type="range"]');
        sliders.forEach(slider => {
            const valueDisplay = document.querySelector(`#${slider.id}Value`);
            if (valueDisplay) {
                valueDisplay.textContent = slider.value;
            }
        });
    }

</script>

<?php
// Include the existing modals and JavaScript functions
// This ensures all functionality is preserved
include 'includes/footer.php';
?> 

CasperSecurity Mini