<?php
session_start();

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

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

function makeApiRequest($url, $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, 10);
    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($server_url, 'get_series_categories') ?: [];
$selected_category = $_GET['cat'] ?? '';
$sort_order = $_GET['sort'] ?? '';
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 50;
$offset = ($page - 1) * $limit;

$series = [];
$total_series = 0;
$featured_series = [];

if ($selected_category) {
    $all_series = makeApiRequest($server_url, 'get_series', ['category_id' => $selected_category]) ?: [];
} else {
    $all_series = makeApiRequest($server_url, 'get_series') ?: [];
}

// Banner con backdrop_path real para series
if (!empty($all_series)) {
    $banner_series = $all_series;
    shuffle($banner_series);
    
    $featured_series = [];
    foreach ($banner_series as $serie) {
        if (count($featured_series) >= 10) break;
        
        if (!empty($serie['name']) && !empty($serie['series_id'])) {
            $serie_details = makeApiRequest($server_url, 'get_series_info', ['series_id' => $serie['series_id']]);
            $serie_info = $serie_details['info'] ?? [];
            
            $backdrop_url = '';
            if (!empty($serie_info['backdrop_path'])) {
                if (is_array($serie_info['backdrop_path'])) {
                    $backdrop_url = $serie_info['backdrop_path'][0] ?? '';
                } else {
                    $backdrop_url = $serie_info['backdrop_path'];
                }
            }
            
            if (empty($backdrop_url)) {
                $backdrop_url = $serie_info['cover_big'] ?? $serie_info['cover'] ?? $serie['cover'] ?? '';
            }
            
            if (!empty($backdrop_url)) {
                $featured_series[] = [
                    'series_id' => $serie['series_id'] ?? '',
                    'name' => $serie_info['name'] ?? $serie['name'] ?? '',
                    'backdrop_url' => $backdrop_url,
                    'plot' => $serie_info['plot'] ?? $serie_info['description'] ?? 'Una serie increíble.',
                    'year' => $serie_info['releaseDate'] ? date('Y', strtotime($serie_info['releaseDate'])) : ($serie['year'] ?? ''),
                    'rating' => $serie_info['rating'] ?? $serie['rating'] ?? $serie['tmdb_rating'] ?? '',
                    'genre' => $serie_info['genre'] ?? $serie['genre'] ?? '',
                    'episode_run_time' => $serie_info['episode_run_time'] ?? ''
                ];
            }
        }
    }
}

if (!empty($all_series)) {
    switch ($sort_order) {
        case 'name_asc':
            usort($all_series, function($a, $b) {
                return strcasecmp($a['name'] ?? '', $b['name'] ?? '');
            });
            break;
        case 'name_desc':
            usort($all_series, function($a, $b) {
                return strcasecmp($b['name'] ?? '', $a['name'] ?? '');
            });
            break;
        case 'recent':
            usort($all_series, function($a, $b) {
                $dateA = strtotime($a['last_modified'] ?? $a['added'] ?? '0');
                $dateB = strtotime($b['last_modified'] ?? $b['added'] ?? '0');
                return $dateB - $dateA;
            });
            break;
        case 'rating':
            usort($all_series, function($a, $b) {
                $ratingA = floatval($a['rating'] ?? $a['tmdb_rating'] ?? 0);
                $ratingB = floatval($b['rating'] ?? $b['tmdb_rating'] ?? 0);
                return $ratingB <=> $ratingA;
            });
            break;
    }
}

$total_series = count($all_series);
$series = array_slice($all_series, $offset, $limit);
$has_more = ($offset + $limit) < $total_series;

