<?php 
// Panggil koneksi database (otomatis memulai session)
require_once '../theme/database/sql.php'; 

// ==========================================
// 1. FUNGSI BANTUAN (HELPERS)
// ==========================================
function formatDuration($seconds) {
    $h = floor($seconds / 3600);
    $m = floor(($seconds % 3600) / 60);
    $s = $seconds % 60;
    if ($h > 0) return sprintf("%d:%02d:%02d", $h, $m, $s);
    return sprintf("%02d:%02d", $m, $s);
}

function formatViews($num) {
    if ($num >= 1000000) return round($num / 1000000, 1) . 'M';
    if ($num >= 1000) return round($num / 1000, 1) . 'K';
    return $num;
}

// ==========================================
// 2. CEK ROLE & PARAMETER URL SLUG
// ==========================================
$is_admin = (isset($_SESSION['role']) && $_SESSION['role'] === 'admin');

if (empty($_GET['slug'])) {
    die("Video tidak ditemukan. Parameter slug kosong.");
}

$slug = trim($_GET['slug']);

// Cari video di database berdasarkan slug
$stmt_vid = $pdo->prepare("SELECT * FROM meta_videos WHERE slug = :slug AND status = 'published' LIMIT 1");
$stmt_vid->execute(['slug' => $slug]);
$video = $stmt_vid->fetch();

if (!$video) {
    header("Location: ../index.php");
    exit;
}

$current_video_id = $video['id'];

// ==========================================
// 3. LOGIKA TAMBAH VIEW (ANTI SPAM VIA SESSION)
// ==========================================
if (!isset($_SESSION['viewed_videos'])) {
    $_SESSION['viewed_videos'] = [];
}

if (!in_array($current_video_id, $_SESSION['viewed_videos'])) {
    $stmt_update_view = $pdo->prepare("UPDATE meta_videos SET views = views + 1 WHERE id = :vid");
    $stmt_update_view->execute(['vid' => $current_video_id]);
    
    $_SESSION['viewed_videos'][] = $current_video_id;
    $video['views'] += 1; 
}

// ==========================================
// 4. LOGIKA AJAX KOMENTAR (REALTIME)
// ==========================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax_request'])) {
    
    header('Content-Type: application/json');

    // Proses Tambah Komentar
    if (isset($_POST['action']) && $_POST['action'] === 'add_comment' && isset($_POST['komentar'])) {
        $komentar = trim($_POST['komentar']);
        $user_id = null;
        $name = '';
        $avatar_url = $domain . '/theme/assets/img/avatar.svg';
        $role = '';

        if (isset($_SESSION['user_id'])) {
            $user_id = $_SESSION['user_id'];
            $name = $_SESSION['name']; 
            $role = $_SESSION['role'] ?? '';
            $avatar_url = !empty($_SESSION['avatar']) ? $_SESSION['avatar'] : $avatar_url;
        } else {
            $name = trim($_POST['nama'] ?? 'Guest');
            if (empty($name)) $name = 'Guest';
        }

        if (!empty($komentar)) {
            $stmt = $pdo->prepare("INSERT INTO site_comments (video_id, user_id, name, comment) VALUES (:vid, :uid, :name, :comment)");
            $stmt->execute([
                'vid' => $current_video_id,
                'uid' => $user_id,
                'name' => $name,
                'comment' => $komentar
            ]);
            
            $new_id = $pdo->lastInsertId();

            echo json_encode([
                'status'  => 'success',
                'id'      => $new_id,
                'name'    => htmlspecialchars($name),
                'comment' => nl2br(htmlspecialchars($komentar)),
                'avatar'  => htmlspecialchars($avatar_url),
                'role'    => $role,
                'is_guest'=> empty($user_id),
                'time'    => date('d M Y, H:i')
            ]);
            exit;
        }
    }
    
    // Proses Hapus Komentar
    if (isset($_POST['action']) && $_POST['action'] === 'delete_comment' && $is_admin) {
        $delete_id = (int)$_POST['delete_comment_id'];
        if ($delete_id > 0) {
            $stmt = $pdo->prepare("DELETE FROM site_comments WHERE id = :id");
            $stmt->execute(['id' => $delete_id]);
            echo json_encode(['status' => 'success']);
            exit;
        }
    }

    echo json_encode(['status' => 'error']);
    exit;
}

