<?php
 
 
 
 
 
 
 
 
 

$videoViews    = Format::number((int)($video['views'] ?? 0));
$videoLikes    = Format::number((int)($video['likes'] ?? 0));
$videoDislikes = Format::number((int)($video['dislikes'] ?? 0));
$videoDuration = Format::duration((int)($video['duration'] ?? 0));
$videoDate     = Format::timeAgo($video['published_at'] ?? $video['created_at']);
$channels       = $video['channels'] ?? [];
?>

<div class="video-page">
    <div class="video-main">
        
        <?php Ads::zone('before_player'); ?>
        <?php echo Player::render($video); ?>

        
        <div class="video-info">
            <h1 class="video-info__title"><?php echo htmlspecialchars($video['title']); ?></h1>

            
            <div class="video-info__bar">
                <?php if ($_watchShowViews || $_watchShowDuration || $_watchShowDate || ($_watchShowChannels && !empty($channels))): ?>
                <div class="video-info__stats">
                    <?php if ($_watchShowViews): ?>
                    <span class="video-info__stat">
                        <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
                        <?php echo $videoViews; ?> <?php echo __('views'); ?>
                    </span>
                    <?php endif; ?>
                    <?php if ($_watchShowDuration): ?>
                    <span class="video-info__stat">
                        <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
                        <?php echo $videoDuration; ?>
                    </span>
                    <?php endif; ?>
                    <?php if ($_watchShowChannels && !empty($channels)): ?>
                    <a class="video-info__stat video-info__stat--channel" href="<?php echo url('/channel/' . htmlspecialchars($channels[0]['slug'])); ?>">
                        <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
                        <?php echo htmlspecialchars($channels[0]['name']); ?>
                    </a>
                    <?php endif; ?>
                    <?php if ($_watchShowDate): ?>
                    <span class="video-info__stat">
                        <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="4" width="18" height="18" rx="2" ry="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>
                        <?php echo $videoDate; ?>
                    </span>
                    <?php endif; ?>
                </div>
                <?php endif; ?>

                <?php if (($_watchShowLikes || $_watchShowFavorites) && ($_user || $_registrationEnabled)): ?>
                <div class="video-info__actions">
                    <?php if ($_watchShowLikes): ?>
                    <button class="vote-btn like<?php echo $userVote === 'like' ? ' active' : ''; ?>"
                            data-video-id="<?php echo (int)$video['id']; ?>" data-vote="like"
                            data-csrf="<?php echo htmlspecialchars(Router::csrfToken()); ?>">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <path d="M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.28a2 2 0 0 0 2-1.7l1.38-9a2 2 0 0 0-2-2.3H14z"></path>
                            <path d="M7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3"></path>
                        </svg>
                        <span class="vote-count"><?php echo $videoLikes; ?></span>
                    </button>
                    <button class="vote-btn dislike<?php echo $userVote === 'dislike' ? ' active' : ''; ?>"
                            data-video-id="<?php echo (int)$video['id']; ?>" data-vote="dislike"
                            data-csrf="<?php echo htmlspecialchars(Router::csrfToken()); ?>">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <path d="M10 15v4a3 3 0 0 0 3 3l4-9V2H5.72a2 2 0 0 0-2 1.7l-1.38 9a2 2 0 0 0 2 2.3H10z"></path>
                            <path d="M17 2h2.67A2.31 2.31 0 0 1 22 4v7a2.31 2.31 0 0 1-2.33 2H17"></path>
                        </svg>
                        <span class="vote-count"><?php echo $videoDislikes; ?></span>
                    </button>
                    <?php endif; ?>
                    <?php if ($_watchShowFavorites && ($_user || $_registrationEnabled)): ?>
                    <button class="btn-icon<?php echo $isFavorited ? ' active' : ''; ?>"
                            data-video-id="<?php echo (int)$video['id']; ?>" id="favoriteBtn" title="<?php echo __('add_to_favorites'); ?>"
                            data-csrf="<?php echo htmlspecialchars(Router::csrfToken()); ?>">
                        <svg width="18" height="18" viewBox="0 0 24 24" fill="<?php echo $isFavorited ? 'currentColor' : 'none'; ?>" stroke="currentColor" stroke-width="2">
                            <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"></path>
                        </svg>
                    </button>
                    <?php endif; ?>
                    <button class="btn-icon" id="reportBtn" title="<?php echo __('report_video'); ?>"
                            data-video-id="<?php echo (int)$video['id']; ?>"
                            data-csrf="<?php echo htmlspecialchars(Router::csrfToken()); ?>">
                        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <path d="M4 15s1-1 4-1 5 2 8 2 4-1 4-1V3s-1 1-4 1-5-2-8-2-4 1-4 1z"></path>
                            <line x1="4" y1="22" x2="4" y2="15"></line>
                        </svg>
                    </button>
                    <button class="btn-icon" id="embedBtn" title="<?php echo __('embed_code'); ?>">
                        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <polyline points="16 18 22 12 16 6"></polyline>
                            <polyline points="8 6 2 12 8 18"></polyline>
                        </svg>
                    </button>
                </div>
                <?php endif; ?>
            </div>

            
            <?php
            $embedUrl = SEO::siteUrl() . '/embed/' . htmlspecialchars($video['slug']);
            $embedCode = '<iframe src="' . $embedUrl . '" width="640" height="360" frameborder="0" allowfullscreen></iframe>';
            ?>
            <div class="video-embed-box" id="embedBox" style="display:none">
                <div class="video-embed-box__inner">
                    <input type="text" readonly value="<?php echo htmlspecialchars($embedCode); ?>" id="embedInput" class="video-embed-box__input" onclick="this.select()">
                    <button type="button" class="video-embed-box__copy" id="embedCopy" title="<?php echo htmlspecialchars(__('simply_copy'), ENT_QUOTES); ?>">
                        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
                    </button>
                </div>
            </div>
            <script>
            (function(){
                var btn=document.getElementById('embedBtn');
                var box=document.getElementById('embedBox');
                var copyBtn=document.getElementById('embedCopy');
                var input=document.getElementById('embedInput');
                if(!btn||!box)return;
                btn.addEventListener('click',function(){
                    box.style.display=box.style.display==='none'?'':'none';
                });
                if(copyBtn&&input){
                    copyBtn.addEventListener('click',function(){
                        input.select();
                        navigator.clipboard.writeText(input.value).then(function(){
                            copyBtn.innerHTML='<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="20 6 9 17 4 12"/></svg>';
                            setTimeout(function(){
                                copyBtn.innerHTML='<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>';
                            },2000);
                        });
                    });
                }
            })();
            </script>

        </div>

        <?php Ads::zone('after_player'); ?>

        
        <?php if (!empty($video['description'])): ?>
        <div class="video-description">
            <span class="video-description__label"><?php echo __('description'); ?></span>
            <p class="video-description__text"><?php echo nl2br(htmlspecialchars($video['description'])); ?></p>
        </div>
        <?php endif; ?>

        
        <?php if ($_watchShowPornstars && !empty($performers)): ?>
        <div class="video-detail-section">
            <div class="video-detail-block">
                <span class="video-detail-label">
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
                    <?php $_isHentai = (($video['video_type'] ?? '') === 'hentai'); $_pl = count($performers) > 1; echo $_isHentai ? __($_pl ? 'artists_label_plural' : 'artists_label') : __($_pl ? 'pornstars_label_plural' : 'pornstars_label'); ?>
                </span>
                <div class="video-performers detail-overflow" data-init="3" data-step="2" data-init-mobile="3" data-step-mobile="2">
                    <?php foreach ($performers as $performer): ?>
                        <a href="<?php echo url('/pornstar/' . htmlspecialchars($performer['slug'])); ?>" class="performer-chip">
                            <?php
                            $chipPhotoUrl = '';
                            if (!empty($performer['photo'])) {
                                $chipPhotoUrl = str_starts_with($performer['photo'], 'http') ? $performer['photo'] : '/uploads/performers/' . $performer['photo'];
                            } elseif (!empty($performer['best_video_folder'])) {
                                $chipPhotoUrl = VideoAsset::thumbUrlFromFolder($performer['best_video_folder'], true, $performer['best_video_storage_id'] ?? null);
                            } elseif (!empty($performer['best_video_thumbnail'])) {
                                $chipPhotoUrl = $performer['best_video_thumbnail'];
                            }
                            ?>
                            <?php if ($chipPhotoUrl !== ''): ?>
                                <img src="<?php echo htmlspecialchars($chipPhotoUrl); ?>" alt="<?php echo htmlspecialchars($performer['name']); ?>" loading="lazy">
                            <?php else: ?>
                                <span class="performer-chip__initial"><?php echo strtoupper(mb_substr($performer['name'], 0, 1)); ?></span>
                            <?php endif; ?>
                            <?php echo htmlspecialchars($performer['name']); ?>
                        </a>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
        <?php endif; ?>

        
        <?php if ($_watchShowCategories && !empty($categories)): ?>
        <div class="video-detail-section">
            <div class="video-detail-block">
                <span class="video-detail-label">
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/></svg>
                    <?php echo count($categories) > 1 ? __('categories_label_plural') : __('categories_label'); ?>
                </span>
                <div class="video-categories detail-overflow" data-init="10" data-step="5" data-init-mobile="5" data-step-mobile="3">
                    <?php foreach ($categories as $cat): ?>
                        <a href="<?php echo url('/category/' . htmlspecialchars($cat['slug'])); ?>" class="tag-link"><?php echo htmlspecialchars($cat['name']); ?></a>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
        <?php endif; ?>

        
        <?php if ($_watchShowTags && !empty($tags)): ?>
        <div class="video-detail-section">
            <div class="video-detail-block">
                <span class="video-detail-label">
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M20.59 13.41l-7.17 7.17a2 2 0 0 1-2.83 0L2 12V2h10l8.59 8.59a2 2 0 0 1 0 2.82z"/><line x1="7" y1="7" x2="7.01" y2="7"/></svg>
                    <?php echo __('tags_label'); ?>
                </span>
                <div class="video-tags detail-overflow" data-init="10" data-step="5" data-init-mobile="5" data-step-mobile="3">
                    <?php foreach ($tags as $tag): ?>
                        <a href="<?php echo url('/tag/' . htmlspecialchars($tag['slug'])); ?>" class="tag-link"><?php echo htmlspecialchars($tag['name']); ?></a>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
        <?php endif; ?>

        
        <script>
        (function(){
            var MOBILE_BP = 576;
            document.querySelectorAll('.detail-overflow').forEach(function(wrap) {
                var items = Array.from(wrap.children).filter(function(el) { return el.tagName !== 'BUTTON'; });
                var total = items.length;
                var isMobile = function() { return window.innerWidth < MOBILE_BP; };
                var init = function() { return isMobile() ? (parseInt(wrap.dataset.initMobile) || 5) : (parseInt(wrap.dataset.init) || 10); };
                var step = function() { return isMobile() ? (parseInt(wrap.dataset.stepMobile) || 3) : (parseInt(wrap.dataset.step) || 5); };
                var shown = init();
                if (total <= shown) return;

                var btn = document.createElement('button');
                btn.type = 'button';
                btn.className = 'detail-overflow__more';
                wrap.appendChild(btn);

                function apply() {
                    var hidden = 0;
                    for (var i = 0; i < total; i++) {
                        if (i < shown) { items[i].style.display = ''; }
                        else { items[i].style.display = 'none'; hidden++; }
                    }
                    if (hidden > 0) {
                        btn.textContent = '+' + hidden;
                        btn.style.display = '';
                    } else {
                        btn.style.display = 'none';
                    }
                }

                btn.addEventListener('click', function() {
                    shown += step();
                    if (shown > total) shown = total;
                    apply();
                });

                apply();

                var resizeTimer;
                window.addEventListener('resize', function() {
                    clearTimeout(resizeTimer);
                    resizeTimer = setTimeout(function() {
                        var newInit = init();
                        if (shown < newInit) shown = newInit;
                        apply();
                    }, 150);
                });
            });
        })();
        </script>

        <?php Ads::zone('before_comments'); ?>

        
        <?php if ($_commentsEnabled): ?>
        <div class="comments">
            <div class="comments__header">
                <h3>
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>
                    <?php $cc = count($comments); echo $cc !== 1 ? __('comments_count_plural', [':count' => $cc]) : __('comments_count', [':count' => $cc]); ?>
                </h3>
            </div>

            <?php if ($_user): ?>
            <form class="comment-form" action="<?php echo url('/video/' . (int)$video['id'] . '/comment'); ?>" method="POST" id="commentForm">
                <?php echo Router::csrfField(); ?>
                <?php echo SpamGuard::formFields(); ?>
                <div class="comment-form__avatar">
                    <?php echo strtoupper(mb_substr($_user['username'] ?? 'U', 0, 1)); ?>
                </div>
                <div class="comment-form__input">
                    <textarea name="body" placeholder="<?php echo __('add_a_comment'); ?>" required rows="1"
                              onfocus="this.closest('.comment-form').classList.add('focused')"
                              oninput="this.style.height='auto';this.style.height=this.scrollHeight+'px'"></textarea>
                    <?php echo Captcha::renderWidget('comment'); ?>
                    <div class="comment-form__actions">
                        <button type="button" class="comment-form__cancel" onclick="var f=this.closest('.comment-form');f.classList.remove('focused');f.querySelector('textarea').value='';f.querySelector('textarea').style.height='auto'"><?php echo __('cancel'); ?></button>
                        <button type="submit" class="comment-form__submit"><?php echo __('comment_btn'); ?></button>
                    </div>
                </div>
            </form>
            <?php elseif (!$_registrationEnabled): ?>
            <form class="comment-form" action="<?php echo url('/video/' . (int)$video['id'] . '/comment'); ?>" method="POST" id="commentForm">
                <?php echo Router::csrfField(); ?>
                <?php echo SpamGuard::formFields(); ?>
                <div class="comment-form__avatar">
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
                </div>
                <div class="comment-form__input">
                    <input type="text" name="guest_name" placeholder="<?php echo __('your_name'); ?>" style="margin-bottom:8px;width:100%;max-width:250px;padding:6px 10px;border:1px solid var(--border, #333);border-radius:6px;background:var(--bg-surface, #1a1a2e);color:var(--text, #e0e0e0);font-size:13px;outline:none;">
                    <textarea name="body" placeholder="<?php echo __('add_a_comment'); ?>" required rows="1"
                              onfocus="this.closest('.comment-form').classList.add('focused')"
                              oninput="this.style.height='auto';this.style.height=this.scrollHeight+'px'"></textarea>
                    <?php echo Captcha::renderWidget('comment'); ?>
                    <div class="comment-form__actions">
                        <button type="button" class="comment-form__cancel" onclick="var f=this.closest('.comment-form');f.classList.remove('focused');f.querySelector('textarea').value='';f.querySelector('textarea').style.height='auto'"><?php echo __('cancel'); ?></button>
                        <button type="submit" class="comment-form__submit"><?php echo __('comment_btn'); ?></button>
                    </div>
                </div>
            </form>
            <?php elseif ($_registrationEnabled): ?>
            <div class="comments__login">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
                <a href="#" onclick="authModal('login');return false;"><?php echo __('log_in'); ?></a> <?php echo __('log_in_to_comment'); ?>
            </div>
            <?php endif; ?>

            <?php if (!empty($comments)): ?>
            <?php $commentCount = count($comments); ?>
            <div class="comments__list" id="commentsList">
                <?php foreach ($comments as $i => $comment): ?>
                    <div class="comment<?php echo $i >= 3 ? ' comment--hidden' : ''; ?>">
                        <div class="comment__avatar">
                            <?php echo strtoupper(mb_substr(htmlspecialchars($comment['username'] ?? 'A'), 0, 1)); ?>
                        </div>
                        <div class="comment__body">
                            <div class="comment__header">
                                <span class="comment__author"><?php echo htmlspecialchars($comment['username'] ?? __('anonymous')); ?></span>
                                <span class="comment__date"><?php echo Format::timeAgo($comment['created_at']); ?></span>
                            </div>
                            <p class="comment__text comment__text--clamped"><?php echo nl2br(htmlspecialchars($comment['body'])); ?></p>

                            <?php if (!empty($comment['replies'])): ?>
                            <div class="comment__replies">
                                <?php foreach ($comment['replies'] as $reply): ?>
                                    <div class="comment comment--reply">
                                        <div class="comment__avatar comment__avatar--sm">
                                            <?php echo strtoupper(mb_substr(htmlspecialchars($reply['username'] ?? 'A'), 0, 1)); ?>
                                        </div>
                                        <div class="comment__body">
                                            <div class="comment__header">
                                                <span class="comment__author"><?php echo htmlspecialchars($reply['username'] ?? __('anonymous')); ?></span>
                                                <span class="comment__date"><?php echo Format::timeAgo($reply['created_at']); ?></span>
                                            </div>
                                            <p class="comment__text comment__text--clamped"><?php echo nl2br(htmlspecialchars($reply['body'])); ?></p>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
            <?php if ($commentCount > 3): ?>
            <?php $moreCount = $commentCount - 3; ?>
            <button type="button" class="comments__view-more" id="commentsViewMore">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="6 9 12 15 18 9"/></svg>
                <?php echo $moreCount !== 1 ? __('view_more_comments_plural', [':count' => $moreCount]) : __('view_more_comments', [':count' => $moreCount]); ?>
            </button>
            <?php endif; ?>
            <script>
            (function(){
                var list=document.getElementById('commentsList');
                var btn=document.getElementById('commentsViewMore');
                if(btn){btn.addEventListener('click',function(){
                    list.querySelectorAll('.comment--hidden').forEach(function(el){el.classList.remove('comment--hidden');});
                    btn.style.display='none';
                });}
                if(!list)return;
                list.querySelectorAll('.comment__text--clamped').forEach(function(el){
                    if(el.scrollHeight>el.offsetHeight+2){
                        var t=document.createElement('button');
                        t.className='comment__text-more';
                        t.textContent=window._t&&window._t.show_more||'Show more';
                        t.addEventListener('click',function(){
                            if(el.classList.contains('comment__text--expanded')){
                                el.classList.remove('comment__text--expanded');
                                t.textContent=window._t&&window._t.show_more||'Show more';
                            }else{
                                el.classList.add('comment__text--expanded');
                                t.textContent=window._t&&window._t.show_less||'Show less';
                            }
                        });
                        el.parentNode.insertBefore(t,el.nextSibling);
                    }
                });
            })();
            </script>
            <?php endif; ?>
        </div>
        <?php endif; ?>
    </div>

    
    <aside class="video-sidebar">
        <?php Ads::zone('sidebar'); ?>
        <?php $sidebarVideos = !empty($similar) ? $similar : array_slice($recommended ?? [], 0, 8); ?>
        <?php if (!empty($sidebarVideos)): ?>
        <h3><?php echo !empty($similar) ? __('related_videos') : __('recommended_videos'); ?></h3>
        <div class="related-grid">
            <?php foreach ($sidebarVideos as $relatedVideo): ?>
                <?php echo hentaiVideoCard($relatedVideo); ?>
                <?php Ads::betweenGrid('between_related', 6); ?>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>
    </aside>
