<template>
    <Head>
        <title>{{ plan.seo_title || plan.hero_title || plan.name }}</title>
        <meta v-if="plan.seo_description" name="description" :content="plan.seo_description" />
        <meta v-if="plan.seo_keywords" name="keywords" :content="plan.seo_keywords" />
        <meta property="og:title" :content="plan.seo_title || plan.hero_title || plan.name" />
        <meta v-if="plan.seo_description || plan.description" property="og:description" :content="plan.seo_description || plan.description" />
        <meta v-if="plan.featured_image" property="og:image" :content="plan.featured_image" />
    </Head>

    <div class="min-h-screen" :style="rootStyles">
        <!-- Top Banner -->
        <div v-if="plan.show_top_banner" class="py-2 sm:py-2.5 px-3 sm:px-4 text-center text-xs sm:text-sm" :style="{ backgroundColor: c.banner_bg, color: '#fff' }">
            <span class="mr-1 sm:mr-3">{{ plan.top_banner_text || 'Prueba gratuita de 7 días. Cancela cuando quieras.' }}</span>
            <a href="#precios" class="font-semibold underline hover:no-underline whitespace-nowrap">Empezar →</a>
        </div>

        <!-- Header -->
        <header class="sticky top-0 z-50 border-b" :style="{ backgroundColor: c.header_bg + 'f2', borderColor: borderColor, backdropFilter: 'blur(12px)', WebkitBackdropFilter: 'blur(12px)' }">
            <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                <div class="flex items-center justify-between h-14 lg:h-16">
                    <a href="/" class="flex items-center gap-3" :aria-label="coach.business_name || coach.name">
                        <img v-if="coach.profile_photo" :src="coach.profile_photo" :alt="coach.name" class="w-9 h-9 rounded-full object-cover" width="36" height="36" loading="eager">
                        <span class="font-bold text-base hidden sm:block" :style="{ color: c.text_primary }">{{ coach.business_name || coach.name }}</span>
                    </a>

                    <!-- Desktop Nav -->
                    <nav class="hidden lg:flex items-center gap-8" role="navigation" aria-label="Navegación principal">
                        <a v-for="link in navLinks" :key="link.id" :href="link.href"
                           class="text-sm transition-colors hover:opacity-80" :style="{ color: c.text_secondary }">
                            {{ link.label }}
                        </a>
                    </nav>

                    <div class="flex items-center gap-2 sm:gap-3">
                        <a href="#precios" class="hidden md:inline-flex px-4 py-2 text-sm font-medium transition-colors hover:opacity-80" :style="{ color: c.text_primary }">
                            {{ plan.hero_secondary_cta_text || 'Ver planes' }}
                        </a>
                        <a href="#precios" class="inline-flex px-3 sm:px-5 py-2 sm:py-2.5 rounded-lg text-xs sm:text-sm font-semibold text-white transition-colors hover:opacity-90 whitespace-nowrap" :style="{ backgroundColor: c.accent }">
                            {{ plan.hero_cta_text || 'Empezar ahora' }}
                        </a>

                        <!-- Mobile menu button -->
                        <button @click="mobileMenuOpen = !mobileMenuOpen" class="lg:hidden p-2 -mr-2" :aria-expanded="mobileMenuOpen" aria-label="Menú de navegación">
                            <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24" :style="{ color: c.text_primary }">
                                <path v-if="!mobileMenuOpen" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16"/>
                                <path v-else stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
                            </svg>
                        </button>
                    </div>
                </div>
            </div>

            <!-- Mobile Nav -->
            <div v-show="mobileMenuOpen" class="lg:hidden border-t" :style="{ backgroundColor: c.header_bg, borderColor: borderColor }">
                <nav class="px-4 py-4 space-y-1" role="navigation" aria-label="Navegación móvil">
                    <a v-for="link in navLinks" :key="link.id" :href="link.href"
                       class="block py-3 px-3 rounded-lg transition-colors" :style="{ color: c.text_secondary }" @click="mobileMenuOpen = false">
                        {{ link.label }}
                    </a>
                    <a href="#precios" class="block py-3 px-3 rounded-lg font-semibold text-white mt-2 text-center" :style="{ backgroundColor: c.accent }" @click="mobileMenuOpen = false">
                        {{ plan.hero_cta_text || 'Empezar ahora' }}
                    </a>
                </nav>
            </div>
        </header>

        <!-- Hero Section -->
        <section id="hero" class="relative overflow-hidden" :style="{ backgroundColor: c.bg_primary }">
            <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12 sm:py-16 lg:py-24">
                <div class="grid lg:grid-cols-2 gap-8 lg:gap-12 items-center">
                    <!-- Content -->
                    <div class="space-y-6 sm:space-y-8 order-2 lg:order-1">
                        <div v-if="plan.hero_badge" class="inline-flex">
                            <span class="px-4 py-1.5 rounded-full text-sm font-semibold uppercase tracking-wide" :style="{ backgroundColor: c.accent + '20', color: c.accent, border: '1px solid ' + c.accent + '30' }">
                                {{ plan.hero_badge }}
                            </span>
                        </div>

                        <h1 class="text-3xl sm:text-4xl lg:text-5xl xl:text-6xl font-bold leading-tight" :style="{ color: c.text_primary }">
                            {{ plan.name }}
                        </h1>

                        <p class="text-base sm:text-lg lg:text-xl leading-relaxed max-w-xl" :style="{ color: c.text_secondary }">
                            {{ plan.hero_description || plan.description }}
                        </p>

                        <div class="flex flex-col sm:flex-row gap-3 sm:gap-4">
                            <a href="#precios"
                               class="inline-flex items-center justify-center px-6 sm:px-8 py-3.5 sm:py-4 rounded-xl text-base sm:text-lg font-semibold text-white transition-all active:scale-[0.98]"
                               :style="{ backgroundColor: c.accent }">
                                {{ plan.hero_cta_text || 'Empieza tu prueba gratis' }}
                            </a>
                            <a href="#metodo"
                               class="inline-flex items-center justify-center px-6 sm:px-8 py-3.5 sm:py-4 rounded-xl text-base sm:text-lg font-medium transition-colors border"
                               :style="{ color: c.text_primary, borderColor: borderColor }">
                                <svg class="w-5 h-5 mr-2" fill="currentColor" viewBox="0 0 20 20" aria-hidden="true">
                                    <path d="M10 18a8 8 0 100-16 8 8 0 000 16zM9.555 7.168A1 1 0 008 8v4a1 1 0 001.555.832l3-2a1 1 0 000-1.664l-3-2z"/>
                                </svg>
                                {{ plan.hero_secondary_cta_text || 'Ver cómo funciona' }}
                            </a>
                        </div>

                        <!-- Stats -->
                        <div v-if="heroStats.length" class="grid grid-cols-1 md:grid-cols-3 gap-3 sm:gap-4 md:gap-6 pt-6 sm:pt-8 border-t" :style="{ borderColor: borderColor }">
                            <div v-for="stat in heroStats" :key="stat.id" class="flex items-center gap-3">
                                <div class="flex-shrink-0 w-8 h-8 sm:w-10 sm:h-10 rounded-lg flex items-center justify-center" :style="{ backgroundColor: c.accent + '20' }">
                                    <svg class="w-4 h-4 sm:w-5 sm:h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" :style="{ color: c.accent }" aria-hidden="true">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/>
                                    </svg>
                                </div>
                                <div class="min-w-0">
                                    <p class="font-semibold text-sm sm:text-base truncate" :style="{ color: c.text_primary }">{{ stat.title }}</p>
                                    <p class="text-xs sm:text-sm truncate" :style="{ color: c.text_secondary }">{{ stat.subtitle }}</p>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Hero Image -->
                    <div class="relative order-1 lg:order-2">
                        <div class="aspect-[4/5] sm:aspect-[3/4] lg:aspect-[4/5] rounded-2xl overflow-hidden" :style="{ backgroundColor: c.bg_card }">
                            <img v-if="plan.featured_image"
                                 :src="plan.featured_image"
                                 :alt="plan.name"
                                 class="w-full h-full object-cover"
                                 loading="eager">
                            <img v-else-if="coach.profile_photo"
                                 :src="coach.profile_photo"
                                 :alt="coach.name"
                                 class="w-full h-full object-cover"
                                 loading="eager">
                            <div v-else class="w-full h-full flex items-center justify-center" :style="{ backgroundColor: c.bg_card }">
                                <svg class="w-24 h-24 sm:w-32 sm:h-32 opacity-20" fill="currentColor" viewBox="0 0 24 24" :style="{ color: c.text_primary }" aria-hidden="true">
                                    <path d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z"/>
                                </svg>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </section>

        <!-- Method Section -->
        <section id="metodo" class="py-16 sm:py-20 lg:py-28" :style="{ backgroundColor: c.bg_secondary }">
            <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                <div class="text-center max-w-3xl mx-auto mb-10 sm:mb-16">
                    <h2 class="text-2xl sm:text-3xl lg:text-4xl xl:text-5xl font-bold mb-4 sm:mb-6" :style="{ color: c.text_primary }">
                        {{ plan.method_title || `El método ${coach.name}` }}
                    </h2>
                    <p class="text-base sm:text-lg" :style="{ color: c.text_secondary }">
                        {{ plan.method_subtitle || 'Un sistema probado para transformar tu cuerpo y tu vida' }}
                    </p>
                </div>

                <div class="grid md:grid-cols-2 lg:grid-cols-3 gap-4 sm:gap-6 lg:gap-8">
                    <article v-for="item in methodItems" :key="item.id"
                         class="p-5 sm:p-6 lg:p-8 rounded-2xl border transition-colors"
                         :style="{ backgroundColor: c.bg_card, borderColor: borderColor }">
                        <div class="w-11 h-11 sm:w-12 sm:h-12 lg:w-14 lg:h-14 rounded-xl flex items-center justify-center mb-4 sm:mb-5 lg:mb-6" :style="{ backgroundColor: c.accent + '20' }">
                            <svg class="w-5 h-5 sm:w-6 sm:h-6 lg:w-7 lg:h-7" fill="none" stroke="currentColor" viewBox="0 0 24 24" :style="{ color: c.accent }" aria-hidden="true">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"/>
                            </svg>
                        </div>
                        <h3 class="text-base sm:text-lg lg:text-xl font-bold mb-2 sm:mb-3" :style="{ color: c.text_primary }">{{ item.title }}</h3>
                        <p class="text-sm sm:text-base leading-relaxed" :style="{ color: c.text_secondary }">{{ item.description }}</p>
                    </article>
                </div>
            </div>
        </section>

        <!-- What's Included Section -->
        <section id="incluye" class="py-16 sm:py-20 lg:py-28" :style="{ backgroundColor: c.bg_primary }">
            <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                <div class="text-center max-w-3xl mx-auto mb-10 sm:mb-16">
                    <h2 class="text-2xl sm:text-3xl lg:text-4xl xl:text-5xl font-bold mb-4 sm:mb-6" :style="{ color: c.text_primary }">
                        {{ plan.includes_title || 'Qué incluye el programa' }}
                    </h2>
                    <p class="text-base sm:text-lg" :style="{ color: c.text_secondary }">
                        {{ plan.includes_subtitle || 'Todo lo que necesitas para alcanzar tus objetivos' }}
                    </p>
                </div>

                <div class="grid md:grid-cols-2 lg:grid-cols-3 gap-4 sm:gap-6 lg:gap-8">
                    <div v-for="item in includesItems" :key="item.id"
                         class="flex items-start gap-3 sm:gap-4 p-5 sm:p-6 lg:p-7 rounded-xl border transition-colors"
                         :style="{ backgroundColor: c.bg_card, borderColor: borderColor }">
                        <div class="flex-shrink-0 w-9 h-9 sm:w-10 sm:h-10 rounded-lg flex items-center justify-center" :style="{ backgroundColor: c.accent + '20' }">
                            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" :style="{ color: c.accent }" aria-hidden="true">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/>
                            </svg>
                        </div>
                        <div class="min-w-0">
                            <h4 class="font-semibold text-sm sm:text-base mb-1 sm:mb-1.5" :style="{ color: c.text_primary }">{{ item.title }}</h4>
                            <p class="text-xs sm:text-sm leading-relaxed" :style="{ color: c.text_secondary }">{{ item.description }}</p>
                        </div>
                    </div>
                </div>
            </div>
        </section>

        <!-- Results Section -->
        <section id="resultados" class="py-16 sm:py-20 lg:py-28" :style="{ backgroundColor: c.bg_secondary }">
            <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                <div class="text-center max-w-3xl mx-auto mb-10 sm:mb-16">
                    <h2 class="text-2xl sm:text-3xl lg:text-4xl xl:text-5xl font-bold mb-4 sm:mb-6" :style="{ color: c.text_primary }">
                        {{ plan.results_title || 'Resultados reales' }}
                    </h2>
                    <p class="text-base sm:text-lg" :style="{ color: c.text_secondary }">
                        {{ plan.results_subtitle || 'Transformaciones de personas reales que siguieron este programa' }}
                    </p>
                </div>

                <div v-if="results && results.length" class="relative">
                    <div class="grid grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4 lg:gap-6">
                        <article v-for="(result, idx) in visibleResults" :key="result.id"
                             class="group cursor-pointer"
                             @click="openLightbox(result, resultsPage * resultsPerPage + idx)"
                             role="button"
                             tabindex="0"
                             :aria-label="`Ver transformación de ${result.client_name}`"
                             @keydown.enter="openLightbox(result, resultsPage * resultsPerPage + idx)">
                            <div class="relative aspect-[3/4] rounded-xl sm:rounded-2xl overflow-hidden" :style="{ backgroundColor: c.bg_card }">
                                <img v-if="result.before_image"
                                     :src="result.before_image"
                                     :alt="`${result.client_name} - Antes`"
                                     class="w-full h-full object-cover transition-transform duration-300 group-hover:scale-105"
                                     loading="lazy"
                                     @error="(e) => e.target.style.display = 'none'">

                                <div v-if="result.after_image"
                                     class="absolute inset-0 opacity-0 group-hover:opacity-100 transition-opacity duration-300">
                                    <img :src="result.after_image"
                                         :alt="`${result.client_name} - Después`"
                                         class="w-full h-full object-cover"
                                         loading="lazy">
                                </div>

                                <div class="absolute top-3 left-3 right-3 flex justify-between">
                                    <span class="px-2.5 py-1 bg-black/60 rounded-full text-xs font-semibold text-white group-hover:opacity-0 transition-opacity">
                                        ANTES
                                    </span>
                                    <span v-if="result.after_image" class="px-2.5 py-1 rounded-full text-xs font-semibold text-white opacity-0 group-hover:opacity-100 transition-opacity" :style="{ backgroundColor: c.accent }">
                                        DESPUÉS
                                    </span>
                                </div>

                                <div class="absolute bottom-0 left-0 right-0 p-3 sm:p-4 bg-black/60">
                                    <p class="text-white font-bold text-sm sm:text-base">{{ result.client_name }}</p>
                                    <p class="text-xs sm:text-sm font-medium" :style="{ color: c.accent }">{{ result.transformation_duration }}</p>
                                </div>
                            </div>
                        </article>
                    </div>

                    <!-- Results pagination -->
                    <div v-if="results.length > resultsPerPage" class="flex justify-center gap-3 sm:gap-4 mt-6 sm:mt-8">
                        <button @click="prevResultsPage" :disabled="resultsPage === 0"
                                class="p-2.5 sm:p-3 rounded-full transition-all disabled:opacity-30"
                                :style="{ backgroundColor: c.bg_card, color: c.text_primary }"
                                aria-label="Página anterior de resultados">
                            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"/></svg>
                        </button>
                        <div class="flex items-center gap-2">
                            <button v-for="page in totalResultsPages" :key="page" @click="resultsPage = page - 1"
                                  class="w-2 h-2 rounded-full cursor-pointer transition-all"
                                  :style="{ backgroundColor: resultsPage === page - 1 ? c.accent : (c.text_secondary + '40'), width: resultsPage === page - 1 ? '24px' : '8px' }"
                                  :aria-label="`Página ${page}`"
                                  :aria-current="resultsPage === page - 1 ? 'page' : undefined">
                            </button>
                        </div>
                        <button @click="nextResultsPage" :disabled="resultsPage >= totalResultsPages - 1"
                                class="p-2.5 sm:p-3 rounded-full transition-all disabled:opacity-30"
                                :style="{ backgroundColor: c.bg_card, color: c.text_primary }"
                                aria-label="Página siguiente de resultados">
                            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/></svg>
                        </button>
                    </div>
                </div>

                <div v-else class="text-center py-12 sm:py-16 rounded-2xl" :style="{ backgroundColor: c.bg_card }">
                    <svg class="w-12 h-12 sm:w-16 sm:h-16 mx-auto mb-4 opacity-40" fill="none" stroke="currentColor" viewBox="0 0 24 24" :style="{ color: c.text_secondary }" aria-hidden="true">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"/>
                    </svg>
                    <p :style="{ color: c.text_secondary }">Pronto añadiremos resultados de nuestros clientes</p>
                </div>

                <div v-if="results && results.length" class="text-center mt-8 sm:mt-10">
                    <a :href="`/plan/${plan.slug}/resultados`"
                       class="inline-flex items-center gap-2 font-semibold transition-colors hover:opacity-80" :style="{ color: c.accent }">
                        Ver todos los resultados
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 8l4 4m0 0l-4 4m4-4H3"/></svg>
                    </a>
                </div>
            </div>
        </section>

        <!-- Coach Section -->
        <section id="coach" class="py-16 sm:py-20 lg:py-28" :style="{ backgroundColor: c.bg_primary }">
            <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                <div class="grid lg:grid-cols-2 gap-8 lg:gap-16 items-center">
                    <div class="relative order-2 lg:order-1">
                        <div class="aspect-square rounded-2xl overflow-hidden" :style="{ backgroundColor: c.bg_card }">
                            <img v-if="coachSectionPhoto" :src="coachSectionPhoto" :alt="coach.name" class="w-full h-full object-cover" loading="lazy">
                            <div v-else class="w-full h-full flex items-center justify-center">
                                <svg class="w-24 h-24 sm:w-32 sm:h-32 opacity-30" fill="currentColor" viewBox="0 0 24 24" :style="{ color: c.text_secondary }" aria-hidden="true">
                                    <path d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z"/>
                                </svg>
                            </div>
                        </div>
                    </div>

                    <div class="space-y-6 sm:space-y-8 order-1 lg:order-2">
                        <div>
                            <p class="font-semibold mb-2" :style="{ color: c.accent }">{{ coachSectionTagline }}</p>
                            <h2 class="text-2xl sm:text-3xl lg:text-4xl xl:text-5xl font-bold" :style="{ color: c.text_primary }">
                                {{ coachSectionTitle }}
                            </h2>
                        </div>

                        <p class="text-base sm:text-lg leading-relaxed" :style="{ color: c.text_secondary }">
                            {{ coachSectionBio }}
                        </p>

                        <ul class="space-y-3 sm:space-y-4" role="list">
                            <li v-for="(credential, index) in coachCredentials" :key="index" class="flex items-start gap-3">
                                <div class="flex-shrink-0 w-6 h-6 rounded-full flex items-center justify-center mt-0.5" :style="{ backgroundColor: c.accent + '20' }">
                                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" :style="{ color: c.accent }" aria-hidden="true">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/>
                                    </svg>
                                </div>
                                <span :style="{ color: c.text_secondary }">{{ credential }}</span>
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
        </section>

        <!-- How It Works Section -->
        <section id="como-funciona" class="py-16 sm:py-20 lg:py-28" :style="{ backgroundColor: c.bg_secondary }">
            <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                <div class="text-center max-w-3xl mx-auto mb-10 sm:mb-16">
                    <h2 class="text-2xl sm:text-3xl lg:text-4xl xl:text-5xl font-bold mb-4 sm:mb-6" :style="{ color: c.text_primary }">
                        {{ plan.how_it_works_title || 'Cómo funciona' }}
                    </h2>
                    <p class="text-base sm:text-lg" :style="{ color: c.text_secondary }">
                        {{ plan.how_it_works_subtitle || 'Un proceso simple para empezar tu transformación' }}
                    </p>
                </div>

                <div class="grid grid-cols-2 lg:grid-cols-4 gap-4 sm:gap-6 lg:gap-8">
                    <div v-for="(step, index) in howItWorksSteps" :key="step.id" class="relative">
                        <div class="w-12 h-12 sm:w-14 sm:h-14 lg:w-16 lg:h-16 rounded-xl sm:rounded-2xl flex items-center justify-center text-xl sm:text-2xl font-bold mb-4 sm:mb-6 text-white" :style="{ backgroundColor: c.accent }">
                            {{ index + 1 }}
                        </div>
                        <h3 class="text-base sm:text-lg lg:text-xl font-bold mb-2 sm:mb-3" :style="{ color: c.text_primary }">{{ step.title }}</h3>
                        <p class="text-sm sm:text-base" :style="{ color: c.text_secondary }">{{ step.description }}</p>
                    </div>
                </div>
            </div>
        </section>

        <!-- Pricing Section -->
        <section id="precios" class="py-16 sm:py-20 lg:py-28" :style="{ backgroundColor: c.bg_primary }">
            <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                <div class="text-center max-w-3xl mx-auto mb-10 sm:mb-16">
                    <h2 class="text-2xl sm:text-3xl lg:text-4xl xl:text-5xl font-bold mb-4 sm:mb-6" :style="{ color: c.text_primary }">
                        {{ plan.pricing_title || 'Planes y precios' }}
                    </h2>
                    <p class="text-base sm:text-lg" :style="{ color: c.text_secondary }">
                        {{ plan.pricing_subtitle || 'Elige el plan que mejor se adapte a tus objetivos' }}
                    </p>
                </div>

                <div class="grid md:grid-cols-2 lg:grid-cols-3 gap-4 sm:gap-6 lg:gap-8 max-w-5xl mx-auto">
                    <article v-for="tier in pricingTiers" :key="tier.id"
                         class="relative p-5 sm:p-6 lg:p-8 rounded-2xl border transition-all"
                         :style="{
                             backgroundColor: tier.featured ? c.accent + '10' : c.bg_card,
                             borderColor: tier.featured ? c.accent + '50' : borderColor,
                             transform: tier.featured ? 'scale(1.02)' : 'scale(1)'
                         }">
                        <div v-if="tier.featured" class="absolute -top-3 sm:-top-3.5 left-1/2 -translate-x-1/2">
                            <span class="px-3 sm:px-4 py-1 rounded-full text-xs sm:text-sm font-semibold text-white whitespace-nowrap" :style="{ backgroundColor: c.accent }">
                                Más popular
                            </span>
                        </div>

                        <h3 class="text-base sm:text-lg lg:text-xl font-bold mb-1 sm:mb-2" :style="{ color: c.text_primary }">{{ tier.name }}</h3>
                        <p class="text-xs sm:text-sm mb-4 sm:mb-5 lg:mb-6" :style="{ color: c.text_secondary }">{{ tier.description }}</p>

                        <div class="mb-4 sm:mb-5 lg:mb-6">
                            <span class="text-2xl sm:text-3xl lg:text-4xl font-bold" :style="{ color: c.text_primary }">{{ formatPrice(tier.price) }}</span>
                            <span class="text-xs sm:text-sm" :style="{ color: c.text_secondary }">/{{ tier.period }}</span>
                        </div>

                        <ul class="space-y-2 sm:space-y-2.5 lg:space-y-3 mb-5 sm:mb-6 lg:mb-8" role="list">
                            <li v-for="(feature, fIdx) in tier.features" :key="fIdx" class="flex items-start gap-2 sm:gap-3">
                                <svg class="w-4 h-4 sm:w-5 sm:h-5 flex-shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24" :style="{ color: c.accent }" aria-hidden="true">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/>
                                </svg>
                                <span class="text-xs sm:text-sm" :style="{ color: c.text_secondary }">{{ feature }}</span>
                            </li>
                        </ul>

                        <a :href="getCheckoutUrl(tier)"
                           class="block w-full py-2.5 sm:py-3 rounded-xl text-sm sm:text-base font-semibold text-center transition-all active:scale-[0.98]"
                           :style="{
                               backgroundColor: tier.featured ? c.accent : 'transparent',
                               color: tier.featured ? '#fff' : c.text_primary,
                               border: tier.featured ? 'none' : '1px solid ' + borderColor
                           }">
                            {{ tier.cta || 'Empezar ahora' }}
                        </a>
                    </article>
                </div>

                <div class="text-center mt-8 sm:mt-12">
                    <p class="text-sm" :style="{ color: c.text_secondary }">
                        {{ plan.pricing_guarantee_text || '✓ Cancela cuando quieras · ✓ Garantía de satisfacción' }}
                    </p>
                </div>
            </div>
        </section>

        <!-- FAQ Section -->
        <section id="faq" class="py-16 sm:py-20 lg:py-28" :style="{ backgroundColor: c.bg_secondary }">
            <div class="max-w-3xl mx-auto px-4 sm:px-6 lg:px-8">
                <div class="text-center mb-10 sm:mb-16">
                    <h2 class="text-2xl sm:text-3xl lg:text-4xl xl:text-5xl font-bold mb-4 sm:mb-6" :style="{ color: c.text_primary }">
                        {{ plan.faq_title || 'Preguntas frecuentes' }}
                    </h2>
                    <p class="text-base sm:text-lg" :style="{ color: c.text_secondary }">
                        {{ plan.faq_subtitle || 'Todo lo que necesitas saber antes de empezar' }}
                    </p>
                </div>

                <div class="space-y-3 sm:space-y-4" role="list">
                    <div v-for="(faq, index) in faqs" :key="index" class="rounded-xl overflow-hidden border" :style="{ borderColor: borderColor }">
                        <button @click="toggleFaq(index)"
                                class="w-full flex items-center justify-between p-5 sm:p-6 text-left transition-colors"
                                :aria-expanded="openFaq === index"
                                :aria-controls="`faq-answer-${index}`">
                            <span class="font-semibold pr-4 text-sm sm:text-base" :style="{ color: c.text_primary }">{{ faq.question }}</span>
                            <svg class="w-5 h-5 flex-shrink-0 transition-transform" :class="{ 'rotate-180': openFaq === index }"
                                 fill="none" stroke="currentColor" viewBox="0 0 24 24" :style="{ color: c.text_secondary }" aria-hidden="true">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"/>
                            </svg>
                        </button>
                        <div v-show="openFaq === index" :id="`faq-answer-${index}`" class="px-5 sm:px-6 pb-5 sm:pb-6" role="region">
                            <p class="text-sm sm:text-base" :style="{ color: c.text_secondary }">{{ faq.answer }}</p>
                        </div>
                    </div>
                </div>

                <div class="text-center mt-8 sm:mt-12">
                    <p class="mb-4" :style="{ color: c.text_secondary }">¿Tienes más preguntas?</p>
                    <a :href="`mailto:${coach.email}`"
                       class="inline-flex items-center gap-2 font-semibold hover:opacity-80 transition-colors" :style="{ color: c.accent }">
                        Contáctanos
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 8l4 4m0 0l-4 4m4-4H3"/></svg>
                    </a>
                </div>
            </div>
        </section>

        <!-- Final CTA Section -->
        <section class="py-16 sm:py-20 lg:py-28" :style="{ backgroundColor: c.bg_primary }">
            <div class="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 text-center">
                <h2 class="text-2xl sm:text-3xl lg:text-4xl xl:text-5xl font-bold mb-4 sm:mb-6" :style="{ color: c.text_primary }">
                    {{ plan.final_cta_title || '¿Listo para transformar tu vida?' }}
                </h2>
                <p class="text-base sm:text-lg lg:text-xl mb-8 sm:mb-10 max-w-2xl mx-auto" :style="{ color: c.text_secondary }">
                    {{ plan.final_cta_subtitle || `Únete a cientos de personas que ya han conseguido resultados increíbles con ${coach.name}` }}
                </p>
                <a href="#precios"
                   class="inline-flex items-center justify-center px-8 sm:px-10 py-4 sm:py-5 rounded-xl text-lg sm:text-xl font-bold text-white transition-all active:scale-[0.98]"
                   :style="{ backgroundColor: c.accent }">
                    {{ plan.final_cta_button_text || 'Empieza tu transformación hoy' }}
                </a>
            </div>
        </section>

        <!-- Footer -->
        <footer class="border-t py-8 sm:py-12" :style="{ borderColor: borderColor, backgroundColor: c.bg_primary }">
            <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                <div class="flex flex-col sm:flex-row items-center justify-between gap-4 sm:gap-6">
                    <div class="flex items-center gap-3">
                        <img v-if="coach.profile_photo" :src="coach.profile_photo" :alt="coach.name" class="w-8 h-8 sm:w-10 sm:h-10 rounded-full object-cover" width="40" height="40" loading="lazy">
                        <span class="font-bold text-sm sm:text-base" :style="{ color: c.text_primary }">{{ coach.business_name || coach.name }}</span>
                    </div>
                    <div class="flex flex-wrap items-center justify-center gap-4 sm:gap-6 text-xs sm:text-sm" :style="{ color: c.text_secondary }">
                        <a href="/terminos" class="hover:opacity-80 transition-colors">Términos y condiciones</a>
                        <a href="/privacidad" class="hover:opacity-80 transition-colors">Política de privacidad</a>
                    </div>
                    <p class="text-xs sm:text-sm" :style="{ color: c.text_secondary }">
                        © {{ new Date().getFullYear() }} {{ coach.business_name || coach.name }}
                    </p>
                </div>
            </div>
        </footer>

        <!-- Lightbox Modal -->
        <Teleport to="body">
            <Transition name="fade">
                <div v-if="lightboxOpen && lightboxResult"
                     class="fixed inset-0 z-[100] bg-black/95 flex items-center justify-center p-4"
                     @click.self="closeLightbox"
                     @touchstart="handleTouchStart"
                     @touchend="handleTouchEnd"
                     role="dialog"
                     aria-modal="true"
                     :aria-label="`Transformación de ${lightboxResult.client_name}`">

                    <button @click="closeLightbox" class="absolute top-4 right-4 z-10 p-2 rounded-full bg-white/10 hover:bg-white/20 transition-colors" aria-label="Cerrar">
                        <svg class="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg>
                    </button>

                    <button v-if="results && results.length > 1" @click.stop="prevLightboxResult"
                            class="absolute left-2 sm:left-4 top-1/2 -translate-y-1/2 p-2 sm:p-3 rounded-full bg-white/10 hover:bg-white/20 transition-colors z-10" aria-label="Anterior">
                        <svg class="w-5 h-5 sm:w-6 sm:h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"/></svg>
                    </button>
                    <button v-if="results && results.length > 1" @click.stop="nextLightboxResult"
                            class="absolute right-2 sm:right-4 top-1/2 -translate-y-1/2 p-2 sm:p-3 rounded-full bg-white/10 hover:bg-white/20 transition-colors z-10" aria-label="Siguiente">
                        <svg class="w-5 h-5 sm:w-6 sm:h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/></svg>
                    </button>

                    <div class="w-full max-w-5xl max-h-[90vh] overflow-y-auto">
                        <div class="grid grid-cols-2 gap-3 sm:gap-4 md:gap-8 mb-4 sm:mb-6">
                            <div class="relative">
                                <span class="absolute top-3 left-3 px-3 py-1 bg-black/60 rounded-full text-xs font-semibold text-white z-10">ANTES</span>
                                <div class="aspect-[3/4] rounded-lg sm:rounded-xl overflow-hidden bg-[#1a1a1a]">
                                    <img v-if="lightboxResult.before_image" :src="lightboxResult.before_image" :alt="`${lightboxResult.client_name} - Antes`" class="w-full h-full object-cover">
                                </div>
                            </div>
                            <div class="relative">
                                <span class="absolute top-3 left-3 px-3 py-1 rounded-full text-xs font-semibold text-white z-10" :style="{ backgroundColor: c.accent }">DESPUÉS</span>
                                <div class="aspect-[3/4] rounded-lg sm:rounded-xl overflow-hidden bg-[#1a1a1a]">
                                    <img v-if="lightboxResult.after_image" :src="lightboxResult.after_image" :alt="`${lightboxResult.client_name} - Después`" class="w-full h-full object-cover">
                                </div>
                            </div>
                        </div>

                        <div class="text-center text-white">
                            <h3 class="text-xl sm:text-2xl md:text-3xl font-bold mb-2">{{ lightboxResult.client_name }}</h3>
                            <p class="text-base sm:text-lg font-medium mb-3 sm:mb-4" :style="{ color: c.accent }">{{ lightboxResult.transformation_duration }}</p>
                            <p v-if="lightboxResult.testimonial" class="text-gray-300 text-sm sm:text-base md:text-lg max-w-2xl mx-auto italic">
                                "{{ lightboxResult.testimonial }}"
                            </p>
                            <div v-if="results && results.length > 1" class="flex justify-center gap-2 mt-4 sm:mt-6">
                                <button v-for="(_, i) in results" :key="i" @click.stop="lightboxIndex = i; lightboxResult = results[i]"
                                      class="w-2 h-2 rounded-full cursor-pointer transition-all"
                                      :style="{ backgroundColor: lightboxIndex === i ? c.accent : 'rgba(255,255,255,0.3)', width: lightboxIndex === i ? '24px' : '8px' }"
                                      :aria-label="`Resultado ${i + 1}`">
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </Transition>
        </Teleport>
    </div>
