@extends('layouts.app')

@section('title', $product->meta_title ?: ($product->name . ' — Buy Online | Divine Drops Luxury Skincare'))
@section('meta_description', $product->meta_description ?: ($product->description ? Str::limit(strip_tags($product->description), 155) : 'Buy 100% natural Indian skincare online at Divine Drops. Free shipping on orders over ₹499.'))
@section('meta_keywords', $product->meta_keywords ?: ($product->name . ', natural skincare, divine drops, organic beauty'))
@section('og_title', $product->og_title ?: ($product->meta_title ?: $product->name))
@section('og_description', $product->og_description ?: ($product->meta_description ?: $product->description))
@section('og_image', asset($product->image))
@section('og_type', 'product')

@php
    $variants = $product->variants->count() > 0 ? $product->variants : collect([]);
    $defaultVariant = $variants->first();

    $activePrice = $defaultVariant ? $defaultVariant->price : $product->price;
    $activeCompare = $defaultVariant ? $defaultVariant->compare_at : $product->compare_at;
    $activeStock = $defaultVariant ? $defaultVariant->stock : $product->stock;

    $off = $activeCompare ? round((1 - $activePrice / $activeCompare) * 100) : null;
    $gallery = is_array($product->gallery) && count($product->gallery) > 0
        ? $product->gallery
        : array_values(array_unique(array_filter([$product->image, $product->image_alt])));

    $jsonLdData = [
        '@context' => 'https://schema.org/',
        '@type' => 'Product',
        'name' => $product->name,
        'image' => [asset($product->image)],
        'description' => strip_tags($product->meta_description ?: $product->description),
        'sku' => $product->slug,
        'brand' => [
            '@type' => 'Brand',
            'name' => 'Divine Drops'
        ],
        'aggregateRating' => [
            '@type' => 'AggregateRating',
            'ratingValue' => (string)($product->rating ?? 5.0),
            'reviewCount' => (string)($product->reviews_count ?? 120)
        ],
        'offers' => [
            '@type' => 'Offer',
            'url' => url()->current(),
            'priceCurrency' => 'INR',
            'price' => (string)$activePrice,
            'itemCondition' => 'https://schema.org/NewCondition',
            'availability' => $activeStock > 0 ? 'https://schema.org/InStock' : 'https://schema.org/OutOfStock'
        ]
    ];
@endphp

@section('json_ld')
<script type="application/ld+json">
{!! json_encode($jsonLdData, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) !!}
</script>
@endsection

