<?php
// Inclure la configuration
require_once 'includes/config.php';

// Vérifier si le mode compte à rebours est activé
if (defined('COUNTDOWN_ENABLED') && COUNTDOWN_ENABLED === true) {
    // Rediriger vers la page de compte à rebours
    require_once 'countdown.php';
    exit;
}

// Inclure le convertisseur Markdown
require_once 'includes/lib/markdown.php';
// Inclure les fonctions de données structurées
require_once 'includes/structured-data.php';

// Appliquer les en-têtes de sécurité
setSecurityHeaders();

// Récupérer l'ID de la vidéo depuis l'URL
$videoId = isset($_GET['id']) ? $_GET['id'] : '';

// Valider l'ID de la vidéo
$videoId = validateVideoId($videoId);
if ($videoId === false) {
    // Rediriger vers la page d'accueil si l'ID est invalide
    header('Location: index.php');
    exit;
}

// Récupérer les détails de la vidéo via l'API PeerTube
$videoData = callPeerTubeApi('videos/' . $videoId);

// Vérifier si la vidéo existe
if (empty($videoData) || isset($videoData['error'])) {
    // Gérer l'erreur : vidéo non trouvée
    $videoNotFound = true;
} else {
    // Formater les données de la vidéo
    $video = [
        'id' => $videoData['uuid'],
        'title' => $videoData['name'],
        'url' => PEERTUBE_URL . '/videos/embed/' . $videoData['uuid'],
        'description' => $videoData['description'] ?? '',
        'truncatedDescription' => $videoData['truncatedDescription'] ?? '',
        'channel' => $videoData['channel']['displayName'],
        'channelId' => $videoData['channel']['id'],
        'channelHandle' => $videoData['channel']['name'],
        'views' => $videoData['views'],
        'likes' => $videoData['likes'],
        'date' => $videoData['publishedAt'],
        'tags' => $videoData['tags'] ?? [],
        'licence' => $videoData['licence'] ?? null
    ];

    // Récupérer l'image de la chaîne
    $channelAvatar = 'img/default-avatar.jpg';
    if (isset($videoData['channel']['avatars'][0]['path'])) {
        $channelAvatar = PEERTUBE_URL . $videoData['channel']['avatars'][0]['path'];
    }

    // Récupérer les vidéos suggérées (de la même chaîne)
    $channelVideos = callPeerTubeApi('video-channels/' . $video['channelHandle'] . '/videos', [
        'count' => 5,
        'isLocal' => true
    ]);
    
    $suggestedVideos = [];
    
    if (!empty($channelVideos['data'])) {
        foreach ($channelVideos['data'] as $suggVid) {
            // Ne pas inclure la vidéo courante dans les suggestions
            if ($suggVid['uuid'] !== $videoId) {
                // Récupérer l'avatar de la chaîne
                $suggAvatar = isset($suggVid['channel']['avatars'][0]['path']) 
                    ? PEERTUBE_URL . $suggVid['channel']['avatars'][0]['path']
                    : '';
                
                $suggestedVideos[] = [
                    'id' => $suggVid['uuid'],
                    'title' => $suggVid['name'],
                    'thumbnail' => PEERTUBE_URL . $suggVid['thumbnailPath'],
                    'views' => $suggVid['views'],
                    'date' => $suggVid['publishedAt'],
                    'duration' => $suggVid['duration'],
                    'channel' => $suggVid['channel']['displayName'],
                    'channelAvatar' => $suggAvatar
                ];
            }
        }
    }
    
    // Si pas assez de vidéos de la même chaîne, ajouter des vidéos tendances
    if (count($suggestedVideos) < 5) {
        $trendingVideos = getTrendingVideos(10);
        
        foreach ($trendingVideos as $trendVid) {
            if ($trendVid['id'] !== $videoId && count($suggestedVideos) < 5) {
                // Vérifier que cette vidéo n'est pas déjà dans les suggestions
                $found = false;
                foreach ($suggestedVideos as $sv) {
                    if ($sv['id'] === $trendVid['id']) {
                        $found = true;
                        break;
                    }
                }
                
                if (!$found) {
                    $suggestedVideos[] = $trendVid;
                }
            }
        }
    }
}
?>

