<!DOCTYPE html>
<html lang="es" class="dark">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>LUMEN — Architectural & Hospitality Stock</title>
  
  <!-- Tailwind CSS CDN -->
  <script src="https://cdn.tailwindcss.com"></script>
  
  <!-- FontAwesome Icons CDN -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" />
  
  <!-- Google Fonts: Plus Jakarta Sans -->
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@200;300;400;500;600;700;800&display=swap" rel="stylesheet">

  <script>
    tailwind.config = {
      theme: {
        extend: {
          fontFamily: {
            sans: ['"Plus Jakarta Sans"', 'sans-serif'],
          },
          colors: {
            brand: {
              dark: '#0a0a0b',
              gray: '#121215',
              accent: '#ffffff'
            }
          }
        }
      }
    }
  </script>

  <style>
    /* Scrollbar ultra-discreta */
    ::-webkit-scrollbar {
      width: 5px;
      height: 5px;
    }
    ::-webkit-scrollbar-track {
      background: #0a0a0b;
    }
    ::-webkit-scrollbar-thumb {
      background: #26262b;
      border-radius: 4px;
    }

    body {
      background-color: #0a0a0b;
      color: #ffffff;
      font-family: 'Plus Jakarta Sans', sans-serif;
      overflow-x: hidden;
      -webkit-tap-highlight-color: transparent;
    }

    /* Animación de entrada fluida */
    .photo-card {
      opacity: 0;
      animation: cardAppear 0.3s cubic-bezier(0.16, 1, 0.3, 1) forwards;
    }

    @keyframes cardAppear {
      to {
        opacity: 1;
      }
    }

    /* Efectos Flares Cinematográficos y Destellos */
    .flare-wrapper {
      position: relative;
      overflow: hidden;
    }

    .flare-wrapper::before {
      content: '';
      position: absolute;
      top: -100%;
      left: -150%;
      width: 300%;
      height: 300%;
      background: linear-gradient(
        45deg,
        transparent 42%,
        rgba(255, 255, 255, 0.03) 47%,
        rgba(255, 255, 255, 0.45) 50%,
        rgba(255, 255, 255, 0.03) 53%,
        transparent 58%
      );
      transform: rotate(25deg);
      transition: opacity 0.4s ease, transform 0.8s cubic-bezier(0.2, 0.8, 0.2, 1);
      pointer-events: none;
      z-index: 10;
      opacity: 0;
    }

    .flare-wrapper::after {
      content: '';
      position: absolute;
      top: var(--mouse-y, 50%);
      left: var(--mouse-x, 50%);
      width: 180px;
      height: 180px;
      background: radial-gradient(
        circle,
        rgba(255, 255, 255, 0.8) 0%,
        rgba(200, 230, 255, 0.35) 25%,
        rgba(255, 200, 150, 0.15) 50%,
        transparent 70%
      );
      transform: translate(-50%, -50%) scale(0.3);
      opacity: 0;
      transition: transform 0.5s ease-out, opacity 0.5s ease-out;
      pointer-events: none;
      mix-blend-mode: screen;
      z-index: 11;
    }

    .flare-wrapper:hover::before {
      opacity: 1;
      transform: rotate(25deg) translate(25%, 25%);
    }

    .flare-wrapper:hover::after {
      opacity: 0.85;
      transform: translate(-50%, -50%) scale(1.4);
    }

    .flare-wrapper img {
      transition: transform 0.7s cubic-bezier(0.16, 1, 0.3, 1), filter 0.5s ease;
      will-change: transform;
    }

    .flare-wrapper:hover img {
      transform: scale(1.06);
      filter: brightness(1.08) contrast(1.03);
    }

    /* Modales */
    .modal-backdrop {
      opacity: 0;
      pointer-events: none;
      transition: opacity 0.3s ease;
    }
    .modal-backdrop.active {
      opacity: 1;
      pointer-events: auto;
    }

    /* Pulsating glow for AI loading */
    @keyframes aiPulse {
      0%, 100% { opacity: 0.4; transform: scale(0.98); }
      50% { opacity: 0.9; transform: scale(1.02); }
    }
    .ai-glow {
      animation: aiPulse 2s infinite ease-in-out;
    }
  </style>
