<?php
session_start();

if (!isset($_SESSION['user_logged']) || $_SESSION['user_logged'] !== true) {
    header('Location: index.php');
    exit;
}

$username = $_SESSION['username'];
$password = $_SESSION['password'];
$server_url = $_SESSION['server_url'];
$server_name = $_SESSION['server_name'];

function makeApiRequest($action, $params = []) {
    global $username, $password, $server_url;
    
    $base_params = [
        'username' => $username,
        'password' => $password,
        'action' => $action
    ];
    
    $all_params = array_merge($base_params, $params);
    $query_string = http_build_query($all_params);
    $full_url = rtrim($server_url, '/') . '/player_api.php?' . $query_string;
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $full_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 8);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
    curl_setopt($ch, CURLOPT_USERAGENT, 'XtremePlayer/1.0');
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($response && $http_code == 200) {
        return json_decode($response, true);
    }
    return false;
}

$categories = makeApiRequest('get_vod_categories') ?: [];
$selected_category = $_GET['cat'] ?? '';
$sort_order = $_GET['sort'] ?? '';
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 50;
$offset = ($page - 1) * $limit;

// Obtener películas
if ($selected_category) {
    $all_movies = makeApiRequest('get_vod_streams', ['category_id' => $selected_category]) ?: [];
} else {
    $all_movies = makeApiRequest('get_vod_streams') ?: [];
}

// BANNER - Mismo estilo que series
$featured_movies = [];
if (!empty($all_movies)) {
    $banner_movies = $all_movies;
    shuffle($banner_movies);
    foreach ($banner_movies as $movie) {
        if (count($featured_movies) >= 6) break;
        if (!empty($movie['name']) && !empty($movie['stream_id'])) {
            $featured_movies[] = [
                'stream_id' => $movie['stream_id'],
                'name' => $movie['name'],
                'backdrop_url' => $movie['stream_icon'] ?? '',
                'plot' => $movie['plot'] ?? 'Sin descripción disponible.',
                'year' => $movie['year'] ?? date('Y'),
                'rating' => $movie['rating'] ?? '8.0',
                'genre' => $movie['genre'] ?? 'Acción',
                'container_extension' => $movie['container_extension'] ?? 'mp4'
            ];
        }
    }
}

// Ordenamiento
if (!empty($all_movies)) {
    switch ($sort_order) {
        case 'name_asc': usort($all_movies, fn($a, $b) => strcasecmp($a['name'] ?? '', $b['name'] ?? '')); break;
        case 'name_desc': usort($all_movies, fn($a, $b) => strcasecmp($b['name'] ?? '', $a['name'] ?? '')); break;
        case 'recent': usort($all_movies, fn($a, $b) => strtotime($b['added'] ?? 0) - strtotime($a['added'] ?? 0)); break;
        case 'rating': usort($all_movies, fn($a, $b) => floatval($b['rating'] ?? 0) <=> floatval($a['rating'] ?? 0)); break;
    }
}

$total_movies = count($all_movies);
$movies = array_slice($all_movies, $offset, $limit);
$has_more = ($offset + $limit) < $total_movies;

