<?php
$id = $_GET['id'] ?? '';
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Cinema México | Ficha interactiva</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <style>
        * { box-sizing: border-box; }
        html, body {
            margin: 0;
            width: 100%;
            min-height: 100%;
            font-family: Arial, Helvetica, sans-serif;
            background: #050505;
            color: #fff;
        }
        body { overflow: hidden; }
        .camera-wrap {
            position: fixed;
            inset: 0;
            background: radial-gradient(circle at center, #222 0%, #050505 72%);
        }
        video {
            position: absolute;
            inset: 0;
            width: 100%;
            height: 100%;
            object-fit: cover;
            opacity: .92;
        }
        .grid-guide {
            position: absolute;
            inset: 72px 22px 190px;
            border: 2px solid rgba(255,255,255,.55);
            border-radius: 24px;
            pointer-events: none;
            box-shadow: 0 0 0 999px rgba(0,0,0,.18);
        }
        .grid-guide::before {
            content: "Apunta al cartel o QR";
            position: absolute;
            left: 50%;
            top: -34px;
            transform: translateX(-50%);
            white-space: nowrap;
            background: rgba(0,0,0,.7);
            border-radius: 999px;
            padding: 8px 13px;
            font-size: 13px;
        }
        .topbar {
            position: fixed;
            top: 14px;
            left: 14px;
            right: 14px;
            z-index: 4;
            display: flex;
            justify-content: space-between;
            gap: 10px;
        }
        .pill, .close {
            border: 0;
            border-radius: 999px;
            background: rgba(0,0,0,.72);
            color: #fff;
            padding: 9px 13px;
            font-size: 13px;
            text-decoration: none;
            backdrop-filter: blur(8px);
        }
        .close { white-space: nowrap; }
        .card {
            position: fixed;
            left: 14px;
            right: 14px;
            bottom: 16px;
            z-index: 5;
            max-height: 48vh;
            overflow: auto;
            background: rgba(255,255,255,.95);
            color: #111;
            border-radius: 22px;
            padding: 16px;
            box-shadow: 0 18px 50px rgba(0,0,0,.45);
        }
        .card-header {
            display: grid;
            grid-template-columns: 76px 1fr;
            gap: 13px;
            align-items: start;
        }
        .poster {
            width: 76px;
            height: 105px;
            border-radius: 14px;
            object-fit: cover;
            background: #ddd;
        }
        h1 {
            margin: 0 0 5px;
            font-size: 20px;
            line-height: 1.15;
            font-weight: 800;
        }
        .meta { margin: 0 0 8px; color: #555; font-size: 13px; }
        .tag {
            display: inline-block;
            margin: 2px 4px 2px 0;
            padding: 4px 8px;
            border-radius: 999px;
            background: #efefef;
            font-size: 12px;
        }
        .section-title {
            margin: 14px 0 7px;
            font-size: 13px;
            letter-spacing: .04em;
            text-transform: uppercase;
            color: #555;
            font-weight: 800;
        }
        .field {
            display: grid;
            grid-template-columns: 108px 1fr;
            gap: 10px;
            padding: 7px 0;
            border-top: 1px solid #eee;
            font-size: 13px;
        }
        .label { color: #666; font-weight: 700; }
        .value { color: #111; }
        .actions { display: flex; gap: 8px; margin-top: 14px; }
        .btn {
            flex: 1;
            text-align: center;
            border-radius: 14px;
            padding: 11px;
            text-decoration: none;
            color: #fff;
            background: #111;
            font-size: 13px;
            font-weight: 700;
        }
        .btn.secondary { color: #111; background: #eee; }
        .message {
            position: fixed;
            left: 18px;
            right: 18px;
            top: 50%;
            transform: translateY(-50%);
            z-index: 3;
            background: rgba(0,0,0,.78);
            color: #fff;
            border-radius: 18px;
            padding: 18px;
            text-align: center;
            line-height: 1.4;
        }
        .hidden { display: none; }
    </style>
</head>
<body>

<div class="camera-wrap">
    <video id="camera" autoplay playsinline muted></video>
    <div class="grid-guide"></div>
</div>

<div class="topbar">
    <div class="pill" id="statusBadge">Iniciando cámara...</div>
    <a class="close" href="javascript:history.back()">Salir</a>
</div>

<div id="cameraMessage" class="message hidden"></div>
<div id="arContent"><div class="message">Cargando ficha de la película...</div></div>

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

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;');
}

function field(label, value) {
    if (!value) return '';
    return `
        <div class="field">
            <div class="label">${escapeHtml(label)}</div>
            <div class="value">${escapeHtml(value)}</div>
        </div>
    `;
}

async function startCamera() {
    const video = document.getElementById('camera');
    const badge = document.getElementById('statusBadge');
    const msg = document.getElementById('cameraMessage');

    if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
        badge.textContent = 'Modo ficha interactiva';
        msg.classList.remove('hidden');
        msg.innerHTML = 'Este navegador no permite abrir la cámara desde esta página. La ficha sí puede visualizarse.';
        return;
    }

    try {
        const stream = await navigator.mediaDevices.getUserMedia({
            video: { facingMode: { ideal: 'environment' } },
            audio: false
        });
        video.srcObject = stream;
        badge.textContent = 'Cámara activa · Cinema México';
    } catch (error) {
        badge.textContent = 'Cámara no disponible';
        msg.classList.remove('hidden');
        msg.innerHTML = 'No se pudo abrir la cámara. En celular normalmente se requiere HTTPS o permiso de cámara. La ficha se muestra abajo para prueba.';
    }
}

async function loadMovie() {
    const content = document.getElementById('arContent');

    if (!id) {
        content.innerHTML = `<div class="message">No se recibió el ID de la película.</div>`;
        return;
    }

    try {
        const response = await fetch(API_URL);
        const json = await response.json();

        if (!json.success) {
            throw new Error(json.message || 'No se pudo cargar la película');
        }

        const p = json.data.pelicula;
        const images = json.data.imagenes || [];
        const image = images.length ? images[0].url : 'assets/img/no-image-cinema.png';
        const title = p.titulo_espanol || p.titulo_original || p.titulo_ingles || 'Sin título';
        const meta = [p.anio, p.pais, p.duracion].filter(Boolean).join(' · ');
        const detalleUrl = `pelicula-detalle.php?id=${encodeURIComponent(p.sic_id || p.id || id)}`;

        content.innerHTML = `
            <article class="card">
                <div class="card-header">
                    <img class="poster" src="${escapeHtml(image)}" alt="${escapeHtml(title)}">
                    <div>
                        <h1>${escapeHtml(title)}</h1>
                        <p class="meta">${escapeHtml(meta)}</p>
                        ${p.tipo_produccion ? `<span class="tag">${escapeHtml(p.tipo_produccion)}</span>` : ''}
                        ${p.genero ? `<span class="tag">${escapeHtml(p.genero)}</span>` : ''}
                        ${p.idioma ? `<span class="tag">${escapeHtml(p.idioma)}</span>` : ''}
                    </div>
                </div>

                <div class="section-title">Ficha técnica</div>
                ${field('Dirección', p.direccion)}
                ${field('Producción', p.produccion)}
                ${field('Guion', p.guion)}
                ${field('Reparto', p.reparto)}
                ${field('Contacto', p.contacto)}

                <div class="section-title">Sinopsis</div>
                <div style="font-size:13px;line-height:1.45;color:#222;">
                    ${p.sinopsis_espanol ? escapeHtml(p.sinopsis_espanol) : 'Sinopsis no disponible.'}
                </div>

                <div class="actions">
                    <a class="btn" href="${detalleUrl}">Ver ficha completa</a>
                    <a class="btn secondary" href="peliculas.php">Catálogo</a>
                </div>
            </article>
        `;
    } catch (error) {
        content.innerHTML = `<div class="message">Error: ${escapeHtml(error.message)}</div>`;
    }
}

startCamera();
loadMovie();
</script>
</body>
</html>