<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo !empty($video['title']) ? htmlspecialchars($video['title']) . ' - ' : ''; ?><?php echo SITE_NAME; ?></title>
    <meta name="description" content="<?php echo !empty($video['description']) ? htmlspecialchars(substr(strip_tags($video['description']), 0, 200)) . '...' : 'Regardez cette vidéo sur ' . SITE_NAME; ?>">
    <?php if (!isset($videoNotFound) && !empty($video)): ?>
    <link rel="canonical" href="<?php echo getBaseUrl() . '/video.php?id=' . $video['id']; ?>">
    <?php endif; ?>
    <link rel="stylesheet" href="css/styles.css?v=<?php echo filemtime('css/styles.css'); ?>">
    <link rel="stylesheet" href="css/video-page.css?v=<?php echo filemtime('css/video-page.css'); ?>">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/7.0.1/css/all.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">
    
    <!-- Meta tags pour le partage sur les réseaux sociaux -->
    <meta property="og:title" content="<?php echo !empty($video['title']) ? htmlspecialchars($video['title']) : 'Vidéo'; ?> - <?php echo SITE_NAME; ?>">
    <meta property="og:description" content="<?php echo !empty($video['description']) ? htmlspecialchars(substr(strip_tags($video['description']), 0, 200)) . '...' : 'Regardez cette vidéo sur ' . SITE_NAME; ?>">
    <?php if (isset($videoData['thumbnailPath'])): ?>
    <meta property="og:image" content="<?php echo PEERTUBE_URL . $videoData['thumbnailPath']; ?>">
    <?php endif; ?>
    <meta property="og:url" content="<?php echo (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; ?>">
    <meta property="og:type" content="video.other">
    <meta property="og:site_name" content="<?php echo SITE_NAME; ?>">
    <meta property="og:locale" content="fr_FR">

    <!-- Meta tags pour Twitter -->
    <meta name="twitter:card" content="summary_large_image">
    <meta name="twitter:title" content="<?php echo !empty($video['title']) ? htmlspecialchars($video['title']) : 'Vidéo'; ?> - <?php echo SITE_NAME; ?>">
    <meta name="twitter:description" content="<?php echo !empty($video['description']) ? htmlspecialchars(substr(strip_tags($video['description']), 0, 200)) . '...' : 'Regardez cette vidéo sur ' . SITE_NAME; ?>">
    <?php if (isset($videoData['thumbnailPath'])): ?>
    <meta name="twitter:image" content="<?php echo PEERTUBE_URL . $videoData['thumbnailPath']; ?>">
    <?php endif; ?>
    
    <?php if (!isset($videoNotFound) && !empty($video)): ?>
    <!-- Données structurées JSON-LD pour la vidéo -->
    <?php
    $videoJsonLd = generateVideoObjectJsonLd($videoData, $video);
    outputJsonLd($videoJsonLd);
    
    // Générer les fils d'Ariane pour la vidéo
    $breadcrumbs = [
        ['name' => 'Accueil', 'url' => getBaseUrl()],
        ['name' => $video['title'], 'url' => getBaseUrl() . '/video.php?id=' . $video['id']]
    ];
    $breadcrumbJsonLd = generateBreadcrumbJsonLd($breadcrumbs);
    outputJsonLd($breadcrumbJsonLd);
    ?>
    <?php endif; ?>
    
    <!-- Script pour éviter le flash en mode sombre -->
    <script nonce="<?php echo getCspNonce(); ?>">
        (function() {
            const savedTheme = localStorage.getItem('theme');
            const systemPrefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
            const shouldUseDark = savedTheme === 'dark' || (!savedTheme && systemPrefersDark);
            
            if (shouldUseDark) {
                document.documentElement.setAttribute('data-theme', 'dark');
            }
        })();
    </script>