</template>

<script setup>
import { ref, computed, onUnmounted } from 'vue';
import { Head } from '@inertiajs/vue3';

const props = defineProps({
    plan: Object,
    coach: Object,
    results: Array,
    colors: { type: Object, default: () => ({}) },
});

// Colors with defaults
const c = computed(() => ({
    bg_primary: props.colors.bg_primary || '#0a0a0a',
    bg_secondary: props.colors.bg_secondary || '#111111',
    bg_card: props.colors.bg_card || '#1a1a1a',
    accent: props.colors.accent || '#dc2626',
    text_primary: props.colors.text_primary || '#ffffff',
    text_secondary: props.colors.text_secondary || '#9ca3af',
    header_bg: props.colors.header_bg || '#0a0a0a',
    banner_bg: props.colors.banner_bg || '#dc2626',
}));

const borderColor = computed(() => {
    const hex = c.value.text_primary.replace('#', '');
    const r = parseInt(hex.substring(0, 2), 16);
    const g = parseInt(hex.substring(2, 4), 16);
    const b = parseInt(hex.substring(4, 6), 16);
    return `rgba(${r},${g},${b},0.08)`;
});

const rootStyles = computed(() => ({
    backgroundColor: c.value.bg_primary,
    color: c.value.text_primary,
}));