// Respuesta AJAX
if (isset($_GET['ajax'])) {
    header('Content-Type: application/json');
    $formatted = array_map(fn($m) => [
        'stream_id' => $m['stream_id'] ?? '',
        'name' => $m['name'] ?? '',
        'stream_icon' => $m['stream_icon'] ?? '',
        'year' => $m['year'] ?? '',
        'rating' => $m['rating'] ?? '',
        'genre' => $m['genre'] ?? '',
        'container_extension' => $m['container_extension'] ?? 'mp4'
    ], $movies);
    echo json_encode(['movies' => $formatted, 'hasMore' => $has_more, 'page' => $page]);
    exit;
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Películas - JTECH TV</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, sans-serif;
            background: #0f171e;
            color: #fff;
            overflow-x: hidden;
        }

        /* BANNER estilo Netflix */
        .banner {
            position: relative;
            height: 50vh;
            min-height: 400px;
            overflow: hidden;
        }

        .banner-slide {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            opacity: 0;
            transition: opacity 2s ease;
        }

        .banner-slide.active {
            opacity: 1;
        }

        .banner-bg {
            width: 100%;
            height: 100%;
            background-size: cover;
            background-position: center;
            background-repeat: no-repeat;
            filter: brightness(0.4);
        }

        .banner-overlay {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, 
                rgba(15,23,30,0.9) 0%, 
                rgba(15,23,30,0.7) 25%, 
                rgba(15,23,30,0.4) 50%, 
                transparent 100%);
            z-index: 5;
        }

        .banner-overlay::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 0;
            width: 100%;
            height: 30%;
            background: linear-gradient(to top, rgba(15,23,30,1) 0%, transparent 100%);
        }

        .banner-content {
            position: absolute;
            left: 5%;
            bottom: 15%;
            max-width: 50%;
            z-index: 10;
        }

        .banner-title {
            font-size: 2.5rem;
            font-weight: 700;
            margin-bottom: 10px;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.8);
        }

        .banner-meta {
            display: flex;
            gap: 15px;
            margin-bottom: 15px;
            flex-wrap: wrap;
        }

        .meta-item {
            background: rgba(0,0,0,0.6);
            padding: 5px 10px;
            border-radius: 4px;
            font-size: 0.8rem;
            font-weight: 600;
        }

        .rating {
            background: #ffa500;
            color: #000;
        }

        .banner-description {
            font-size: 1rem;
            line-height: 1.5;
            margin-bottom: 20px;
            color: rgba(255,255,255,0.9);
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
        }

        .banner-buttons {
            display: flex;
            gap: 15px;
        }

        .btn {
            padding: 10px 25px;
            border: none;
            border-radius: 6px;
            font-size: 0.9rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .btn-play {
            background: #fff;
            color: #000;
        }

        .btn-play:hover {
            background: #f0f0f0;
        }

        .btn-info {
            background: rgba(255,255,255,0.2);
            color: #fff;
            border: 1px solid rgba(255,255,255,0.4);
        }

        .btn-info:hover {
            background: rgba(255,255,255,0.3);
        }

        .banner-dots {
            position: absolute;
            bottom: 20px;
            left: 5%;
            display: flex;
            gap: 8px;
            z-index: 15;
        }

        .dot {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background: rgba(255,255,255,0.4);
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .dot.active {
            background: #E50914;
            width: 20px;
            border-radius: 10px;
        }

        /* FILTROS FLOTANTES */
        .filters-floating {
            position: fixed;
            top: 90px;
            right: 4%;
            z-index: 900;
            transition: all 0.3s ease;
        }

        .filters-trigger {
            background: rgba(20, 20, 20, 0.9);
            color: white;
            border: 1px solid rgba(255, 255, 255, 0.2);
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 10px;
            backdrop-filter: blur(10px);
        }

        .filters-trigger:hover {
            background: rgba(40, 40, 40, 1);
            border-color: #E50914;
        }

        .filters-panel {
            display: none;
            position: absolute;
            top: 45px;
            right: 0;
            background: rgba(20, 20, 20, 0.98);
            border: 1px solid #333;
            padding: 20px;
            border-radius: 8px;
            width: 250px;
            box-shadow: -5px 10px 25px rgba(0,0,0,0.7);
        }

        .filters-panel.active {
            display: block;
            animation: fadeInRight 0.2s ease-out;
        }

        @keyframes fadeInRight {
            from { opacity: 0; transform: translateX(10px); }
            to { opacity: 1; transform: translateX(0); }
        }

        .btn-sort {
            background: #222;
            color: white;
            border: 1px solid #333;
            padding: 10px;
            border-radius: 4px;
            cursor: pointer;
            text-align: left;
            transition: 0.3s;
            font-size: 13px;
            width: 100%;
            margin-bottom: 8px;
        }

        .btn-sort:hover {
            background: #E50914;
            border-color: #E50914;
        }

        /* GRID DE PELÍCULAS estilo series */
        .movies-section {
            padding: 30px 5%;
        }

        .section-title {
            font-size: 1.3rem;
            font-weight: 600;
            margin-bottom: 20px;
            color: #e5e5e5;
        }

        .movies-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
            gap: 20px;
        }

        .movie-card {
            position: relative;
            border-radius: 8px;
            overflow: hidden;
            cursor: pointer;
            transition: all 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94);
            background: transparent;
        }

        .movie-card:hover {
            transform: scale(1.05);
            z-index: 10;
        }

        .movie-poster {
            position: relative;
            width: 100%;
            height: 270px;
            overflow: hidden;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.3);
        }

        .movie-poster img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            transition: all 0.4s ease;
        }

        .movie-card:hover .movie-poster img {
            transform: scale(1.1);
            filter: brightness(0.7);
        }

        .movie-overlay {
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            background: linear-gradient(to top, 
                rgba(0,0,0,0.9) 0%, 
                rgba(0,0,0,0.7) 40%, 
                transparent 100%);
            padding: 15px 12px 12px;
            transform: translateY(100%);
            transition: all 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94);
        }

        .movie-card:hover .movie-overlay {
            transform: translateY(0);
        }

        .movie-title {
            font-size: 0.9rem;
            font-weight: 700;
            margin-bottom: 6px;
            color: #fff;
            line-height: 1.2;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
        }

        .movie-quick-info {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 8px;
        }

        .movie-year {
            color: rgba(255,255,255,0.8);
            font-size: 0.75rem;
            font-weight: 500;
        }

        .movie-rating {
            background: rgba(255,193,7,0.9);
            color: #000;
            padding: 2px 6px;
            border-radius: 10px;
            font-size: 0.7rem;
            font-weight: 700;
        }

        .movie-genre {
            color: rgba(255,255,255,0.7);
            font-size: 0.7rem;
            font-weight: 500;
        }

        .quality-badge {
            position: absolute;
            top: 8px;
            left: 8px;
            background: rgba(0,0,0,0.8);
            backdrop-filter: blur(4px);
            color: #fff;
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 0.65rem;
            font-weight: 600;
            text-transform: uppercase;
            border: 1px solid rgba(255,255,255,0.2);
        }

        .duration-badge {
            position: absolute;
            top: 8px;
            right: 8px;
            background: rgba(0,0,0,0.8);
            backdrop-filter: blur(4px);
            color: #fff;
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 0.65rem;
            font-weight: 500;
            border: 1px solid rgba(255,255,255,0.2);
        }

        .play-button {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 50px;
            height: 50px;
            background: rgba(255,255,255,0.9);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            opacity: 0;
            transition: all 0.3s ease;
            cursor: pointer;
        }

        .play-button i {
            color: #000;
            font-size: 1.2rem;
            margin-left: 2px;
        }

        .movie-card:hover .play-button {
            opacity: 1;
            transform: translate(-50%, -50%) scale(1.1);
        }

        .play-button:hover {
            background: #fff;
            transform: translate(-50%, -50%) scale(1.2) !important;
        }

        .loading {
            text-align: center;
            padding: 40px;
            color: #999;
        }

        @media (max-width: 768px) {
            .banner { height: 40vh; min-height: 300px; }
            .banner-title { font-size: 1.8rem; }
            .banner-content { max-width: 85%; bottom: 10%; }
            .movies-grid { grid-template-columns: repeat(auto-fill, minmax(140px, 1fr)); gap: 12px; }
            .movie-poster { height: 210px; }
            .filters-floating { top: 80px; right: 2%; }
            .section-title { font-size: 1.1rem; }
        }

        @media (max-width: 480px) {
            .movies-grid { grid-template-columns: repeat(auto-fill, minmax(120px, 1fr)); gap: 10px; }
            .movie-poster { height: 180px; }
            .movie-title { font-size: 0.75rem; }
        }
    </style>