</head>
<body>
    <?php include 'includes/sidebar.php'; ?>
    
    <!-- Contenu principal -->
    <main class="main-content" id="main-content" role="main">
        <?php include 'includes/header.php'; ?>
        
        <?php if (isset($videoNotFound)): ?>
        <!-- Message d'erreur si la vidéo n'existe pas -->
        <section class="error-message" role="alert" aria-labelledby="error-heading">
            <i class="fas fa-exclamation-triangle" aria-hidden="true"></i>
            <h1 id="error-heading">Vidéo non trouvée</h1>
            <p>La vidéo que vous recherchez n'existe pas ou a été supprimée.</p>
            <a href="index.php" class="btn-primary">Retour à l'accueil</a>
        </section>
        
        <?php else: ?>
        <!-- Section vidéo -->
        <article class="video-page" itemscope itemtype="https://schema.org/VideoObject">
            <section class="video-player-container">
                <div class="video-player">
                    <iframe src="<?php echo htmlspecialchars($video['url']); ?>?warningTitle='0'" 
                            frameborder="0" 
                            allowfullscreen="allowfullscreen" 
                            allow="autoplay; fullscreen" 
                            title="Lecteur vidéo: <?php echo htmlspecialchars($video['title']); ?>"
                            aria-describedby="video-description">
                    </iframe>
                </div>
            </section>
            
            <div class="video-content">
                <header class="video-primary-info">
                    <h1 id="video-description" class="video-title" itemprop="name"><?php echo htmlspecialchars($video['title']); ?></h1>
                    
                    <div class="video-info">
                        <div class="video-metadata">
                            <?php if (defined('SHOW_VIDEO_VIEWS') && SHOW_VIDEO_VIEWS): ?>
                            <span class="video-views"><i class="fas fa-eye" aria-hidden="true"></i> <?php echo formatViewCount($video['views']); ?> vues</span>
                            <?php endif; ?>
                            <span class="video-date"><i class="far fa-calendar-alt" aria-hidden="true"></i> <time datetime="<?php echo $video['date']; ?>"><?php echo formatDate($video['date']); ?></time></span>
                        </div>
                        
                        <div class="video-actions">
                            <button class="action-button" id="share-btn" aria-label="Partager cette vidéo">
                                <i class="fas fa-share" aria-hidden="true"></i>
                                <span>Partager</span>
                            </button>
                            <button class="action-button" id="download-btn" aria-label="Télécharger cette vidéo">
                                <i class="fas fa-download" aria-hidden="true"></i>
                                <span>Télécharger</span>
                            </button>
                        </div>
                    </div>
                    
                    <?php if (!empty($video['licence'])): ?>
                    <section class="video-licence">
                        <h2 class="licence-title">Licence</h2>
                        <?php 
                        $licenceLabels = [
                            1 => "CC BY (Attribution)", 
                            2 => "CC BY-SA (Attribution - Partage dans les Mêmes Conditions)", 
                            3 => "CC BY-ND (Attribution - Pas de Modification)", 
                            4 => "CC BY-NC (Attribution - Pas d'Utilisation Commerciale)", 
                            5 => "CC BY-NC-SA (Attribution - Pas d'Utilisation Commerciale - Partage dans les Mêmes Conditions)", 
                            6 => "CC BY-NC-ND (Attribution - Pas d'Utilisation Commerciale - Pas de Modification)", 
                            7 => "CC0 (Domaine Public)"
                        ];
                        
                        $licenceUrls = [
                            1 => "https://mirrors.creativecommons.org/presskit/buttons/88x31/png/by.png",
                            2 => "https://mirrors.creativecommons.org/presskit/buttons/88x31/png/by-sa.png",
                            3 => "https://mirrors.creativecommons.org/presskit/buttons/88x31/png/by-nd.png",
                            4 => "https://mirrors.creativecommons.org/presskit/buttons/88x31/png/by-nc.png",
                            5 => "https://mirrors.creativecommons.org/presskit/buttons/88x31/png/by-nc-sa.png",
                            6 => "https://mirrors.creativecommons.org/presskit/buttons/88x31/png/by-nc-nd.png",
                            7 => "https://mirrors.creativecommons.org/presskit/buttons/88x31/png/cc-zero.png"
                        ];
                        
                        $licenceInfoUrls = [
                            1 => "https://creativecommons.org/licenses/by/4.0/deed.fr",
                            2 => "https://creativecommons.org/licenses/by-sa/4.0/deed.fr",
                            3 => "https://creativecommons.org/licenses/by-nd/4.0/deed.fr",
                            4 => "https://creativecommons.org/licenses/by-nc/4.0/deed.fr",
                            5 => "https://creativecommons.org/licenses/by-nc-sa/4.0/deed.fr",
                            6 => "https://creativecommons.org/licenses/by-nc-nd/4.0/deed.fr",
                            7 => "https://creativecommons.org/publicdomain/zero/1.0/deed.fr"
                        ];
                        
                        $licenceId = $video['licence']['id'];
                        $licenceLabel = isset($licenceLabels[$licenceId]) ? $licenceLabels[$licenceId] : "Licence inconnue";
                        $licenceUrl = isset($licenceUrls[$licenceId]) ? $licenceUrls[$licenceId] : "";
                        $licenceInfoUrl = isset($licenceInfoUrls[$licenceId]) ? $licenceInfoUrls[$licenceId] : "";
                        ?>
                        <div class="licence-info">
                            <?php if (!empty($licenceUrl) && !empty($licenceInfoUrl)): ?>
                            <a href="<?php echo $licenceInfoUrl; ?>" target="_blank" rel="noopener noreferrer" class="licence-link" title="En savoir plus sur cette licence">
                                <img src="<?php echo $licenceUrl; ?>" alt="<?php echo $licenceLabel; ?>" class="licence-logo">
                                <span class="licence-label"><?php echo $licenceLabel; ?></span>
                            </a>
                            <?php else: ?>
                            <?php if (!empty($licenceUrl)): ?>
                            <img src="<?php echo $licenceUrl; ?>" alt="<?php echo $licenceLabel; ?>" class="licence-logo">
                            <?php endif; ?>
                            <span class="licence-label"><?php echo $licenceLabel; ?></span>
                            <?php endif; ?>
                        </div>
                    </section>
                    <?php endif; ?>
                </header>
                
                <section class="video-secondary-info">
                    <div class="channel-info">
                        <?php 
                        $channelUrl = PEERTUBE_URL . '/c/' . $video['channelHandle'];
                        ?>
                        <?php if (strpos($channelAvatar, 'default-avatar') !== false || empty($channelAvatar)): ?>
                            <a href="<?php echo $channelUrl; ?>" target="_blank" rel="noopener noreferrer" class="channel-avatar-link" aria-label="Voir la chaîne <?php echo htmlspecialchars($video['channel']); ?>">
                                <div class="channel-avatar-placeholder" role="img" aria-label="Avatar par défaut">
                                    <i class="fas fa-user-circle" aria-hidden="true"></i>
                                </div>
                            </a>
                        <?php else: ?>
                            <a href="<?php echo $channelUrl; ?>" target="_blank" rel="noopener noreferrer" class="channel-avatar-link" aria-label="Voir la chaîne <?php echo htmlspecialchars($video['channel']); ?>">
                                <div class="channel-avatar">
                                    <img src="<?php echo $channelAvatar; ?>" alt="Avatar de la chaîne <?php echo htmlspecialchars($video['channel']); ?>">
                                </div>
                            </a>
                        <?php endif; ?>
                        <div class="channel-details">
                            <a href="<?php echo $channelUrl; ?>" target="_blank" rel="noopener noreferrer" class="channel-name-link">
                                <h2 class="channel-name"><?php echo htmlspecialchars($video['channel']); ?></h2>
                            </a>
                        </div>
                    </div>
                    
                    <div class="video-description" itemprop="description">
                        <?php 
                        // Vérifier si on a une description tronquée et si la description complète est plus longue
                        $hasTruncatedDesc = !empty($video['truncatedDescription']) && 
                                          strlen($video['truncatedDescription']) < strlen($video['description']);
                        
                        if ($hasTruncatedDesc): 
                        ?>
                            <div class="truncated-description">
                                <?php echo markdown_to_html($video['truncatedDescription']); ?>
                                <button class="show-more-btn" aria-expanded="false" aria-controls="full-description">
                                    <span>Voir plus</span>
                                    <i class="fas fa-chevron-down" aria-hidden="true"></i>
                                </button>
                            </div>
                            <div id="full-description" class="full-description" style="display: none;" nonce="<?php echo getCspNonce(); ?>">
                                <?php echo markdown_to_html($video['description']); ?>
                                <button class="show-less-btn" aria-expanded="true" aria-controls="full-description">
                                    <span>Voir moins</span>
                                    <i class="fas fa-chevron-up" aria-hidden="true"></i>
                                </button>
                            </div>
                        <?php else: ?>
                            <?php echo markdown_to_html($video['description']); ?>
                        <?php endif; ?>
                    </div>
                    
                    <?php if (!empty($video['tags'])): ?>
                    <div class="video-tags">
                        <?php foreach ($video['tags'] as $tag): ?>
                            <a href="recherche.php?q=<?php echo urlencode('#' . $tag); ?>" class="tag">#<?php echo htmlspecialchars($tag); ?></a>
                        <?php endforeach; ?>
                    </div>
                    <?php endif; ?>
                </section>
                
                <!-- Commentaires -->
                <section class="comments-section" aria-labelledby="comments-heading">
                    <header class="section-header">
                        <div class="section-title-wrapper">
                            <h2 id="comments-heading" class="section-title">Commentaires</h2>
                        </div>
                        <a href="<?php echo PEERTUBE_URL; ?>/videos/watch/<?php echo $videoData['uuid']; ?>" target="_blank" class="view-on-peertube" aria-label="Voir cette vidéo sur <?php echo PEERTUBE_DISPLAY_NAME; ?>">
                            <i class="fas fa-external-link-alt" aria-hidden="true"></i> Voir sur <?php echo PEERTUBE_DISPLAY_NAME; ?>
                        </a>
                    </header>
                    <div class="comments-list">
                        <?php
                        $comments = getVideoComments($videoData['uuid']);
                        if (!empty($comments)):
                            foreach ($comments as $comment):
                        ?>
                        <article class="comment">
                            <div class="comment-avatar">
                                <?php if (isset($comment['account']['avatar']) && !empty($comment['account']['avatar']['path'])): ?>
                                    <img src="<?php echo PEERTUBE_URL . $comment['account']['avatar']['path']; ?>" alt="<?php echo htmlspecialchars($comment['account']['displayName']); ?>">
                                <?php else: ?>
                                    <div class="channel-avatar-placeholder mini" role="img" aria-label="Avatar par défaut">
                                        <i class="fas fa-user-circle" aria-hidden="true"></i>
                                    </div>
                                <?php endif; ?>
                            </div>
                            <div class="comment-content">
                                <header class="comment-header">
                                    <span class="comment-author"><?php echo htmlspecialchars($comment['account']['displayName']); ?></span>
                                    <time class="comment-date" datetime="<?php echo $comment['createdAt']; ?>"><?php echo formatDate($comment['createdAt']); ?></time>
                                </header>
                                <div class="comment-text"><?php echo nl2br(htmlspecialchars($comment['text'])); ?></div>
                                
                                <?php if (isset($comment['totalReplies']) && $comment['totalReplies'] > 0): ?>
                                <div class="comment-replies-toggle">
                                    <a href="<?php echo PEERTUBE_URL; ?>/videos/watch/<?php echo $videoData['uuid']; ?>" target="_blank" class="show-replies" aria-label="Voir les réponses sur PeerTube">
                                        <i class="fas fa-reply" aria-hidden="true"></i> Voir les <?php echo $comment['totalReplies']; ?> réponse<?php echo $comment['totalReplies'] > 1 ? 's' : ''; ?>
                                    </a>
                                </div>
                                <?php endif; ?>
                            </div>
                        </article>
                        <?php
                            endforeach;
                        ?>
                        <div class="comments-info">
                            <i class="fas fa-info-circle"></i>
                            <p>Les commentaires sont visibles mais l'ajout de commentaires et les threads de réponses sont désactivés sur cette page.</p>
                            <p>Pour ajouter des commentaires ou voir les réponses, veuillez vous rendre sur <a href="<?php echo PEERTUBE_URL; ?>/videos/watch/<?php echo $videoData['uuid']; ?>" target="_blank" class="show-replies"> <?php echo PEERTUBE_DISPLAY_NAME; ?></a>.</p>
                        </div>
                        <?php else: ?>
                        <div class="no-comments">
                            <i class="fas fa-comments"></i>
                            <p>Aucun commentaire pour cette vidéo.</p>
                            <p>Pour ajouter des commentaires, veuillez vous rendre sur <a href="<?php echo PEERTUBE_URL; ?>/videos/watch/<?php echo $videoData['uuid']; ?>" target="_blank" class="show-replies"> <?php echo PEERTUBE_DISPLAY_NAME; ?></a>.</p>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            
            <aside class="video-suggestions" aria-labelledby="suggestions-heading">
                <h2 id="suggestions-heading">Vidéos suggérées</h2>
                
                <?php if (!empty($suggestedVideos)): ?>
                    <div class="suggestion-list">
                        <?php foreach ($suggestedVideos as $suggestedVideo): ?>
                            <article class="suggested-video">
                                <a href="video.php?id=<?php echo $suggestedVideo['id']; ?>" class="suggested-video-link" aria-labelledby="suggestion-title-<?php echo $suggestedVideo['id']; ?>">
                                <div class="suggested-video-thumbnail">
                                    <img src="<?php echo $suggestedVideo['thumbnail']; ?>" alt="<?php echo $suggestedVideo['title']; ?>">
                                </div>
                                <div class="suggested-video-info">
                                    <span class="suggested-video-duration"><?php echo formatDuration($suggestedVideo['duration']); ?></span>
                                    <h3 id="suggestion-title-<?php echo $suggestedVideo['id']; ?>" class="suggested-video-title"><?php echo htmlspecialchars($suggestedVideo['title']); ?></h3>
                                    <div class="suggested-video-channel">
                                        <?php 
                                        // Vérifier si un avatar de chaîne est disponible pour la vidéo suggérée
                                        $suggestedAvatar = isset($suggestedVideo['channelAvatar']) ? $suggestedVideo['channelAvatar'] : '';
                                        
                                        if (empty($suggestedAvatar) || strpos($suggestedAvatar, 'default-avatar') !== false): 
                                        ?>
                                            <div class="channel-avatar-placeholder mini">
                                                <i class="fas fa-user-circle"></i>
                                            </div>
                                        <?php else: ?>
                                            <img src="<?php echo $suggestedAvatar; ?>" alt="<?php echo $suggestedVideo['channel']; ?>" class="channel-avatar mini">
                                        <?php endif; ?>
                                        <span class="channel-name"><?php echo $suggestedVideo['channel']; ?></span>
                                    </div>
                                    <div class="suggested-video-metadata">
                                        <?php if (defined('SHOW_VIDEO_VIEWS') && SHOW_VIDEO_VIEWS): ?>
                                        <span class="suggested-video-views"><?php echo formatViewCount($suggestedVideo['views']); ?> vues</span>
                                        <?php endif; ?>
                                        <span class="suggested-video-date"><?php echo formatDate($suggestedVideo['date']); ?></span>
                                    </div>
                                </div>
                                </a>
                            </article>
                        <?php endforeach; ?>
                    </div>
                <?php else: ?>
                    <p>Aucune vidéo suggérée disponible</p>
                <?php endif; ?>
            </aside>
        </article>
        <?php endif; ?>
    </main>
    <?php include 'includes/footer.php'; ?>
    <?php include 'includes/mobile-menu.php'; ?>
    
    <!-- Modal de téléchargement -->
    <div id="download-modal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>Télécharger la vidéo</h3>
                <button class="modal-close"><i class="fas fa-times"></i></button>
            </div>
            <div class="modal-body">
                <p>Choisissez la résolution souhaitée :</p>
                <div class="download-options">
                    <?php 
                    $downloadOptions = getVideoDownloadOptions($videoData['uuid']);
                    if (!empty($downloadOptions)):
                        foreach ($downloadOptions as $option):
                    ?>
                    <a href="<?php echo $option['url']; ?>" class="download-option" download>
                        <div class="download-resolution">
                            <i class="fas fa-film"></i>
                            <span><?php echo $option['resolution']; ?></span>
                        </div>
                        <div class="download-info">
                            <span class="download-size"><?php echo $option['size']; ?></span>
                            <i class="fas fa-download"></i>
                        </div>
                    </a>
                    <?php 
                        endforeach;
                    else:
                    ?>
                    <p class="no-download-options">Aucune option de téléchargement disponible pour cette vidéo.</p>
                    <?php endif; ?>
                </div>
            </div>
            <div class="modal-footer">
                <p class="download-info-text">Le téléchargement démarrera automatiquement après avoir cliqué sur une résolution.</p>
            </div>
        </div>
    </div>
    
    <!-- Modal de partage -->
    <div id="share-modal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>Partager la vidéo</h3>
                <button class="modal-close"><i class="fas fa-times"></i></button>
            </div>
            <div class="modal-body">
                <div class="share-link-container">
                    <p>Lien de la vidéo :</p>
                    <div class="share-link-box">
                        <input type="text" id="share-link" value="<?php echo htmlspecialchars((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"); ?>" readonly>
                        <button id="copy-link-btn" class="copy-btn" title="Copier le lien">
                            <i class="fas fa-copy"></i>
                        </button>
                    </div>
                </div>
                
                <p class="share-platforms-title">Partager sur :</p>
                <div class="share-platforms">
                    <a href="mailto:?subject=<?php echo urlencode(htmlspecialchars($video['title'])); ?>&body=<?php echo urlencode(htmlspecialchars($video['title']) . ' - ' . (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"); ?>" class="share-platform-btn" title="Partager par e-mail">
                        <i class="fas fa-envelope"></i>
                        <span>E-mail</span>
                    </a>
                    
                    <a href="https://www.facebook.com/sharer/sharer.php?u=<?php echo urlencode((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"); ?>" target="_blank" class="share-platform-btn" title="Partager sur Facebook">
                        <i class="fab fa-facebook-f"></i>
                        <span>Facebook</span>
                    </a>
                    
                    <a href="https://twitter.com/intent/tweet?text=<?php echo urlencode(htmlspecialchars($video['title'])); ?>&url=<?php echo urlencode((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"); ?>" target="_blank" class="share-platform-btn" title="Partager sur X/Twitter">
                        <i class="fab fa-x-twitter"></i>
                        <span>X</span>
                    </a>
                    
                    <a href="https://wa.me/?text=<?php echo urlencode(htmlspecialchars($video['title']) . ' - ' . (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"); ?>" target="_blank" class="share-platform-btn" title="Partager sur WhatsApp">
                        <i class="fab fa-whatsapp"></i>
                        <span>WhatsApp</span>
                    </a>
                    
                    <a href="https://www.linkedin.com/sharing/share-offsite/?url=<?php echo urlencode((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"); ?>" target="_blank" class="share-platform-btn" title="Partager sur LinkedIn">
                        <i class="fab fa-linkedin-in"></i>
                        <span>LinkedIn</span>
                    </a>
                    
                    <a href="https://t.me/share/url?url=<?php echo urlencode((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"); ?>&text=<?php echo urlencode($video['title']); ?>" target="_blank" class="share-platform-btn" title="Partager sur Telegram">
                        <i class="fab fa-telegram-plane"></i>
                        <span>Telegram</span>
                    </a>
                </div>
                
                <div class="share-embed">
                    <p>Intégrer la vidéo :</p>
                    <div class="share-link-box">
                        <input type="text" id="embed-code" value='<iframe width="560" height="315" src="<?php echo $video['url']; ?>" frameborder="0" allowfullscreen></iframe>' readonly>
                        <button id="copy-embed-btn" class="copy-btn" title="Copier le code d'intégration">
                            <i class="fas fa-copy"></i>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script src="js/main.js"></script>
    <script nonce="<?php echo getCspNonce(); ?>">
        // Script pour la modal de téléchargement
        document.addEventListener('DOMContentLoaded', function() {
            // Gestion de la description tronquée
            const showMoreBtn = document.querySelector('.show-more-btn');
            const showLessBtn = document.querySelector('.show-less-btn');
            
            if (showMoreBtn) {
                showMoreBtn.addEventListener('click', function() {
                    document.querySelector('.truncated-description').style.display = 'none';
                    document.querySelector('.full-description').style.display = 'block';
                });
            }
            
            if (showLessBtn) {
                showLessBtn.addEventListener('click', function() {
                    document.querySelector('.full-description').style.display = 'none';
                    document.querySelector('.truncated-description').style.display = 'block';
                });
            }
            
            const downloadModal = document.getElementById('download-modal');
            const downloadBtn = document.getElementById('download-btn');
            const downloadCloseBtn = downloadModal.querySelector('.modal-close');
            
            // Ouvrir la modal
            downloadBtn.addEventListener('click', function() {
                downloadModal.classList.add('show');
                document.body.style.overflow = 'hidden'; // Empêcher le défilement
            });
            
            // Fermer la modal
            downloadCloseBtn.addEventListener('click', function() {
                downloadModal.classList.remove('show');
                document.body.style.overflow = ''; // Réactiver le défilement
            });
            
            // Fermer la modal si on clique en dehors
            window.addEventListener('click', function(event) {
                if (event.target === downloadModal) {
                    downloadModal.classList.remove('show');
                    document.body.style.overflow = '';
                }
            });
            
            // Script pour la modal de partage
            const shareModal = document.getElementById('share-modal');
            const shareBtn = document.getElementById('share-btn');
            const shareCloseBtn = shareModal.querySelector('.modal-close');
            const copyLinkBtn = document.getElementById('copy-link-btn');
            const copyEmbedBtn = document.getElementById('copy-embed-btn');
            const shareLink = document.getElementById('share-link');
            const embedCode = document.getElementById('embed-code');
            
            // Ouvrir la modal de partage
            shareBtn.addEventListener('click', function() {
                shareModal.classList.add('show');
                document.body.style.overflow = 'hidden';
            });
            
            // Fermer la modal de partage
            shareCloseBtn.addEventListener('click', function() {
                shareModal.classList.remove('show');
                document.body.style.overflow = '';
            });
            
            // Fermer la modal si on clique en dehors
            window.addEventListener('click', function(event) {
                if (event.target === shareModal) {
                    shareModal.classList.remove('show');
                    document.body.style.overflow = '';
                }
            });
            
            // Copier le lien
            copyLinkBtn.addEventListener('click', function() {
                shareLink.select();
                document.execCommand('copy');
                showCopySuccess(copyLinkBtn);
            });
            
            // Copier le code d'intégration
            copyEmbedBtn.addEventListener('click', function() {
                embedCode.select();
                document.execCommand('copy');
                showCopySuccess(copyEmbedBtn);
            });
            
            // Afficher un message de succès après la copie
            function showCopySuccess(button) {
                const originalIcon = button.innerHTML;
                button.innerHTML = '<i class="fas fa-check"></i>';
                button.classList.add('copied');
                
                setTimeout(function() {
                    button.innerHTML = originalIcon;
                    button.classList.remove('copied');
                }, 2000);
            }
        });
    </script>

    <script src="js/pwa-update.js?v=<?php echo filemtime('js/pwa-update.js'); ?>"></script>
</body>
</html> 