const mobileMenuOpen = ref(false);
const openFaq = ref(0);

// Lightbox
const lightboxOpen = ref(false);
const lightboxResult = ref(null);
const lightboxIndex = ref(0);

const openLightbox = (result, index) => {
    lightboxResult.value = result;
    lightboxIndex.value = index;
    lightboxOpen.value = true;
    document.body.style.overflow = 'hidden';
};

const closeLightbox = () => {
    lightboxOpen.value = false;
    lightboxResult.value = null;
    document.body.style.overflow = '';
};

const nextLightboxResult = () => {
    if (props.results?.length) {
        lightboxIndex.value = (lightboxIndex.value + 1) % props.results.length;
        lightboxResult.value = props.results[lightboxIndex.value];
    }
};

const prevLightboxResult = () => {
    if (props.results?.length) {
        lightboxIndex.value = (lightboxIndex.value - 1 + props.results.length) % props.results.length;
        lightboxResult.value = props.results[lightboxIndex.value];
    }
};

// Touch swipe
let touchStartX = 0;
const handleTouchStart = (e) => { touchStartX = e.changedTouches[0].screenX; };
const handleTouchEnd = (e) => {
    const delta = touchStartX - e.changedTouches[0].screenX;
    if (delta > 50) nextLightboxResult();
    else if (delta < -50) prevLightboxResult();
};

