<?php
$id = $_GET['id'] ?? '';
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Cinema México | Ficha técnica</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="assets/css/cinema.css">
   
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css">
</head>
<body class="cm-movie-page">
<main id="detailContainer" class="cm-movie-shell">
    <div class="cm-movie-loading">
        <span class="cm-loading-spinner"></span>
        Cargando ficha técnica...
    </div>
</main>

<script>
const id = <?= json_encode($id) ?>;
const API_URL = `../api/index.php?r=peliculas&id=${encodeURIComponent(id)}`;
let images = [];
let currentImage = 0;

async function loadDetail() {
    const container = document.getElementById('detailContainer');
    try {
        const response = await fetch(API_URL);
        if (!response.ok) throw new Error(`Error HTTP: ${response.status}`);
        const json = await response.json();
        if (!json.success) throw new Error(json.message || 'No se pudo cargar la película');

        images = (json.data.imagenes || []).filter(item => item && item.url);
        renderDetail(json.data.pelicula);
    } catch (error) {
        console.error(error);
        container.innerHTML = `
            <div class="cm-movie-error">
                <i class="fa-solid fa-triangle-exclamation"></i>
                <h2>No pudimos cargar esta película</h2>
                <p>${escapeHtml(error.message)}</p>
                <a href="javascript:history.back()"><i class="fa-solid fa-arrow-left"></i> Regresar</a>
            </div>`;
    }
}

function renderDetail(p) {
    const container = document.getElementById('detailContainer');
    const title = p.titulo_espanol || p.titulo_original || 'Sin título';
    const originalTitle = p.titulo_original && p.titulo_original !== title ? p.titulo_original : '';
    const englishTitle = p.titulo_ingles && p.titulo_ingles !== title ? p.titulo_ingles : '';
    const firstImage = images.length ? images[0].url : '';
    const meta = [p.tipo_produccion, p.genero, p.pais, p.anio].filter(Boolean);

    container.innerHTML = `
        <section class="cm-movie-hero" ${firstImage ? `style="--cm-hero-image:url('${safeCssUrl(firstImage)}')"` : ''}>
            <div class="cm-movie-hero-overlay"></div>
            <nav class="cm-movie-nav">
                <a href="index.php" class="cm-movie-brand"><i class="fa-solid fa-film"></i><span>Cinema<br>México</span></a>
                <a href="javascript:history.back()" class="cm-movie-back"><i class="fa-solid fa-arrow-left"></i> Volver al catálogo</a>
            </nav>

            <div class="cm-movie-intro">
                <div class="cm-movie-kicker">${meta.map(escapeHtml).join('<span>•</span>')}</div>
                <h1>${escapeHtml(title)}</h1>
                ${originalTitle ? `<p class="cm-movie-original">Título original: ${escapeHtml(originalTitle)}</p>` : ''}
                ${englishTitle ? `<p class="cm-movie-original">${escapeHtml(englishTitle)}</p>` : ''}
                <div class="cm-movie-summary-meta">
                    ${p.duracion ? `<span><i class="fa-regular fa-clock"></i>${escapeHtml(p.duracion)}</span>` : ''}
                    ${p.idioma ? `<span><i class="fa-solid fa-language"></i>${escapeHtml(p.idioma)}</span>` : ''}
                    ${p.direccion ? `<span><i class="fa-solid fa-clapperboard"></i>${escapeHtml(p.direccion)}</span>` : ''}
                </div>
                ${p.sinopsis_espanol ? `<p class="cm-movie-hero-synopsis">${escapeHtml(p.sinopsis_espanol)}</p>` : ''}
                <a href="#ficha-tecnica" class="cm-movie-primary-btn"><i class="fa-solid fa-circle-info"></i> Ver ficha técnica</a>
            </div>
        </section>

        ${renderGallery(title)}

        <section class="cm-movie-content" id="ficha-tecnica">
            <article class="cm-movie-card cm-movie-technical">
                <div class="cm-movie-section-heading">
                    <span>Información de la obra</span>
                    <h2>Ficha técnica</h2>
                </div>
                <div class="cm-movie-fields">
                    ${field('Título original', p.titulo_original, 'fa-heading')}
                    ${field('País', p.pais, 'fa-earth-americas')}
                    ${field('Año', p.anio, 'fa-calendar')}
                    ${field('Duración', p.duracion, 'fa-clock')}
                    ${field('Tipo de producción', p.tipo_produccion, 'fa-film')}
                    ${field('Género', p.genero, 'fa-masks-theater')}
                    ${field('Idioma', p.idioma, 'fa-language')}
                    ${field('Locación', p.locacion, 'fa-location-dot')}
                    ${field('Dirección', p.direccion, 'fa-clapperboard')}
                    ${field('Producción', p.produccion, 'fa-briefcase')}
                    ${field('Guion', p.guion, 'fa-pen-nib')}
                    ${field('Cinematografía', p.cinematografia, 'fa-camera')}
                    ${field('Edición', p.edicion, 'fa-scissors')}
                    ${field('Sonido', p.sonido, 'fa-volume-high')}
                    ${field('Música', p.musica, 'fa-music')}
                    ${field('Dirección de arte', p.direccion_arte, 'fa-palette')}
                    ${field('Animación', p.animacion, 'fa-wand-magic-sparkles')}
                    ${field('Compañía productora', p.compania_productora, 'fa-building')}
                    ${field('Apoyos', p.apoyos, 'fa-handshake-angle')}
                    ${field('Contacto', p.contacto, 'fa-address-card')}
                </div>
            </article>

            <aside class="cm-movie-side">
                <article class="cm-movie-card">
                    <div class="cm-movie-section-heading">
                        <span>Historia</span>
                        <h2>Sinopsis</h2>
                    </div>
                    <div class="cm-movie-synopsis-copy">
                        ${p.sinopsis_espanol ? `<p>${formatText(p.sinopsis_espanol)}</p>` : '<p class="cm-movie-muted">Sinopsis no disponible.</p>'}
                        ${p.sinopsis_ingles ? `<div class="cm-movie-language-divider"><span>English synopsis</span></div><p class="cm-movie-english">${formatText(p.sinopsis_ingles)}</p>` : ''}
                    </div>
                </article>

                ${p.reparto ? `
                <article class="cm-movie-card cm-movie-cast">
                    <div class="cm-movie-section-heading">
                        <span>Créditos</span>
                        <h2>Reparto</h2>
                    </div>
                    <p>${formatText(p.reparto)}</p>
                </article>` : ''}
            </aside>
        </section>

        <footer class="cm-movie-footer">
            <span>Cinema México</span>
            <a href="peliculas.php">Explorar más películas <i class="fa-solid fa-arrow-right"></i></a>
        </footer>`;
}

