@extends('layouts.landing')

@php
    use App\Enums\TicketCapacityStrategy;
    use App\Enums\TicketIac;
    use App\Services\FeeCalculator;

    /** @var \App\Models\Event $event */
    $tickets = $event->ticketTypes;

    $payloadTickets = $tickets->map(function ($t) {
        $effectiveCap = $t->effectiveCapacity();
        $sold = (int) ($t->quantity_sold ?? 0);
        $available = $effectiveCap === null ? 9999 : max(0, $effectiveCap - $sold);
        $basePrice = (float) ($t->sale_price ?? $t->price);
        $totalPrice = FeeCalculator::calculateTotalForAttendee($basePrice);

        return [
            'id' => $t->id,
            'name' => $t->name,
            'description' => (string) $t->description,
            'price' => $totalPrice,
            'price_label' => '$'.number_format($totalPrice, 2),
            'available' => $available,
            'unlimited' => $effectiveCap === null,
            'iac' => $t->iac instanceof TicketIac ? $t->iac->value : (string) ($t->iac ?? 'required'),
            'is_active' => (bool) $t->is_active,
        ];
    })->values();

    $customFieldsByTicket = $tickets->mapWithKeys(function ($t) {
        return [$t->id => $t->customFields->map(function ($cf) {
            return [
                'id' => $cf->id,
                'slug' => $cf->slug,
                'label' => $cf->label,
                'type' => $cf->type?->value ?? 'text',
                'required' => (bool) $cf->required,
                'options' => is_array($cf->options) ? array_values($cf->options) : [],
                'sort_order' => (int) $cf->sort_order,
            ];
        })->values()->all()];
    });

    $feePreview = FeeCalculator::calculate(0.0);

    $checkoutConfig = [
        'eventId'              => $event->id,
        'eventSlug'            => $event->slug,
        'storeUrl'             => route('landing.event.checkout', ['event' => $event->slug]),
        'fixedFee'             => FeeCalculator::fixedFee(),
        'percentageFee'        => FeeCalculator::percentageFee(),
        'tickets'              => $payloadTickets->values(),
        'customFieldsByTicket' => $customFieldsByTicket,
        'strings'              => [
            'modalTitle' => __('Detalle de los asistentes'),
        ],
    ];

    $venueHeader = $event->venue;
    $headerMapEmbedUrl = null;
    $headerHasCoords = false;
    $headerGeocodeQuery = '';
    $venueDirectionsUrl = null;
    $googleMapsBrowserKey = (string) config('services.google_maps.browser_key');

    if ($venueHeader) {
        $headerHasCoords = $venueHeader->latitude !== null && $venueHeader->longitude !== null;
        if ($headerHasCoords) {
            $headerMapEmbedUrl = 'https://www.google.com/maps?q='.urlencode($venueHeader->latitude.','.$venueHeader->longitude).'&z=15&output=embed';
        } else {
            $headerParts = [];
            foreach (['address_line_1', 'address_line_2', 'city', 'region', 'postal_code', 'country'] as $field) {
                $val = $venueHeader->{$field} ?? null;
                if ($val !== null && $val !== '') {
                    $headerParts[] = $val;
                }
            }
            $headerGeocodeQuery = implode(', ', $headerParts);
            if ($headerGeocodeQuery === '') {
                $headerGeocodeQuery = trim(($venueHeader->name ?? '').' '.($venueHeader->city ?? ''));
            }
            if ($headerGeocodeQuery !== '') {
                $headerMapEmbedUrl = 'https://www.google.com/maps?q='.urlencode($headerGeocodeQuery).'&z=14&output=embed';
            }
        }

        if ($headerHasCoords) {
            $venueDirectionsUrl = 'https://www.google.com/maps/dir/?api=1&destination='.urlencode($venueHeader->latitude.','.$venueHeader->longitude);
        } elseif (filled((string) ($venueHeader->address_line_1 ?? ''))) {
            $venueDirectionsUrl = 'https://www.google.com/maps/search/?api=1&query='.urlencode(trim((string) $venueHeader->address_line_1.' '.($venueHeader->city ?? '')));
        } elseif ($headerGeocodeQuery !== '') {
            $venueDirectionsUrl = 'https://www.google.com/maps/search/?api=1&query='.urlencode($headerGeocodeQuery);
        }
    }
    $showHeaderVenueMap = $headerMapEmbedUrl !== null;
@endphp

@section('title', $event->title.' | '.config('app.name'))
@section('meta_description', $event->short_description ?: Str::limit(strip_tags((string) $event->description), 160))
@section('og_title', $event->title.' | '.config('app.name'))
@section('og_image', $card['image'])