if (isset($_GET['ajax'])) {
    header('Content-Type: application/json');
    $formatted_series = [];
    foreach ($series as $serie) {
        $formatted_series[] = [
            'series_id' => $serie['series_id'] ?? '',
            'name' => $serie['name'] ?? '',
            'cover' => $serie['cover'] ?? '',
            'year' => $serie['year'] ?? '',
            'rating' => $serie['rating'] ?? '',
            'tmdb_rating' => $serie['tmdb_rating'] ?? '',
            'genre' => $serie['genre'] ?? '',
            'plot' => $serie['plot'] ?? '',
            'episode_run_time' => $serie['episode_run_time'] ?? '',
            'last_modified' => $serie['last_modified'] ?? '',
            'added' => $serie['added'] ?? ''
        ];
    }
    echo json_encode(['series' => $formatted_series, '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>Series - 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;
        }

        /* HEADER ESTILO NETFLIX CON BUSCADOR INTEGRADO */
        .netflix-header {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            background: linear-gradient(to bottom, rgba(0,0,0,0.95) 0%, rgba(0,0,0,0.85) 100%);
            z-index: 1000;
            padding: 0 4%;
            transition: all 0.3s ease;
            backdrop-filter: blur(10px);
        }

        .header-container {
            display: flex;
            align-items: center;
            justify-content: space-between;
            height: 70px;
        }

        .logo-area {
            display: flex;
            align-items: center;
            gap: 40px;
            flex: 1;
        }

        .logo-text {
            font-size: 1.8rem;
            font-weight: 800;
            background: linear-gradient(135deg, #E50914 0%, #ff4d4d 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
            letter-spacing: -0.5px;
        }

        .nav-menu {
            display: flex;
            align-items: center;
            gap: 20px;
        }

        .nav-link {
            color: #e5e5e5;
            text-decoration: none;
            font-size: 0.9rem;
            font-weight: 500;
            transition: color 0.3s ease;
        }

        .nav-link:hover, .nav-link.active {
            color: #fff;
        }

        /* SEARCH SECTION - NETFLIX STYLE */
        .search-section {
            margin-left: 20px;
        }

        .search-container {
            position: relative;
        }

        .search-wrapper {
            position: relative;
            display: flex;
            align-items: center;
        }

        .search-box {
            width: 250px;
            padding: 8px 35px 8px 40px;
            font-size: 14px;
            background: rgba(0, 0, 0, 0.75);
            border: 1px solid rgba(255, 255, 255, 0.2);
            border-radius: 4px;
            color: white;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        }

        .search-box:focus {
            outline: none;
            width: 350px;
            background: rgba(0, 0, 0, 0.95);
            border-color: #e50914;
            border-width: 2px;
            padding: 7px 34px 7px 39px;
        }

        .search-box::placeholder {
            color: rgba(255, 255, 255, 0.5);
            font-size: 13px;
        }

        .search-icon {
            position: absolute;
            left: 12px;
            top: 50%;
            transform: translateY(-50%);
            color: rgba(255, 255, 255, 0.6);
            font-size: 14px;
            pointer-events: none;
            transition: all 0.3s ease;
        }

        .search-box:focus + .search-icon {
            color: #e50914;
        }

        .search-spinner {
            position: absolute;
            right: 12px;
            top: 50%;
            transform: translateY(-50%);
            color: #e50914;
            font-size: 14px;
            animation: spin 0.6s linear infinite;
        }

        .search-clear-btn {
            position: absolute;
            right: 10px;
            top: 50%;
            transform: translateY(-50%);
            background: none;
            border: none;
            color: rgba(255, 255, 255, 0.5);
            cursor: pointer;
            padding: 4px;
            font-size: 14px;
            transition: all 0.2s ease;
            border-radius: 50%;
        }

        .search-clear-btn:hover {
            color: #e50914;
            transform: translateY(-50%) scale(1.15);
            background: rgba(255, 255, 255, 0.1);
        }

        @keyframes spin {
            0% { transform: translateY(-50%) rotate(0deg); }
            100% { transform: translateY(-50%) rotate(360deg); }
        }

        /* Resultados de búsqueda dropdown */
        .search-results {
            position: absolute;
            top: calc(100% + 5px);
            left: 0;
            right: 0;
            background: rgba(20, 20, 20, 0.98);
            backdrop-filter: blur(10px);
            border-radius: 8px;
            border: 1px solid rgba(255, 255, 255, 0.1);
            max-height: 400px;
            overflow-y: auto;
            z-index: 1000;
            display: none;
        }

        .search-results.show {
            display: block;
            animation: fadeInDown 0.2s ease;
        }

        @keyframes fadeInDown {
            from {
                opacity: 0;
                transform: translateY(-10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .search-result-item {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px 16px;
            cursor: pointer;
            transition: all 0.2s ease;
            border-bottom: 1px solid rgba(255, 255, 255, 0.05);
        }

        .search-result-item:hover {
            background: rgba(229, 9, 20, 0.15);
            padding-left: 20px;
        }

        .result-icon {
            width: 40px;
            height: 40px;
            border-radius: 4px;
            overflow: hidden;
            background: rgba(255, 255, 255, 0.1);
        }

        .result-icon img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .result-info {
            flex: 1;
        }

        .result-title {
            color: white;
            font-size: 14px;
            font-weight: 500;
            margin-bottom: 4px;
        }

        .result-type {
            color: rgba(255, 255, 255, 0.5);
            font-size: 11px;
        }

        /* User Menu */
        .user-menu {
            display: flex;
            align-items: center;
            gap: 20px;
            position: relative;
        }

        .user-avatar {
            display: flex;
            align-items: center;
            gap: 8px;
            cursor: pointer;
            padding: 8px;
            border-radius: 4px;
            transition: background 0.3s ease;
        }

        .user-avatar:hover {
            background: rgba(255, 255, 255, 0.1);
        }

        .avatar-icon {
            width: 32px;
            height: 32px;
            background: #E50914;
            border-radius: 4px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .avatar-name {
            font-size: 0.85rem;
            font-weight: 500;
        }

        .dropdown-menu {
            position: absolute;
            top: 100%;
            right: 0;
            background: rgba(0, 0, 0, 0.95);
            border: 1px solid rgba(255, 255, 255, 0.1);
            border-radius: 8px;
            min-width: 200px;
            padding: 8px 0;
            display: none;
            z-index: 1000;
        }

        .user-menu:hover .dropdown-menu {
            display: block;
        }

        .dropdown-item {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 10px 20px;
            color: #e5e5e5;
            text-decoration: none;
            transition: all 0.2s ease;
        }

        .dropdown-item:hover {
            background: rgba(229, 9, 20, 0.2);
            color: #fff;
        }

        .dropdown-item.logout {
            border-top: 1px solid rgba(255, 255, 255, 0.1);
            margin-top: 8px;
            color: #E50914;
        }

        .hamburger-menu {
            display: none;
        }

        .hamburger-btn {
            background: none;
            border: none;
            cursor: pointer;
            padding: 10px;
        }

        .hamburger-btn span {
            display: block;
            width: 25px;
            height: 2px;
            background: white;
            margin: 5px 0;
            transition: 0.3s;
        }

        .main-content {
            margin-top: 70px;
            background: #0f171e;
        }

        /* BANNER */
        .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%, 
                rgba(15,23,30,0.2) 75%, 
                rgba(15,23,30,0.1) 90%,
                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: 3rem;
            font-weight: 700;
            margin-bottom: 15px;
            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.9rem;
            font-weight: 600;
        }

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

        .banner-description {
            font-size: 1.1rem;
            line-height: 1.5;
            margin-bottom: 20px;
            color: rgba(255,255,255,0.9);
            text-shadow: 1px 1px 2px rgba(0,0,0,0.8);
        }

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

        .btn {
            padding: 12px 25px;
            border: none;
            border-radius: 6px;
            font-size: 1rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            display: 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: 30px;
            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: #fff;
        }

        /* 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);
            transition: all 0.3s ease;
        }

        .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%;
        }

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

        /* GRID DE SERIES */
        .series {
            padding: 30px 5%;
        }

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

        .series-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;
        }

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

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

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

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

        .series-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);
        }

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

        .series-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;
        }

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

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

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

        .series-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;
        }

        .series-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;
        }

        /* RESPONSIVE */
        @media (max-width: 992px) {
            .banner { height: 40vh; min-height: 300px; }
            .banner-title { font-size: 2.5rem; }
            .banner-content { max-width: 70%; }
            .search-box { width: 180px; }
            .search-box:focus { width: 250px; }
        }

        @media (max-width: 768px) {
            .banner { height: 35vh; min-height: 250px; }
            .banner-content { max-width: 85%; left: 20px; bottom: 10%; }
            .banner-title { font-size: 2rem; }
            .nav-menu { display: none; }
            .hamburger-menu { display: block; }
            .search-section { margin-left: auto; }
            .search-box { width: 150px; }
            .search-box:focus { width: 200px; }
            .series-grid { grid-template-columns: repeat(auto-fill, minmax(140px, 1fr)); gap: 10px; }
            .filters-floating { top: 80px; right: 2%; }
        }
    </style>