</div>


<?php if (!empty($recommended)): ?>
<div class="recommended-section" id="recommendedSection">
    <h2 class="section-title"><?php echo __('recommended_videos'); ?></h2>
    <div class="video-grid" id="recommendedGrid" data-video-id="<?php echo (int) $video['id']; ?>" data-init-ids="<?php echo implode(',', array_map(static fn($rv) => (int) ($rv['id'] ?? 0), $recommended)); ?>">
        <?php foreach ($recommended as $recVideo): ?>
            <?php echo hentaiVideoCard($recVideo); ?>
        <?php endforeach; ?>
    </div>
    <div class="recommended-more" id="recommendedMore">
        <button type="button" class="recommended-more__btn" id="loadMoreBtn">
            <?php echo __('load_more'); ?>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 9 12 15 18 9"/></svg>
        </button>
    </div>
</div>
<script>
(function(){
    var grid = document.getElementById('recommendedGrid');
    var btn = document.getElementById('loadMoreBtn');
    var wrap = document.getElementById('recommendedMore');
    if (!grid || !btn) return;
    var vid = grid.getAttribute('data-video-id');
    var exclude = (grid.getAttribute('data-init-ids') || '').split(',').filter(Boolean);
    var loading = false, exhausted = false, targetRows = 3;

    
    function cols(){
        var g = getComputedStyle(grid).gridTemplateColumns;
        if (g && g !== 'none'){
            var n = g.split(' ').filter(Boolean).length;
            if (n > 0) return n;
        }
        return parseInt(getComputedStyle(document.body).getPropertyValue('--grid-cols')) || 4;
    }

    
    
    function render(){
        var c = cols();
        var loaded = grid.children.length;
        var want = targetRows * c;
        var vis;
        if (loaded >= want){
            vis = want;
        } else if (exhausted){
            vis = loaded;
        } else {
            vis = Math.floor(loaded / c) * c || loaded;
            if (!loading) fetchMore(render);
        }
        var cards = grid.children;
        for (var i = 0; i < cards.length; i++){ cards[i].style.display = i < vis ? '' : 'none'; }
        wrap.style.display = (exhausted && vis >= loaded) ? 'none' : '';
    }

    function fetchMore(done){
        if (loading || exhausted){ if (done) done(); return; }
        loading = true; btn.disabled = true; btn.classList.add('is-loading');
        var ex = encodeURIComponent(exclude.slice(-400).join(','));
        var path = location.pathname.replace(/[?#].*$/, '');
        var i = path.lastIndexOf('/video/');
        var base = (i >= 0 ? path.slice(0, i) : '') + '/video/' + vid + '/recommended';
        fetch(base + '?exclude=' + ex, {headers: {'X-Requested-With': 'XMLHttpRequest'}})
            .then(function(r){ return r.ok ? r.json() : null; })
            .then(function(d){
                loading = false; btn.disabled = false; btn.classList.remove('is-loading');
                if (!d || !d.html || !d.ids || !d.ids.length){ exhausted = true; if (done) done(); return; }
                grid.insertAdjacentHTML('beforeend', d.html);
                exclude = exclude.concat(d.ids.map(String));
                if (!d.hasMore){ exhausted = true; }
                if (done) done();
            })
            .catch(function(){ loading = false; btn.disabled = false; btn.classList.remove('is-loading'); if (done) done(); });
    }

    render();
    btn.addEventListener('click', function(){ targetRows += 3; render(); });
    var rt;
    window.addEventListener('resize', function(){ clearTimeout(rt); rt = setTimeout(render, 150); });
})();
</script>
<?php endif; ?>


<div id="reportModal" style="display:none;position:fixed;inset:0;z-index:9999;background:rgba(0,0,0,.7);align-items:center;justify-content:center">
    <div style="background:var(--bg-surface, #1a1a2e);border:1px solid var(--border, #333);border-radius:12px;padding:24px;max-width:420px;width:calc(100% - 32px);position:relative">
        <button type="button" onclick="closeReportModal()" style="position:absolute;top:12px;right:12px;background:none;border:none;color:var(--text-muted, #888);cursor:pointer;padding:4px">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
        </button>
        <h3 style="margin:0 0 4px;font-size:16px;color:var(--text, #e0e0e0)">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="vertical-align:text-bottom;margin-right:6px"><path d="M4 15s1-1 4-1 5 2 8 2 4-1 4-1V3s-1 1-4 1-5-2-8-2-4 1-4 1z"/><line x1="4" y1="22" x2="4" y2="15"/></svg>
            <?php echo __('report_video'); ?>
        </h3>
        <p style="margin:0 0 16px;font-size:13px;color:var(--text-muted, #888)"><?php echo __('report_video_desc'); ?></p>
        <select id="reportReason" style="width:100%;padding:10px 12px;border:1px solid var(--border);border-radius:8px;background-color:var(--bg);color:var(--text);font-size:13px;outline:none;margin-bottom:12px;box-sizing:border-box">
            <option value="" disabled selected><?php echo __('report_select_reason'); ?></option>
            <?php
            $reportReasons = [
                'illegal'   => __('report_reason_illegal'),
                'copyright' => __('report_reason_copyright'),
                'spam'      => __('report_reason_spam'),
                'broken'    => __('report_reason_broken'),
                'underage'  => __('report_reason_underage'),
                'other'     => __('report_reason_other'),
            ];
            foreach ($reportReasons as $key => $label): ?>
            <option value="<?php echo $key; ?>"><?php echo $label; ?></option>
            <?php endforeach; ?>
        </select>
        <input type="email" id="reportEmail" placeholder="<?php echo __('report_email_placeholder'); ?>" style="width:100%;padding:8px 12px;border:1px solid var(--border, #333);border-radius:8px;background:var(--bg, #0f0f23);color:var(--text, #e0e0e0);font-size:13px;outline:none;margin-bottom:12px;box-sizing:border-box">
        <textarea id="reportDetails" rows="4" placeholder="<?php echo __('report_details_placeholder'); ?>" style="width:100%;padding:8px 12px;border:1px solid var(--border, #333);border-radius:8px;background:var(--bg, #0f0f23);color:var(--text, #e0e0e0);font-size:13px;resize:vertical;outline:none;margin-bottom:16px;box-sizing:border-box"></textarea>
        <?php echo SpamGuard::formFields(); ?>
        <div style="display:flex;justify-content:flex-end;gap:8px">
            <button type="button" onclick="closeReportModal()" style="padding:8px 16px;border:1px solid var(--border, #333);border-radius:8px;background:transparent;color:var(--text-muted, #888);font-size:13px;cursor:pointer"><?php echo __('cancel'); ?></button>
            <button type="button" id="reportSubmitBtn" onclick="submitReport()" style="padding:8px 20px;border:none;border-radius:8px;background:var(--primary, #6366f1);color:#fff;font-size:13px;font-weight:600;cursor:pointer;opacity:.5;pointer-events:none" disabled><?php echo __('report_submit'); ?></button>
        </div>
        <div id="reportMessage" style="display:none;margin-top:12px;padding:10px 14px;border-radius:8px;font-size:13px"></div>
    </div>
</div>
<script>
(function(){
    var modal=document.getElementById('reportModal');
    var btn=document.getElementById('reportBtn');
    var submitBtn=document.getElementById('reportSubmitBtn');
    var msgEl=document.getElementById('reportMessage');
    var reasonSelect=document.getElementById('reportReason');
    if(!btn||!modal)return;

    btn.addEventListener('click',function(){
        modal.style.display='flex';
        msgEl.style.display='none';
        submitBtn.disabled=true;
        submitBtn.style.opacity='.5';
        submitBtn.style.pointerEvents='none';
        reasonSelect.selectedIndex=0;
        document.getElementById('reportEmail').value='';
        document.getElementById('reportDetails').value='';
    });

    modal.addEventListener('click',function(e){if(e.target===modal)closeReportModal();});

    reasonSelect.addEventListener('change',function(){
        if(this.value){
            submitBtn.disabled=false;
            submitBtn.style.opacity='1';
            submitBtn.style.pointerEvents='auto';
        }
    });

    window.closeReportModal=function(){modal.style.display='none';};

    window.submitReport=function(){
        var reason=reasonSelect.value;
        if(!reason)return;
        submitBtn.disabled=true;
        submitBtn.textContent='...';

        var videoId=btn.getAttribute('data-video-id');
        var csrf=btn.getAttribute('data-csrf');
        var details=document.getElementById('reportDetails').value.trim();
        var email=document.getElementById('reportEmail').value.trim();

        var payload={reason:reason,details:details,reporter_email:email,_csrf_token:csrf};
        var sgTs=modal.querySelector('input[name="_sg_ts"]');
        var sgH=modal.querySelector('input[name="_sg_h"]');
        var hp=modal.querySelector('input[name="website"]');
        if(sgTs)payload._sg_ts=sgTs.value;
        if(sgH)payload._sg_h=sgH.value;
        if(hp)payload.website=hp.value;

        fetch('/video/'+videoId+'/report',{
            method:'POST',
            headers:{'Content-Type':'application/json','X-CSRF-Token':csrf},
            body:JSON.stringify(payload)
        })
        .then(function(r){return r.json().then(function(d){return{ok:r.ok,data:d};});})
        .then(function(res){
            msgEl.style.display='block';
            if(res.ok){
                msgEl.style.background='rgba(34,197,94,.15)';
                msgEl.style.color='#22c55e';
                msgEl.textContent=res.data.message||(window._t&&window._t.report_submitted||'Report submitted.');
                setTimeout(closeReportModal,2000);
            }else{
                msgEl.style.background='rgba(239,68,68,.15)';
                msgEl.style.color='#ef4444';
                msgEl.textContent=res.data.message||(window._t&&window._t.an_error_occurred||'An error occurred.');
                submitBtn.disabled=false;
                submitBtn.textContent='<?php echo __('report_submit'); ?>';
                submitBtn.style.opacity='1';
                submitBtn.style.pointerEvents='auto';
            }
        })
        .catch(function(){
            msgEl.style.display='block';
            msgEl.style.background='rgba(239,68,68,.15)';
            msgEl.style.color='#ef4444';
            msgEl.textContent=window._t&&window._t.network_error||'Network error. Please try again.';
            submitBtn.disabled=false;
            submitBtn.textContent='<?php echo __('report_submit'); ?>';
            submitBtn.style.opacity='1';
            submitBtn.style.pointerEvents='auto';
        });
    };
})();
</script>


<script>
(function(){
    var KEY = 'tubepress_history';
    var MAX = 100;
    var video = {
        id: <?php echo (int)$video['id']; ?>,
        slug: <?php echo json_encode($video['slug']); ?>,
        title: <?php echo json_encode($video['title']); ?>,
        thumbnail: <?php echo json_encode(VideoAsset::thumbUrl($video, true)); ?>,
        preview: <?php echo json_encode(VideoAsset::previewUrl($video)); ?>,
        duration: <?php echo json_encode($videoDuration); ?>,
        views: <?php echo (int)($video['views'] ?? 0); ?>,
        likes: <?php echo (int)($video['likes'] ?? 0); ?>,
        published_at: <?php echo json_encode($video['published_at'] ?? $video['created_at']); ?>,
        video_type: <?php echo json_encode($video['video_type'] ?? ''); ?>
    };
    var history;
    try { history = JSON.parse(localStorage.getItem(KEY)) || []; } catch(e) { history = []; }
    if (!Array.isArray(history)) history = [];
    history = history.filter(function(v){ return v && v.id !== video.id; });
    history.unshift(video);
    if (history.length > MAX) history = history.slice(0, MAX);
    try { localStorage.setItem(KEY, JSON.stringify(history)); } catch(e) {}
})();
</script>