@push('jsonld')
    <script type="application/ld+json">
    {!! json_encode([
        '@context' => 'https://schema.org',
        '@type' => 'Event',
        'name' => $event->title,
        'description' => $event->short_description ?: strip_tags($event->description),
        'image' => $event->featured_image_path ? asset($event->featured_image_path) : asset('images/logotipo-regiticket.png'),
        'startDate' => $event->start_date?->toIso8601String(),
        'endDate' => $event->end_date?->toIso8601String(),
        'eventStatus' => 'https://schema.org/EventScheduled',
        'eventAttendanceMode' => 'https://schema.org/OfflineEventAttendanceMode',
        'location' => [
            '@type' => 'Place',
            'name' => $event->venue?->name,
            'address' => [
                '@type' => 'PostalAddress',
                'streetAddress' => $event->venue?->address_line_1,
                'addressLocality' => $event->venue?->city,
                'addressRegion' => $event->venue?->region,
                'postalCode' => $event->venue?->postal_code,
                'addressCountry' => $event->venue?->country ?: 'US'
            ],
            'geo' => $event->venue?->latitude ? [
                '@type' => 'GeoCoordinates',
                'latitude' => $event->venue->latitude,
                'longitude' => $event->venue->longitude
            ] : null
        ],
        'offers' => $tickets->map(fn($t) => [
            '@type' => 'Offer',
            'name' => $t->name,
            'price' => FeeCalculator::calculateTotalForAttendee((float)($t->sale_price ?? $t->price)),
            'priceCurrency' => 'USD',
            'availability' => ($t->effectiveCapacity() === null || ($t->effectiveCapacity() - $t->quantity_sold) > 0) ? 'https://schema.org/InStock' : 'https://schema.org/OutOfStock',
            'url' => url()->current()
        ])->values()->all(),
        'organizer' => [
            '@type' => 'Organization',
            'name' => $event->organization_name ?: config('app.name'),
            'url' => config('app.url')
        ]
    ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) !!}
    </script>
@endpush

@if (! $tickets->isEmpty())
    @push('head')
        {{-- Estilos SweetAlert2: mismo aspecto que el modal nativo; el mapa usa Swal; el checkout usa Vue + Teleport --}}
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css" crossorigin="anonymous">
    @endpush
@endif

@section('content')
    <div class="rt-page-under-fixed-nav">
        <section class="rt-event-header pb-5" aria-labelledby="rt-event-show-title">
            <div class="container">
                <div class="row align-items-stretch gy-4 gy-lg-0 rt-event-header-row">

                    {{-- Columna izquierda: info del evento --}}
                    <div class="col-lg-6 d-flex flex-column justify-content-center pe-lg-5">
                        <div class="rt-event-header-info-inner">

                            {{-- Breadcrumb --}}
                            <nav aria-label="{{ __('Miga de pan') }}" class="mb-4">
                                <p class="rt-event-breadcrumb mb-0">
                                    <a href="{{ route('landing.events') }}">{{ __('Eventos') }}</a>
                                    <span class="mx-1" aria-hidden="true">/</span>
                                    <span>{{ $event->category?->name ?: __('Evento') }}</span>
                                </p>
                            </nav>

                            {{-- Badges --}}
                            <div class="d-flex align-items-center gap-2 flex-wrap mb-3">
                                <span class="rt-event-category-badge">
                                    <i class="bi bi-tag-fill" aria-hidden="true"></i>
                                    {{ $event->category?->name ?: __('Evento') }}
                                </span>
                                <span class="rt-event-available-pill">{{ __('En venta') }}</span>
                            </div>

                            {{-- Título --}}
                            <h1 id="rt-event-show-title" class="rt-event-header-title text-white mb-0">{{ $event->title }}</h1>

                            <hr class="rt-event-header-divider">

                            {{-- Meta: lugar y fecha --}}
                            <div class="rt-event-header-meta">
                                @if ($event->venue)
                                    <div class="rt-event-header-meta-item">
                                        <i class="bi bi-geo-alt-fill" aria-hidden="true"></i>
                                        <span>{{ $event->venue->name }}{{ $event->venue->city ? ', '.$event->venue->city : '' }}</span>
                                    </div>
                                @endif
                                <div class="rt-event-header-meta-item">
                                    <span>{{ $card['time_label'] }}</span>
                                </div>

                                @if ($showHeaderVenueMap)
                                    <div class="mt-3 pt-1 d-flex flex-wrap gap-2">
                                        <button
                                            type="button"
                                            class="btn btn-sm rt-event-header-map-btn"
                                            id="rt-event-open-venue-map"
                                            data-google-maps-key="{{ e($googleMapsBrowserKey) }}"
                                            data-lat="{{ $headerHasCoords ? e($venueHeader->latitude) : '' }}"
                                            data-lng="{{ $headerHasCoords ? e($venueHeader->longitude) : '' }}"
                                            data-geocode-query="{{ e($headerGeocodeQuery) }}"
                                            data-map-embed="{{ e($headerMapEmbedUrl) }}"
                                            data-venue-label="{{ e($venueHeader->name) }}"
                                            data-directions-url="{{ e($venueDirectionsUrl ?? '') }}"
                                        >
                                            <i class="bi bi-map me-1" aria-hidden="true"></i>{{ __('Ver mapa') }}
                                        </button>

                                        @if ($venueDirectionsUrl)
                                            <a href="{{ $venueDirectionsUrl }}" 
                                               target="_blank" rel="noopener noreferrer" 
                                               class="btn btn-sm btn-outline-light rounded-pill px-3 shadow-sm fw-bold border-opacity-25"
                                               style="background: rgba(255,255,255,0.1); backdrop-filter: blur(4px);">
                                                <i class="bi bi-sign-turn-right me-1"></i>{{ __('Cómo llegar') }}
                                            </a>
                                        @endif
                                    </div>
                                @endif

                            </div>


                        </div>
                    </div>

                    {{-- Columna derecha: imagen destacada --}}
                    <div class="col-lg-6">
                        <div class="rt-event-hero-media-card">
                            <div class="rt-event-hero-media-frame">
                                <img
                                    src="{{ $card['image'] }}"
                                    alt="{{ $event->title }}"
                                    class="rt-event-hero-media-img"
                                    loading="eager"
                                    decoding="async"
                                >
                            </div>
                        </div>
                    </div>

                </div>
            </div>
        </section>

        <article class="rt-event-body py-5 py-lg-6">
            <div class="container">
                <div class="row gy-4">
                    <div class="col-lg-7">
                        @if ($event->short_description)
                            <p class="lead mb-4">{{ $event->short_description }}</p>
                        @endif
                        @if ($event->description)
                            <div class="rt-landing-prose">
                                {!! $event->description !!}
                            </div>
                        @endif
                    </div>

                    <div class="col-lg-5">
                        @if ($tickets->isEmpty())
                            <div class="rt-tickets-wrapper rt-tickets-wrapper--empty">
                                <p class="mb-0 text-secondary">{{ __('Las entradas para este evento aún no están publicadas.') }}</p>
                            </div>
                        @else
                            @include('landing.partials.event-checkout-vue')
                        @endif
                    </div>

                </div>
            </div>
        </article>
    </div>
@endsection

@push('scripts')
    @if (! $tickets->isEmpty() || $showHeaderVenueMap)
        <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    @endif
    @if ($showHeaderVenueMap)
        <script src="{{ asset('js/landing-venue-map-modal.js') }}?v=2"></script>
        <script>
            (function () {
                function openVenueMapModal() {
                    var btn = document.getElementById('rt-event-open-venue-map');
                    if (!btn) {
                        return;
                    }
                    var embed = btn.getAttribute('data-map-embed');
                    var label = btn.getAttribute('data-venue-label') || '';
                    if (!embed) {
                        return;
                    }
                    if (typeof Swal === 'undefined') {
                        window.open(embed.replace(/&output=embed/, ''), '_blank', 'noopener,noreferrer');
                        return;
                    }
                    Swal.fire({
                        title: label || @json(__('Ubicación del recinto')),
                        html: '<div id="rt-swal-venue-map-slot"></div>',
                        width: 'min(92vw, 720px)',
                        padding: '1.25rem',
                        showCloseButton: true,
                        confirmButtonText: @json(__('Cerrar')),
                        confirmButtonColor: '#b72f27',
                        customClass: {
                            popup: 'rt-swal-venue-map-popup',
                            confirmButton: 'rt-swal-venue-map-confirm',
                        },
                        didOpen: function () {
                            var slot = document.getElementById('rt-swal-venue-map-slot');
                            if (!slot || !window.rtLandingVenueMapModal) {
                                return;
                            }
                            window.rtLandingVenueMapModal.initModalMap({
                                slot: slot,
                                apiKey: btn.getAttribute('data-google-maps-key') || '',
                                lat: btn.getAttribute('data-lat'),
                                lng: btn.getAttribute('data-lng'),
                                geocodeQuery: btn.getAttribute('data-geocode-query') || '',
                                directionsUrl: btn.getAttribute('data-directions-url'),
                                embedFallback: embed,
                                title: label,
                            });

                        },
                    });
                }
                document.addEventListener('DOMContentLoaded', function () {
                    var openBtn = document.getElementById('rt-event-open-venue-map');
                    if (!openBtn) {
                        return;
                    }
                    openBtn.addEventListener('click', openVenueMapModal);
                });
            })();
        </script>
    @endif
    @if (! $tickets->isEmpty())
        {{-- Vue global incluye compilador (template en #rt-checkout-template). Orden: Vue, luego bootstrap del checkout. --}}
        <script src="https://cdn.jsdelivr.net/npm/vue@3.5.13/dist/vue.global.prod.js" crossorigin="anonymous" defer></script>
        <script src="{{ asset('js/landing-checkout-vue.js') }}?v=1" defer></script>
    @endif
@endpush