</head>
<body>
<?php include 'header.php'; ?>

<!-- FILTROS FLOTANTES -->
<div class="filters-floating" id="filtersFloating">
    <button class="filters-trigger" onclick="toggleFilters()">
        <i class="fas fa-sort-amount-down"></i> Filtrar Contenido
    </button>
    
    <div class="filters-panel" id="filtersPanel">
        <h4 style="margin-bottom:12px; color: #E50914; font-size: 13px; text-transform: uppercase; letter-spacing: 1px;">Categorías</h4>
        <select onchange="filterCategory(this.value)" style="width:100%; padding:10px; background:#000; border:1px solid #444; color:white; border-radius:4px; margin-bottom:20px; cursor:pointer;">
            <option value="">Todas las categorías</option>
            <?php foreach($categories as $cat): ?>
                <option value="<?= $cat['category_id'] ?>" <?= $selected_category == $cat['category_id'] ? 'selected' : '' ?>>
                    <?= htmlspecialchars($cat['category_name']) ?>
                </option>
            <?php endforeach; ?>
        </select>

        <h4 style="margin-bottom:12px; color: #E50914; font-size: 13px; text-transform: uppercase; letter-spacing: 1px;">Ordenar por</h4>
        <div>
            <button onclick="sortMovies('recent')" class="btn-sort"><i class="fas fa-history" style="width:20px"></i> Más Recientes</button>
            <button onclick="sortMovies('name_asc')" class="btn-sort"><i class="fas fa-font" style="width:20px"></i> Alfabético (A-Z)</button>
            <button onclick="sortMovies('rating')" class="btn-sort"><i class="fas fa-star" style="width:20px"></i> Populares</button>
        </div>
    </div>