// Keyboard support for lightbox
const handleKeydown = (e) => {
    if (!lightboxOpen.value) return;
    if (e.key === 'Escape') closeLightbox();
    if (e.key === 'ArrowRight') nextLightboxResult();
    if (e.key === 'ArrowLeft') prevLightboxResult();
};
if (typeof window !== 'undefined') {
    window.addEventListener('keydown', handleKeydown);
}
onUnmounted(() => {
    if (typeof window !== 'undefined') {
        window.removeEventListener('keydown', handleKeydown);
    }
});

// Navigation links
const navLinks = computed(() => {
    if (props.plan.nav_links?.length) return props.plan.nav_links;
    return [
        { id: 1, label: 'Método', href: '#metodo' },
        { id: 2, label: 'Qué incluye', href: '#incluye' },
        { id: 3, label: 'Resultados', href: '#resultados' },
        { id: 4, label: 'Planes', href: '#precios' },
        { id: 5, label: 'FAQ', href: '#faq' },
    ];
});

// Hero stats
const heroStats = computed(() => {
    if (props.plan.hero_stats?.length) return props.plan.hero_stats;
    return [
        { id: 1, title: 'Coach certificado', subtitle: 'Profesional cualificado' },
        { id: 2, title: '+500 transformaciones', subtitle: 'Resultados reales' },
        { id: 3, title: 'Seguimiento por app', subtitle: 'Soporte continuo' },
    ];
});