// ==========================================
// 5. AMBIL DATA KOMENTAR AWAL
// ==========================================
$stmt_comments = $pdo->prepare("
    SELECT c.*, u.avatar, u.role 
    FROM site_comments c 
    LEFT JOIN site_users u ON c.user_id = u.id 
    WHERE c.video_id = :vid 
    ORDER BY c.create_at ASC
");
$stmt_comments->execute(['vid' => $current_video_id]);
$comments_data = $stmt_comments->fetchAll();
$total_comments = count($comments_data);

// ==========================================
// 6. PERSIAPAN DATA METADATA
// ==========================================
$kategori_array = !empty($video['categories']) ? array_map('trim', explode(',', $video['categories'])) : [];
$actress_array = !empty($video['actress']) ? array_map('trim', explode(',', $video['actress'])) : [];
$tags_array = !empty($video['tags']) ? array_map('trim', explode(',', $video['tags'])) : [];

// ---> TAMBAHAN WAJIB UNTUK MENGIRIM DATA KE HEADER.PHP <---
// Definisikan variabel-variabel ini agar bisa ditangkap oleh logika SEO di header.php
$video_title         = $video['name']; // Judul video
$video_description   = $video['description']; // Deskripsi video
$video_keywords   	 = $video['tags'];
$video_thumbnail_url = $video['thumbnails']; // Gambar thumbnail
$video_publish_date  = $video['created_at']; // Tanggal upload (pastikan nama kolomnya benar 'created_at')
$video_iframe_url    = $video['videos']; // Aktifkan ini jika Anda punya link iframe di database untuk Schema VideoObject


// Panggil Header
include '../theme/header.php'; 
?>

<style>
    .btn-delete-comment { background: transparent; border: none; color: #ef4444; cursor: pointer; padding: 2px; margin-left: 8px; margin-top: -3px; display: inline-flex; align-items: center; vertical-align: middle; transition: color 0.2s; }
    .btn-delete-comment:hover { color: var(--text-muted); }
    .btn-delete-comment svg { width: 14px; height: 14px; }

    .popup-overlay { position: fixed; inset: 0; background: rgba(11, 4, 26, 0.8); backdrop-filter: blur(5px); display: flex; align-items: center; justify-content: center; z-index: 9999; opacity: 0; pointer-events: none; transition: opacity 0.3s ease; }
    .popup-overlay.show { opacity: 1; pointer-events: auto; }
    .popup-card { background: var(--bg-card); border: 1px solid var(--border-purple); border-radius: 1rem; padding: 2rem; width: 90%; max-width: 380px; text-align: center; box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.6); transform: scale(0.9); transition: transform 0.3s ease; }
    .popup-overlay.show .popup-card { transform: scale(1); }
    .popup-title { font-size: 1.25rem; font-weight: bold; color: white; margin-bottom: 0.5rem; letter-spacing: 0.025em; }
    .popup-btn-close { flex: 1; font-weight: bold; font-size: 0.875rem; padding: 0.75rem; border-radius: 0.5rem; transition: 0.3s; border: none; cursor: pointer; }
</style>

<main class="content-container">

    <div class="watch-layout">
        
        <div class="watch-main">
            
            <div class="player-wrapper">
    <div class="player-area">
        <?php
            // 1. Ekstrak data JSON dari kolom videos
            $video_data = json_decode($video['videos'], true) ?? trim($video['videos'], '"');
            
            // 2. Jika formatnya array, ambil link yang pertama
            $video_src = is_array($video_data) ? $video_data[0] : $video_data;

            // 3. Deteksi tipe data dan tampilkan iframe
            if (strpos($video_src, '<iframe') !== false) {
                // Skenario A: Jika di database sudah ada tag <iframe...>, langsung cetak (tanpa htmlspecialchars)
                // Tambahkan style inline agar ukurannya pas dengan kontainer
                echo str_replace('<iframe', '<iframe style="width:100%; height:100%; border:none;"', $video_src);
            } else {
                // Skenario B: Jika di database hanya berupa link URL, kita buatkan tag iframe-nya
        ?>
            <iframe src="<?php echo htmlspecialchars($video_src); ?>" 
                    style="width: 100%; height: 100%; border: none;" 
                    allowfullscreen>
            </iframe>
        <?php 
            } 
        ?>
    </div>
    
    <a href="<?php echo $telegram_group; ?>" target="_blank" class="btn-join">

JOIN GRUP

</a>
</div>

            <div class="watch-title-area">
                <h1 class="watch-title"><?php echo htmlspecialchars($video['name']); ?></h1>
                <div class="watch-meta">
                    <div class="meta-item">
                        <svg fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" /><path stroke-linecap="round" stroke-linejoin="round" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" /></svg>
                        <span><?php echo formatViews($video['views']); ?> views</span>
                    </div>
                    <div class="meta-item">
                        <svg fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>
                        <span><?php echo formatDuration($video['duration']); ?></span>
                    </div>
                </div>
            </div>

            <div class="detail-box">
                <?php if (!empty($kategori_array)): ?>
                <div class="detail-row">
                    <span class="detail-label">Categories</span>
                    <div class="detail-tags">
                        <?php foreach($kategori_array as $kat): ?>
                            <a href="../index.php?categories=<?php echo urlencode($kat); ?>" class="tag-pill"><?php echo htmlspecialchars($kat); ?></a>
                        <?php endforeach; ?>
                    </div>
                </div>
                <?php endif; ?>

                <?php if (!empty($actress_array)): ?>
                <div class="detail-row">
                    <span class="detail-label">Actress</span>
                    <div class="detail-tags">
                        <?php foreach($actress_array as $act): ?>
                            <a href="../index.php?actress=<?php echo urlencode($act); ?>" class="tag-pill blue"><?php echo htmlspecialchars($act); ?></a>
                        <?php endforeach; ?>
                    </div>
                </div>
                <?php endif; ?>

                <?php if (!empty($tags_array)): ?>
                <div class="detail-row">
                    <span class="detail-label">Tags</span>
                    <div class="detail-tags">
                        <?php foreach($tags_array as $tag): ?>
                            <a href="../index.php?tags=<?php echo urlencode($tag); ?>" class="tag-pill gray"><?php echo htmlspecialchars($tag); ?></a>
                        <?php endforeach; ?>
                    </div>
                </div>
                <?php endif; ?>

                <div class="detail-desc">
                    <p><?php echo nl2br(htmlspecialchars($video['description'])); ?></p>
                </div>
            </div>
            
        </div> 

        <div class="watch-sidebar" id="comment-section">
            <div class="comment-container">
                
                <div class="comment-header">
                    <h2>
                        <svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 5v-5z"></path></svg>
                        Komentar (<span id="komentar-count"><?php echo $total_comments; ?></span>)
                    </h2>
                </div>

                <div id="comment-list" class="comment-list">
                    <?php
                    if ($total_comments > 0) {
                        foreach($comments_data as $c) {
                            $avatar_url = (!empty($c['avatar'])) ? $c['avatar'] : $domain . '/theme/assets/img/avatar.svg';
                            $waktu = date('d M Y, H:i', strtotime($c['create_at']));
                            
                            $badge = '';
                            if (isset($c['role']) && $c['role'] === 'admin') {
                                $badge = ' <svg style="width:12px; height:12px; color:#3b82f6; display:inline; margin-bottom:-2px;" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"></path></svg>';
                            } elseif (empty($c['user_id'])) {
                                $badge = ' <span style="font-size:9px; font-weight:normal; color:var(--text-muted);">(Guest)</span>';
                            }

                            $trash_html = '';
                            if ($is_admin) {
                                $trash_html = '
                                <button type="button" class="btn-delete-comment" onclick="triggerDeletePopup(this, '.$c['id'].')" title="Hapus Komentar">
                                    <svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path></svg>
                                </button>';
                            }

                            echo '
                            <div class="comment-item animate-fade-in-up">
                                <img src="'.htmlspecialchars($avatar_url).'" alt="Avatar" class="comment-avatar" style="object-fit: cover; background: rgba(255,255,255,0.05); border: 1px solid rgba(147, 51, 234, 0.2);">
                                <div class="comment-body">
                                    <div class="comment-meta">'.htmlspecialchars($c['name']).$badge.' <span class="comment-time">'.$waktu.'</span>'.$trash_html.'</div>
                                    <p class="comment-text">'.nl2br(htmlspecialchars($c['comment'])).'</p>
                                </div>
                            </div>';
                        }
                    } else {
                        echo '<p id="empty-comment-msg" style="text-align:center; color:var(--text-muted); font-size:0.875rem; margin-top:2rem;">Jadilah yang pertama berkomentar!</p>';
                    }
                    ?>
                </div>

                <div class="comment-form-box">
                    <form id="comment-form" class="comment-form">
                        <input type="hidden" name="action" value="add_comment">
                        
                        <?php if (isset($_SESSION['user_id'])): ?>
                            <div style="font-size: 0.75rem; color: var(--text-muted); padding: 0 4px;">
                                Berkomentar sebagai <strong style="color: var(--primary-hover);"><?php echo htmlspecialchars($_SESSION['name']); ?></strong>
                            </div>
                        <?php else: ?>
                            <input type="text" name="nama" placeholder="Nama Anda" required class="input-text">
                        <?php endif; ?>
                        
                        <textarea name="komentar" rows="2" placeholder="Tulis komentar..." required class="input-textarea"></textarea>
                        
                        <button type="submit" id="btn-submit-comment" class="btn-submit">
                            <svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"></path></svg>
                            <span>Kirim Komentar</span>
                        </button>
                    </form>
                </div>

            </div>
        </div> 
    </div> 
    
    <div style="border-top: 1px solid var(--border-purple); padding-top: 2rem; margin-top: 0.5rem; margin-bottom: 1.5rem;">
        <div class="section-header">
            <h2 class="section-title">Related Videos</h2>
        </div>

        <div class="video-grid" id="related-video-container">
            <?php
            $clean_title = preg_replace('/[^A-Za-z0-9\s]/', '', strtolower($video['name']));
            $title_words = explode(' ', $clean_title);
            
            $stop_words = ['episode', 'season', 'subtitle', 'indonesia', 'sub', 'indo', 'the', 'and', 'part', 'movie', 'ova', 'ona', 'hd', 'full', 'lengkap', 'dari', 'di', 'ke'];
            
            $filtered_words = array_filter($title_words, function($w) use ($stop_words) {
                return strlen($w) > 3 && !in_array($w, $stop_words);
            });
            
            shuffle($filtered_words);
            $search_words = array_slice($filtered_words, 0, 2);

            $related_videos = [];
            $exclude_ids = [$current_video_id]; 

            if (!empty($search_words)) {
                $where_likes = [];
                $params = ['vid' => $current_video_id];
                
                foreach ($search_words as $index => $word) {
                    $where_likes[] = "name LIKE :word" . $index;
                    $params["word" . $index] = '%' . $word . '%';
                }
                
                $sql_related = "SELECT * FROM meta_videos WHERE status = 'published' AND id != :vid AND (" . implode(' OR ', $where_likes) . ") ORDER BY created_at DESC LIMIT 12";
                
                $stmt_related = $pdo->prepare($sql_related);
                $stmt_related->execute($params);
                $related_videos = $stmt_related->fetchAll();

                foreach($related_videos as $rv) {
                    $exclude_ids[] = $rv['id'];
                }
            }

            $make_up_count = count($related_videos);
            if ($make_up_count < 12) {
                $deficit = 12 - $make_up_count;
                $in_placeholders = implode(',', array_fill(0, count($exclude_ids), '?'));
                
                $sql_fallback = "SELECT * FROM meta_videos WHERE status = 'published' AND id NOT IN ($in_placeholders) ORDER BY RAND() LIMIT " . (int)$deficit;
                
                $stmt_fallback = $pdo->prepare($sql_fallback);
                $stmt_fallback->execute($exclude_ids);
                $fallback_videos = $stmt_fallback->fetchAll();
                
                $related_videos = array_merge($related_videos, $fallback_videos);
            }

            $i = 1;
            foreach ($related_videos as $rel) {
                $is_cached = (rand(0, 1) == 1); 
                // Di sini kelas tersembunyi (hidden-video) dipasang ke video index 9 ke atas (total ada 4 video tersembunyi)
                $hiddenClass = ($i > 8) ? "hidden hidden-video" : "";
                $link_rel = $domain . "/watch/?slug=" . $rel['slug'];
                ?>
                <div class="video-card <?php echo $hiddenClass; ?>">
                    <a href="<?php echo $link_rel; ?>" class="video-thumb-wrapper">
                        <img src="<?php echo htmlspecialchars(json_decode($rel['thumbnails'], true) ?? trim($rel['thumbnails'], '"')); ?>" alt="Thumbnail" loading="lazy">
                        
                        <div class="badge-tl">
                            <?php if ($is_cached): ?>
                                <svg class="text-yellow" fill="currentColor" viewBox="0 0 24 24"><path d="M13 2L3 14h9l-1 8 10-12h-9l1-8z"/></svg>
                            <?php else: ?>
                                <svg class="text-muted" fill="currentColor" viewBox="0 0 24 24"><path d="M13 2L3 14h9l-1 8 10-12h-9l1-8z"/></svg>
                            <?php endif; ?>
                        </div>

                        <div class="badge-bl">
                                <svg class="text-muted" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" /><path stroke-linecap="round" stroke-linejoin="round" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" /></svg>
                              <span><?php echo formatViews($rel['views']); ?></span>
                            </div>
                            <div class="badge-br">
                              <svg class="text-muted" style="margin-bottom: -2.5px;" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"></circle><polyline points="12 6 12 12 16 14"></polyline></svg>
                                <span><?php echo formatDuration($rel['duration']); ?></span>
                          </div>
                    </a>
                    <div class="video-info">
                        <a href="<?php echo $link_rel; ?>" class="video-title line-clamp-2" title="<?php echo htmlspecialchars($rel['name']); ?>">
                            <?php echo htmlspecialchars($rel['name']); ?>
                        </a>
                    </div>
                </div>
                <?php
                $i++;
            }
            ?>
        </div>

        <?php if (count($related_videos) > 8): ?>
        <div class="btn-more-container">
            <button id="btn-load-more" class="btn-more">
                <span>Lihat Lebih Banyak</span>
                <svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path></svg>
            </button>
        </div>
        <?php endif; ?>
    </div>

</main>

<div id="popup-delete-confirm" class="popup-overlay">
    <div class="popup-card" style="border-color: rgba(220, 38, 38, 0.4);">
        <div style="display: flex; justify-content: center; color: #ef4444; margin-bottom: 1rem;">
            <svg fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24" style="width: 48px; height: 48px;"><path stroke-linecap="round" stroke-linejoin="round" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"></path></svg>
        </div>
        <h3 class="popup-title">Hapus Komentar?</h3>
        <p style="color: var(--text-light); font-size: 0.85rem; margin-bottom: 1.5rem; line-height: 1.4;">Apakah Anda yakin ingin menghapus komentar ini? Data akan terhapus secara permanen.</p>
        
        <div style="display: flex; gap: 0.75rem;">
            <button class="popup-btn-close" style="background: rgba(255,255,255,0.1); color: var(--text-light);" onclick="closeDeletePopup()">Batal</button>
            <button class="popup-btn-close" style="background: #dc2626; color: white;" id="confirm-delete-btn">Ya, Hapus</button>
        </div>
    </div>
</div>

<script>
let currentDeleteId = null;
let currentDeleteElement = null;
const isAdmin = <?php echo $is_admin ? 'true' : 'false'; ?>;

function triggerDeletePopup(btnElement, commentId) {
    currentDeleteId = commentId;
    currentDeleteElement = btnElement.closest('.comment-item');
    const popup = document.getElementById('popup-delete-confirm');
    if (popup) popup.classList.add('show');
}

function closeDeletePopup() {
    const popup = document.getElementById('popup-delete-confirm');
    if (popup) popup.classList.remove('show');
    currentDeleteId = null;
    currentDeleteElement = null;
}

document.addEventListener('DOMContentLoaded', () => {
    const commentList = document.getElementById('comment-list');
    const komentarCountEl = document.getElementById('komentar-count');
    const emptyMsg = document.getElementById('empty-comment-msg');
    
    if (commentList) commentList.scrollTop = commentList.scrollHeight;

    // AJAX TAMBAH KOMENTAR
    const commentForm = document.getElementById('comment-form');
    if (commentForm) {
        commentForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const btnSubmit = document.getElementById('btn-submit-comment');
            const originalText = btnSubmit.innerHTML;
            btnSubmit.innerHTML = 'Mengirim...';
            btnSubmit.disabled = true;

            const formData = new FormData(commentForm);
            formData.append('ajax_request', '1'); 

            fetch(window.location.href, {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    let badgeHtml = data.is_guest ? '<span style="font-size:9px; font-weight:normal; color:var(--text-muted);">(Guest)</span>' : '';
                    if (data.role === 'admin') {
                        badgeHtml = ' <svg style="width:12px; height:12px; color:#3b82f6; display:inline; margin-bottom:-2px;" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"></path></svg>';
                    }
                    
                    let trashHtml = isAdmin ? `
                        <button type="button" class="btn-delete-comment" onclick="triggerDeletePopup(this, ${data.id})" title="Hapus Komentar">
                            <svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path></svg>
                        </button>` : '';

                    const newCommentHtml = `
                        <div class="comment-item animate-fade-in-up">
                            <img src="${data.avatar}" alt="Avatar" class="comment-avatar" style="object-fit: cover; background: rgba(255,255,255,0.05); border: 1px solid rgba(147, 51, 234, 0.2);">
                            <div class="comment-body">
                                <div class="comment-meta">${data.name}${badgeHtml} <span class="comment-time">${data.time}</span>${trashHtml}</div>
                                <p class="comment-text">${data.comment}</p>
                            </div>
                        </div>
                    `;

                    if (emptyMsg) emptyMsg.remove();
                    commentList.insertAdjacentHTML('beforeend', newCommentHtml);
                    komentarCountEl.innerText = parseInt(komentarCountEl.innerText) + 1;
                    commentList.scrollTop = commentList.scrollHeight;

                    const textarea = commentForm.querySelector('textarea');
                    if (textarea) textarea.value = '';
                }
            })
            .catch(error => console.error('Error:', error))
            .finally(() => {
                btnSubmit.innerHTML = originalText;
                btnSubmit.disabled = false;
            });
        });
    }

    // AJAX HAPUS KOMENTAR
    const confirmDeleteBtn = document.getElementById('confirm-delete-btn');
    if (confirmDeleteBtn) {
        confirmDeleteBtn.addEventListener('click', () => {
            if (!currentDeleteId || !currentDeleteElement) return;

            const formData = new FormData();
            formData.append('ajax_request', '1');
            formData.append('action', 'delete_comment');
            formData.append('delete_comment_id', currentDeleteId);

            fetch(window.location.href, {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    currentDeleteElement.style.transition = 'opacity 0.3s ease, transform 0.3s ease';
                    currentDeleteElement.style.opacity = '0';
                    currentDeleteElement.style.transform = 'translateY(-10px)';
                    
                    setTimeout(() => {
                        currentDeleteElement.remove();
                        let currentCount = parseInt(komentarCountEl.innerText);
                        if (currentCount > 0) komentarCountEl.innerText = currentCount - 1;
                    }, 300);
                }
            })
            .catch(error => console.error('Error:', error))
            .finally(() => {
                closeDeletePopup();
            });
        });
    }

    // =========================================================
    // LOGIKA REVISI: LOAD MORE + REDIRECT DENGAN CLICK COUNT
    // =========================================================
    const btnLoadMore = document.getElementById('btn-load-more');
    const hiddenVideos = document.querySelectorAll('.hidden-video');
    let clickCount = 0; // Kembalikan penghitung klik
    
    if (btnLoadMore) {
        btnLoadMore.addEventListener('click', (e) => {
            e.preventDefault();
            clickCount++;

            if (clickCount === 1) {
                // Klik Pertama: Munculkan 4 video sisa (penambal acak/keyword)
                hiddenVideos.forEach(video => {
                    video.classList.remove('hidden');
                    video.classList.remove('hidden-video');
                });
            } 
            else if (clickCount >= 2) {
                // Klik Kedua: Buka Google di tab baru
                window.open('<?php echo $ads_direct; ?>', '_blank');
            }
        });
    }
});
</script>

<?php 
include '../theme/footer.php'; 
?>