@section('content')

    <x-breadcrumb :items="[['label' => 'Shop', 'url' => route('shop')], ['label' => $product->name]]" />

    {{-- Product overview --}}
    <section class="py-10 lg:py-16">
        <div class="container-shop grid gap-10 lg:grid-cols-2 lg:gap-16">

            {{-- Gallery --}}
            <div data-gallery>
                <div class="overflow-hidden bg-cream-50 rounded-2xl border border-cream-200 p-6 flex items-center justify-center">
                    <img src="{{ asset($product->image) }}" alt="{{ $product->name }}" width="900" height="900" class="aspect-square w-full object-contain max-h-[500px]" data-gallery-main>
                </div>
                <div class="mt-4 grid grid-cols-4 gap-3">
                    @foreach ($gallery as $i => $image)
                        <button type="button" class="cursor-pointer overflow-hidden border-2 bg-cream-50 rounded-xl p-2 transition-all {{ $i === 0 ? 'border-ink-900 shadow-sm' : 'border-transparent hover:border-cream-300' }}" data-gallery-thumb aria-label="View image {{ $i + 1 }}">
                            <img src="{{ asset($image) }}" alt="{{ $product->name }} — view {{ $i + 1 }}" width="900" height="900" class="aspect-square w-full object-contain" loading="lazy">
                        </button>
                    @endforeach
                </div>
            </div>

            {{-- Info --}}
            <div>
                <form action="{{ route('cart.add') }}" method="POST">
                    @csrf
                    <input type="hidden" name="product_id" value="{{ $product->id }}">

                    @if ($product->badge)
                        <span class="inline-block bg-terra-500 px-2.5 py-1 text-[10px] font-semibold tracking-[0.14em] text-white uppercase rounded-xs">{{ $product->badge }}</span>
                    @endif
                    <h1 class="mt-3 font-serif text-3xl font-medium text-ink-900 sm:text-4xl">{{ $product->name }}</h1>
                    <p class="mt-2 text-sm text-ink-500">{{ $product->tag }}</p>
                    <div class="mt-3"><x-stars :rating="$product->rating" :reviews="$product->reviews_count" size="h-4 w-4" /></div>

                    <!-- Dynamic Variant Price Display -->
                    <div class="mt-5 flex items-baseline gap-3">
                        <span class="text-3xl font-semibold text-ink-900" id="selected-price">₹{{ number_format($activePrice) }}</span>
                        <s class="text-lg text-ink-400 {{ $activeCompare ? '' : 'hidden' }}" id="selected-compare">₹{{ number_format($activeCompare) }}</s>
                        <span class="bg-terra-100 px-2 py-0.5 text-xs font-semibold text-terra-600 {{ $off ? '' : 'hidden' }}" id="selected-discount">Save {{ $off }}%</span>
                    </div>
                    <p class="mt-1 text-xs text-ink-400">MRP inclusive of all taxes | Stock Available: <strong class="text-ink-700" id="selected-stock">{{ $activeStock }}</strong> units</p>

                    {{-- Size Variant Selector --}}
                    <fieldset class="mt-7">
                        <legend class="field-label">Select Size / Volume</legend>
                        <div class="flex flex-wrap gap-2.5 mt-2">
                            @if($variants->count() > 0)
                                @foreach ($variants as $i => $var)
                                    <label class="cursor-pointer">
                                        <input type="radio" name="variant_id" value="{{ $var->id }}" class="peer sr-only" {{ $i === 0 ? 'checked' : '' }}
                                            data-price="{{ $var->price }}"
                                            data-compare="{{ $var->compare_at ?? 0 }}"
                                            data-stock="{{ $var->stock }}"
                                            data-name="{{ $var->name }}"
                                            onchange="updateVariantDetails(this)">
                                        <span class="inline-flex items-center gap-2 border border-sand-300 px-5 py-2.5 text-sm text-ink-700 transition-colors peer-checked:border-ink-900 peer-checked:bg-ink-900 peer-checked:text-white hover:border-ink-900 rounded-lg">
                                            <span>{{ $var->name }}</span>
                                            <span class="font-semibold">&middot; ₹{{ number_format($var->price) }}</span>
                                        </span>
                                    </label>
                                @endforeach
                            @else
                                <span class="inline-block border border-ink-900 bg-ink-900 text-white px-5 py-2.5 text-sm rounded-lg">Standard Size</span>
                            @endif
                        </div>
                    </fieldset>

                    {{-- Quantity + CTAs --}}
                    <div class="mt-7 flex flex-wrap items-stretch gap-3">
                        <div class="flex items-center border border-sand-300 rounded-lg" data-qty>
                            <button type="button" class="flex h-full w-11 cursor-pointer items-center justify-center text-ink-500 transition-colors hover:text-ink-900" data-qty-minus aria-label="Decrease quantity"><x-icon name="minus" class="h-4 w-4" /></button>
                            <input type="text" name="quantity" value="1" inputmode="numeric" aria-label="Quantity" class="w-10 border-0 bg-transparent p-0 text-center text-sm font-medium focus:ring-0 focus:outline-none">
                            <button type="button" class="flex h-full w-11 cursor-pointer items-center justify-center text-ink-500 transition-colors hover:text-ink-900" data-qty-plus aria-label="Increase quantity"><x-icon name="plus" class="h-4 w-4" /></button>
                        </div>
                        <button type="submit" class="btn-primary flex-1 sm:min-w-44 cursor-pointer">Add to Bag</button>
                    </div>
                </form>

                {{-- Benefit icons --}}
                <div class="mt-8 grid grid-cols-3 gap-4 border-y border-cream-200 py-6">
                    @foreach ([
                        ['icon' => 'leaf', 'label' => '100% Natural'],
                        ['icon' => 'shield', 'label' => 'Clinically Tested'],
                        ['icon' => 'droplet', 'label' => 'pH Balanced'],
                    ] as $benefit)
                        <div class="flex flex-col items-center gap-2 text-center">
                            <span class="flex h-11 w-11 items-center justify-center rounded-full bg-moss-50 text-moss-600"><x-icon :name="$benefit['icon']" class="h-5 w-5" /></span>
                            <span class="text-xs font-medium text-ink-700">{{ $benefit['label'] }}</span>
                        </div>
                    @endforeach
                </div>

                {{-- Accordions --}}
                <div class="mt-6 divide-y divide-cream-200 border-y border-cream-200">
                    <details class="group" open>
                        <summary class="flex cursor-pointer items-center justify-between py-4 text-sm font-semibold tracking-[0.12em] uppercase [&::-webkit-details-marker]:hidden">
                            Description
                            <x-icon name="chevron-down" class="h-4 w-4 shrink-0 transition-transform duration-200 group-open:rotate-180" />
                        </summary>
                        <p class="pb-5 text-sm leading-relaxed text-ink-700">{{ $product->description ?? 'A gentle, everyday formulation made in small batches with farm-fresh ingredients.' }}</p>
                    </details>
                    <details class="group">
                        <summary class="flex cursor-pointer items-center justify-between py-4 text-sm font-semibold tracking-[0.12em] uppercase [&::-webkit-details-marker]:hidden">
                            Shipping & Delivery
                            <x-icon name="chevron-down" class="h-4 w-4 shrink-0 transition-transform duration-200 group-open:rotate-180" />
                        </summary>
                        <p class="pb-5 text-sm leading-relaxed text-ink-700">Orders ship within 24 hours. Free shipping across India on orders above ₹499.</p>
                    </details>
                </div>
            </div>
        </div>
    </section>

    {{-- Related products --}}
    <section class="py-16 lg:py-20">
        <div class="container-shop">
            <x-section-heading eyebrow="Pairs well with" title="You May Also Like" :link="route('shop')" />
            <div class="grid grid-cols-2 gap-x-5 gap-y-10 md:grid-cols-4">
                @foreach ($related as $item)
                    <x-product-card :product="$item" />
                @endforeach
            </div>
        </div>
    </section>

<script>
function updateVariantDetails(el) {
    const price = parseFloat(el.dataset.price);
    const compare = parseFloat(el.dataset.compare);
    const stock = el.dataset.stock;

    document.getElementById('selected-price').innerText = '₹' + price.toLocaleString('en-IN');
    
    const compareEl = document.getElementById('selected-compare');
    const discountEl = document.getElementById('selected-discount');
    
    if (compare && compare > price) {
        compareEl.classList.remove('hidden');
        compareEl.innerText = '₹' + compare.toLocaleString('en-IN');
        const off = Math.round((1 - price / compare) * 100);
        discountEl.classList.remove('hidden');
        discountEl.innerText = 'Save ' + off + '%';
    } else {
        compareEl.classList.add('hidden');
        discountEl.classList.add('hidden');
    }

    const stockEl = document.getElementById('selected-stock');
    if (stockEl) stockEl.innerText = stock;
}
</script>
@endsection