</div>

<div class="main-content">
    <!-- BANNER -->
    <?php if (!empty($featured_movies)): ?>
    <div class="banner">
        <?php foreach ($featured_movies as $index => $movie): ?>
        <div class="banner-slide <?= $index === 0 ? 'active' : '' ?>">
            <div class="banner-bg" style="background-image: url('<?= htmlspecialchars($movie['backdrop_url']) ?>');"></div>
            <div class="banner-overlay"></div>
            
            <div class="banner-content">
                <h1 class="banner-title"><?= htmlspecialchars($movie['name']) ?></h1>
                
                <div class="banner-meta">
                    <?php if (!empty($movie['rating'])): ?>
                    <span class="meta-item rating">★ <?= number_format(floatval($movie['rating']), 1) ?></span>
                    <?php endif; ?>
                    
                    <?php if (!empty($movie['year'])): ?>
                    <span class="meta-item"><?= htmlspecialchars($movie['year']) ?></span>
                    <?php endif; ?>
                    
                    <?php if (!empty($movie['genre'])): ?>
                    <span class="meta-item"><?= htmlspecialchars($movie['genre']) ?></span>
                    <?php endif; ?>
                </div>
                
                <p class="banner-description">
                    <?= htmlspecialchars(substr($movie['plot'], 0, 120)) ?>...
                </p>
                
                <div class="banner-buttons">
                    <button class="btn btn-play" onclick="playMovie('<?= $movie['stream_id'] ?>', '<?= $movie['container_extension'] ?>')">
                        <i class="fas fa-play"></i> Reproducir
                    </button>
                    <button class="btn btn-info" onclick="openMovie('<?= $movie['stream_id'] ?>')">
                        <i class="fas fa-info-circle"></i> Más Información
                    </button>
                </div>
            </div>
        </div>
        <?php endforeach; ?>

        <?php if (count($featured_movies) > 1): ?>
        <div class="banner-dots">
            <?php for($i = 0; $i < count($featured_movies); $i++): ?>
            <div class="dot <?= $i === 0 ? 'active' : '' ?>" onclick="goToSlide(<?= $i ?>)"></div>
            <?php endfor; ?>
        </div>
        <?php endif; ?>
    </div>
    <?php endif; ?>

    <!-- GRID DE PELÍCULAS -->
    <section class="movies-section">
        <h2 class="section-title">🎬 Películas Destacadas</h2>
        <div class="movies-grid" id="moviesGrid">
            <?php foreach ($movies as $movie): ?>
            <div class="movie-card" onclick="openMovie('<?= $movie['stream_id'] ?>')">
                <div class="movie-poster">
                    <img src="<?= htmlspecialchars($movie['stream_icon']) ?>" 
                         alt="<?= htmlspecialchars($movie['name']) ?>"
                         loading="lazy"
                         onerror="this.src='https://via.placeholder.com/300x450/1a252f/E50914?text=No+Image'">
                    
                    <div class="quality-badge">PELÍCULA</div>
                    
                    <?php if (!empty($movie['duration'])): ?>
                    <div class="duration-badge"><?= htmlspecialchars($movie['duration']) ?></div>
                    <?php endif; ?>
                    
                    <div class="play-button" onclick="event.stopPropagation(); playMovie('<?= $movie['stream_id'] ?>', '<?= $movie['container_extension'] ?? 'mp4' ?>')">
                        <i class="fas fa-play"></i>
                    </div>
                    
                    <div class="movie-overlay">
                        <div class="movie-title"><?= htmlspecialchars($movie['name']) ?></div>
                        <div class="movie-quick-info">
                            <span class="movie-year"><?= !empty($movie['year']) ? htmlspecialchars($movie['year']) : 'N/A' ?></span>
                            <?php 
                            $rating = $movie['rating'] ?? '';
                            if ($rating && $rating != '0'): ?>
                            <span class="movie-rating">★ <?= number_format(floatval($rating), 1) ?></span>
                            <?php endif; ?>
                        </div>
                        <?php if (!empty($movie['genre'])): ?>
                        <div class="movie-genre"><?= htmlspecialchars($movie['genre']) ?></div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
        
        <?php if ($has_more): ?>
        <div class="loading" id="loading">
            <i class="fas fa-spinner fa-spin"></i> Cargando más películas...
        </div>
        <?php endif; ?>
    </section>