</head>
<body class="min-h-screen pb-24 select-none bg-neutral-950 text-white">

  <!-- BARRA SUPERIOR DE FILTROS & HERRAMIENTAS IA -->
  <header class="fixed top-4 left-1/2 -translate-x-1/2 z-40 w-11/12 max-w-5xl flex items-center justify-between gap-2 p-1.5 bg-neutral-900/80 backdrop-blur-2xl border border-white/15 rounded-full shadow-2xl">
    
    <!-- Filtro Desplegable -->
    <div class="relative">
      <button id="filter-dropdown-btn" onclick="toggleFilterDropdown()" class="flex items-center gap-2 px-3.5 py-2 bg-black/60 rounded-full hover:bg-white/10 border border-white/10 transition-all text-xs uppercase tracking-wider font-medium text-white">
        <i class="fa-solid fa-sliders text-white/60 text-xs"></i>
        <span id="active-filter-label" class="truncate max-w-[110px] sm:max-w-none">Filtro: Todos</span>
        <span id="active-filter-count" class="px-2 py-0.5 bg-white/10 rounded-full text-[10px] font-mono text-white/80">12</span>
        <i id="dropdown-chevron" class="fa-solid fa-chevron-down text-[10px] text-white/50 transition-transform duration-300"></i>
      </button>

      <div id="filter-dropdown-menu" class="hidden absolute top-full left-0 mt-2 w-64 bg-neutral-950/95 backdrop-blur-2xl border border-white/15 rounded-2xl shadow-2xl p-2 z-50 transition-all">
        <div class="text-[10px] uppercase tracking-widest text-white/40 font-mono px-3 py-1.5 border-b border-white/10 flex justify-between items-center">
          <span>Sectores / Categorías</span>
          <span class="text-[9px] text-white/30">Filtrar</span>
        </div>

        <div id="filter-options-list" class="py-1 max-h-64 overflow-y-auto space-y-0.5">
          <!-- Opciones inyectadas dinámicamente -->
        </div>
      </div>
    </div>

    <!-- Botones de Acción de IA -->
    <div class="flex items-center gap-1.5">
      <!-- Botón Generador Studio IA -->
      <button onclick="openAiStudioModal()" class="flex items-center gap-2 px-3.5 py-2 bg-gradient-to-r from-indigo-600 to-purple-600 hover:from-indigo-500 hover:to-purple-500 rounded-full text-xs font-semibold tracking-wide transition-all shadow-lg shadow-indigo-950/50 hover:scale-105 active:scale-95">
        <i class="fa-solid fa-wand-magic-sparkles text-amber-300 animate-pulse"></i>
        <span>IA</span>
      </button>

      <!-- Botón Briefing IA -->
      <button onclick="openBriefingModal()" class="flex items-center gap-1.5 px-3 py-2 bg-neutral-800 hover:bg-neutral-700 text-white/90 border border-white/15 rounded-full text-xs font-medium transition-all hover:scale-105 active:scale-95">
        <i class="fa-solid fa-clipboard-list text-emerald-400"></i>
        <span class="hidden md:inline">Planificador Brief IA</span>
      </button>

      <!-- Configuración API Key -->
      <button onclick="openApiKeyModal()" title="Configuración de Clave API Gemini" class="w-8 h-8 flex items-center justify-center bg-black/50 hover:bg-white/10 text-white/70 hover:text-white rounded-full border border-white/10 transition-all text-xs">
        <i class="fa-solid fa-key"></i>
      </button>
    </div>
  </header>

  <!-- GALERÍA FOTOGRÁFICA FULL FRAME (2 cols Móvil | 4 cols Escritorio) -->
  <main class="w-full min-h-screen pt-20 grid grid-cols-2 md:grid-cols-4 gap-0 border-b border-white/5" id="gallery-grid">

    <!-- Item 1 - Gastronomía -->
    <div class="photo-card gastronomia flare-wrapper aspect-square cursor-pointer bg-neutral-900 group relative" style="animation-delay: 0.03s" onclick="openLightbox(0)">
      <img src="https://images.unsplash.com/photo-1555396273-367ea4eb4db5?auto=format&fit=crop&w=1200&q=85" alt="Plato de Autor & Alta Cocina" class="w-full h-full object-cover block" loading="lazy">
      <div class="absolute inset-0 bg-gradient-to-t from-black/80 via-transparent to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300 p-4 flex flex-col justify-end z-20 pointer-events-none">
        <span class="text-[10px] tracking-widest uppercase text-amber-300 font-medium">Gastronomía & Restauración</span>
        <h3 class="text-sm font-light text-white tracking-wide">Plato de Autor & Alta Cocina</h3>
      </div>
    </div>

    <!-- Item 2 - Hotelería -->
    <div class="photo-card hoteleria flare-wrapper aspect-square cursor-pointer bg-neutral-900 group relative" style="animation-delay: 0.06s" onclick="openLightbox(1)">
      <img src="https://images.unsplash.com/photo-1582719478250-c89cae4dc85b?auto=format&fit=crop&w=1200&q=85" alt="Suite Presidencial Hotel" class="w-full h-full object-cover" loading="lazy">
      <div class="absolute inset-0 bg-gradient-to-t from-black/80 via-transparent to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300 p-4 flex flex-col justify-end z-20 pointer-events-none">
        <span class="text-[10px] tracking-widest uppercase text-sky-300 font-medium">Hotelería & Resorts</span>
        <h3 class="text-sm font-light text-white tracking-wide">Suite de Lujo con Vistas</h3>
      </div>
    </div>

    <!-- Item 3 - Arquitectura -->
    <div class="photo-card arquitectura flare-wrapper aspect-square cursor-pointer bg-neutral-900 group relative" style="animation-delay: 0.09s" onclick="openLightbox(2)">
      <img src="https://images.unsplash.com/photo-1600585154340-be6161a56a0c?auto=format&fit=crop&w=1200&q=85" alt="Villa Minimalista Contemporánea" class="w-full h-full object-cover" loading="lazy">
      <div class="absolute inset-0 bg-gradient-to-t from-black/80 via-transparent to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300 p-4 flex flex-col justify-end z-20 pointer-events-none">
        <span class="text-[10px] tracking-widest uppercase text-white/60 font-medium">Arquitectura</span>
        <h3 class="text-sm font-light text-white tracking-wide">Estructura Residencial Luxe</h3>
      </div>
    </div>

    <!-- Item 4 - Comparativa Antes/Después -->
    <div class="photo-card comparativa flare-wrapper aspect-square cursor-pointer bg-neutral-900 group relative border-2 border-indigo-500/30 overflow-hidden" style="animation-delay: 0.12s" onclick="openLightbox(3)" data-type="ba">
      <img src="https://images.unsplash.com/photo-1517248135467-4c7edcad34c4?auto=format&fit=crop&w=1200&q=85" alt="Comparativa de Edición Comercial" class="w-full h-full object-cover block filter contrast-110" loading="lazy">
      <div class="absolute top-3 right-3 z-20 px-2.5 py-1 bg-indigo-950/80 backdrop-blur-md rounded-full border border-indigo-400/50 text-[10px] font-mono tracking-widest text-indigo-200 flex items-center gap-1.5 shadow-lg">
        <i class="fa-solid fa-sliders text-xs text-indigo-400"></i>
        <span>Antes / Después</span>
      </div>
      <div class="absolute inset-0 bg-gradient-to-t from-black/80 via-transparent to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300 p-4 flex flex-col justify-end z-20 pointer-events-none">
        <span class="text-[10px] tracking-widest uppercase text-indigo-300 font-medium">Calidad de Producción</span>
        <h3 class="text-sm font-light text-white tracking-wide">Edición Comercial & Color Grading</h3>
      </div>
    </div>

    <!-- Item 5 - Gastronomía -->
    <div class="photo-card gastronomia flare-wrapper aspect-square cursor-pointer bg-neutral-900 group relative" style="animation-delay: 0.15s" onclick="openLightbox(4)">
      <img src="https://images.unsplash.com/photo-1514933651103-005eec06c04b?auto=format&fit=crop&w=1200&q=85" alt="Coctelería de Autor" class="w-full h-full object-cover" loading="lazy">
      <div class="absolute inset-0 bg-gradient-to-t from-black/80 via-transparent to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300 p-4 flex flex-col justify-end z-20 pointer-events-none">
        <span class="text-[10px] tracking-widest uppercase text-amber-300 font-medium">Gastronomía & Barra</span>
        <h3 class="text-sm font-light text-white tracking-wide">Mixología & Coctelería Fina</h3>
      </div>
    </div>

    <!-- Item 6 - Hotelería -->
    <div class="photo-card hoteleria flare-wrapper aspect-square cursor-pointer bg-neutral-900 group relative" style="animation-delay: 0.18s" onclick="openLightbox(5)">
      <img src="https://images.unsplash.com/photo-1571896349842-33c89424de2d?auto=format&fit=crop&w=1200&q=85" alt="Piscina Resort Infinity" class="w-full h-full object-cover" loading="lazy">
      <div class="absolute inset-0 bg-gradient-to-t from-black/80 via-transparent to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300 p-4 flex flex-col justify-end z-20 pointer-events-none">
        <span class="text-[10px] tracking-widest uppercase text-sky-300 font-medium">Hotelería & Resorts</span>
        <h3 class="text-sm font-light text-white tracking-wide">Piscina Infinity al Atardecer</h3>
      </div>
    </div>

    <!-- Item 7 - 360° VR Tour -->
    <div class="photo-card v360 flare-wrapper aspect-square cursor-pointer bg-neutral-900 group relative" style="animation-delay: 0.21s" onclick="openLightbox(6)" data-type="360" data-iframe-url="https://vauru.github.io/360/">
      <img src="https://images.unsplash.com/photo-1600585154526-990dced4db0d?auto=format&fit=crop&w=1200&q=85" alt="Tour Virtual 360° VR" class="w-full h-full object-cover block" loading="lazy">
      <div class="absolute top-3 right-3 z-20 px-2.5 py-1 bg-black/70 backdrop-blur-md rounded-full border border-indigo-400/40 text-[10px] font-mono tracking-widest text-indigo-300 flex items-center gap-1.5 shadow-lg">
        <i class="fa-solid fa-vr-cardboard text-xs text-indigo-400"></i>
        <span>Tour 360° VR</span>
      </div>
      <div class="absolute inset-0 bg-gradient-to-t from-black/80 via-transparent to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300 p-4 flex flex-col justify-end z-20 pointer-events-none">
        <span class="text-[10px] tracking-widest uppercase text-indigo-300 font-medium">Experiencia Inmersiva</span>
        <h3 class="text-sm font-light text-white tracking-wide">Recorrido Virtual para Reservas</h3>
      </div>
    </div>

    <!-- Item 8 - Gastronomía -->
    <div class="photo-card gastronomia flare-wrapper aspect-square cursor-pointer bg-neutral-900 group relative" style="animation-delay: 0.24s" onclick="openLightbox(7)">
      <img src="https://images.unsplash.com/photo-1544025162-d76694265947?auto=format&fit=crop&w=1200&q=85" alt="Cena en Restaurante Luxe" class="w-full h-full object-cover" loading="lazy">
      <div class="absolute inset-0 bg-gradient-to-t from-black/80 via-transparent to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300 p-4 flex flex-col justify-end z-20 pointer-events-none">
        <span class="text-[10px] tracking-widest uppercase text-amber-300 font-medium">Gastronomía & Salón</span>
        <h3 class="text-sm font-light text-white tracking-wide">Ambiente de Salón & Experiencia</h3>
      </div>
    </div>

    <!-- Item 9 - Hotelería -->
    <div class="photo-card hoteleria flare-wrapper aspect-square cursor-pointer bg-neutral-900 group relative" style="animation-delay: 0.27s" onclick="openLightbox(8)">
      <img src="https://images.unsplash.com/photo-1540555700478-4be289fbecef?auto=format&fit=crop&w=1200&q=85" alt="Spa y Wellness Resort" class="w-full h-full object-cover" loading="lazy">
      <div class="absolute inset-0 bg-gradient-to-t from-black/80 via-transparent to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300 p-4 flex flex-col justify-end z-20 pointer-events-none">
        <span class="text-[10px] tracking-widest uppercase text-sky-300 font-medium">Hotelería & Wellness</span>
        <h3 class="text-sm font-light text-white tracking-wide">Área Spa & Relajación Lux</h3>
      </div>
    </div>

    <!-- Item 10 - Arquitectura -->
    <div class="photo-card arquitectura flare-wrapper aspect-square cursor-pointer bg-neutral-900 group relative" style="animation-delay: 0.30s" onclick="openLightbox(9)">
      <img src="https://images.unsplash.com/photo-1512917774080-9991f1c4c750?auto=format&fit=crop&w=1200&q=85" alt="Geometría Fachada Moderna" class="w-full h-full object-cover" loading="lazy">
      <div class="absolute inset-0 bg-gradient-to-t from-black/80 via-transparent to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300 p-4 flex flex-col justify-end z-20 pointer-events-none">
        <span class="text-[10px] tracking-widest uppercase text-white/60 font-medium">Arquitectura</span>
        <h3 class="text-sm font-light text-white tracking-wide">Líneas y Sombras Contemporáneas</h3>
      </div>
    </div>

    <!-- Item 11 - Gastronomía -->
    <div class="photo-card gastronomia flare-wrapper aspect-square cursor-pointer bg-neutral-900 group relative" style="animation-delay: 0.33s" onclick="openLightbox(10)">
      <img src="https://images.unsplash.com/photo-1565299624946-b28f40a0ae38?auto=format&fit=crop&w=1200&q=85" alt="Fotografía Gourmet Digital" class="w-full h-full object-cover" loading="lazy">
      <div class="absolute inset-0 bg-gradient-to-t from-black/80 via-transparent to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300 p-4 flex flex-col justify-end z-20 pointer-events-none">
        <span class="text-[10px] tracking-widest uppercase text-amber-300 font-medium">Gastronomía & Cartas</span>
        <h3 class="text-sm font-light text-white tracking-wide">Carta Digital & Delivery Premium</h3>
      </div>
    </div>

    <!-- Item 12 - Hotelería -->
    <div class="photo-card hoteleria flare-wrapper aspect-square cursor-pointer bg-neutral-900 group relative" style="animation-delay: 0.36s" onclick="openLightbox(11)">
      <img src="https://images.unsplash.com/photo-1566073771259-6a8506099945?auto=format&fit=crop&w=1200&q=85" alt="Recepción Hotel Boutique" class="w-full h-full object-cover" loading="lazy">
      <div class="absolute inset-0 bg-gradient-to-t from-black/80 via-transparent to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300 p-4 flex flex-col justify-end z-20 pointer-events-none">
        <span class="text-[10px] tracking-widest uppercase text-sky-300 font-medium">Hotelería Boutique</span>
        <h3 class="text-sm font-light text-white tracking-wide">Lobby & Recepción Exclusiva</h3>
      </div>
    </div>

  </main>

  <!-- MODAL / LIGHTBOX CON HERRAMIENTAS DE ANÁLISIS DE IA -->
  <div id="lightbox" class="fixed inset-0 z-50 bg-black/95 backdrop-blur-2xl opacity-0 pointer-events-none transition-opacity duration-300 flex flex-col items-center justify-center p-3 md:p-6 overflow-y-auto">
    
    <!-- Header del Lightbox -->
    <div class="w-full max-w-6xl flex justify-between items-center mb-3 z-30">
      <div id="lb-counter-wrapper" class="text-white/70 font-mono text-xs tracking-widest">
        <span id="lb-counter">01 / 12</span>
      </div>

      <div class="flex items-center gap-2">
        <button id="ai-analyze-btn" onclick="analyzeCurrentImageWithGemini()" class="px-3 py-1.5 bg-gradient-to-r from-purple-600 to-indigo-600 hover:from-purple-500 hover:to-indigo-500 rounded-full text-xs font-semibold tracking-wide text-white flex items-center gap-1.5 transition-all shadow-lg shadow-purple-950/50">
          <i class="fa-solid fa-eye text-amber-300"></i>
          <span>LUMEN AI Lens</span>
        </button>

        <button id="ai-tts-btn" onclick="speakImagePitchWithGemini()" class="px-3 py-1.5 bg-neutral-800 hover:bg-neutral-700 rounded-full text-xs font-medium text-white/90 border border-white/20 flex items-center gap-1.5 transition-all">
          <i class="fa-solid fa-volume-high text-sky-400"></i>
          <span class="hidden sm:inline">Escuchar Pitch Audio</span>
        </button>

        <button onclick="closeLightbox()" aria-label="Cerrar visor" class="w-9 h-9 flex items-center justify-center rounded-full bg-white/10 hover:bg-white/20 text-white text-lg transition-all ml-2">
          <i class="fa-solid fa-xmark"></i>
        </button>
      </div>
    </div>

    <!-- Botón Imagen Previa -->
    <button id="lb-prev-btn" onclick="prevImage()" aria-label="Imagen anterior" class="fixed left-3 md:left-6 top-1/2 -translate-y-1/2 text-white/70 hover:text-white text-2xl w-12 h-12 flex items-center justify-center rounded-full bg-black/60 hover:bg-white/20 backdrop-blur-md transition-all z-40 border border-white/10">
      <i class="fa-solid fa-chevron-left"></i>
    </button>

    <!-- Contenedor Visor Central -->
    <div id="lightbox-img-wrapper" class="relative max-w-5xl w-full flex-1 flex flex-col items-center justify-center overflow-hidden my-auto">
      <!-- Imagen Estándar -->
      <img id="lightbox-img" src="" alt="Fotografía ampliada" class="max-w-full max-h-[70vh] object-contain select-none rounded-lg shadow-2xl">
      
      <!-- Componente Antes / Después -->
      <div id="lightbox-ba-container" class="hidden relative max-w-4xl w-full h-[60vh] rounded-2xl overflow-hidden shadow-2xl border border-white/20 select-none">
        <img src="https://images.unsplash.com/photo-1517248135467-4c7edcad34c4?auto=format&fit=crop&w=1600&q=90" class="absolute inset-0 w-full h-full object-cover filter contrast-110 brightness-105" alt="Fotografía Editada Profesional">
        <span class="absolute top-4 right-4 bg-emerald-500/80 text-white px-3 py-1 rounded-full text-[10px] font-mono tracking-widest uppercase z-10 backdrop-blur-md">
          Con Edición Lumière & Iluminación Pro
        </span>

        <div id="ba-before-wrapper" class="absolute top-0 left-0 bottom-0 w-1/2 overflow-hidden border-r-2 border-white/80 z-10">
          <img src="https://images.unsplash.com/photo-1517248135467-4c7edcad34c4?auto=format&fit=crop&w=1600&q=90" class="absolute top-0 left-0 max-w-none h-full object-cover filter grayscale contrast-75 brightness-75 blur-[0.5px]" id="ba-before-img" alt="Foto Sin Producción">
          <span class="absolute top-4 left-4 bg-black/80 text-white/80 px-3 py-1 rounded-full text-[10px] font-mono tracking-widest uppercase backdrop-blur-md">
            Sin Producción Pro
          </span>
        </div>

        <div id="ba-slider-handle" class="absolute top-0 bottom-0 left-1/2 w-8 -ml-4 z-20 flex items-center justify-center cursor-ew-resize">
          <div class="w-8 h-8 rounded-full bg-white text-black shadow-2xl flex items-center justify-center text-xs">
            <i class="fa-solid fa-code-compare"></i>
          </div>
        </div>
      </div>

      <!-- Contenedor iFrame Vista 360° -->
      <div id="lightbox-iframe-container" class="hidden w-full h-[65vh] max-w-5xl relative rounded-2xl overflow-hidden shadow-2xl border border-white/20 bg-neutral-900">
        <div id="iframe-loader" class="absolute inset-0 flex flex-col items-center justify-center bg-neutral-950 text-white/60 text-xs font-mono tracking-widest gap-3 z-0">
          <i class="fa-solid fa-circle-notch fa-spin text-2xl text-indigo-400"></i>
          <span>CARGANDO EXPERIENCIA 360°...</span>
        </div>
        <iframe id="lightbox-iframe" class="w-full h-full border-0 relative z-10 bg-transparent" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; xr-spatial-tracking; fullscreen; vr" allowfullscreen onload="document.getElementById('iframe-loader')?.classList.add('hidden')"></iframe>
      </div>
    </div>

    <!-- PANEL DE ANÁLISIS DE IA DESPLEGABLE -->
    <div id="ai-analysis-drawer" class="hidden w-full max-w-4xl bg-neutral-900/90 border border-purple-500/30 rounded-2xl p-4 mt-3 backdrop-blur-xl shadow-2xl transition-all max-h-[30vh] overflow-y-auto">
      <div class="flex justify-between items-center pb-2 border-b border-white/10 mb-3">
        <span class="text-xs font-bold text-purple-300 font-mono flex items-center gap-2">
          <i class="fa-solid fa-brain text-purple-400"></i>
          Análisis Fotográfico Comercial (Gemini Vision AI)
        </span>
        <div class="flex items-center gap-2">
          <!-- Reproductor de Audio si existe -->
          <button id="ai-drawer-audio-play" onclick="playDrawerAudio()" class="hidden px-2.5 py-1 bg-sky-950 text-sky-300 border border-sky-500/30 rounded-full text-[10px] font-mono items-center gap-1">
            <i class="fa-solid fa-play"></i> Reproducir Audio Pitch
          </button>
          <button onclick="closeAiDrawer()" class="text-white/50 hover:text-white text-xs">
            <i class="fa-solid fa-xmark"></i>
          </button>
        </div>
      </div>

      <div id="ai-analysis-loading" class="hidden py-6 text-center text-xs font-mono text-purple-300/80 flex flex-col items-center justify-center gap-2">
        <i class="fa-solid fa-atom fa-spin text-2xl text-purple-400"></i>
        <span>Analizando composición, iluminación y potencial comercial con Gemini...</span>
      </div>

      <div id="ai-analysis-content" class="text-xs text-neutral-300 leading-relaxed font-light space-y-2">
        <!-- Inyectado por IA -->
      </div>
    </div>

    <!-- Botón Imagen Siguiente -->
    <button id="lb-next-btn" onclick="nextImage()" aria-label="Imagen siguiente" class="fixed right-3 md:right-6 top-1/2 -translate-y-1/2 text-white/70 hover:text-white text-2xl w-12 h-12 flex items-center justify-center rounded-full bg-black/60 hover:bg-white/20 backdrop-blur-md transition-all z-40 border border-white/10">
      <i class="fa-solid fa-chevron-right"></i>
    </button>

  </div>

  <!-- MODAL: GENERADOR DE CONCEPTOS FOTOGRÁFICOS CON IA (IMAGEN 4 & GEMINI FLASH IMAGE) -->
  <div id="ai-studio-modal" class="modal-backdrop fixed inset-0 z-50 bg-black/90 backdrop-blur-2xl flex items-center justify-center p-4">
    <div class="bg-neutral-900 border border-white/15 rounded-3xl max-w-3xl w-full p-6 md:p-8 shadow-2xl max-h-[90vh] overflow-y-auto relative">
      
      <button onclick="closeAiStudioModal()" class="absolute top-5 right-5 text-white/50 hover:text-white text-xl w-8 h-8 flex items-center justify-center rounded-full hover:bg-white/10">
        <i class="fa-solid fa-xmark"></i>
      </button>

      <div class="flex items-center gap-3 mb-4">
        <div class="w-10 h-10 rounded-2xl bg-gradient-to-tr from-indigo-600 to-purple-600 flex items-center justify-center text-white text-lg shadow-lg">
          <i class="fa-solid fa-wand-magic-sparkles"></i>
        </div>
        <div>
          <h2 class="text-xl font-bold tracking-tight text-white">AI Studio Shoot Generator</h2>
          <p class="text-xs text-white/60">Crea o edita conceptos de fotografía stock a medida usando Imagen 4 e IA Generativa.</p>
        </div>
      </div>

      <!-- Presets de Pruebas -->
      <div class="mb-4">
        <label class="text-[10px] uppercase font-mono tracking-widest text-white/40 block mb-2">Presets de Estilo Comercial</label>
        <div class="flex flex-wrap gap-2">
          <button onclick="setStudioPrompt('Fotografía editorial de arquitectura moderna minimalista, villa de lujo con piscina infinity frente al mar al atardecer, luz cálida cine, 8k')" class="px-3 py-1.5 bg-neutral-800 hover:bg-neutral-700 border border-white/10 rounded-full text-[11px] text-white/80 transition-all">
            🏛️ Villa Infinity Pool
          </button>
          <button onclick="setStudioPrompt('Fotografía gastronómica de estrella Michelin, plato de deconstrucción gourmet con iluminación focal dramática, estilo sofisticado y oscuro')" class="px-3 py-1.5 bg-neutral-800 hover:bg-neutral-700 border border-white/10 rounded-full text-[11px] text-white/80 transition-all">
            🍽️ Plato Michelin
          </button>
          <button onclick="setStudioPrompt('Coctelería de autor premium en barra de bar boutique con luces de neón suave, vaso de cristal con humo botánico')" class="px-3 py-1.5 bg-neutral-800 hover:bg-neutral-700 border border-white/10 rounded-full text-[11px] text-white/80 transition-all">
            🍸 Mixología Boutique
          </button>
          <button onclick="setStudioPrompt('Suite presidencial de hotel de gran lujo con ventanal panorámico a las montañas de los Alpes, sábanas de lino, luz natural')" class="px-3 py-1.5 bg-neutral-800 hover:bg-neutral-700 border border-white/10 rounded-full text-[11px] text-white/80 transition-all">
            🛋️ Suite de Lujo
          </button>
        </div>
      </div>

      <!-- Campo de Entrada de Prompt -->
      <div class="space-y-3 mb-6">
        <div>
          <label class="text-[10px] uppercase font-mono tracking-widest text-white/40 block mb-1">Descripción del Concepto / Prompt</label>
          <textarea id="studio-prompt-input" rows="3" class="w-full bg-neutral-950 border border-white/20 rounded-xl p-3 text-xs text-white focus:outline-none focus:border-purple-500 transition-all placeholder:text-white/30" placeholder="Describe la toma deseada (ej. Fachada de hotel boutique en Madrid con arquitectura clásica y luz de tarde)..."></textarea>
        </div>

        <div class="flex justify-between items-center gap-4">
          <div class="flex-1">
            <label class="text-[10px] uppercase font-mono tracking-widest text-white/40 block mb-1">Modelo de Generación</label>
            <select id="studio-model-select" class="w-full bg-neutral-950 border border-white/20 rounded-xl px-3 py-2 text-xs text-white focus:outline-none">
              <option value="imagen-4.0-generate-001">Imagen 4.0 Pro (Máxima Calidad Fotorrealista)</option>
              <option value="gemini-3.1-flash-image-preview">Gemini 3.1 Flash Image (Rápido / Edición Conversacional)</option>
            </select>
          </div>

          <button onclick="generateStudioImage()" id="studio-gen-btn" class="mt-4 px-6 py-2.5 bg-gradient-to-r from-indigo-600 to-purple-600 hover:from-indigo-500 hover:to-purple-500 text-white rounded-xl text-xs font-bold tracking-wide transition-all flex items-center gap-2 shadow-lg shadow-purple-950/50">
            <i class="fa-solid fa-sparkles"></i>
            <span>Generar Imagen</span>
          </button>
        </div>
      </div>

      <!-- Área de Resultado de la Imagen -->
      <div id="studio-result-area" class="min-h-[250px] bg-neutral-950 border border-white/10 rounded-2xl flex flex-col items-center justify-center p-4 relative overflow-hidden">
        <div id="studio-placeholder" class="text-center space-y-2 text-white/40">
          <i class="fa-solid fa-image text-3xl text-white/20"></i>
          <p class="text-xs font-mono">Los conceptos generados por IA aparecerán aquí.</p>
        </div>

        <div id="studio-loading" class="hidden flex-col items-center justify-center text-center space-y-3">
          <div class="w-12 h-12 rounded-full border-2 border-purple-500 border-t-transparent animate-spin"></div>
          <span class="text-xs font-mono text-purple-300 animate-pulse">Renderizando fotografía fotorrealista con IA...</span>
        </div>

        <img id="studio-output-img" src="" class="hidden max-h-[60vh] object-contain rounded-xl shadow-2xl">
      </div>

      <!-- Acciones tras la generación -->
      <div id="studio-actions" class="hidden flex justify-between items-center mt-4">
        <div class="text-[10px] font-mono text-emerald-400 flex items-center gap-1.5">
          <i class="fa-solid fa-check-circle"></i> Concepto listo para uso
        </div>
        <div class="flex items-center gap-2">
          <button onclick="addGeneratedImageToGallery()" class="px-4 py-2 bg-emerald-600 hover:bg-emerald-500 text-white rounded-xl text-xs font-semibold transition-all flex items-center gap-1.5">
            <i class="fa-solid fa-plus"></i> Añadir a la Galería LUMEN
          </button>
        </div>
      </div>

    </div>
  </div>

  <!-- MODAL: ASISTENTE DE BRIEFING & LISTA DE TOMAS CON IA -->
  <div id="briefing-modal" class="modal-backdrop fixed inset-0 z-50 bg-black/90 backdrop-blur-2xl flex items-center justify-center p-4">
    <div class="bg-neutral-900 border border-white/15 rounded-3xl max-w-3xl w-full p-6 md:p-8 shadow-2xl max-h-[90vh] overflow-y-auto relative">
      
      <button onclick="closeBriefingModal()" class="absolute top-5 right-5 text-white/50 hover:text-white text-xl w-8 h-8 flex items-center justify-center rounded-full hover:bg-white/10">
        <i class="fa-solid fa-xmark"></i>
      </button>

      <div class="flex items-center gap-3 mb-4">
        <div class="w-10 h-10 rounded-2xl bg-gradient-to-tr from-emerald-600 to-teal-600 flex items-center justify-center text-white text-lg shadow-lg">
          <i class="fa-solid fa-clipboard-list"></i>
        </div>
        <div>
          <h2 class="text-xl font-bold tracking-tight text-white">Planificador de Briefing IA</h2>
          <p class="text-xs text-white/60">Genera una guía técnica de fotografía, shot-list y conceptos comerciales para tu marca.</p>
        </div>
      </div>

      <div class="grid grid-cols-1 md:grid-cols-2 gap-3 mb-4">
        <div>
          <label class="text-[10px] uppercase font-mono tracking-widest text-white/40 block mb-1">Tipo de Negocio</label>
          <select id="brief-type" class="w-full bg-neutral-950 border border-white/20 rounded-xl px-3 py-2 text-xs text-white focus:outline-none">
            <option value="Hotel Boutique de Lujo">Hotel Boutique / Resort</option>
            <option value="Restaurante de Alta Cocina / Michelin">Restaurante / Alta Gastronomía</option>
            <option value="Estudio de Arquitectura / Proyecto Residencial">Proyecto Arquitectónico</option>
            <option value="Bar de Coctelería de Autor">Bar / Coctelería de Autor</option>
          </select>
        </div>

        <div>
          <label class="text-[10px] uppercase font-mono tracking-widest text-white/40 block mb-1">Nombre de Marca / Establecimiento</label>
          <input id="brief-brand" type="text" placeholder="Ej. Hotel Gran Meliá Palacio" class="w-full bg-neutral-950 border border-white/20 rounded-xl px-3 py-2 text-xs text-white focus:outline-none placeholder:text-white/30">
        </div>
      </div>

      <div class="mb-4">
        <label class="text-[10px] uppercase font-mono tracking-widest text-white/40 block mb-1">Objetivos Visuales y Estilo Deseado</label>
        <textarea id="brief-goals" rows="2" class="w-full bg-neutral-950 border border-white/20 rounded-xl p-3 text-xs text-white focus:outline-none placeholder:text-white/30" placeholder="Ej. Buscamos transmitir serenidad, luz natural matutina, enfocado en reservas directas para Airbnb Luxe..."></textarea>
      </div>

      <button onclick="generateBriefingWithGemini()" id="brief-gen-btn" class="w-full py-2.5 bg-gradient-to-r from-emerald-600 to-teal-600 hover:from-emerald-500 hover:to-teal-500 text-white rounded-xl text-xs font-bold tracking-wide transition-all flex items-center justify-center gap-2 shadow-lg shadow-emerald-950/50 mb-4">
        <i class="fa-solid fa-atom"></i>
        <span>Generar Propuesta de Producción con Gemini</span>
      </button>

      <!-- Salida de Briefing -->
      <div id="briefing-output-container" class="hidden bg-neutral-950 border border-white/10 rounded-2xl p-4 space-y-3">
        <div class="flex justify-between items-center border-b border-white/10 pb-2">
          <span class="text-xs font-bold text-emerald-400 font-mono flex items-center gap-1.5">
            <i class="fa-solid fa-check"></i> Briefing Técnico Generado
          </span>
          <button id="brief-audio-btn" onclick="speakBriefingAudio()" class="px-2.5 py-1 bg-sky-950 text-sky-300 border border-sky-500/30 rounded-full text-[10px] font-mono flex items-center gap-1 hover:bg-sky-900 transition-all">
            <i class="fa-solid fa-volume-high"></i> Escuchar Briefing en Audio
          </button>
        </div>

        <div id="briefing-output-text" class="text-xs text-neutral-300 leading-relaxed font-light max-h-60 overflow-y-auto space-y-2">
          <!-- Inyectado por IA -->
        </div>
      </div>

    </div>
  </div>

  <!-- MODAL DE PERFIL Y COTIZADOR EXPRESS -->
  <div id="profile-modal" class="modal-backdrop fixed inset-0 z-50 bg-black/95 backdrop-blur-2xl flex items-center justify-center p-4">
    <div id="lightbox-profile-wrapper" class="relative max-w-4xl w-full bg-neutral-950/95 border border-white/15 rounded-3xl overflow-hidden shadow-2xl text-white z-20 transition-all flex flex-col md:flex-row max-h-[88vh]">
      
      <button onclick="closeProfileModal()" class="absolute top-4 right-4 text-white/50 hover:text-white text-xl z-30 w-8 h-8 flex items-center justify-center bg-black/60 rounded-full">
        <i class="fa-solid fa-xmark"></i>
      </button>

      <!-- Sección Fotográfica Protagonista -->
      <div class="relative w-full md:w-5/12 h-48 md:h-auto overflow-hidden bg-neutral-900 flex-shrink-0">
        <img src="https://images.unsplash.com/photo-1534528741775-53994a69daeb?auto=format&fit=crop&w=1200&q=85" alt="Retrato Mateo Valenzuela" class="w-full h-full object-cover object-center">
        
        <div class="absolute bottom-4 left-4 z-20 flex flex-col gap-1">
          <span class="px-3 py-1 bg-black/70 backdrop-blur-md border border-white/20 rounded-full text-[10px] uppercase tracking-widest text-white/90 font-medium w-fit">
            Director Fotográfico
          </span>
          <span class="text-[10px] text-white/70 font-mono pl-1">Especialista Gastronomía & Hoteles</span>
        </div>
      </div>

      <!-- Información B2B, Cotizador Express y Clientes -->
      <div class="w-full md:w-7/12 p-6 md:p-8 flex flex-col justify-between space-y-4 overflow-y-auto">
        <div>
          <div class="flex justify-between items-start mb-2">
            <div>
              <span class="text-[10px] tracking-widest uppercase text-amber-400 font-mono block">Proyectos Comerciales & Stock</span>
              <h2 class="text-2xl font-bold tracking-tight text-white">Mateo Valenzuela</h2>
            </div>
            <span class="px-2.5 py-1 bg-emerald-950/60 text-emerald-300 border border-emerald-500/30 rounded-full text-[10px] font-mono">
              <i class="fa-solid fa-check-double mr-1"></i> Licencia Incluida
            </span>
          </div>
          
          <p class="text-xs leading-relaxed text-white/70 font-light mb-4">
            Aumento del impacto visual para cartas digitales, plataformas de reserva (Booking, Airbnb Luxe) y campañas de prensa. Más de 120 proyectos ejecutados.
          </p>

          <!-- Cotizador Exprés B2B Incorporado -->
          <div class="bg-neutral-900/80 p-4 rounded-2xl border border-white/10 mb-4 space-y-3">
            <div class="flex items-center justify-between border-b border-white/10 pb-2">
              <span class="text-[11px] font-semibold text-white tracking-wider uppercase"><i class="fa-solid fa-calculator text-amber-400 mr-1.5"></i> Cotizador Express B2B</span>
              <span class="text-[10px] text-white/40 font-mono">Estimación al instante</span>
            </div>

            <div class="grid grid-cols-2 gap-2 text-xs">
              <div>
                <label class="text-[10px] text-white/50 block mb-1">Sector / Servicio</label>
                <select id="quote-sector" onchange="calculateQuote()" class="w-full bg-neutral-950 border border-white/20 rounded-lg px-2 py-1.5 text-xs text-white focus:outline-none">
                  <option value="gastronomia">Gastronomía & Cartas</option>
                  <option value="hoteleria">Hotel & Resort Completo</option>
                  <option value="360">Tour Virtual 360° VR</option>
                </select>
              </div>

              <div>
                <label class="text-[10px] text-white/50 block mb-1">Volumen / Unidades</label>
                <select id="quote-volume" onchange="calculateQuote()" class="w-full bg-neutral-950 border border-white/20 rounded-lg px-2 py-1.5 text-xs text-white focus:outline-none">
                  <option value="pack1">Pack Básico (10 Fotos)</option>
                  <option value="pack2" selected>Pack Editorial (25 Fotos)</option>
                  <option value="pack3">Producción Completa (+50 Fotos + 360°)</option>
                </select>
              </div>
            </div>

            <div class="flex justify-between items-center pt-1 border-t border-white/10">
              <span class="text-[11px] text-white/70 font-light">Estimado aproximado:</span>
              <span id="quote-price" class="text-sm font-bold text-emerald-400 font-mono">€450 EUR</span>
            </div>
          </div>

          <!-- Social Proof Logos -->
          <div>
            <span class="text-[9px] uppercase tracking-widest text-white/30 font-mono block mb-2">Clientes & Colaboraciones</span>
            <div class="flex items-center gap-3 opacity-60 grayscale hover:grayscale-0 transition-all text-xs text-white/80">
              <span class="px-2 py-1 bg-white/5 rounded border border-white/10 font-bold tracking-tighter">BOUTIQUE HOTELS</span>
              <span class="px-2 py-1 bg-white/5 rounded border border-white/10 font-bold tracking-tighter">MICHELIN GUIDE</span>
              <span class="px-2 py-1 bg-white/5 rounded border border-white/10 font-bold tracking-tighter">RELAIS & CHÂTEAUX</span>
            </div>
          </div>
        </div>

        <!-- Botones de Acción Sutiles -->
        <div class="pt-2 flex items-center justify-start gap-2.5">
          <button onclick="sendQuoteWhatsApp()" class="px-4 py-2 bg-emerald-600 hover:bg-emerald-500 text-white rounded-full text-xs font-semibold transition-all flex items-center gap-2 shadow-lg shadow-emerald-950/50">
            <i class="fa-brands fa-whatsapp text-sm"></i>
            <span>Enviar Cotización por WhatsApp</span>
          </button>

          <a href="tel:+34600000000" class="px-3.5 py-2 bg-white/10 hover:bg-white/20 text-white/90 border border-white/20 rounded-full text-xs font-medium transition-all flex items-center gap-1.5">
            <i class="fa-solid fa-phone text-[10px]"></i>
            <span>Llamar</span>
          </a>
        </div>
      </div>

    </div>
  </div>

  <!-- MODAL DE CONFIGURACIÓN DE API KEY GEMINI -->
  <div id="apikey-modal" class="modal-backdrop fixed inset-0 z-50 bg-black/90 backdrop-blur-2xl flex items-center justify-center p-4">
    <div class="bg-neutral-900 border border-white/15 rounded-3xl max-w-md w-full p-6 shadow-2xl relative">
      <button onclick="closeApiKeyModal()" class="absolute top-4 right-4 text-white/50 hover:text-white text-lg">
        <i class="fa-solid fa-xmark"></i>
      </button>

      <div class="flex items-center gap-2 mb-3">
        <i class="fa-solid fa-key text-amber-400 text-lg"></i>
        <h3 class="text-base font-bold text-white">Clave API Gemini (Opcional)</h3>
      </div>

      <p class="text-xs text-white/60 leading-relaxed mb-4">
        Si deseas usar una clave propia de la API de Google Gemini para las funciones de IA (LUMEN Lens, Audio TTS, Studio Generador), ingresala aquí. De lo contrario, se usará el entorno del sistema.
      </p>

      <input id="apikey-input" type="password" placeholder="AIzaSy..." class="w-full bg-neutral-950 border border-white/20 rounded-xl px-3 py-2 text-xs text-white font-mono focus:outline-none focus:border-purple-500 mb-4">

      <div class="flex justify-end gap-2">
        <button onclick="saveApiKey()" class="px-4 py-2 bg-purple-600 hover:bg-purple-500 text-white rounded-xl text-xs font-semibold transition-all">
          Guardar Clave
        </button>
      </div>
    </div>
  </div>

  <!-- FOOTER FIJO MINIMALISTA -->
  <footer class="fixed bottom-0 left-0 right-0 z-40 bg-white text-neutral-900 border-t border-neutral-200 px-4 sm:px-6 py-3 sm:py-4 md:px-12 flex justify-between items-center shadow-[0_-5px_25px_rgba(0,0,0,0.06)]">
    
    <a href="#" class="flex items-center gap-2 group">
      <div class="w-7 h-7 bg-neutral-900 flex items-center justify-center rounded-sm text-white font-bold text-xs tracking-widest group-hover:bg-neutral-800 transition-colors">
        L
      </div>
      <span class="font-extrabold text-sm tracking-tighter uppercase text-neutral-900">LUMEN</span>
      <span class="text-[10px] tracking-widest uppercase text-neutral-400 border-l border-neutral-300 pl-2 font-medium hidden sm:inline-block">Commercial Stock & AI Lens</span>
    </a>

    <div class="flex items-center gap-2 sm:gap-3">
      
      <button onclick="openProfileModal()" title="Perfil" class="w-10 h-10 sm:w-28 sm:h-auto py-2 flex items-center justify-center gap-2 text-neutral-700 hover:text-black hover:bg-neutral-100 rounded-full text-xs font-semibold tracking-wide transition-all border border-neutral-200/80 hover:border-neutral-300 shadow-sm">
        <i class="fa-regular fa-user text-xs text-neutral-800"></i>
        <span class="hidden sm:inline">Perfil</span>
      </button>

      <a href="https://wa.me/34600000000" target="_blank" rel="noopener noreferrer" title="WhatsApp" class="w-10 h-10 sm:w-28 sm:h-auto py-2 flex items-center justify-center gap-2 text-neutral-700 hover:text-emerald-600 hover:bg-emerald-50 rounded-full text-xs font-semibold tracking-wide transition-all border border-neutral-200/80 hover:border-emerald-200 shadow-sm">
        <i class="fa-brands fa-whatsapp text-sm text-emerald-500"></i>
        <span class="hidden sm:inline">WhatsApp</span>
      </a>

      <a href="tel:+34600000000" title="Llamar" class="w-10 h-10 sm:w-28 sm:h-auto py-2 flex items-center justify-center gap-2 text-neutral-700 hover:text-black hover:bg-neutral-100 rounded-full text-xs font-semibold tracking-wide transition-all border border-neutral-200/80 hover:border-neutral-300 shadow-sm">
        <i class="fa-solid fa-phone text-xs text-neutral-800"></i>
        <span class="hidden sm:inline">Llamar</span>
      </a>

    </div>
  </footer>

  <script>
    let allCards = Array.from(document.querySelectorAll('.photo-card'));
    let activeCards = [...allCards];
    let currentIndex = 0;
    let currentDrawerAudioBlob = null;
    let currentAudioElement = null;

    // Lista de categorías adaptadas para clientes B2B
    let categories = [
      { id: 'all', name: 'Todos los Trabajos' },
      { id: 'gastronomia', name: 'Gastronomía & Cartas' },
      { id: 'hoteleria', name: 'Hotelería & Resorts' },
      { id: 'arquitectura', name: 'Arquitectura' },
      { id: 'v360', name: 'Tours Virtuales 360°' },
      { id: 'comparativa', name: 'Calidad Antes / Después' },
      { id: 'aigen', name: '✨ Generadas con IA' }
    ];
    let activeFilterId = 'all';

    // API Key Helper
    function getApiKey() {
      const stored = localStorage.getItem('lumen_gemini_key');
      return stored ? stored.trim() : "";
    }

    function openApiKeyModal() {
      document.getElementById('apikey-input').value = getApiKey();
      document.getElementById('apikey-modal').classList.add('active');
    }
    function closeApiKeyModal() {
      document.getElementById('apikey-modal').classList.remove('active');
    }
    function saveApiKey() {
      const val = document.getElementById('apikey-input').value.trim();
      localStorage.setItem('lumen_gemini_key', val);
      closeApiKeyModal();
      alert("Clave API guardada con éxito.");
    }

    function renderFilterDropdown() {
      const listEl = document.getElementById('filter-options-list');
      if (!listEl) return;

      listEl.innerHTML = categories.map(cat => {
        const isSelected = cat.id === activeFilterId;
        const count = cat.id === 'all' 
          ? allCards.length 
          : allCards.filter(c => c.classList.contains(cat.id)).length;

        return `
          <button onclick="selectFilter('${cat.id}')" class="w-full flex items-center justify-between px-3 py-2 rounded-xl text-xs font-medium transition-all ${
            isSelected 
              ? 'bg-white text-black font-semibold shadow-md' 
              : 'text-white/70 hover:text-white hover:bg-white/10'
          }">
            <span class="capitalize">${cat.name}</span>
            <span class="text-[10px] font-mono opacity-60">(${count})</span>
          </button>
        `;
      }).join('');
    }

    function toggleFilterDropdown() {
      const menu = document.getElementById('filter-dropdown-menu');
      const chevron = document.getElementById('dropdown-chevron');
      const isHidden = menu.classList.contains('hidden');
      
      if (isHidden) {
        renderFilterDropdown();
        menu.classList.remove('hidden');
        chevron.classList.add('rotate-180');
      } else {
        menu.classList.add('hidden');
        chevron.classList.remove('rotate-180');
      }
    }

    document.addEventListener('click', (e) => {
      const dropdownBtn = document.getElementById('filter-dropdown-btn');
      const dropdownMenu = document.getElementById('filter-dropdown-menu');
      if (dropdownBtn && dropdownMenu && !dropdownBtn.contains(e.target) && !dropdownMenu.contains(e.target)) {
        dropdownMenu.classList.add('hidden');
        const chevron = document.getElementById('dropdown-chevron');
        if (chevron) chevron.classList.remove('rotate-180');
      }
    });

    function selectFilter(categoryId) {
      activeFilterId = categoryId;
      const categoryObj = categories.find(c => c.id === categoryId) || { name: categoryId };
      
      document.getElementById('active-filter-label').textContent = `Filtro: ${categoryObj.name}`;
      document.getElementById('filter-dropdown-menu').classList.add('hidden');
      document.getElementById('dropdown-chevron').classList.remove('rotate-180');

      activeCards = [];

      allCards.forEach(card => {
        const matches = categoryId === 'all' || card.classList.contains(categoryId);
        if (matches) {
          card.style.display = 'block';
          card.style.animation = 'none';
          void card.offsetWidth;
          card.style.animation = `cardAppear 0.3s cubic-bezier(0.16, 1, 0.3, 1) ${activeCards.length * 0.015}s forwards`;
          activeCards.push(card);
        } else {
          card.style.display = 'none';
        }
      });

      document.getElementById('active-filter-count').textContent = activeCards.length;
    }

    // Flare interactivo por ratón
    document.querySelectorAll('.flare-wrapper').forEach(card => {
      card.addEventListener('mousemove', (e) => {
        const rect = card.getBoundingClientRect();
        const x = e.clientX - rect.left;
        const y = e.clientY - rect.top;
        card.style.setProperty('--mouse-x', `${x}px`);
        card.style.setProperty('--mouse-y', `${y}px`);
      });
    });

    // Lightbox & Visor logic
    const lightbox = document.getElementById('lightbox');
    const lightboxImg = document.getElementById('lightbox-img');
    const lightboxIframeContainer = document.getElementById('lightbox-iframe-container');
    const lightboxIframe = document.getElementById('lightbox-iframe');
    const lightboxBaContainer = document.getElementById('lightbox-ba-container');
    const lightboxWrapper = document.getElementById('lightbox-img-wrapper');
    const prevBtn = document.getElementById('lb-prev-btn');
    const nextBtn = document.getElementById('lb-next-btn');
    const counterEl = document.getElementById('lb-counter');

    function openLightbox(cardIndexInAll) {
      const selectedCard = allCards[cardIndexInAll];
      currentIndex = activeCards.indexOf(selectedCard);
      if (currentIndex === -1) currentIndex = 0;

      closeAiDrawer();
      updateLightboxContent();
      lightbox.classList.add('active');
      document.body.style.overflow = 'hidden';
    }

    function closeLightbox() {
      lightbox.classList.remove('active');
      document.body.style.overflow = '';
      if (lightboxIframe) {
        lightboxIframe.removeAttribute('srcdoc');
        lightboxIframe.src = 'about:blank';
      }
      closeAiDrawer();
    }

    function updateLightboxContent() {
      if (activeCards.length === 0) return;
      
      closeAiDrawer();
      lightboxWrapper.style.opacity = '0';
      lightboxWrapper.style.transform = 'scale(0.97)';

      setTimeout(() => {
        const currentCard = activeCards[currentIndex];
        const is360 = currentCard.dataset.type === '360' || currentCard.classList.contains('v360');
        const isBa = currentCard.dataset.type === 'ba' || currentCard.classList.contains('comparativa');

        // Reset visibility
        lightboxImg.classList.add('hidden');
        lightboxIframeContainer.classList.add('hidden');
        lightboxBaContainer.classList.add('hidden');

        if (isBa) {
          lightboxBaContainer.classList.remove('hidden');
          initBaSlider();
        } else if (is360) {
          lightboxIframeContainer.classList.remove('hidden');
          const loader = document.getElementById('iframe-loader');
          if (loader) loader.classList.remove('hidden');

          const directIframeUrl = currentCard.dataset.iframeUrl;
          if (directIframeUrl) {
            lightboxIframe.removeAttribute('srcdoc');
            lightboxIframe.src = directIframeUrl;
          }
        } else {
          lightboxIframe.removeAttribute('srcdoc');
          lightboxIframe.src = 'about:blank';
          lightboxImg.classList.remove('hidden');
          const imgEl = currentCard.querySelector('img');
          lightboxImg.src = imgEl.src;
          lightboxImg.alt = imgEl.alt;
        }

        const totalFormatted = activeCards.length < 10 ? `0${activeCards.length}` : activeCards.length;
        const currentFormatted = (currentIndex + 1) < 10 ? `0${currentIndex + 1}` : (currentIndex + 1);
        counterEl.textContent = `${currentFormatted} / ${totalFormatted}`;

        lightboxWrapper.style.opacity = '1';
        lightboxWrapper.style.transform = 'scale(1)';
      }, 150);
    }

    function initBaSlider() {
      const container = document.getElementById('lightbox-ba-container');
      const beforeWrapper = document.getElementById('ba-before-wrapper');
      const beforeImg = document.getElementById('ba-before-img');
      const handle = document.getElementById('ba-slider-handle');

      if (!container || !beforeWrapper || !handle) return;

      function updateWidth(clientX) {
        const rect = container.getBoundingClientRect();
        let x = clientX - rect.left;
        if (x < 0) x = 0;
        if (x > rect.width) x = rect.width;
        
        const percentage = (x / rect.width) * 100;
        beforeWrapper.style.width = `${percentage}%`;
        beforeImg.style.width = `${rect.width}px`;
        handle.style.left = `${percentage}%`;
      }

      let isDragging = false;
      handle.onmousedown = () => isDragging = true;
      window.onmouseup = () => isDragging = false;
      window.onmousemove = (e) => {
        if (isDragging) updateWidth(e.clientX);
      };

      handle.ontouchstart = () => isDragging = true;
      window.ontouchend = () => isDragging = false;
      window.ontouchmove = (e) => {
        if (isDragging) updateWidth(e.touches[0].clientX);
      };
    }

    function nextImage() {
      if (activeCards.length === 0) return;
      currentIndex = (currentIndex + 1) % activeCards.length;
      updateLightboxContent();
    }

    function prevImage() {
      if (activeCards.length === 0) return;
      currentIndex = (currentIndex - 1 + activeCards.length) % activeCards.length;
      updateLightboxContent();
    }

    // LUMEN AI Lens (Gemini Vision Analysis)
    async function analyzeCurrentImageWithGemini() {
      const currentCard = activeCards[currentIndex];
      if (!currentCard) return;

      const imgEl = currentCard.querySelector('img');
      const title = currentCard.querySelector('h3')?.innerText || "Fotografía Comercial LUMEN";
      const category = currentCard.querySelector('span')?.innerText || "General";

      const drawer = document.getElementById('ai-analysis-drawer');
      const loading = document.getElementById('ai-analysis-loading');
      const content = document.getElementById('ai-analysis-content');

      drawer.classList.remove('hidden');
      loading.classList.remove('hidden');
      content.innerHTML = "";

      try {
        const apiKey = getApiKey();
        const apiUrl = `https://generativelanguage.googleapis.com/v1beta/models/gemini-3-flash-preview:generateContent?key=${apiKey}`;

        const systemPrompt = "Actúa como un Director de Arte y Fotógrafo Comercial galardonado. Analiza la fotografía descrita y produce una síntesis profesional estructurada en HTML limpio (p, ul, li, strong) con: 1) Análisis de Composición y Esquema de Luz, 2) Paleta de Colores Sugerida (Hex), 3) Texto Publicitario / Copy para Instagram/Web de Hotel o Restaurante, 4) Hashtags y Alt-Text SEO comercial.";
        
        const userPrompt = `Fotografía titulada '${title}', categoría '${category}'. URL de referencia: ${imgEl.src}. Proporciona el análisis fotográfico técnico y comercial detallado.`;

        const payload = {
          contents: [{ parts: [{ text: userPrompt }] }],
          systemInstruction: { parts: [{ text: systemPrompt }] }
        };

        const res = await fetch(apiUrl, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(payload)
        });

        const data = await res.json();
        loading.classList.add('hidden');

        if (data.candidates && data.candidates[0]?.content?.parts?.[0]?.text) {
          let text = data.candidates[0].content.parts[0].text;
          // Format bullet points or Markdown if returned
          text = text.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
          content.innerHTML = text;
        } else {
          content.innerHTML = "<p class='text-red-400'>No se pudo completar el análisis. Por favor verifica la clave API o reintenta.</p>";
        }

      } catch (err) {
        loading.classList.add('hidden');
        content.innerHTML = `<p class='text-red-400'>Error al procesar el análisis: ${err.message}</p>`;
      }
    }

    function closeAiDrawer() {
      const drawer = document.getElementById('ai-analysis-drawer');
      if (drawer) drawer.classList.add('hidden');
      if (currentAudioElement) {
        currentAudioElement.pause();
        currentAudioElement = null;
      }
    }

    // Gemini TTS Audio Voiceover Generator
    async function speakImagePitchWithGemini() {
      const currentCard = activeCards[currentIndex];
      if (!currentCard) return;

      const title = currentCard.querySelector('h3')?.innerText || "Fotografía de Autor";
      const category = currentCard.querySelector('span')?.innerText || "Comercial";

      const btn = document.getElementById('ai-tts-btn');
      const originalText = btn.innerHTML;
      btn.innerHTML = `<i class="fa-solid fa-spinner fa-spin text-sky-400"></i> Generando Audio...`;

      try {
        const apiKey = getApiKey();
        const apiUrl = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-preview-tts:generateContent?key=${apiKey}`;

        const promptText = `Di con voz elegante, profesional y seductora para un cliente de hotel o restaurante: Bienvenido a la colección Lumière. Esta fotografía titulada '${title}' en el sector '${category}', captura la esencia del lujo contemporáneo, la iluminación de autor y la sofisticación necesaria para elevar las reservas directas de tu marca.`;

        const payload = {
          contents: [{ parts: [{ text: promptText }] }],
          generationConfig: {
            responseModalities: ["AUDIO"],
            speechConfig: {
              voiceConfig: {
                prebuiltVoiceConfig: { voiceName: "Aoede" }
              }
            }
          }
        };

        const res = await fetch(apiUrl, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(payload)
        });

        const data = await res.json();
        const part = data?.candidates?.[0]?.content?.parts?.[0];

        if (part && part.inlineData?.data) {
          const sampleRate = parseInt(part.inlineData.mimeType?.match(/rate=(\d+)/)?.[1] || "24000", 10);
          const pcmBuffer = base64ToArrayBuffer(part.inlineData.data);
          const pcm16 = new Int16Array(pcmBuffer);
          const wavBlob = pcmToWav(pcm16, sampleRate);
          
          currentDrawerAudioBlob = wavBlob;
          const audioUrl = URL.createObjectURL(wavBlob);
          
          if (currentAudioElement) currentAudioElement.pause();
          currentAudioElement = new Audio(audioUrl);
          currentAudioElement.play();

          // Show audio play button in drawer
          const audioPlayBtn = document.getElementById('ai-drawer-audio-play');
          if (audioPlayBtn) audioPlayBtn.classList.remove('hidden');

        } else {
          alert("No se pudo generar el audio TTS.");
        }

      } catch (err) {
        alert("Error al generar voz TTS: " + err.message);
      } finally {
        btn.innerHTML = originalText;
      }
    }

    function base64ToArrayBuffer(base64) {
      const binaryString = window.atob(base64);
      const len = binaryString.length;
      const bytes = new Uint8Array(len);
      for (let i = 0; i < len; i++) {
        bytes[i] = binaryString.charCodeAt(i);
      }
      return bytes.buffer;
    }

    function pcmToWav(pcmData, sampleRate = 24000, numChannels = 1) {
      const buffer = new ArrayBuffer(44 + pcmData.length * 2);
      const view = new DataView(buffer);

      function writeString(offset, string) {
        for (let i = 0; i < string.length; i++) {
          view.setUint8(offset + i, string.charCodeAt(i));
        }
      }

      writeString(0, 'RIFF');
      view.setUint32(4, 36 + pcmData.length * 2, true);
      writeString(8, 'WAVE');
      writeString(12, 'fmt ');
      view.setUint32(16, 16, true);
      view.setUint16(20, 1, true); // PCM
      view.setUint16(22, numChannels, true);
      view.setUint32(24, sampleRate, true);
      view.setUint32(28, sampleRate * numChannels * 2, true);
      view.setUint16(32, numChannels * 2, true);
      view.setUint16(34, 16, true);
      writeString(36, 'data');
      view.setUint32(40, pcmData.length * 2, true);

      let offset = 44;
      for (let i = 0; i < pcmData.length; i++, offset += 2) {
        view.setInt16(offset, pcmData[i], true);
      }

      return new Blob([view], { type: 'audio/wav' });
    }

    function playDrawerAudio() {
      if (currentAudioElement) {
        currentAudioElement.currentTime = 0;
        currentAudioElement.play();
      }
    }

    // Modales & AI Studio Shoot Generator
    function openAiStudioModal() {
      document.getElementById('ai-studio-modal').classList.add('active');
    }
    function closeAiStudioModal() {
      document.getElementById('ai-studio-modal').classList.remove('active');
    }

    function setStudioPrompt(text) {
      document.getElementById('studio-prompt-input').value = text;
    }

    let lastGeneratedImageUrl = null;

    async function generateStudioImage() {
      const prompt = document.getElementById('studio-prompt-input').value.trim();
      const model = document.getElementById('studio-model-select').value;

      if (!prompt) {
        alert("Por favor escribe una descripción para generar la imagen.");
        return;
      }

      const placeholder = document.getElementById('studio-placeholder');
      const loading = document.getElementById('studio-loading');
      const outputImg = document.getElementById('studio-output-img');
      const actions = document.getElementById('studio-actions');
      const genBtn = document.getElementById('studio-gen-btn');

      placeholder.classList.add('hidden');
      outputImg.classList.add('hidden');
      actions.classList.add('hidden');
      loading.classList.remove('hidden');
      genBtn.disabled = true;

      try {
        const apiKey = getApiKey();
        let imageUrl = null;

        if (model === 'imagen-4.0-generate-001') {
          const apiUrl = `https://generativelanguage.googleapis.com/v1beta/models/imagen-4.0-generate-001:predict?key=${apiKey}`;
          const payload = {
            instances: [{ prompt: prompt }],
            parameters: { sampleCount: 1 }
          };

          const res = await fetch(apiUrl, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(payload)
          });
          const data = await res.json();
          if (data.predictions && data.predictions[0]?.bytesBase64Encoded) {
            imageUrl = `data:image/png;base64,${data.predictions[0].bytesBase64Encoded}`;
          } else {
            throw new Error(data.error?.message || "No se pudo generar con Imagen 4.");
          }

        } else {
          // Gemini 3.1 Flash Image
          const apiUrl = `https://generativelanguage.googleapis.com/v1beta/models/gemini-3.1-flash-image-preview:generateContent?key=${apiKey}`;
          const payload = {
            contents: [{ parts: [{ text: prompt }] }],
            generationConfig: {
              responseModalities: ['IMAGE'],
              imageConfig: { aspectRatio: "1:1" }
            }
          };

          const res = await fetch(apiUrl, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(payload)
          });
          const data = await res.json();
          const part = data?.candidates?.[0]?.content?.parts?.find(p => p.inlineData);
          if (part && part.inlineData?.data) {
            imageUrl = `data:${part.inlineData.mimeType};base64,${part.inlineData.data}`;
          } else {
            throw new Error(data.error?.message || "No se obtuvo respuesta de imagen.");
          }
        }

        lastGeneratedImageUrl = imageUrl;
        outputImg.src = imageUrl;
        loading.classList.add('hidden');
        outputImg.classList.remove('hidden');
        actions.classList.remove('hidden');

      } catch (err) {
        loading.classList.add('hidden');
        placeholder.classList.remove('hidden');
        alert("Error al generar imagen: " + err.message);
      } finally {
        genBtn.disabled = false;
      }
    }

    function addGeneratedImageToGallery() {
      if (!lastGeneratedImageUrl) return;

      const galleryGrid = document.getElementById('gallery-grid');
      const newCard = document.createElement('div');
      
      const newIndex = allCards.length;
      newCard.className = "photo-card aigen flare-wrapper aspect-square cursor-pointer bg-neutral-900 group relative border border-purple-500/40";
      newCard.innerHTML = `
        <img src="${lastGeneratedImageUrl}" alt="Concepto Creado con IA Studio" class="w-full h-full object-cover block">
        <div class="absolute top-3 right-3 z-20 px-2 py-0.5 bg-purple-950/80 backdrop-blur-md rounded-full border border-purple-400/50 text-[9px] font-mono tracking-widest text-purple-200">
          ✨ IA Studio
        </div>
        <div class="absolute inset-0 bg-gradient-to-t from-black/80 via-transparent to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300 p-4 flex flex-col justify-end z-20 pointer-events-none">
          <span class="text-[10px] tracking-widest uppercase text-purple-300 font-medium">Concepto IA Personalizado</span>
          <h3 class="text-sm font-light text-white tracking-wide">Producción Digital a Medida</h3>
        </div>
      `;

      newCard.onclick = () => openLightbox(newIndex);

      galleryGrid.prepend(newCard);
      allCards.push(newCard);
      
      selectFilter('aigen');
      closeAiStudioModal();
      alert("¡Imagen añadida con éxito a tu galería!");
    }

    // Briefing Modal & Generator
    function openBriefingModal() {
      document.getElementById('briefing-modal').classList.add('active');
    }
    function closeBriefingModal() {
      document.getElementById('briefing-modal').classList.remove('active');
    }

    let lastBriefingText = "";

    async function generateBriefingWithGemini() {
      const type = document.getElementById('brief-type').value;
      const brand = document.getElementById('brief-brand').value.trim() || "Marca Premium";
      const goals = document.getElementById('brief-goals').value.trim() || "Mejorar presencia digital y reservas";

      const btn = document.getElementById('brief-gen-btn');
      const container = document.getElementById('briefing-output-container');
      const output = document.getElementById('briefing-output-text');

      btn.disabled = true;
      btn.innerHTML = `<i class="fa-solid fa-atom fa-spin text-amber-300"></i> Diseñando Plan de Rodaje con Gemini...`;

      try {
        const apiKey = getApiKey();
        const apiUrl = `https://generativelanguage.googleapis.com/v1beta/models/gemini-3-flash-preview:generateContent?key=${apiKey}`;

        const systemPrompt = "Eres un Productor Ejecutivo Fotográfico especializado en hospitalidad y arquitectura de lujo. Genera una propuesta técnica impecable estructurada con secciones: 1) CONCEPTO & MOODBOARD, 2) SHOT-LIST (5 Tomas clave), 3) ESQUEMA DE LUZ RECOMENDADO, 4) ESTIMACIÓN DE IMPACTO COMERCIAL.";

        const userPrompt = `Crea un Plan de Producción Fotográfica para '${brand}', tipo de establecimiento: '${type}'. Objetivos clave: ${goals}. Responde en texto estructurado limpio con negritas y viñetas.`;

        const payload = {
          contents: [{ parts: [{ text: userPrompt }] }],
          systemInstruction: { parts: [{ text: systemPrompt }] }
        };

        const res = await fetch(apiUrl, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(payload)
        });

        const data = await res.json();
        const text = data.candidates?.[0]?.content?.parts?.[0]?.text;

        if (text) {
          lastBriefingText = text;
          let formattedHtml = text
            .replace(/\*\*(.*?)\*\*/g, '<strong class="text-emerald-300">$1</strong>')
            .replace(/\n/g, '<br>');
          output.innerHTML = formattedHtml;
          container.classList.remove('hidden');
        } else {
          alert("No se pudo generar la propuesta.");
        }

      } catch (err) {
        alert("Error al conectar con Gemini: " + err.message);
      } finally {
        btn.disabled = false;
        btn.innerHTML = `<i class="fa-solid fa-atom"></i> Generar Propuesta de Producción con Gemini`;
      }
    }

    async function speakBriefingAudio() {
      if (!lastBriefingText) return;

      const btn = document.getElementById('brief-audio-btn');
      btn.innerHTML = `<i class="fa-solid fa-spinner fa-spin"></i> Generando Audio...`;

      try {
        const apiKey = getApiKey();
        const apiUrl = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-preview-tts:generateContent?key=${apiKey}`;

        // Summary for TTS
        const shortSummary = `Resumen de propuesta técnica para ${document.getElementById('brief-brand').value || 'tu marca'}: Plan fotográfico enfocado en capturar iluminación de alta gama, tomas de arquitectura y detalles gastronómicos diseñados para aumentar tus reservas directas.`;

        const payload = {
          contents: [{ parts: [{ text: shortSummary }] }],
          generationConfig: {
            responseModalities: ["AUDIO"],
            speechConfig: {
              voiceConfig: { prebuiltVoiceConfig: { voiceName: "Puck" } }
            }
          }
        };

        const res = await fetch(apiUrl, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(payload)
        });

        const data = await res.json();
        const part = data?.candidates?.[0]?.content?.parts?.[0];

        if (part && part.inlineData?.data) {
          const sampleRate = parseInt(part.inlineData.mimeType?.match(/rate=(\d+)/)?.[1] || "24000", 10);
          const pcmBuffer = base64ToArrayBuffer(part.inlineData.data);
          const pcm16 = new Int16Array(pcmBuffer);
          const wavBlob = pcmToWav(pcm16, sampleRate);
          
          const audioUrl = URL.createObjectURL(wavBlob);
          const audio = new Audio(audioUrl);
          audio.play();
        }

      } catch (err) {
        alert("Error de Audio: " + err.message);
      } finally {
        btn.innerHTML = `<i class="fa-solid fa-volume-high"></i> Escuchar Briefing en Audio`;
      }
    }

    // Profile Modal
    function openProfileModal() {
      document.getElementById('profile-modal').classList.add('active');
      calculateQuote();
    }
    function closeProfileModal() {
      document.getElementById('profile-modal').classList.remove('active');
    }

    // Cotizador Express
    function calculateQuote() {
      const sector = document.getElementById('quote-sector').value;
      const volume = document.getElementById('quote-volume').value;
      let price = 350;

      if (sector === 'gastronomia') price = 350;
      if (sector === 'hoteleria') price = 650;
      if (sector === '360') price = 500;

      if (volume === 'pack2') price += 200;
      if (volume === 'pack3') price += 450;

      document.getElementById('quote-price').textContent = `€${price} EUR`;
    }

    function sendQuoteWhatsApp() {
      const sectorText = document.getElementById('quote-sector').options[document.getElementById('quote-sector').selectedIndex].text;
      const volumeText = document.getElementById('quote-volume').options[document.getElementById('quote-volume').selectedIndex].text;
      const priceText = document.getElementById('quote-price').textContent;

      const message = `Hola Mateo, estuve viendo tu portfolio LUMEN. Me interesa cotizar un servicio de fotografía:\n- Sector: ${sectorText}\n- Paquete: ${volumeText}\n- Estimado aproximado: ${priceText}\n¿Podemos coordinar una llamada o disponibilidad?`;
      
      const encoded = encodeURIComponent(message);
      window.open(`https://wa.me/34600000000?text=${encoded}`, '_blank');
    }

    // Teclado
    document.addEventListener('keydown', (e) => {
      if (e.key === 'Escape') {
        closeLightbox();
        closeAiStudioModal();
        closeBriefingModal();
        closeProfileModal();
        closeApiKeyModal();
      }
      if (lightbox.classList.contains('active')) {
        if (e.key === 'ArrowRight') nextImage();
        if (e.key === 'ArrowLeft') prevImage();
      }
    });
  </script>
</body>
</html>