<?php
 
 
 
?>

<?php if ($pagination->page === 1) { Ads::heroBlock(); } ?>

<?php if ($pagination->page === 1 && ($_hpWatchedEnabled ?? true)): ?>

<section class="home-section" id="beingWatched" style="display:none">
    <div class="section-title-row">
        <h2 class="section-title"><?php echo htmlspecialchars($_hpTitleWatched ?? __('simply_section_watch_again')); ?></h2>
        <a href="<?php echo url('/watch-history'); ?>" class="section-more" aria-label="<?php echo htmlspecialchars(__('simply_more_aria')); ?>"><?php echo __('simply_more'); ?></a>
    </div>
    <div class="video-grid" id="beingWatchedGrid"></div>
</section>
<?php endif; ?>


<?php
    $_videoSectionTitle = ($_hpSortTitles ?? [])[$sort] ?? __('simply_section_latest');
?>
<section class="home-section">
    <div class="section-title-row">
        <h2 class="section-title"><?php echo htmlspecialchars($_videoSectionTitle); ?></h2>
        <?php echo simplySortDropdown($sort); ?>
    </div>
    <div class="video-grid">
        <?php foreach ($videos as $video): ?>
            <?php echo simplyVideoCard($video); ?>
            <?php Ads::betweenGrid('homepage_between', 10); ?>
        <?php endforeach; ?>
    </div>
    <?php if (empty($videos)): ?>
        <div class="empty-state">
            <div class="empty-state__icon"><i class="fa-light fa-video-slash"></i></div>
            <p class="empty-state__text"><?php echo __('no_videos'); ?></p>
        </div>
    <?php endif; ?>
    <?php echo simplyPagination($pagination); ?>
    <?php Ads::zone('homepage_bottom'); ?>
</section>

<?php if ($pagination->page === 1): ?>
<script>
(function(){
    var KEY = 'tubepress_history';
    var section = document.getElementById('beingWatched');
    var grid = document.getElementById('beingWatchedGrid');
    if (!section || !grid) return;

    var history;
    try { history = JSON.parse(localStorage.getItem(KEY)) || []; } catch(e) { history = []; }
    if (!Array.isArray(history) || history.length === 0) return;
    var activeVType = <?php echo json_encode($_activeVideoType); ?>;
    if (activeVType) {
        history = history.filter(function(v) { return !v.video_type || v.video_type === activeVType; });
        if (history.length === 0) return;
    }

    var t = window._t || {};

    
    var showDuration = <?php echo json_encode($_cardShowDuration ?? true); ?>;
    var showTitle = <?php echo json_encode($_cardShowTitle ?? true); ?>;
    var metaLeft = <?php echo json_encode($_cardMetaLeft ?? 'views'); ?>;
    var metaRight = <?php echo json_encode($_cardMetaRight ?? 'time'); ?>;
    var titleClass = <?php echo json_encode((($_cardTitleLines ?? 1) >= 2) ? 'video-card__title video-card__title--clamp2' : 'video-card__title'); ?>;
    var baseHref = <?php echo json_encode(url('/video/')); ?>;
    var noThumb = 'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 180"><rect fill="%23334155" width="320" height="180"/><text x="160" y="95" text-anchor="middle" fill="%2394a3b8" font-size="14"><?php echo rawurlencode(__('simply_no_thumbnail')); ?></text></svg>';

    function esc(s) { return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;'); }

    function fmtNumber(n) {
        n = parseInt(n) || 0;
        if (n >= 1000000) { var v = (n/1000000).toFixed(1).replace(/\.0$/, ''); return v + 'M'; }
        if (n >= 1000) { var v = (n/1000).toFixed(1).replace(/\.0$/, ''); return v + 'K'; }
        return String(n);
    }

    function fmtTimeAgo(dateStr) {
        if (!dateStr) return '';
        var ts = new Date(dateStr.replace(' ', 'T') + 'Z').getTime();
        if (isNaN(ts)) return '';
        var diff = Math.floor((<?php echo time(); ?> * 1000 - ts) / 1000);
        if (diff < 0) diff = 0;
        if (diff < 60) return t.time_seconds_ago || '';
        if (diff < 3600) { var m = Math.floor(diff/60); return m === 1 ? (t.time_minute_ago || '') : (t.time_minutes_ago || '').replace(':count', m); }
        if (diff < 86400) { var h = Math.floor(diff/3600); return h === 1 ? (t.time_hour_ago || '') : (t.time_hours_ago || '').replace(':count', h); }
        if (diff < 2592000) { var d = Math.floor(diff/86400); return d === 1 ? (t.time_day_ago || '') : (t.time_days_ago || '').replace(':count', d); }
        if (diff < 31536000) { var mo = Math.floor(diff/2592000); return mo === 1 ? (t.time_month_ago || '') : (t.time_months_ago || '').replace(':count', mo); }
        var y = Math.floor(diff/31536000); return y === 1 ? (t.time_year_ago || '') : (t.time_years_ago || '').replace(':count', y);
    }

    function getMeta(v, which) {
        if (which === 'views') return (t.views_count || ':count views').replace(':count', fmtNumber(v.views));
        if (which === 'likes') return (t.likes_count || ':count likes').replace(':count', fmtNumber(v.likes));
        if (which === 'time') return fmtTimeAgo(v.published_at);
        return '';
    }

    
    var cols = parseInt(getComputedStyle(document.body).getPropertyValue('--grid-cols')) || 4;
    var max = cols * 2;
    var items = history.slice(0, max);

    var html = '';
    for (var i = 0; i < items.length; i++) {
        var v = items[i];
        if (!v || !v.slug || !v.title) continue;
        var thumb = v.thumbnail ? (v.thumbnail.indexOf('/') === 0 || v.thumbnail.indexOf('http') === 0 ? v.thumbnail : noThumb) : noThumb;
        var href = baseHref + encodeURIComponent(v.slug);
        var left = getMeta(v, metaLeft);
        var right = getMeta(v, metaRight);

        var preview = v.preview || '';
        html += '<article class="video-card">';
        html += '<a href="' + href + '" class="video-card__thumb"' + (preview ? ' data-preview="' + esc(preview) + '"' : '') + '>';
        html += '<img src="' + esc(thumb) + '" alt="' + esc(v.title) + '" loading="lazy" onerror="tpImgFallback(this)">';
        
        if (showDuration && v.duration) {
            html += '<span class="video-card__duration">' + esc(v.duration) + '</span>';
        }
        html += '</a>';
        if (showTitle || left || right) {
            html += '<div class="video-card__info">';
            if (showTitle) {
                html += '<h3 class="' + titleClass + '"><a href="' + href + '">' + esc(v.title) + '</a></h3>';
            }
            if (left || right) {
                html += '<div class="video-card__meta"><span>' + esc(left) + '</span><span>' + esc(right) + '</span></div>';
            }
            html += '</div>';
        }
        html += '</article>';
    }

    if (html) {
        grid.innerHTML = html;
        section.style.display = '';
    }

    
    var resizeTimer;
    window.addEventListener('resize', function() {
        clearTimeout(resizeTimer);
        resizeTimer = setTimeout(function() {
            var newCols = parseInt(getComputedStyle(document.body).getPropertyValue('--grid-cols')) || 4;
            var newMax = newCols * 2;
            var cards = grid.children;
            for (var j = 0; j < cards.length; j++) {
                cards[j].style.display = j < newMax ? '' : 'none';
            }
        }, 150);
    });
})();
</script>
<?php endif; ?>