</div>

<script>
    // Variables globales
    let currentSlide = 0;
    let currentPage = <?= $page ?>;
    let hasMore = <?= $has_more ? 'true' : 'false' ?>;
    let isLoading = false;
    let selectedCategory = <?= json_encode($selected_category) ?>;
    let sortOrder = <?= json_encode($sort_order) ?>;
    
    const slides = document.querySelectorAll('.banner-slide');
    const dots = document.querySelectorAll('.dot');
    
    // Funciones del banner
    function goToSlide(index) {
        if (slides.length === 0) return;
        if (slides[currentSlide]) slides[currentSlide].classList.remove('active');
        if (dots[currentSlide]) dots[currentSlide].classList.remove('active');
        
        currentSlide = index;
        
        if (slides[currentSlide]) slides[currentSlide].classList.add('active');
        if (dots[currentSlide]) dots[currentSlide].classList.add('active');
    }
    
    function playMovie(id, ext) {
        window.location.href = `player.php?id=${id}&slug=movie&ext=${ext}`;
    }
    
    function openMovie(id) {
        window.location.href = `movie-detail.php?id=${id}`;
    }
    
    function filterCategory(catId) {
        let url = 'movies.php';
        let params = [];
        if (catId) params.push(`cat=${catId}`);
        if (sortOrder) params.push(`sort=${sortOrder}`);
        if (params.length > 0) url += '?' + params.join('&');
        window.location.href = url;
    }
    
    function sortMovies(sort) {
        let url = 'movies.php';
        let params = [];
        if (selectedCategory) params.push(`cat=${selectedCategory}`);
        if (sort) params.push(`sort=${sort}`);
        if (params.length > 0) url += '?' + params.join('&');
        window.location.href = url;
    }
    
    function toggleFilters() {
        const panel = document.getElementById('filtersPanel');
        panel.classList.toggle('active');
    }
    
    // Cerrar filtros al hacer click fuera
    document.addEventListener('click', function(e) {
        const container = document.getElementById('filtersFloating');
        if (container && !container.contains(e.target)) {
            const panel = document.getElementById('filtersPanel');
            if (panel) panel.classList.remove('active');
        }
    });
    
    // Auto-slide del banner
    if (slides.length > 1) {
        setInterval(() => {
            goToSlide((currentSlide + 1) % slides.length);
        }, 7000);
    }
    
    // Scroll infinito
    function loadMoreMovies() {
        if (isLoading || !hasMore) return;
        
        isLoading = true;
        const loadingDiv = document.getElementById('loading');
        if (loadingDiv) loadingDiv.style.display = 'block';
        
        fetch(`movies.php?page=${currentPage + 1}&ajax=1${selectedCategory ? '&cat=' + selectedCategory : ''}${sortOrder ? '&sort=' + sortOrder : ''}`)
            .then(response => response.json())
            .then(data => {
                const grid = document.getElementById('moviesGrid');
                if (data.movies && data.movies.length > 0) {
                    data.movies.forEach(movie => {
                        const rating = movie.rating || '';
                        const card = document.createElement('div');
                        card.className = 'movie-card';
                        card.onclick = () => openMovie(movie.stream_id);
                        card.innerHTML = `
                            <div class="movie-poster">
                                <img src="${movie.stream_icon}" alt="${escapeHtml(movie.name)}" loading="lazy" onerror="this.src='https://via.placeholder.com/300x450/1a252f/E50914?text=No+Image'">
                                <div class="quality-badge">PELÍCULA</div>
                                ${movie.duration ? `<div class="duration-badge">${movie.duration}</div>` : ''}
                                <div class="play-button" onclick="event.stopPropagation(); playMovie('${movie.stream_id}', '${movie.container_extension || 'mp4'}')">
                                    <i class="fas fa-play"></i>
                                </div>
                                <div class="movie-overlay">
                                    <div class="movie-title">${escapeHtml(movie.name)}</div>
                                    <div class="movie-quick-info">
                                        <span class="movie-year">${movie.year || 'N/A'}</span>
                                        ${rating ? `<span class="movie-rating">★ ${parseFloat(rating).toFixed(1)}</span>` : ''}
                                    </div>
                                    ${movie.genre ? `<div class="movie-genre">${escapeHtml(movie.genre)}</div>` : ''}
                                </div>
                            </div>
                        `;
                        grid.appendChild(card);
                    });
                }
                currentPage++;
                hasMore = data.hasMore;
                isLoading = false;
                if (loadingDiv) loadingDiv.style.display = hasMore ? 'block' : 'none';
            })
            .catch(error => {
                console.error('Error loading more movies:', error);
                isLoading = false;
                const loadingDiv = document.getElementById('loading');
                if (loadingDiv) loadingDiv.style.display = 'none';
            });
    }
    
    function escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
    
    // Intersection Observer para scroll infinito
    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting && hasMore && !isLoading) {
                loadMoreMovies();
            }
        });
    }, { threshold: 0.1 });
    
    const loadingDiv = document.getElementById('loading');
    if (loadingDiv) observer.observe(loadingDiv);
    
    // Header scroll effect
    window.addEventListener('scroll', () => {
        const header = document.getElementById('netflixHeader');
        if (window.scrollY > 50) {
            if (header) header.style.background = 'rgba(0, 0, 0, 0.95)';
        } else {
            if (header) header.style.background = 'linear-gradient(to bottom, rgba(0,0,0,0.95) 0%, rgba(0,0,0,0.85) 100%)';
        }
    });
</script>
</body>
</html>