function renderGallery(title) {
    if (!images.length) return '';
    const thumbs = images.map((image, index) => `
        <button class="cm-movie-thumb ${index === 0 ? 'active' : ''}" data-index="${index}" onclick="selectImage(${index})" aria-label="Ver imagen ${index + 1}">
            <img src="${escapeHtml(image.url)}" alt="${escapeHtml(image.pie || title)}" loading="lazy" onerror="this.closest('button').style.display='none'">
        </button>`).join('');

    return `
        <section class="cm-movie-gallery">
            <div class="cm-movie-gallery-head">
                <div><span>Material visual</span><h2>Galería de imágenes</h2></div>
                <div class="cm-movie-counter"><strong id="imageCurrent">01</strong> / ${String(images.length).padStart(2, '0')}</div>
            </div>
            <div class="cm-movie-gallery-stage">
                ${images.length > 1 ? `<button class="cm-movie-gallery-arrow prev" onclick="prevImage()" aria-label="Imagen anterior"><i class="fa-solid fa-chevron-left"></i></button>` : ''}
                <img id="mainGalleryImage" src="${escapeHtml(images[0].url)}" alt="${escapeHtml(title)}">
                ${images.length > 1 ? `<button class="cm-movie-gallery-arrow next" onclick="nextImage()" aria-label="Imagen siguiente"><i class="fa-solid fa-chevron-right"></i></button>` : ''}
                <div class="cm-movie-gallery-caption" id="galleryCaption">${escapeHtml(images[0].pie || images[0].descripcion || '')}</div>
            </div>
            ${images.length > 1 ? `<div class="cm-movie-thumbnails">${thumbs}</div>` : ''}
        </section>`;
}

function field(label, value, icon) {
    if (!value) return '';
    return `<div class="cm-movie-field"><div class="cm-movie-field-icon"><i class="fa-solid ${icon}"></i></div><div><span>${escapeHtml(label)}</span><p>${formatText(value)}</p></div></div>`;
}

function selectImage(index) {
    currentImage = index;
    const image = images[index];
    const main = document.getElementById('mainGalleryImage');
    main.classList.add('changing');
    setTimeout(() => {
        main.src = image.url;
        main.alt = image.pie || image.descripcion || '';
        document.getElementById('galleryCaption').textContent = image.pie || image.descripcion || '';
        document.getElementById('imageCurrent').textContent = String(index + 1).padStart(2, '0');
        document.querySelectorAll('.cm-movie-thumb').forEach((thumb, i) => thumb.classList.toggle('active', i === index));
        main.classList.remove('changing');
    }, 130);
}
function prevImage() { if (images.length) selectImage((currentImage - 1 + images.length) % images.length); }
function nextImage() { if (images.length) selectImage((currentImage + 1) % images.length); }

function formatText(value) {
    return escapeHtml(value).replace(/\r?\n/g, '<br>');
}
function safeCssUrl(value) {
    return String(value).replace(/["'()\\]/g, '\\$&');
}
function escapeHtml(value) {
    if (value === null || value === undefined) return '';
    return String(value).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#039;');
}

document.addEventListener('keydown', e => {
    if (e.key === 'ArrowLeft') prevImage();
    if (e.key === 'ArrowRight') nextImage();
});
loadDetail();
</script>
</body>
</html>