// Method items
const methodItems = computed(() => {
    if (props.plan.method_items?.length) return props.plan.method_items;
    return [
        { id: 1, icon: 'dumbbell', title: 'Plan de entrenamiento progresivo', description: 'Rutinas diseñadas específicamente para tus objetivos, nivel y disponibilidad.' },
        { id: 2, icon: 'nutrition', title: 'Nutrición estratégica', description: 'Plan alimenticio personalizado que se adapta a tu estilo de vida y preferencias.' },
        { id: 3, icon: 'tracking', title: 'Seguimiento 1:1', description: 'Revisiones semanales y ajustes continuos para maximizar tus resultados.' },
    ];
});

// Includes items
const includesItems = computed(() => {
    if (props.plan.includes_items?.length) return props.plan.includes_items;
    return [
        { id: 1, title: 'Evaluación integral inicial', description: 'Análisis completo de tu estado actual' },
        { id: 2, title: 'Plan de entrenamiento', description: 'Rutinas personalizadas semana a semana' },
        { id: 3, title: 'Plan nutricional', description: 'Guía alimenticia adaptada a ti' },
        { id: 4, title: 'Seguimiento por app', description: 'Comunicación directa con tu coach' },
        { id: 5, title: 'Ajustes semanales', description: 'Optimización continua de tu plan' },
        { id: 6, title: 'Acceso a comunidad', description: 'Grupo exclusivo de apoyo' },
    ];
});

