<?php
// Inclure la configuration
require_once 'includes/config.php';
// Appliquer les en-têtes de sécurité
setSecurityHeaders();
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="csrf-token" content="<?php echo generateCSRFToken(); ?>">
    <title>kaubuntu.re - Plateforme Multimédia</title>
    <link rel="stylesheet" href="css/styles.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <link rel="stylesheet" href="css/mastodon-timeline.min.css">

    <!-- Favicons -->
    <link rel="apple-touch-icon" sizes="180x180" href="img/apple-touch-icon.png">
    <link rel="icon" type="image/png" sizes="32x32" href="img/favicon-32x32.png">
    <link rel="icon" type="image/png" sizes="16x16" href="img/favicon-16x16.png">
    <link rel="manifest" href="site.webmanifest">
    <link rel="icon" type="image/x-icon" href="img/favicon.ico">
    <meta name="theme-color" content="#FF0000">
    
    <!-- PWA Meta Tags -->
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="default">
    <meta name="apple-mobile-web-app-title" content="kaubuntu.re">
    <meta name="application-name" content="kaubuntu.re">
    <meta name="msapplication-TileColor" content="#FF0000">
    <meta name="msapplication-config" content="browserconfig.xml">
</head>
<body>
    <?php include 'includes/sidebar.php'; ?>
    <!-- Contenu principal -->
    <div class="main-content">
        <?php include 'includes/header.php'; ?>
        <!-- Hero and Mastodon container -->
        <div class="hero-mastodon-wrapper">
            <!-- Hero Banner -->
            <div class="hero">
                <?php
                // Vérifier s'il y a un direct en cours
                $liveStream = getLiveStream();

                if ($liveStream) {
                    // Afficher le direct en cours
                    ?>
                    <div class="live-badge">
                        <i class="fas fa-circle"></i> DIRECT
                    </div>
                    <div class="hero-video-container">
                        <iframe
                            src="<?php echo PEERTUBE_URL; ?>/videos/embed/<?php echo $liveStream['id']; ?>?autoplay=1&muted=1"
                            frameborder="0"
                            allowfullscreen="allowfullscreen"
                            allow="autoplay; fullscreen"
                            title="<?php echo htmlspecialchars($liveStream['title']); ?>">
                        </iframe>
                    </div>
                    <div class="hero-video-info">
                        <h2><?php echo htmlspecialchars($liveStream['title']); ?></h2>
                        <div class="hero-channel-info">
                            <?php if (strpos($liveStream['channelAvatar'], 'default-avatar.png') !== false || empty($liveStream['channelAvatar'])): ?>
                                <div class="channel-avatar-placeholder">
                                    <i class="fas fa-user-circle"></i>
                                </div>
                            <?php else: ?>
                                <img src="<?php echo $liveStream['channelAvatar']; ?>" alt="<?php echo $liveStream['channel']; ?>" class="channel-avatar">
                            <?php endif; ?>
                            <span class="channel-name"><?php echo $liveStream['channel']; ?></span>
                        </div>
                    </div>
                <?php
                } else {
                    // Aucun direct en cours
                    ?>
                    <div class="hero-no-live">
                        <i class="fas fa-tv"></i>
                        <h2>Aucun direct en cours</h2>
                        <p>Revenez plus tard pour découvrir nos prochaines diffusions en direct.</p>
                    </div>
                <?php
                }
                ?>
            </div>

            <div id="mt-container" class="mt-container">
                <div class="mt-header">
                    <h2 class="mt-title">Fil d'actualités <i class="fab fa-mastodon"></i></h2>
                </div>
                <div class="mt-body" role="feed">
                    <div class="mt-loading-spinner"></div>
                </div>
            </div>
        </div>


        <!-- Hashtags en ligne -->
        <div class="tags-section">
            <?php
            if (defined('POPULAR_TAGS') && !empty(POPULAR_TAGS)):
                foreach (POPULAR_TAGS as $tag):
                    $encodedTag = urlencode('#' . $tag);
            ?>
            <a href="recherche.php?q=<?php echo $encodedTag; ?>" class="tag">#<?php echo htmlspecialchars($tag); ?></a>
            <?php
                endforeach;
            endif;
            ?>
        </div>

        <!-- Séparateur stylisé -->
        <hr class="section-divider">

        <!-- Section Shorts -->
        <div class="video-section">
            <div class="section-header">
                <div class="section-logo">
                    <img src="img/logo.png" alt="kaubuntu.re">
                </div>
                <h2 class="section-title">Shorts</h2>
            </div>

            <div class="carousel">
                <div class="carousel-container">
                    <?php
                    // Récupérer les shorts depuis l'API PeerTube
                    $shorts = getShorts();

                    // Traiter le cas où aucun short n'est trouvé
                    if (empty($shorts)) {
                        echo '<div class="no-results">Aucun short disponible pour le moment</div>';
                    } else {
                        foreach ($shorts as $video):
                    ?>
                    <div class="carousel-item">
                        <div class="video-card" data-video-id="<?php echo $video['id']; ?>">
                            <div class="video-thumbnail">
                                <img src="<?php echo $video['thumbnail']; ?>" alt="<?php echo $video['title']; ?>">
                                <div class="video-play-icon">
                                    <i class="fas fa-play-circle"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                    <?php
                        endforeach;
                    }
                    ?>
                </div>

                <?php if (!empty($shorts) && count($shorts) > 1): ?>
                <div class="carousel-controls">
                    <?php for ($i = 0; $i < count($shorts); $i++): ?>
                    <div class="carousel-dot <?php echo $i === 0 ? 'active' : ''; ?>"></div>
                    <?php endfor; ?>
                </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Séparateur stylisé -->
        <hr class="section-divider">

        <!-- Section Dernières vidéos -->
        <div class="video-section">
            <div class="section-header">
                <div class="section-logo">
                    <img src="img/logo.png" alt="kaubuntu.re">
                </div>
                <h2 class="section-title">Dernières vidéos</h2>
            </div>

            <div class="video-grid">
                <?php
                // Récupérer les vidéos récentes depuis l'API PeerTube
                $recentVideos = getRecentVideos();

                // Traiter le cas où aucune vidéo n'est trouvée
                if (empty($recentVideos)) {
                    echo '<div class="no-results">Aucune vidéo disponible pour le moment</div>';
                } else {
                    foreach ($recentVideos as $video):
                ?>
                <div class="video-card" data-video-id="<?php echo $video['id']; ?>">
                    <div class="video-thumbnail">
                        <img src="<?php echo $video['thumbnail']; ?>" alt="<?php echo $video['title']; ?>">
                        <div class="video-play-icon">
                            <i class="fas fa-play-circle"></i>
                        </div>
                        <div class="video-duration"><?php echo formatDuration($video['duration']); ?></div>
                    </div>
                    <div class="video-info">
                        <h3 class="video-title"><?php echo $video['title']; ?></h3>
                        <div class="video-channel">
                            <?php if (strpos($video['channelAvatar'], 'default-avatar.png') !== false || empty($video['channelAvatar'])): ?>
                                <div class="channel-avatar-placeholder">
                                    <i class="fas fa-user-circle"></i>
                                </div>
                            <?php else: ?>
                                <img src="<?php echo $video['channelAvatar']; ?>" alt="<?php echo $video['channel']; ?>" class="channel-avatar">
                            <?php endif; ?>
                            <span class="channel-name"><?php echo $video['channel']; ?></span>
                        </div>
                        <div class="video-metadata">
                            <span class="video-views"><i class="fas fa-eye"></i> <?php echo formatViewCount($video['views']); ?> vues</span>
                            <span class="video-date"><i class="far fa-calendar-alt"></i> <?php echo formatDate($video['date']); ?></span>
                        </div>
                    </div>
                </div>
                <?php
                    endforeach;
                }
                ?>
            </div>

            <button class="view-more">Voir plus</button>
        </div>

        <!-- Séparateur stylisé -->
        <hr class="section-divider">

        <!-- Section Tendances -->
        <div class="video-section">
            <div class="section-header">
                <div class="section-logo">
                    <img src="img/logo.png" alt="kaubuntu.re">
                </div>
                <h2 class="section-title">Tendances</h2>
            </div>

            <div class="video-grid">
                <?php
                // Récupérer les vidéos tendances depuis l'API PeerTube
                $trendingVideos = getTrendingVideos();

                // Traiter le cas où aucune vidéo n'est trouvée
                if (empty($trendingVideos)) {
                    echo '<div class="no-results">Aucune vidéo disponible pour le moment</div>';
                } else {
                    foreach ($trendingVideos as $video):
                ?>
                <div class="video-card" data-video-id="<?php echo $video['id']; ?>">
                    <div class="video-thumbnail">
                        <img src="<?php echo $video['thumbnail']; ?>" alt="<?php echo $video['title']; ?>">
                        <div class="video-play-icon">
                            <i class="fas fa-play-circle"></i>
                        </div>
                        <div class="video-duration"><?php echo formatDuration($video['duration']); ?></div>
                    </div>
                    <div class="video-info">
                        <h3 class="video-title"><?php echo $video['title']; ?></h3>
                        <div class="video-channel">
                            <?php if (strpos($video['channelAvatar'], 'default-avatar.png') !== false || empty($video['channelAvatar'])): ?>
                                <div class="channel-avatar-placeholder">
                                    <i class="fas fa-user-circle"></i>
                                </div>
                            <?php else: ?>
                                <img src="<?php echo $video['channelAvatar']; ?>" alt="<?php echo $video['channel']; ?>" class="channel-avatar">
                            <?php endif; ?>
                            <span class="channel-name"><?php echo $video['channel']; ?></span>
                        </div>
                        <div class="video-metadata">
                            <span class="video-views"><i class="fas fa-eye"></i> <?php echo formatViewCount($video['views']); ?> vues</span>
                            <span class="video-date"><i class="far fa-calendar-alt"></i> <?php echo formatDate($video['date']); ?></span>
                        </div>
                    </div>
                </div>
                <?php
                    endforeach;
                }
                ?>
            </div>

            <button class="view-more">Voir plus</button>
        </div>

        <!-- Séparateur stylisé -->
        <hr class="section-divider">

        <!-- Sections par catégorie -->
        <?php
        // Récupérer les catégories avec leurs vidéos
        $displayCategories = getDisplayCategories();

        // Afficher chaque catégorie qui a des vidéos
        foreach ($displayCategories as $category):
            if (!empty($category['videos'])):
        ?>
        <!-- Section Catégorie: <?php echo $category['name']; ?> -->
        <div class="video-section" data-category-id="<?php echo $category['id']; ?>">
            <div class="section-header">
                <div class="section-logo">
                    <img src="img/logo.png" alt="kaubuntu.re">
                </div>
                <h2 class="section-title"><?php echo $category['name']; ?></h2>
            </div>

            <div class="video-grid">
                <?php foreach ($category['videos'] as $video): ?>
                <div class="video-card" data-video-id="<?php echo $video['id']; ?>">
                    <div class="video-thumbnail">
                        <img src="<?php echo $video['thumbnail']; ?>" alt="<?php echo $video['title']; ?>">
                        <div class="video-play-icon">
                            <i class="fas fa-play-circle"></i>
                        </div>
                        <div class="video-duration"><?php echo formatDuration($video['duration']); ?></div>
                    </div>
                    <div class="video-info">
                        <h3 class="video-title"><?php echo $video['title']; ?></h3>
                        <div class="video-channel">
                            <?php if (strpos($video['channelAvatar'], 'default-avatar.png') !== false || empty($video['channelAvatar'])): ?>
                                <div class="channel-avatar-placeholder">
                                    <i class="fas fa-user-circle"></i>
                                </div>
                            <?php else: ?>
                                <img src="<?php echo $video['channelAvatar']; ?>" alt="<?php echo $video['channel']; ?>" class="channel-avatar">
                            <?php endif; ?>
                            <span class="channel-name"><?php echo $video['channel']; ?></span>
                        </div>
                        <div class="video-metadata">
                            <span class="video-views"><i class="fas fa-eye"></i> <?php echo formatViewCount($video['views']); ?> vues</span>
                            <span class="video-date"><i class="far fa-calendar-alt"></i> <?php echo formatDate($video['date']); ?></span>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>

            <button class="view-more">Voir plus</button>
        </div>

        <!-- Séparateur stylisé -->
        <hr class="section-divider">

        <?php
            endif;
        endforeach;
        ?>

        <!-- Section Flexbox pour Informations et Tendances Hashtags -->
        <div class="info-tags-container">
            <?php if (defined('MOVEMENT_DESCRIPTION') && !empty(MOVEMENT_DESCRIPTION)): ?>
            <!-- Section Informations -->
            <div class="info-section">
                <h2 class="info-header"><?php echo MOVEMENT_DESCRIPTION; ?></h2>

                <?php if (defined('MOVEMENT_IMAGE') && !empty(MOVEMENT_IMAGE)): ?>
                <figure class="movement-figure">
                    <img src="<?php echo MOVEMENT_IMAGE; ?>" alt="<?php echo defined('MOVEMENT_IMAGE_ALT') ? MOVEMENT_IMAGE_ALT : ''; ?>" class="info-image">
                    <?php if (defined('MOVEMENT_CAPTION') && !empty(MOVEMENT_CAPTION)): ?>
                    <figcaption class="movement-caption">
                        <?php echo MOVEMENT_CAPTION; ?>
                    </figcaption>
                    <?php endif; ?>
                </figure>
                <?php endif; ?>
            </div>
            <?php endif; ?>

            <!-- Section Tendances Hashtags -->
            <div class="tags-section-container">
                <h2 class="section-title centered">Tendances</h2>

                <div class="tags-section">
                    <?php
                    if (defined('POPULAR_TAGS') && !empty(POPULAR_TAGS)):
                        foreach (POPULAR_TAGS as $tag):
                            $encodedTag = urlencode('#' . $tag);
                    ?>
                    <a href="recherche.php?q=<?php echo $encodedTag; ?>" class="tag">#<?php echo htmlspecialchars($tag); ?></a>
                    <?php
                        endforeach;
                    endif;
                    ?>
                </div>
            </div>
        </div>
    </div>
    <?php include 'includes/footer.php'; ?>
    <?php include 'includes/mobile-menu.php'; ?>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <script src="js/main.js"></script>
    <script src="js/mastodon-timeline.umd.js"></script>
    <script src="js/mastodon-config.php"></script>
    
    <!-- PWA Service Worker -->
    <script>
        if ('serviceWorker' in navigator) {
            window.addEventListener('load', function() {
                navigator.serviceWorker.register('/sw.js')
                    .then(function(registration) {
                        console.log('Service Worker enregistré avec succès:', registration.scope);
                        
                        // Écouter les mises à jour
                        registration.addEventListener('updatefound', function() {
                            const newWorker = registration.installing;
                            newWorker.addEventListener('statechange', function() {
                                if (newWorker.state === 'installed' && navigator.serviceWorker.controller) {
                                    // Nouvelle version disponible
                                    console.log('Nouvelle version disponible');
                                    if (confirm('Une nouvelle version est disponible. Voulez-vous recharger la page ?')) {
                                        window.location.reload();
                                    }
                                }
                            });
                        });
                    })
                    .catch(function(err) {
                        console.log('Échec de l\'enregistrement du Service Worker:', err);
                    });
            });
        }
        
        // Gestion de l'installation PWA
        let deferredPrompt;
        const installButton = document.getElementById('install-pwa');
        
        window.addEventListener('beforeinstallprompt', function(e) {
            e.preventDefault();
            deferredPrompt = e;
            
            // Afficher le bouton d'installation s'il existe
            if (installButton) {
                installButton.style.display = 'block';
                installButton.addEventListener('click', function() {
                    deferredPrompt.prompt();
                    deferredPrompt.userChoice.then(function(choiceResult) {
                        if (choiceResult.outcome === 'accepted') {
                            console.log('PWA installée');
                        }
                        deferredPrompt = null;
                        installButton.style.display = 'none';
                    });
                });
            }
        });
        
        // Masquer le bouton après installation
        window.addEventListener('appinstalled', function() {
            console.log('PWA installée avec succès');
            if (installButton) {
                installButton.style.display = 'none';
            }
        });
    </script>
</body>
</html>