</head>
<body>
   <?php include 'header.php'; ?>

    <div class="main-content">
        <!-- BANNER -->
        <?php if (!empty($featured_series)): ?>
        <div class="banner">
            <?php foreach ($featured_series as $index => $serie): ?>
            <div class="banner-slide <?= $index === 0 ? 'active' : '' ?>">
                <div class="banner-bg" style="background-image: url('<?= htmlspecialchars($serie['backdrop_url']) ?>');"></div>
                <div class="banner-overlay"></div>
                
                <div class="banner-content">
                    <h1 class="banner-title"><?= htmlspecialchars($serie['name']) ?></h1>
                    
                    <div class="banner-meta">
                        <?php if (!empty($serie['rating'])): ?>
                        <span class="meta-item rating">★ <?= number_format(floatval($serie['rating']), 1) ?></span>
                        <?php endif; ?>
                        
                        <?php if (!empty($serie['year'])): ?>
                        <span class="meta-item"><?= htmlspecialchars($serie['year']) ?></span>
                        <?php endif; ?>
                        
                        <?php if (!empty($serie['genre'])): ?>
                        <span class="meta-item"><?= htmlspecialchars($serie['genre']) ?></span>
                        <?php endif; ?>

                        <?php if (!empty($serie['episode_run_time'])): ?>
                        <span class="meta-item"><?= htmlspecialchars($serie['episode_run_time']) ?> min/ep</span>
                        <?php endif; ?>
                    </div>
                    
                    <p class="banner-description">
                        <?= htmlspecialchars(substr($serie['plot'], 0, 150)) ?>...
                    </p>
                    
                    <div class="banner-buttons">
                        <button class="btn btn-play" onclick="openSeries('<?= $serie['series_id'] ?>')">
                            <i class="fas fa-play"></i> Ver Serie
                        </button>
                        <button class="btn btn-info" onclick="openSeries('<?= $serie['series_id'] ?>')">
                            <i class="fas fa-info-circle"></i> Más Info
                        </button>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>

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

        <!-- 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' : '' ?>>
                            <?= $cat['category_name'] ?>
                        </option>
                    <?php endforeach; ?>
                </select>

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

        <!-- SERIES -->
        <div class="series">
            <div class="series-grid" id="seriesGrid">
                <?php foreach ($series as $serie): ?>
                <div class="series-card" onclick="openSeries(<?= $serie['series_id'] ?>)">
                    <div class="series-poster">
                        <?php if (!empty($serie['cover'])): ?>
                            <img src="<?= htmlspecialchars($serie['cover']) ?>" 
                                 alt="<?= htmlspecialchars($serie['name']) ?>"
                                 onerror="this.style.display='none';">
                        <?php endif; ?>

                        <div class="quality-badge">SERIE</div>

                        <?php if (!empty($serie['episode_run_time'])): ?>
                            <div class="duration-badge"><?= htmlspecialchars($serie['episode_run_time']) ?> min</div>
                        <?php endif; ?>

                        <div class="play-button" onclick="event.stopPropagation(); openSeries('<?= $serie['series_id'] ?>')">
                            <i class="fas fa-play"></i>
                        </div>

                        <div class="series-overlay">
                            <div class="series-title"><?= htmlspecialchars($serie['name']) ?></div>
                            
                            <div class="series-quick-info">
                                <span class="series-year"><?= !empty($serie['year']) ? htmlspecialchars($serie['year']) : 'N/A' ?></span>
                                
                                <?php 
                                $rating = $serie['rating'] ?? $serie['tmdb_rating'] ?? '';
                                if ($rating && $rating != '0'): ?>
                                <span class="series-rating">★ <?= number_format(floatval($rating), 1) ?></span>
                                <?php endif; ?>
                            </div>

                            <?php if (!empty($serie['genre'])): ?>
                            <div class="series-genre"><?= htmlspecialchars($serie['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 series...
            </div>
            <?php endif; ?>
        </div>
    </div>

    <script>
        // Variables globales
        let currentSlide = 0;
        let currentPage = <?= $page ?>;
        let hasMore = <?= $has_more ? 'true' : 'false' ?>;
        let loading = false;
        const featuredSeries = <?= json_encode($featured_series) ?>;
        const selectedCategory = <?= !empty($selected_category) ? "'" . addslashes($selected_category) . "'" : 'null' ?>;
        const sortOrder = <?= !empty($sort_order) ? "'" . addslashes($sort_order) . "'" : 'null' ?>;
        
        // Variables para búsqueda global
        let searchTimeout;
        const searchInput = document.getElementById('globalSearchInput');
        const searchResults = document.getElementById('globalSearchResults');
        const searchSpinner = document.getElementById('globalSearchSpinner');
        const searchClear = document.getElementById('globalSearchClear');

        // Funciones del banner
        function goToSlide(index) {
            const slides = document.querySelectorAll('.banner-slide');
            const dots = document.querySelectorAll('.dot');
            
            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 openSeries(seriesId) {
            window.location.href = `series-detail.php?id=${seriesId}`;
        }

        function filterCategory(categoryId) {
            let url = 'series.php';
            let params = [];
            if (categoryId) params.push(`cat=${categoryId}`);
            if (sortOrder) params.push(`sort=${sortOrder}`);
            if (params.length > 0) url += '?' + params.join('&');
            window.location.href = url;
        }

        function sortSeries(sort) {
            let url = 'series.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 (featuredSeries && featuredSeries.length > 1) {
            setInterval(() => {
                goToSlide((currentSlide + 1) % featuredSeries.length);
            }, 8000);
        }

        // ==================== BUSCADOR GLOBAL NETFLIX STYLE ====================
        function toggleClearButton() {
            if (searchClear) {
                searchClear.style.display = searchInput.value.length > 0 ? 'block' : 'none';
            }
        }

        if (searchClear) {
            searchClear.addEventListener('click', function() {
                searchInput.value = '';
                searchInput.focus();
                toggleClearButton();
                searchResults.classList.remove('show');
                searchResults.innerHTML = '';
            });
        }

        searchInput.addEventListener('input', function() {
            toggleClearButton();
            const query = this.value.trim();
            
            clearTimeout(searchTimeout);
            
            if (query.length >= 2) {
                if (searchSpinner) searchSpinner.style.display = 'block';
                
                searchTimeout = setTimeout(() => {
                    performGlobalSearch(query);
                }, 500);
            } else {
                if (searchSpinner) searchSpinner.style.display = 'none';
                searchResults.classList.remove('show');
                searchResults.innerHTML = '';
            }
        });

        function performGlobalSearch(query) {
            fetch(`search_series_ajax.php?q=${encodeURIComponent(query)}`)
                .then(response => response.json())
                .then(data => {
                    if (searchSpinner) searchSpinner.style.display = 'none';
                    
                    if (data.results && data.results.length > 0) {
                        let html = '';
                        data.results.forEach(item => {
                            html += `
                                <div class="search-result-item" onclick="openSeries('${item.series_id}')">
                                    <div class="result-icon">
                                        ${item.cover ? `<img src="${item.cover}" alt="${item.name}">` : '<i class="fas fa-tv" style="width:100%;height:100%;display:flex;align-items:center;justify-content:center;"></i>'}
                                    </div>
                                    <div class="result-info">
                                        <div class="result-title">${escapeHtml(item.name)}</div>
                                        <div class="result-type">${item.year ? item.year + ' • ' : ''}Serie</div>
                                    </div>
                                </div>
                            `;
                        });
                        searchResults.innerHTML = html;
                        searchResults.classList.add('show');
                    } else {
                        searchResults.innerHTML = '<div class="search-result-item" style="justify-content:center;"><div class="result-info">No se encontraron resultados</div></div>';
                        searchResults.classList.add('show');
                    }
                })
                .catch(error => {
                    console.error('Error en búsqueda:', error);
                    if (searchSpinner) searchSpinner.style.display = 'none';
                });
        }

        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }

        // Cerrar resultados al hacer click fuera
        document.addEventListener('click', function(e) {
            if (!searchResults.contains(e.target) && e.target !== searchInput) {
                searchResults.classList.remove('show');
            }
        });

        // Scroll infinito
        window.addEventListener('scroll', () => {
            if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight - 500 && hasMore && !loading) {
                loading = true;
                const loadingDiv = document.getElementById('loading');
                if (loadingDiv) loadingDiv.style.display = 'block';
                
                fetch(`series.php?page=${currentPage + 1}&ajax=1${selectedCategory ? '&cat=' + selectedCategory : ''}${sortOrder ? '&sort=' + sortOrder : ''}`)
                    .then(response => response.json())
                    .then(data => {
                        const grid = document.getElementById('seriesGrid');
                        data.series.forEach(serie => {
                            const card = document.createElement('div');
                            card.className = 'series-card';
                            card.onclick = () => openSeries(serie.series_id);
                            
                            const rating = serie.rating || serie.tmdb_rating || '';
                            
                            card.innerHTML = `
                                <div class="series-poster">
                                    ${serie.cover ? 
                                        `<img src="${serie.cover}" alt="${serie.name}" onerror="this.style.display='none';">` : ''
                                    }
                                    
                                    <div class="quality-badge">SERIE</div>
                                    ${serie.episode_run_time ? `<div class="duration-badge">${serie.episode_run_time} min</div>` : ''}
                                    
                                    <div class="play-button" onclick="event.stopPropagation(); openSeries('${serie.series_id}')">
                                        <i class="fas fa-play"></i>
                                    </div>

                                    <div class="series-overlay">
                                        <div class="series-title">${escapeHtml(serie.name)}</div>
                                        
                                        <div class="series-quick-info">
                                            <span class="series-year">${serie.year || 'N/A'}</span>
                                            ${rating ? `<span class="series-rating">★ ${parseFloat(rating).toFixed(1)}</span>` : ''}
                                        </div>

                                        ${serie.genre ? `<div class="series-genre">${escapeHtml(serie.genre)}</div>` : ''}
                                    </div>
                                </div>
                            `;
                            grid.appendChild(card);
                        });
                        currentPage++;
                        hasMore = data.hasMore;
                        loading = false;
                        if (loadingDiv) loadingDiv.style.display = hasMore ? 'block' : 'none';
                    })
                    .catch(error => {
                        console.error('Error loading more series:', error);
                        loading = false;
                        const loadingDiv = document.getElementById('loading');
                        if (loadingDiv) loadingDiv.style.display = 'none';
                    });
            }
        });

        // Header scroll effect
        window.addEventListener('scroll', () => {
            const header = document.getElementById('netflixHeader');
            if (window.scrollY > 50) {
                header.style.background = 'rgba(0, 0, 0, 0.95)';
                header.style.backdropFilter = 'blur(10px)';
            } else {
                header.style.background = 'linear-gradient(to bottom, rgba(0,0,0,0.95) 0%, rgba(0,0,0,0.85) 100%)';
            }
        });
    </script>
</body>
</html>