// How it works steps
const howItWorksSteps = computed(() => {
    if (props.plan.how_it_works_steps?.length) return props.plan.how_it_works_steps;
    return [
        { id: 1, title: 'Aplica', description: 'Completa el formulario con tus datos y objetivos.' },
        { id: 2, title: 'Plan personalizado', description: 'Recibirás tu plan adaptado a ti.' },
        { id: 3, title: 'Seguimiento', description: 'Conecta con tu coach y comienza.' },
        { id: 4, title: 'Resultados', description: 'Ve tu progreso y alcanza tus metas.' },
    ];
});

// Pricing tiers
const pricingTiers = computed(() => {
    if (props.plan.pricing_tiers?.length) {
        return props.plan.pricing_tiers.map((tier, index) => ({
            ...tier,
            id: tier.id || (index + 1),
            featured: tier.featured === true || tier.featured === 'true' || tier.featured === 1 || tier.featured === '1',
        }));
    }
    return [
        { id: 1, name: 'Mensual', description: 'Perfecto para probar', price: props.plan.price || 0, period: 'mes', features: ['Plan de entrenamiento personalizado', 'Plan nutricional básico', 'Soporte por chat', 'Acceso a la app'], featured: false, cta: 'Empezar ahora' },
        { id: 2, name: 'Trimestral', description: 'Más resultados, mejor precio', price: (props.plan.price || 0) * 2.5, period: '3 meses', features: ['Todo lo del plan mensual', 'Videollamadas mensuales', 'Ajustes semanales del plan', 'Acceso a masterclass', 'Ahorra un 17%'], featured: true, cta: 'Mejor opción' },
        { id: 3, name: 'Semestral', description: 'Transformación completa', price: (props.plan.price || 0) * 4.5, period: '6 meses', features: ['Todo lo del plan trimestral', 'Seguimiento premium', 'Sesiones 1:1 extras', 'Ahorra un 25%'], featured: false, cta: 'Empezar ahora' },
    ];
});

