<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>
<?php
function yt_time_ago($date_str) {
    if (!$date_str) return '';
    $diff = time() - strtotime($date_str);
    if ($diff < 60)       return 'Baru saja';
    if ($diff < 3600)     return floor($diff/60) . ' menit lalu';
    if ($diff < 86400)    return floor($diff/3600) . ' jam lalu';
    if ($diff < 2592000)  return floor($diff/86400) . ' hari lalu';
    if ($diff < 31536000) return floor($diff/2592000) . ' bulan lalu';
    return floor($diff/31536000) . ' tahun lalu';
}
?>
<style>
.yt-wrap { font-family: 'Plus Jakarta Sans', system-ui, sans-serif; }

/* ── SEARCH BAR ─────────────────────────────────────────── */
.yt-search-bar {
    background: linear-gradient(135deg, #0f766e, #14b8a6, #2dd4bf);
    border-radius: 16px;
    padding: 20px 24px;
    margin-bottom: 20px;
    box-shadow: 0 8px 28px rgba(15,118,110,.25);
}
.yt-search-bar h5 { color:#fff; font-weight:800; margin-bottom:12px; font-size:1rem; }
.yt-search-group { display:flex; gap:10px; }
.yt-search-input {
    flex:1; border-radius:12px; border:none; padding:10px 16px;
    font-size:.9rem; outline:none; box-shadow:0 2px 8px rgba(0,0,0,.1);
}
.yt-search-input:focus { box-shadow:0 0 0 3px rgba(20,184,166,.3); }
.yt-search-btn {
    background:#fff; color:#0f766e; border:none; border-radius:12px;
    font-weight:800; padding:10px 20px; cursor:pointer; font-size:.85rem;
    transition:.15s; white-space:nowrap;
}
.yt-search-btn:hover { background:#f0fdfa; }

.yt-info { font-size:.78rem; color:#64748b; margin-bottom:14px; padding:0 2px; }

/* ── PLAYER (DESKTOP) ───────────────────────────────────── */
#ytPlayerWrap {
    display: none;
    background: #fff;
    border-radius: 16px;
    border: 1px solid #e2e8f0;
    box-shadow: 0 4px 20px rgba(0,0,0,.08);
    overflow: hidden;
    margin-bottom: 20px;
}
.yt-player-inner {
    display: grid;
    grid-template-columns: 1fr 320px;
    min-height: 260px;
}
.yt-embed-wrap {
    position: relative;
    aspect-ratio: 16/9;
    background: #000;
}
/* Desktop overlay top: block pointer-events agar logo tidak bisa diklik */
.yt-embed-wrap .yt-overlay-top {
    position: absolute; top:0; left:0; right:0; height:60px;
    z-index:9; pointer-events:all; background:transparent;
}
.yt-embed-wrap .yt-overlay-logo {
    position: absolute; bottom:0; right:46px;
    width:80px; height:35px; z-index:11; pointer-events:all;
    background: rgba(0,0,0,.90); display:flex; align-items:center;
    justify-content:center; border-radius:6px 6px 0 0;
    color:#2dd4bf; font-size:.7rem; font-weight:800;
    letter-spacing:.5px; cursor:default; user-select:none;
}
.yt-embed-wrap iframe {
    position:absolute; inset:0; width:100%; height:100%; border:none;
}
.yt-player-meta {
    padding: 16px 18px; overflow-y: auto;
    border-left: 1px solid #f1f5f9;
    display: flex; flex-direction: column; gap: 8px;
}
.yt-player-close {
    align-self: flex-end; background: #f1f5f9; border: none;
    border-radius: 8px; padding: 4px 10px; font-size: .72rem;
    font-weight: 700; color: #64748b; cursor: pointer; transition: .15s;
}
.yt-player-close:hover { background:#e2e8f0; color:#1e293b; }
.yt-player-title { font-weight:800; font-size:.9rem; color:#1e293b; line-height:1.4; }
.yt-player-stats {
    display:flex; flex-wrap:wrap; gap:8px; font-size:.72rem; color:#64748b;
}
.yt-player-stats span { display:flex; align-items:center; gap:3px; }
.yt-player-stats i { color:#14b8a6; }
.yt-player-desc {
    font-size:.75rem; color:#94a3b8; line-height:1.6;
    max-height:90px; overflow-y:auto; flex:1;
}
.yt-player-spin {
    grid-column:1/-1; display:flex; align-items:center;
    justify-content:center; min-height:200px; gap:12px;
    color:#94a3b8; font-size:.82rem;
}
.yt-player-spin .spinner-border { color:#14b8a6 !important; }

/* ── MODAL PLAYER (MOBILE) ──────────────────────────────── */
#ytModalOverlay {
    display: none;
    position: fixed;
    inset: 0;
    z-index: 9999;
    background: rgba(0,0,0,.88);
    flex-direction: column;
    -webkit-overflow-scrolling: touch;
}
#ytModalOverlay.open { display: flex !important; }

.yt-modal-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px 14px 10px;
    background: #0f172a;
    flex-shrink: 0;
}
.yt-modal-header-title {
    font-size: .82rem;
    font-weight: 700;
    color: #fff;
    flex: 1;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    margin-right: 10px;
}
.yt-modal-close-btn {
    background: rgba(255,255,255,.12);
    border: none;
    color: #fff;
    border-radius: 50%;
    width: 34px; height: 34px;
    min-width: 34px;
    display: flex; align-items: center; justify-content: center;
    font-size: 1rem; cursor: pointer; flex-shrink: 0;
    transition: background .15s;
    -webkit-tap-highlight-color: transparent;
    touch-action: manipulation;
}
.yt-modal-close-btn:active { background: rgba(255,255,255,.25); }

.yt-modal-video {
    background: #000;
    position: relative;
    width: 100%;
    aspect-ratio: 16/9;
    flex-shrink: 0;
}
.yt-modal-video iframe {
    position: absolute; inset: 0; width: 100%; height: 100%; border: none;
    z-index: 1;
}
/* Mobile overlay top: pointer-events none agar iframe bisa diklik/kontrol */
.yt-modal-video .yt-overlay-top {
    position: absolute; top:0; left:0; right:0; height:50px;
    z-index:2; pointer-events: none;
}
.yt-modal-video .yt-overlay-logo {
    position: absolute; bottom:0; right:46px; width:60px; height:26px; z-index:3;
    pointer-events: none;
    background:rgba(0,0,0,.75); display:flex; align-items:center;
    justify-content:center; border-radius:5px 5px 0 0; color:#2dd4bf;
    font-size:.62rem; font-weight:800; user-select:none;
}

.yt-modal-meta {
    flex: 1;
    overflow-y: auto;
    -webkit-overflow-scrolling: touch;
    padding: 14px 16px;
    background: #0f172a;
}
.yt-modal-meta-title {
    font-size: .9rem;
    font-weight: 800;
    color: #f1f5f9;
    line-height: 1.4;
    margin-bottom: 10px;
}
.yt-modal-stats {
    display: flex;
    flex-wrap: wrap;
    gap: 8px 14px;
    font-size: .73rem;
    color: #94a3b8;
    margin-bottom: 10px;
}
.yt-modal-stats span { display:flex; align-items:center; gap:4px; }
.yt-modal-stats i { color:#2dd4bf; }
.yt-modal-desc {
    font-size: .75rem;
    color: #64748b;
    line-height: 1.6;
    border-top: 1px solid #1e293b;
    padding-top: 10px;
}
.yt-modal-spin {
    display: flex; align-items: center; justify-content: center;
    flex-direction: column; gap: 10px; padding: 40px 0;
    color: #94a3b8; font-size: .82rem;
}
.yt-modal-spin .spinner-border { color: #14b8a6 !important; }

/* ── GRID ───────────────────────────────────────────────── */
.yt-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
    gap: 16px;
    position: relative;
    z-index: 1;
}

/* ── CARD ───────────────────────────────────────────────── */
.yt-card {
    background: #fff; border-radius: 14px; overflow: hidden;
    border: 1px solid #e2e8f0; box-shadow: 0 2px 8px rgba(0,0,0,.05);
    cursor: pointer;
    transition: transform .15s, box-shadow .15s;
    position: relative;
    z-index: 2;
    /* Perbaikan tap mobile */
    -webkit-tap-highlight-color: transparent;
    touch-action: manipulation;
    user-select: none;
}
.yt-card:hover { transform:translateY(-3px); box-shadow:0 8px 24px rgba(0,0,0,.1); }
.yt-card:active { transform:scale(.98); opacity:.9; }
.yt-card.yt-card-active {
    border-color: #14b8a6;
    box-shadow: 0 0 0 2px rgba(20,184,166,.25), 0 4px 16px rgba(20,184,166,.15);
}
.yt-thumb-wrap { position:relative; aspect-ratio:16/9; overflow:hidden; background:#000; }
.yt-thumb-wrap img {
    width:100%; height:100%; object-fit:cover; transition:transform .3s;
    pointer-events: none; /* cegah img menghalangi tap */
}
.yt-card:hover .yt-thumb-wrap img { transform:scale(1.04); }
.yt-play-icon {
    position:absolute; inset:0; display:flex; align-items:center;
    justify-content:center; opacity:0; background:rgba(0,0,0,.35); transition:.2s;
    pointer-events: none; /* jangan halangi tap */
}
.yt-card:hover .yt-play-icon,
.yt-card.yt-card-active .yt-play-icon { opacity:1; }
.yt-play-icon i { font-size:2.6rem; color:#fff; filter:drop-shadow(0 2px 6px rgba(0,0,0,.5)); }
.yt-card-active .yt-play-icon i { color:#2dd4bf; }
.yt-card-body { padding:11px 13px 13px; pointer-events: none; /* tap lewat ke card */ }
.yt-card-title {
    font-size:.82rem; font-weight:700; color:#1e293b; line-height:1.4; margin-bottom:5px;
    display:-webkit-box; -webkit-line-clamp:2; -webkit-box-orient:vertical; overflow:hidden;
}
.yt-card-ch { font-size:.72rem; color:#64748b; font-weight:600; display:flex; align-items:center; gap:4px; }
.yt-card-ch i { color:#14b8a6; }
.yt-card-date { font-size:.68rem; color:#94a3b8; margin-top:3px; }

/* ── PAGINATION ─────────────────────────────────────────── */
.yt-pag { display:flex; gap:10px; justify-content:center; margin-top:22px; }
.yt-pag a {
    background:#fff; border:1px solid #e2e8f0; color:#475569;
    border-radius:10px; padding:9px 20px; font-weight:700;
    font-size:.82rem; text-decoration:none; transition:.15s;
    touch-action: manipulation;
    -webkit-tap-highlight-color: transparent;
}
.yt-pag a:hover { background:#0f766e; border-color:#0f766e; color:#fff; }

/* ── EMPTY / ERROR ──────────────────────────────────────── */
.yt-empty { text-align:center; padding:50px 20px; color:#94a3b8; }
.yt-empty i { font-size:3.5rem; display:block; margin-bottom:12px; color:#e2e8f0; }
.yt-error {
    background:#fef2f2; border:1px solid #fecaca; border-radius:12px;
    padding:14px 18px; color:#dc2626; font-size:.85rem; font-weight:600; margin-bottom:16px;
}

/* ── RESPONSIVE ─────────────────────────────────────────── */
@media (max-width: 767.98px) {
    /* Sembunyikan inline player di mobile — pakai modal */
    #ytPlayerWrap { display: none !important; }

    .yt-grid { grid-template-columns: repeat(2, 1fr); gap: 10px; }
    .yt-search-bar { padding: 14px; border-radius: 12px; }
    .yt-search-bar h5 { font-size: .9rem; margin-bottom: 10px; }
    .yt-search-input { font-size: .85rem; padding: 9px 12px; }
    .yt-search-btn { padding: 9px 14px; font-size: .8rem; }

    .yt-card-title { font-size: .76rem; }
    .yt-card-ch { font-size: .68rem; }
    .yt-card-date { font-size: .65rem; }
    .yt-card-body { padding: 9px 10px 11px; }

    /* Pastikan card tap area penuh */
    .yt-card { -webkit-tap-highlight-color: transparent; }
}

@media (max-width: 400px) {
    .yt-grid { grid-template-columns: 1fr; }
}

/* Desktop: sembunyikan modal overlay */
@media (min-width: 768px) {
    #ytModalOverlay { display: none !important; }
    #ytModalOverlay.open { display: none !important; }
}
</style>

<div class="yt-wrap">

<!-- Search -->
<form method="GET" action="<?php echo base_url('youtube') ?>">
<div class="yt-search-bar">
    <h5><i class="bi bi-camera-video me-2"></i>Cari Video</h5>
    <div class="yt-search-group">
        <input type="text" name="q" value="<?php echo htmlspecialchars($keyword) ?>"
               class="yt-search-input" placeholder="Ketik kata kunci video..."
               id="ytSearchInput" autocomplete="off">
        <button type="submit" class="yt-search-btn">
            <i class="bi bi-search me-1"></i>Cari
        </button>
    </div>
</div>
</form>

<!-- Error -->
<?php if($error): ?>
<div class="yt-error"><i class="bi bi-exclamation-triangle me-2"></i><?php echo $error ?></div>
<?php endif; ?>

<!-- Info -->
<?php if($keyword && !$error): ?>
<div class="yt-info">
    <?php if($total_results > 0): ?>
    Menampilkan hasil untuk: <strong>"<?php echo htmlspecialchars($keyword) ?>"</strong>
    &mdash; sekitar <?php echo number_format($total_results) ?> video ditemukan
    <?php else: ?>
    Tidak ada hasil untuk "<strong><?php echo htmlspecialchars($keyword) ?></strong>"
    <?php endif; ?>
</div>
<?php endif; ?>

<!-- ── DESKTOP: Inline Player ───────────────────────────── -->
<div id="ytPlayerWrap">
    <div class="yt-player-inner" id="ytPlayerInner">
        <div class="yt-player-spin">
            <div class="spinner-border" style="width:1.4rem;height:1.4rem;" role="status"></div>
            <span>Memuat video...</span>
        </div>
    </div>
</div>

<!-- ── MOBILE: Fullscreen Modal Player ──────────────────── -->
<div id="ytModalOverlay">
    <!-- Header -->
    <div class="yt-modal-header">
        <div class="yt-modal-header-title" id="ytModalHeaderTitle">Memuat video...</div>
        <button class="yt-modal-close-btn" id="ytModalCloseBtn" type="button">
            <i class="bi bi-x-lg"></i>
        </button>
    </div>

    <!-- Video -->
    <div class="yt-modal-video" id="ytModalVideo">
        <div class="yt-modal-spin" id="ytModalSpin">
            <div class="spinner-border" style="width:1.8rem;height:1.8rem;" role="status"></div>
            <span>Memuat video...</span>
        </div>
    </div>

    <!-- Meta -->
    <div class="yt-modal-meta" id="ytModalMeta" style="display:none;">
        <div class="yt-modal-meta-title" id="ytModalTitle"></div>
        <div class="yt-modal-stats" id="ytModalStats"></div>
        <div class="yt-modal-desc" id="ytModalDesc"></div>
    </div>
</div>

<!-- Grid -->
<?php if(!empty($results)): ?>
<div class="yt-grid" id="ytGrid">
    <?php foreach($results as $v): ?>
    <div class="yt-card" id="card-<?php echo $v['video_id'] ?>"
         data-video-id="<?php echo $v['video_id'] ?>">
        <div class="yt-thumb-wrap">
            <img src="<?php echo htmlspecialchars($v['thumbnail']) ?>"
                 alt="<?php echo htmlspecialchars($v['title']) ?>"
                 loading="lazy"
                 onerror="this.src='https://via.placeholder.com/320x180?text=No+Thumb'">
            <div class="yt-play-icon"><i class="bi bi-play-circle-fill"></i></div>
        </div>
        <div class="yt-card-body">
            <div class="yt-card-title"><?php echo htmlspecialchars($v['title']) ?></div>
            <div class="yt-card-ch">
                <i class="bi bi-person-circle"></i><?php echo htmlspecialchars($v['channel']) ?>
            </div>
            <div class="yt-card-date"><?php echo yt_time_ago($v['published']) ?></div>
        </div>
    </div>
    <?php endforeach; ?>
</div>

<!-- Pagination -->
<div class="yt-pag">
    <?php if($prev_page_token): ?>
    <a href="<?php echo base_url('youtube?q='.urlencode($keyword).'&page='.urlencode($prev_page_token)) ?>">
        <i class="bi bi-chevron-left me-1"></i>Sebelumnya
    </a>
    <?php endif; ?>
    <?php if($next_page_token): ?>
    <a href="<?php echo base_url('youtube?q='.urlencode($keyword).'&page='.urlencode($next_page_token)) ?>">
        Selanjutnya<i class="bi bi-chevron-right ms-1"></i>
    </a>
    <?php endif; ?>
</div>

<?php elseif($keyword && !$error): ?>
<div class="yt-empty">
    <i class="bi bi-film"></i>
    <div style="font-size:.9rem;font-weight:700;color:#64748b;">Tidak ada video ditemukan</div>
    <div style="font-size:.78rem;margin-top:5px;">Coba gunakan kata kunci lain</div>
</div>
<?php else: ?>
<div class="yt-empty">
    <i class="bi bi-camera-video" style="color:#99f6e4;"></i>
    <div style="font-size:.9rem;font-weight:700;color:#64748b;">Cari video favorit kamu</div>
    <div style="font-size:.78rem;margin-top:5px;">Masukkan kata kunci di kotak pencarian di atas</div>
</div>
<?php endif; ?>

</div><!-- .yt-wrap -->
<script>
var YT_BASE = '<?php echo base_url(); ?>';
var ytCurId = '';

function isMobile() {
    return window.innerWidth < 768;
}

/* ── INIT EVENT LISTENERS ────────────────────────────────── */
document.addEventListener('DOMContentLoaded', function() {

    // Tombol close modal
    var closeBtn = document.getElementById('ytModalCloseBtn');
    if (closeBtn) {
        closeBtn.addEventListener('click', function(e) {
            e.preventDefault();
            e.stopPropagation();
            ytClose();
        });
    }

    // Event pada card — hanya pakai click (bekerja di desktop & mobile)
    // Deteksi tap vs scroll menggunakan touchstart/touchend delta
    var grid = document.getElementById('ytGrid');
    if (grid) {
        var touchStartY = 0;
        var touchStartX = 0;
        var touchMoved  = false;

        grid.addEventListener('touchstart', function(e) {
            touchStartY = e.touches[0].clientY;
            touchStartX = e.touches[0].clientX;
            touchMoved  = false;
        }, { passive: true });

        grid.addEventListener('touchmove', function(e) {
            var dy = Math.abs(e.touches[0].clientY - touchStartY);
            var dx = Math.abs(e.touches[0].clientX - touchStartX);
            // Jika geser > 8px anggap scroll, bukan tap
            if (dy > 8 || dx > 8) touchMoved = true;
        }, { passive: true });

        grid.addEventListener('touchend', function(e) {
            if (touchMoved) return; // skip jika user sedang scroll
            var card = e.target.closest('.yt-card');
            if (card) {
                e.preventDefault(); // cegah double-fire dengan click
                ytOpen(card.dataset.videoId);
            }
        }, { passive: false });

        // Click untuk desktop (dan fallback mobile tanpa touch)
        grid.addEventListener('click', function(e) {
            // Di mobile, touchend sudah handle — skip click
            if (touchMoved !== undefined && !touchMoved && isMobile()) return;
            var card = e.target.closest('.yt-card');
            if (card) {
                e.preventDefault();
                ytOpen(card.dataset.videoId);
            }
        });
    }

    // Tutup modal via back button Android
    window.addEventListener('popstate', function() {
        var overlay = document.getElementById('ytModalOverlay');
        if (overlay && overlay.classList.contains('open')) ytClose();
    });

    // Tutup modal jika klik area luar (overlay background)
    var overlay = document.getElementById('ytModalOverlay');
    if (overlay) {
        overlay.addEventListener('click', function(e) {
            if (e.target === overlay) ytClose();
        });
    }
});

/* ── OPEN ─────────────────────────────────────────────────── */
function ytOpen(videoId) {
    if (!videoId) return;

    document.querySelectorAll('.yt-card').forEach(function(c) {
        c.classList.remove('yt-card-active');
    });
    var activeCard = document.getElementById('card-' + videoId);
    if (activeCard) activeCard.classList.add('yt-card-active');

    if (ytCurId === videoId) {
        if (isMobile()) {
            var ov = document.getElementById('ytModalOverlay');
            if (ov && ov.classList.contains('open')) { ytClose(); return; }
        } else {
            var wrap = document.getElementById('ytPlayerWrap');
            if (wrap && wrap.style.display === 'block') { ytClose(); return; }
        }
    }
    ytCurId = videoId;

    if (isMobile()) {
        ytOpenMobile(videoId);
    } else {
        ytOpenDesktop(videoId);
    }
}

/* ── DESKTOP ──────────────────────────────────────────────── */
function ytOpenDesktop(videoId) {
    var wrap  = document.getElementById('ytPlayerWrap');
    var inner = document.getElementById('ytPlayerInner');
    wrap.style.display = 'block';
    inner.innerHTML =
        '<div class="yt-player-spin">' +
        '<div class="spinner-border" style="width:1.4rem;height:1.4rem;" role="status"></div>' +
        '<span>Memuat video...</span></div>';
    wrap.scrollIntoView({ behavior:'smooth', block:'start' });
    fetchVideoDetail(videoId, renderDesktop);
}

function renderDesktop(v) {
    var inner = document.getElementById('ytPlayerInner');
    if (!v) {
        inner.innerHTML =
            '<div class="yt-player-spin" style="color:#ef4444;">' +
            '<i class="bi bi-exclamation-circle" style="font-size:1.5rem;"></i>' +
            '<span>Gagal memuat video</span></div>';
        return;
    }
    var embedSrc = buildEmbedSrc(v.video_id);
    inner.innerHTML =
        '<div class="yt-embed-wrap">' +
            '<div class="yt-overlay-top"></div>' +
            '<div class="yt-overlay-logo">&#9654;&nbsp;Auto RT</div>' +
            '<iframe src="' + embedSrc + '" ' +
            'allow="autoplay; encrypted-media; picture-in-picture" ' +
            'sandbox="allow-scripts allow-same-origin allow-presentation allow-forms" allowfullscreen></iframe>' +
        '</div>' +
        '<div class="yt-player-meta">' +
            '<button class="yt-player-close" onclick="ytClose()" type="button">' +
            '<i class="bi bi-x-lg me-1"></i>Tutup</button>' +
            '<div class="yt-player-title">' + escHtml(v.title) + '</div>' +
            '<div class="yt-player-stats">' +
                '<span><i class="bi bi-eye"></i>' + v.view_count + ' tayangan</span>' +
                '<span><i class="bi bi-hand-thumbs-up"></i>' + v.like_count + '</span>' +
                '<span><i class="bi bi-person-circle"></i>' + escHtml(v.channel) + '</span>' +
                '<span><i class="bi bi-clock"></i>' + v.duration + '</span>' +
            '</div>' +
            '<div class="yt-player-desc">' + escHtml(v.description) + '</div>' +
        '</div>';
}

/* ── MOBILE ───────────────────────────────────────────────── */
function ytOpenMobile(videoId) {
    var overlay     = document.getElementById('ytModalOverlay');
    var headerTitle = document.getElementById('ytModalHeaderTitle');
    var modalVideo  = document.getElementById('ytModalVideo');
    var modalMeta   = document.getElementById('ytModalMeta');
    var modalSpin   = document.getElementById('ytModalSpin');

    headerTitle.textContent  = 'Memuat video...';
    modalMeta.style.display  = 'none';
    modalSpin.style.display  = 'flex';

    var toRemove = modalVideo.querySelectorAll('iframe, .yt-overlay-top, .yt-overlay-logo');
    toRemove.forEach(function(el) { el.remove(); });

    overlay.classList.add('open');
    document.body.style.overflow = 'hidden';

    history.pushState({ ytModal: true }, '');

    fetchVideoDetail(videoId, function(v) {
        modalSpin.style.display = 'none';

        if (!v) {
            headerTitle.textContent = 'Gagal memuat';
            document.getElementById('ytModalTitle').textContent = 'Video tidak dapat dimuat.';
            document.getElementById('ytModalStats').innerHTML   = '';
            document.getElementById('ytModalDesc').textContent  = 'Silakan coba video lain.';
            modalMeta.style.display = 'block';
            return;
        }

        var embedSrc = buildEmbedSrc(v.video_id);
        var iframe   = document.createElement('iframe');
        iframe.src   = embedSrc;
        iframe.setAttribute('allow', 'autoplay; encrypted-media; picture-in-picture');
        iframe.setAttribute('sandbox', 'allow-scripts allow-same-origin allow-presentation allow-forms');
        iframe.setAttribute('allowfullscreen', '');
        modalVideo.insertBefore(iframe, modalSpin);

        var ot = document.createElement('div');
        ot.className = 'yt-overlay-top';
        modalVideo.appendChild(ot);

        var ol = document.createElement('div');
        ol.className = 'yt-overlay-logo';
        ol.innerHTML = '&#9654;&nbsp;RT';
        modalVideo.appendChild(ol);

        headerTitle.textContent = v.title;
        document.getElementById('ytModalTitle').textContent = v.title;
        document.getElementById('ytModalStats').innerHTML =
            '<span><i class="bi bi-eye"></i>' + v.view_count + ' tayangan</span>' +
            '<span><i class="bi bi-hand-thumbs-up"></i>' + v.like_count + '</span>' +
            '<span><i class="bi bi-person-circle"></i>' + escHtml(v.channel) + '</span>' +
            '<span><i class="bi bi-clock"></i>' + v.duration + '</span>';
        document.getElementById('ytModalDesc').textContent = v.description || '';
        modalMeta.style.display = 'block';
    });
}

/* ── CLOSE ────────────────────────────────────────────────── */
function ytClose() {
    var wrap = document.getElementById('ytPlayerWrap');
    if (wrap) {
        var iframe = wrap.querySelector('iframe');
        if (iframe) iframe.src = '';
        wrap.style.display = 'none';
    }

    var overlay = document.getElementById('ytModalOverlay');
    if (overlay && overlay.classList.contains('open')) {
        overlay.classList.remove('open');
        var mIframe = document.getElementById('ytModalVideo').querySelector('iframe');
        if (mIframe) mIframe.src = '';
        document.body.style.overflow = '';
    }

    document.querySelectorAll('.yt-card').forEach(function(c) {
        c.classList.remove('yt-card-active');
    });
    ytCurId = '';
}

/* ── HELPERS ──────────────────────────────────────────────── */
function buildEmbedSrc(videoId) {
    return 'https://www.youtube.com/embed/' + videoId
        + '?autoplay=1&rel=0&modestbranding=1'
        + '&origin=' + encodeURIComponent(window.location.origin);
}

function fetchVideoDetail(videoId, callback) {
    fetch(YT_BASE + 'youtube/ajax_detail', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'video_id=' + encodeURIComponent(videoId)
    })
    .then(function(r) { return r.json(); })
    .then(function(d) { callback(d.ok ? d.data : null); })
    .catch(function()  { callback(null); });
}

function escHtml(str) {
    if (!str) return '';
    return str.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;')
              .replace(/"/g,'&quot;').replace(/'/g,'&#039;');
}
</script>