<?php


require_once '../includes/auth.php';
require_once '../includes/db.php';

// Function to get comprehensive figures data
function getFiguresData($pdo, $sport = null) {
    $figuresData = [
        'sports' => [],
        'categories' => [],
        'items' => [],
        'by_sport' => [],
        'stats' => []
    ];
    
    try {
        // Get all sports
        $sportsQuery = $pdo->prepare("SELECT * FROM figure_sports WHERE is_active = 1 ORDER BY sport_name");
        $sportsQuery->execute();
        $figuresData['sports'] = $sportsQuery->fetchAll(PDO::FETCH_ASSOC);
        
        // Get categories (filtered by sport if provided)
        $categoriesQuery = $sport ? 
            $pdo->prepare("SELECT * FROM figure_categories WHERE sport_name = ? AND is_active = 1 ORDER BY sort_order, category_name") :
            $pdo->prepare("SELECT * FROM figure_categories WHERE is_active = 1 ORDER BY sport_name, sort_order, category_name");
        
        if ($sport) {
            $categoriesQuery->execute([$sport]);
        } else {
            $categoriesQuery->execute();
        }
        $figuresData['categories'] = $categoriesQuery->fetchAll(PDO::FETCH_ASSOC);
        
        // Get items (filtered by sport if provided)
        if ($sport) {
            $itemsQuery = $pdo->prepare("
                SELECT fi.*, fc.category_name, fc.sport_name 
                FROM figure_items fi
                JOIN figure_categories fc ON fi.sport_name = fc.sport_name AND fi.category_name = fc.category_name
                WHERE fi.sport_name = ? AND fi.is_active = 1 
                ORDER BY fc.sort_order, fi.sort_order, fi.item_name
            ");
            $itemsQuery->execute([$sport]);
        } else {
            $itemsQuery = $pdo->prepare("
                SELECT fi.*, fc.category_name 
                FROM figure_items fi
                JOIN figure_categories fc ON fi.sport_name = fc.sport_name AND fi.category_name = fc.category_name
                WHERE fi.is_active = 1 
                ORDER BY fi.sport_name, fc.sort_order, fi.sort_order, fi.item_name
            ");
            $itemsQuery->execute();
        }
        $figuresData['items'] = $itemsQuery->fetchAll(PDO::FETCH_ASSOC);
        
        // Organize by sport and category
        foreach ($figuresData['items'] as $item) {
            $figuresData['by_sport'][$item['sport_name']][$item['category_name']][] = $item;
        }
        
        // Generate statistics
        $statsQuery = $pdo->prepare("
            SELECT 
                fs.sport_name,
                COUNT(DISTINCT fc.category_name) as category_count,
                COUNT(fi.item_name) as item_count
            FROM figure_sports fs
            LEFT JOIN figure_categories fc ON fs.sport_name = fc.sport_name AND fc.is_active = 1
            LEFT JOIN figure_items fi ON fc.sport_name = fi.sport_name AND fc.category_name = fi.category_name AND fi.is_active = 1
            WHERE fs.is_active = 1
            GROUP BY fs.sport_name
            ORDER BY fs.sport_name
        ");
        $statsQuery->execute();
        $figuresData['stats'] = $statsQuery->fetchAll(PDO::FETCH_ASSOC);
        
    } catch (PDOException $e) {
        error_log("Figures data error: " . $e->getMessage());
    }
    
    return $figuresData;
}

// Get selected sport from URL parameter
$selectedSport = $_GET['sport'] ?? '';
$searchTerm = $_GET['search'] ?? '';

// Get figures data
$figuresData = getFiguresData($pdo, $selectedSport ?: null);
$allSports = $figuresData['sports'];
$allStats = $figuresData['stats'];

// Get sport details with brand colors and icons
$sportsWithDetails = $pdo->query("
    SELECT fs.*, fsd.icon_path, fsd.brand_color_hex, fsd.slug
    FROM figure_sports fs
    LEFT JOIN figure_sport_details fsd ON fs.id = fsd.sport_id
    WHERE fs.is_active = 1
    ORDER BY fs.sport_name
")->fetchAll(PDO::FETCH_ASSOC);

// Create lookup for sport details
$sportDetails = [];
foreach ($sportsWithDetails as $sport) {
    $sportDetails[$sport['sport_name']] = $sport;
}

// Function to get SVG content with brand color fill
function getSvgWithColor($iconPath, $brandColor, $sportSlug, $size = 24) {
    if (empty($iconPath) || !file_exists('../' . $iconPath)) {
        return "<i class=\"fas fa-medal me-2\" style=\"color: $brandColor;\"></i>";
    }
    
    $svgContent = file_get_contents('../' . $iconPath);
    if ($svgContent === false) {
        return "<i class=\"fas fa-medal me-2\" style=\"color: $brandColor;\"></i>";
    }
    
    // Create unique class name from sport slug
    $uniqueClass = 'sport-' . preg_replace('/[^a-z0-9\-]/', '', strtolower($sportSlug ?? 'default'));
    
    // Add brand color, size, and unique class to SVG
    $svgContent = preg_replace('/(<svg[^>]*)(>)/', '$1 width="' . $size . '" height="' . $size . '" class="me-2 ' . $uniqueClass . '"$2', $svgContent);
    
    // Remove any existing fill attributes from all elements
    $svgContent = preg_replace('/fill="[^"]*"/', '', $svgContent);
    
    // Remove existing CSS styles and classes that might conflict
    $svgContent = preg_replace('/<style[^>]*>.*?<\/style>/s', '', $svgContent);
    $svgContent = preg_replace('/class="[^"]*"(?![^<]*class="me-2)/', '', $svgContent);
    
    return $svgContent;
}

// Function to generate subtle background color from brand color
function generateSubtleBg($brandColorHex) {
    if (empty($brandColorHex)) {
        return 'background: linear-gradient(175deg, rgb(13 110 253 / 14%) 0%, rgb(13 110 253 / 56%) 100%);'; // Default primary
    }
    
    // Remove # if present
    $hex = ltrim($brandColorHex, '#');
    
    // Convert hex to RGB
    if (strlen($hex) === 6) {
        $r = hexdec(substr($hex, 0, 2));
        $g = hexdec(substr($hex, 2, 2));
        $b = hexdec(substr($hex, 4, 2));
    } else {
        // Fallback to default
        return 'background: linear-gradient(175deg, rgb(13 110 253 / 14%) 0%, rgb(13 110 253 / 56%) 100%);';
    }
    
    // Create subtle gradient background with new style
    return "background: linear-gradient(175deg, rgb($r $g $b / 14%) 0%, rgb($r $g $b / 56%) 100%);";
}

// Function to get border color from brand color
function getBorderColor($brandColorHex) {
    if (empty($brandColorHex)) {
        return '#0d6efd'; // Default primary
    }
    return $brandColorHex;
}

// Filter data based on search term
$filteredData = $figuresData['by_sport'];
if (!empty($searchTerm)) {
    $filteredData = [];
    foreach ($figuresData['by_sport'] as $sport => $categories) {
        foreach ($categories as $category => $items) {
            $filteredItems = array_filter($items, function($item) use ($searchTerm) {
                return stripos($item['item_name'], $searchTerm) !== false ||
                       stripos($item['item_description'] ?? '', $searchTerm) !== false ||
                       stripos($item['item_code'] ?? '', $searchTerm) !== false;
            });
            if (!empty($filteredItems)) {
                $filteredData[$sport][$category] = $filteredItems;
            }
        }
    }
}

$pageTitle = 'Figures Dictionary Viewer';
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= $pageTitle ?> - Style Score Admin</title>
    <?php include_once '../includes/stylesheets.php'; ?>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
       
        
        .figure-item {
            transition: transform 0.2s ease;
            cursor: pointer;
        }
        
        .figure-item:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }
        
        .search-container {
            background: #ffffff;
            border: 1px solid #dee2e6;
            border-radius: 0.375rem;
            padding: 1.5rem;
            margin-bottom: 2rem;
        }
    </style>
</head>
<body class="body-bg-aurora-bright">
    <?php include '../menu.php'; ?>
   
    <div class="container-fluid container-StyleScore p-4">
        <?php       
            $use_localStorage = true;
            $show_header = false;
            include 'event_actions_menu.php'; 
            ?>
        <!-- Help Button and Modal -->
        <div class="position-fixed end-0 top-0 p-3  help_f_button" style="z-index: 1055;">
            <button type="button" class="btn btn-info btn-lg rounded-circle shadow" title="Help / Guide" data-bs-toggle="modal" data-bs-target="#helpModal" style="width:56px; height:56px;">
                <i class="fas fa-question"></i>
            </button>
        </div>
        <!-- Help Modal -->
        <div class="modal fade" id="helpModal" tabindex="-1" aria-labelledby="helpModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-xl modal-dialog-scrollable">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="helpModalLabel"><i class="fas fa-book me-2"></i>Figures Dictionary Viewer Help</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body p-0" style="height:80vh;">
                        <iframe src="../help/figures_viewer_help.html" style="width:100%;height:100%;border:0;" title="Figures Viewer Help"></iframe>
                    </div>
                </div>
            </div>
        </div>
         <div class="row justify-content-center">
            <div class="col-10">
                <!-- Header -->
                <div class="row mb-3">
                    <div class="col-12">
                        <div class="border-0 shadow-none card border-0 shadow-sm bg-primary text-white">
                            <div class="border-0 shadow-none card-body text-center py-3">
                                <h3 class="fw-bold mb-2">
                                    <i class="fas fa-book me-2"></i>Figures Dictionary Viewer
                                </h3>
                                <p class="mb-0 small">Browse and search figure dictionaries across all sports</p>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Quick Actions -->
                <div class="row mb-3">
                    <div class="col-12">
                        <div class="border-0 shadow-none card border-0 shadow-sm">
                            <div class="border-0 shadow-none card-body py-2 bg-transparent border border-0 card h-100 shadow-none">
                                <h6 class="card-title mb-2">
                                    <i class="fas fa-bolt me-1 text-warning"></i>Quick Actions
                                </h6>
                                <div class="d-flex flex-wrap gap-1">
                                    <a href="scoring_formats.php" class="btn btn-outline-secondary btn-sm">
                                        <i class="fas fa-arrow-left me-1"></i>Back to Formats
                                    </a>
                                    <a href="figures_management.php" class="btn btn-primary btn-sm">
                                        <i class="fas fa-edit me-1"></i>Manage Figures
                                    </a>
                                    <button type="button" class="btn btn-outline-primary btn-sm" onclick="exportAllFigures()">
                                        <i class="fas fa-download me-1"></i>Export All
                                    </button>
                                    <button type="button" class="btn btn-outline-success btn-sm" onclick="printFigures()">
                                        <i class="fas fa-print me-1"></i>Print View
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

            <!-- Search and Filter Section -->
            <div class="border-0 shadow-none card border-0 shadow-sm mb-3">
                <div class="border-0 shadow-none card-body py-2 ">
                    <h6 class="card-title mb-2">
                        <i class="fas fa-search me-1 text-info"></i>Search & Filter
                    </h6>
                    <form method="GET" class="row g-2">
                        <div class="col-md-5">
                            <input type="text" class="form-control form-control-sm" id="search" name="search" 
                                   value="<?= htmlspecialchars($searchTerm) ?>" 
                                   placeholder="Search by name, description, or code...">
                        </div>
                        <div class="col-md-4">
                            <select class="form-select form-select-sm" id="sport" name="sport">
                                <option value="">All Sports</option>
                                <?php foreach ($allSports as $sport): ?>
                                    <option value="<?= htmlspecialchars($sport['sport_name']) ?>" 
                                            <?= $selectedSport === $sport['sport_name'] ? 'selected' : '' ?>>
                                        <?= htmlspecialchars(ucfirst($sport['sport_name'])) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <div class="d-flex gap-1">
                                <button type="submit" class="btn btn-primary btn-sm flex-grow-1">
                                    <i class="fas fa-search me-1"></i>Search
                                </button>
                                <?php if (!empty($searchTerm) || !empty($selectedSport)): ?>
                                    <a href="?" class="btn btn-outline-secondary btn-sm">
                                        <i class="fas fa-times"></i>
                                    </a>
                                <?php endif; ?>
                            </div>
                        </div>
                    </form>
                    
                    <?php if (!empty($searchTerm) || !empty($selectedSport)): ?>
                        <div class="mt-2">
                            <small class="text-muted">
                                <?php if (!empty($searchTerm)): ?>
                                    Searching for: <strong>"<?= htmlspecialchars($searchTerm) ?>"</strong>
                                <?php endif; ?>
                                <?php if (!empty($selectedSport)): ?>
                                    <?= !empty($searchTerm) ? ' in ' : 'Showing ' ?>
                                    <strong><?= htmlspecialchars(ucfirst($selectedSport)) ?></strong>
                                <?php endif; ?>
                            </small>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

                <!-- Statistics Overview -->
                <?php 
                $totalSports = count($allStats);
                $totalCategories = array_sum(array_column($allStats, 'category_count'));
                $totalItems = array_sum(array_column($allStats, 'item_count'));
                ?>
                <div class="row g-2 mb-3">
                    <div class="col-md-4">
                        <div class="border-0 shadow-none card border-primary h-100">
                            <div class="border-0 shadow-none card-body text-center p-2">
                                <div class="fs-4 mb-1 text-primary">
                                    <i class="fas fa-medal"></i>
                                </div>
                                <h4 class="mb-0 text-primary"><?= $totalSports ?></h4>
                                <small class="text-muted">Sports</small>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="border-0 shadow-none card border-success h-100">
                            <div class="border-0 shadow-none card-body text-center p-2">
                                <div class="fs-4 mb-1 text-success">
                                    <i class="fas fa-layer-group"></i>
                                </div>
                                <h4 class="mb-0 text-success"><?= $totalCategories ?></h4>
                                <small class="text-muted">Categories</small>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="border-0 shadow-none card border-info h-100">
                            <div class="border-0 shadow-none card-body text-center p-2">
                                <div class="fs-4 mb-1 text-info">
                                    <i class="fas fa-puzzle-piece"></i>
                                </div>
                                <h4 class="mb-0 text-info"><?= $totalItems ?></h4>
                                <small class="text-muted">Figure Items</small>
                            </div>
                        </div>
                    </div>
                </div>            <!-- Figures Display -->
            <?php if (!empty($filteredData)): ?>
                <?php foreach ($filteredData as $sportName => $categories): ?>
                    <?php 
                    $sportDetail = $sportDetails[$sportName] ?? null;
                    $brandColor = $sportDetail['brand_color_hex'] ?? '#6c757d';
                    $iconPath = $sportDetail['icon_path'] ?? '';
                    $sportSlug = str_replace(' ', '-', strtolower($sportName));
                    $uniqueClass = 'sport-' . $sportSlug . '-' . substr(md5($sportName), 0, 8);
                    
                    // Generate dynamic styles for this sport
                    if ($sportDetail && !empty($brandColor)):
                    ?>
                    <style>
                        .<?= $uniqueClass ?>-bg {
                            background: linear-gradient(135deg, <?= $brandColor ?>15 0%, <?= $brandColor ?>08 100%);
                            border-color: <?= $brandColor ?>40;
                        }
                        .<?= $uniqueClass ?>-border {
                            border-color: <?= $brandColor ?>60 !important;
                        }
                        .<?= $uniqueClass ?>-text {
                            color: <?= $brandColor ?> !important;
                        }
                        .<?= $uniqueClass ?>-icon svg {
                            fill: <?= $brandColor ?> !important;
                        }
                         .<?= $uniqueClass ?>-active {
                                                background: linear-gradient(135deg, <?= $brandColor ?>25 0%, <?= $brandColor ?>15 100%);
                                                border-left: 3px solid <?= $brandColor ?>;
                                            }
                    </style>
                    <?php endif; ?>
                    
                        <div class="border-0 shadow-none card border <?= $sportDetail ? $uniqueClass . '-active' : '' ?> mb-3">
                            <div class="border-0 shadow-none card-header bg-light py-2 <?= $sportDetail ? $uniqueClass . '-bg' : '' ?>">
                                <div class="d-flex justify-content-between align-items-center">
                                    <h5 class="mb-0 d-flex align-items-center">
                                        <?php if (!empty($iconPath)): ?>
                                            <div class="me-2 <?= $uniqueClass ?>-icon">
                                                <?= getSvgWithColor($iconPath, $brandColor, $uniqueClass) ?>
                                            </div>
                                        <?php else: ?>
                                            <i class="fas fa-skating me-2 <?= $sportDetail ? $uniqueClass . '-text' : 'text-secondary' ?>"></i>
                                        <?php endif; ?>
                                        <span class="<?= $sportDetail ? $uniqueClass . '-text' : '' ?>">
                                            <?= htmlspecialchars(ucfirst($sportName)) ?>
                                        </span>
                                    </h5>
                                    <div class="d-flex align-items-center gap-1">
                                        <span class="badge bg-light text-dark">
                                            <?= count($categories) ?> categories
                                        </span>
                                        <span class="badge bg-light text-dark">
                                            <?= array_sum(array_map('count', $categories)) ?> items
                                        </span>
                                        <a href="figures_management.php?sport=<?= urlencode($sportName) ?>" 
                                           class="btn btn-outline-primary btn-sm ms-1" 
                                           title="Edit <?= htmlspecialchars($sportName) ?> figures">
                                            <i class="fas fa-edit"></i>
                                        </a>
                                    </div>
                                </div>
                            </div>
                        <div class="border-0 shadow-none card-body p-2 ">
                            <div class="row g-2">
                                <?php foreach ($categories as $categoryName => $items): ?>
                                    <div class="col-lg-6 col-md-12">
                                        <div class="border-0 shadow-none card border h-100 bg-transparent bg-transparent shadow-none border-0">
                                            <div class="border-0 shadow-none card-header bg-light py-1 <?= $sportDetail ? $uniqueClass . '-bg' : '' ?>">
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <h6 class="mb-0">
                                                        <i class="fas fa-layer-group me-1 text-primary"></i>
                                                        <?= htmlspecialchars($categoryName) ?>
                                                    </h6>
                                                    <span class="badge bg-primary badge-sm"><?= count($items) ?></span>
                                                </div>
                                            </div>
                                            <div class="border-0 shadow-none card-body p-2">
                                                <div class="row g-1">
                                                    <?php foreach ($items as $item): ?>
                                                        <div class="col-4">
                                                            <div class="figure-item border rounded p-2 bg-light h-100 <?= $sportDetail ? $uniqueClass . '-bg' : '' ?>">
                                                                <div class="d-flex justify-content-between align-items-start mb-1">
                                                                    <strong class="small"><?= htmlspecialchars($item['item_name']) ?></strong>
                                                                    <div class="d-flex gap-1 align-items-center">
                                                                        <?php if (!empty($item['item_code'])): ?>
                                                                            <code class="small bg-white px-1 rounded"><?= htmlspecialchars($item['item_code']) ?></code>
                                                                        <?php endif; ?>
                                                                        <?php if (!empty($item['sort_order'])): ?>
                                                                            <small class="text-muted">#<?= htmlspecialchars($item['sort_order']) ?></small>
                                                                        <?php endif; ?>
                                                                    </div>
                                                                </div>
                                                                <?php if (!empty($item['item_description'])): ?>
                                                                    <small class="text-muted d-block mb-1">
                                                                        <?= htmlspecialchars($item['item_description']) ?>
                                                                    </small>
                                                                <?php endif; ?>
                                                                <div class="d-flex flex-wrap gap-1">
                                                                    <?php if (!empty($item['difficulty_base'])): ?>
                                                                        <span class="badge bg-warning text-dark">
                                                                            Base: <?= htmlspecialchars($item['difficulty_base']) ?>
                                                                        </span>
                                                                    <?php endif; ?>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    <?php endforeach; ?>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php else: ?>
                <div class="border-0 shadow-none card border">
                    <div class="border-0 shadow-none card-body text-center py-4">
                        <i class="fas fa-search fa-2x text-muted mb-2"></i>
                        <h5 class="text-muted mb-1">No Figures Found</h5>
                        <p class="text-muted mb-0">
                            <?php if (!empty($searchTerm)): ?>
                                No figures match your search criteria. Try adjusting your search terms.
                            <?php elseif (!empty($selectedSport)): ?>
                                No figures found for <?= htmlspecialchars($selectedSport) ?>.
                            <?php else: ?>
                                No figure data available. 
                                <a href="figures_management.php" class="text-decoration-none">Add some figures</a> to get started.
                            <?php endif; ?>
                        </p>
                        <?php if (!empty($searchTerm) || !empty($selectedSport)): ?>
                            <a href="?" class="btn btn-primary btn-sm mt-2">
                                <i class="fas fa-times me-1"></i>Clear Filters
                            </a>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endif; ?>

            <!-- Export Options -->
            <?php if (!empty($filteredData)): ?>
                <div class="border-0 shadow-none card mt-4">
                    <div class="border-0 shadow-none card-body">
                        <h5 class="card-title">
                            <i class="fas fa-download me-2"></i>Export Options
                        </h5>
                        <div class="d-flex flex-wrap gap-2">
                            <button type="button" class="btn btn-outline-primary" onclick="exportAllFigures()">
                                <i class="fas fa-file-export me-1"></i>Export All Data (JSON)
                            </button>
                            <?php if (!empty($selectedSport)): ?>
                                <button type="button" class="btn btn-outline-info" onclick="exportSportFigures('<?= htmlspecialchars($selectedSport) ?>')">
                                    <i class="fas fa-file-download me-1"></i>Export <?= htmlspecialchars(ucfirst($selectedSport)) ?> Only
                                </button>
                            <?php endif; ?>
                            <button type="button" class="btn btn-outline-success" onclick="printFigures()">
                                <i class="fas fa-print me-1"></i>Print View
                            </button>
                        </div>
                    </div>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <script>
        // Export all figures data
        function exportAllFigures() {
            const figuresData = {
                exported_at: new Date().toISOString(),
                total_stats: {
                    sports: <?= $totalSports ?>,
                    categories: <?= $totalCategories ?>,
                    items: <?= $totalItems ?>
                },
                figures: <?= json_encode($figuresData['by_sport']) ?>,
                stats_by_sport: <?= json_encode($allStats) ?>
            };

            const blob = new Blob([JSON.stringify(figuresData, null, 2)], { type: 'application/json' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'all_figures_dictionary.json';
            a.click();
            URL.revokeObjectURL(url);
        }

        // Export specific sport figures
        function exportSportFigures(sport) {
            const sportData = <?= json_encode($figuresData['by_sport']) ?>[sport] || {};
            const figuresData = {
                sport: sport,
                exported_at: new Date().toISOString(),
                figures: sportData
            };

            const blob = new Blob([JSON.stringify(figuresData, null, 2)], { type: 'application/json' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = sport + '_figures.json';
            a.click();
            URL.revokeObjectURL(url);
        }

        // Print figures view
        function printFigures() {
            window.print();
        }

        // Enhanced search functionality
        document.addEventListener('DOMContentLoaded', function() {
            const searchInput = document.getElementById('search');
            const sportSelect = document.getElementById('sport');
            
            // Auto-submit on sport change
            if (sportSelect) {
                sportSelect.addEventListener('change', function() {
                    this.form.submit();
                });
            }
            
            // Add search on Enter key
            if (searchInput) {
                searchInput.addEventListener('keypress', function(e) {
                    if (e.key === 'Enter') {
                        e.preventDefault();
                        this.form.submit();
                    }
                });
            }

            // Add fade-in animation
            const cards = document.querySelectorAll('.card');
            cards.forEach((card, index) => {
                setTimeout(() => {
                    card.style.opacity = '0';
                    card.style.transform = 'translateY(20px)';
                    card.style.transition = 'all 0.3s ease';
                    setTimeout(() => {
                        card.style.opacity = '1';
                        card.style.transform = 'translateY(0)';
                    }, 50);
                }, index * 100);
            });
        });
    </script>

    <?php include 'footer.php'; ?>
</body>
</html>