// FAQs
const faqs = computed(() => {
    if (props.plan.faqs?.length) return props.plan.faqs;
    return [
        { question: '¿Para quién es este programa?', answer: 'Este programa está diseñado para cualquier persona que quiera transformar su físico de manera sostenible, independientemente de su nivel de experiencia.' },
        { question: '¿Necesito equipo de gimnasio?', answer: 'No necesariamente. Podemos adaptar el programa tanto para entrenamiento en casa como en gimnasio.' },
        { question: '¿Cuánto tiempo tarda en verse resultados?', answer: 'La mayoría de nuestros clientes empiezan a ver cambios notables en las primeras 4-6 semanas.' },
        { question: '¿Puedo cancelar en cualquier momento?', answer: 'Sí, puedes cancelar tu suscripción en cualquier momento sin penalizaciones.' },
        { question: '¿El plan de nutrición incluye recetas?', answer: 'Sí, incluimos recetas fáciles de preparar y una guía completa de alimentación adaptada a tus preferencias.' },
    ];
});

// Coach section
const coachSectionPhoto = computed(() => {
    if (props.plan.coach_section_photo) return `/storage/${props.plan.coach_section_photo}`;
    return props.coach.profile_photo || null;
});

const coachSectionTitle = computed(() => props.plan.coach_section_title || `¿Quién es ${props.coach.name}?`);

const coachSectionBio = computed(() => {
    return props.plan.coach_section_bio || props.coach.bio || `${props.coach.name} es un entrenador personal certificado con años de experiencia ayudando a personas a alcanzar sus metas de fitness.`;
});

const coachSectionTagline = computed(() => props.plan.coach_section_tagline || 'Tu coach');

const coachCredentials = computed(() => {
    if (props.plan.coach_section_stats) {
        const stats = props.plan.coach_section_stats.split('|').map(s => s.trim()).filter(s => s);
        if (stats.length) return stats;
    }
    if (props.coach.credentials?.length) return props.coach.credentials;
    return ['Entrenador personal certificado', 'Especialista en nutrición deportiva', 'Años de experiencia transformando vidas'];
});

// Helpers
const formatPrice = (price) => {
    const currency = props.plan.currency || 'USD';
    const symbol = props.plan.currency_symbol || '$';
    const supported = ['USD', 'EUR', 'GBP', 'MXN', 'COP', 'ARS', 'CLP', 'PEN', 'DOP'];
    if (supported.includes(currency)) {
        return new Intl.NumberFormat('es-ES', { style: 'currency', currency, minimumFractionDigits: 0 }).format(price);
    }
    return `${symbol}${new Intl.NumberFormat('es-ES', { minimumFractionDigits: 0 }).format(price)}`;
};

const getCheckoutUrl = (tier) => {
    if (tier.link && tier.link !== '#') return tier.link;
    const tierId = tier.id;
    if (tierId && tierId !== 'undefined') return `/checkout/plan/${props.plan.slug}/${tierId}`;
    return `/checkout/plan/${props.plan.slug}`;
};

const toggleFaq = (index) => { openFaq.value = openFaq.value === index ? -1 : index; };

// Results pagination
const resultsPage = ref(0);
const resultsPerPage = 4;
const totalResultsPages = computed(() => {
    if (!props.results?.length) return 0;
    return Math.ceil(props.results.length / resultsPerPage);
});
const visibleResults = computed(() => {
    if (!props.results?.length) return [];
    const start = resultsPage.value * resultsPerPage;
    return props.results.slice(start, start + resultsPerPage);
});
const nextResultsPage = () => { if (resultsPage.value < totalResultsPages.value - 1) resultsPage.value++; };
const prevResultsPage = () => { if (resultsPage.value > 0) resultsPage.value--; };
</script>

<style scoped>
html { scroll-behavior: smooth; }
.fade-enter-active, .fade-leave-active { transition: opacity 0.3s ease; }
.fade-enter-from, .fade-leave-to { opacity: 0; }
</style>
