@extends('layouts.app')

@section('title', $product->name . ' - Memorycloset Media')

@section('description', \Illuminate\Support\Str::limit($product->description ?? 'Check out ' . $product->name . ' from Memorycloset Media. Exceptional visual storytelling services.', 160))

@section('content')
<div class="container mx-auto px-4 py-8">
    <x-breadcrumbs :items="[
        ['label' => 'Home', 'url' => route('home')],
        ['label' => 'Products', 'url' => route('products.index')],
        ['label' => $product->name]
    ]" />
    <div class="grid grid-cols-1 md:grid-cols-2 gap-8">
        <!-- Product Images -->
        <div>
            @if($product->images->count() > 0)
                <div class="mb-4">
                    <img id="main-image" src="{{ $product->images->first()->image_data_url }}" alt="{{ $product->name }}" 
                         onclick="openLightbox('{{ $product->images->first()->image_data_url }}')"
                         class="w-full h-96 object-cover rounded-lg cursor-zoom-in">
                </div>
                @if($product->images->count() > 1)
                    <div class="grid grid-cols-4 gap-2">
                        @foreach($product->images as $image)
                            <img src="{{ $image->image_data_url }}" alt="{{ $product->name }}" 
                                 onclick="changeMainImage('{{ $image->image_data_url }}'); openLightbox('{{ $image->image_data_url }}')"
                                 class="w-full h-24 object-cover rounded cursor-pointer hover:opacity-75 transition">
                        @endforeach
                    </div>
                @endif
            @else
                <div class="w-full h-96 bg-gradient-to-br from-[#f5f0e8] via-[#e8ddd0] to-[#d4c4b0] rounded-lg flex flex-col items-center justify-center relative overflow-hidden">
                    <!-- Decorative pattern -->
                    <div class="absolute inset-0 opacity-5">
                        <svg class="w-full h-full" viewBox="0 0 100 100" preserveAspectRatio="none">
                            <circle cx="20" cy="20" r="2" fill="#7d6a52"/>
                            <circle cx="80" cy="30" r="1.5" fill="#9d8566"/>
                            <circle cx="40" cy="70" r="1.5" fill="#c97d60"/>
                            <circle cx="70" cy="80" r="2" fill="#7d6a52"/>
                        </svg>
                    </div>
                    
                    <!-- Cupcake Icon -->
                    <div class="relative z-10 flex flex-col items-center">
                        <svg class="w-32 h-32 mb-4 drop-shadow-lg" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <!-- Cupcake Base -->
                            <path d="M12 18 L8 22 L16 22 Z" fill="#f5f0e8" stroke="#7d6a52" stroke-width="1.5" stroke-linejoin="round"/>
                            <path d="M8 22 L9 24 L15 24 L16 22 Z" fill="#e8ddd0" stroke="#7d6a52" stroke-width="1.5" stroke-linejoin="round"/>
                            
                            <!-- Frosting -->
                            <path d="M8 18 Q9 14 12 14 Q15 14 16 18" fill="#c97d60" stroke="#9d8566" stroke-width="1.5" stroke-linejoin="round"/>
                            <path d="M9 17 Q12 15 15 17" fill="#e8b4a0"/>
                            
                            <!-- Cherry on top -->
                            <circle cx="12" cy="12" r="3.5" fill="#c97d60" stroke="#9d8566" stroke-width="0.5"/>
                            <circle cx="12.5" cy="11.5" r="1.5" fill="#ff6b6b"/>
                            <path d="M12 8.5 L12 12" stroke="#7d6a52" stroke-width="1.5" stroke-linecap="round"/>
                            
                            <!-- Sprinkles -->
                            <circle cx="10" cy="16" r="1" fill="#ffd93d"/>
                            <circle cx="14" cy="17" r="1" fill="#6bcf7f"/>
                            <circle cx="11" cy="15.5" r="1" fill="#4d96ff"/>
                            <circle cx="13" cy="15.5" r="1" fill="#ff6b6b"/>
                        </svg>
                        <span class="text-[#7d6a52] font-semibold text-lg">No Image Available</span>
                    </div>
                </div>
            @endif
        </div>
        
        <!-- Product Info -->
        <div class="product-print">
            <h1 class="text-4xl font-serif font-bold mb-4 text-[#524438]">{{ $product->name }}</h1>
            @if($product->is_on_sale)
                <div class="mb-4">
                    <div class="flex items-center gap-3">
                        <span class="text-3xl font-bold text-[#c97d60]">R{{ number_format($product->sale_price, 2) }}</span>
                        <span class="text-xl text-[#9d8566] line-through">R{{ number_format($product->price, 2) }}</span>
                        <span class="bg-[#c97d60] text-white text-sm px-3 py-1 rounded-full font-semibold">ON SALE</span>
                    </div>
                </div>
            @else
                <p class="text-2xl font-bold text-[#7d6a52] mb-4">R{{ number_format($product->price, 2) }}</p>
            @endif
            <p class="text-[#645443] mb-6 leading-relaxed">{{ $product->description }}</p>
            
            @if($product->specs)
                <div class="mb-6 bg-[#faf8f5] p-4 rounded-xl border border-[#e8ddd0]">
                    <h3 class="text-lg font-serif font-semibold mb-3 text-[#524438]">Specifications</h3>
                    <ul class="space-y-2">
                        @foreach($product->specs as $key => $value)
                            <li class="flex items-start">
                                <span class="font-semibold text-[#524438] min-w-[120px]">{{ $key }}:</span>
                                <span class="text-[#645443]">{{ $value }}</span>
                            </li>
                        @endforeach
                    </ul>
                </div>
            @endif
            
            <div class="mb-6 bg-[#faf8f5] p-4 rounded-xl border border-[#e8ddd0]">
                <div class="space-y-2">
                    <p class="flex items-center">
                        <span class="font-semibold text-[#524438] min-w-[120px]">Category:</span>
                        <a href="{{ route('products.index', ['category' => $product->category_id]) }}" class="text-[#9d8566] hover:text-[#7d6a52] transition-colors">
                            {{ $product->category->name }}
                        </a>
                    </p>
                    <p class="flex items-center">
                        <span class="font-semibold text-[#524438] min-w-[120px]">Availability:</span>
                        <span class="{{ $product->availability ? 'text-green-600' : 'text-red-600' }} font-medium">
                            {{ $product->availability ? 'In Stock' : 'Out of Stock' }}
                        </span>
                    </p>
                </div>
            </div>
            
            <div class="space-y-3">
                @if($product->availability)
                    @if($cartQuantity > 0)
                        <div class="bg-green-50 border-2 border-green-200 rounded-xl p-4 mb-3">
                            <div class="flex items-center justify-between">
                                <div class="flex items-center gap-2">
                                    <svg class="w-5 h-5 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                                    </svg>
                                    <span class="text-green-700 font-semibold">{{ $cartQuantity }} in your cart</span>
                                </div>
                            </div>
                        </div>
                        
                        <div class="flex gap-2 mb-3">
                            <button onclick="updateCartQuantity({{ $product->id }}, {{ $cartQuantity - 1 }})" class="flex-1 bg-gray-200 text-gray-700 px-4 py-3 rounded-full font-semibold hover:bg-gray-300 transition-all">
                                -
                            </button>
                            <input type="number" 
                                   id="product-quantity" 
                                   value="{{ $cartQuantity }}" 
                                   min="0" 
                                   class="w-20 text-center border-2 border-[#e8ddd0] rounded-full font-semibold text-[#524438]"
                                   onchange="updateCartQuantity({{ $product->id }}, this.value)">
                            <button onclick="updateCartQuantity({{ $product->id }}, {{ $cartQuantity + 1 }})" class="flex-1 bg-gray-200 text-gray-700 px-4 py-3 rounded-full font-semibold hover:bg-gray-300 transition-all">
                                +
                            </button>
                        </div>
                    @endif
                    
                    <button onclick="quickAddToCart({{ $product->id }})" class="w-full bg-[#c97d60] text-white px-6 py-3 rounded-full font-semibold hover:bg-[#b86a4f] transition-all shadow-lg hover:shadow-xl transform hover:scale-105 flex items-center justify-center gap-2">
                        <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="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z"></path>
                        </svg>
                        {{ $cartQuantity > 0 ? 'Update Cart' : 'Add to Cart' }}
                    </button>
                    <button onclick="openModal('inquiry-modal')" class="w-full bg-[#7d6a52] text-white px-6 py-3 rounded-full font-semibold hover:bg-[#9d8566] transition-all shadow-lg hover:shadow-xl transform hover:scale-105">
                        Contact to Order
                    </button>
                    <div class="flex gap-2">
                        <button onclick="shareProduct()" class="flex-1 bg-white border-2 border-[#7d6a52] text-[#7d6a52] px-4 py-3 rounded-full hover:bg-[#f5f0e8] transition-all font-medium" aria-label="Share product" title="Share">
                            <svg class="w-5 h-5 inline mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8.684 13.342C8.886 12.938 9 12.482 9 12c0-.482-.114-.938-.316-1.342m0 2.684a3 3 0 110-2.684m0 2.684l6.632 3.316m-6.632-6l6.632-3.316m0 0a3 3 0 105.367-2.684 3 3 0 00-5.367 2.684zm0 9.316a3 3 0 105.368 2.684 3 3 0 00-5.368-2.684z"></path>
                            </svg>
                            Share
                        </button>
                        <button onclick="window.print()" class="flex-1 bg-white border-2 border-[#7d6a52] text-[#7d6a52] px-4 py-3 rounded-full hover:bg-[#f5f0e8] transition-all font-medium no-print" aria-label="Print page" title="Print">
                            <svg class="w-5 h-5 inline mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 17h2a2 2 0 002-2v-4a2 2 0 00-2-2H5a2 2 0 00-2 2v4a2 2 0 002 2h2m2 4h6a2 2 0 002-2v-4a2 2 0 00-2-2H9a2 2 0 00-2 2v4a2 2 0 002 2zm8-12V5a2 2 0 00-2-2H9a2 2 0 00-2 2v4h10z"></path>
                            </svg>
                            Print
                        </button>
                    </div>
                @else
                    <button disabled class="w-full bg-[#d4c4b0] text-[#7d6a52] px-6 py-3 rounded-full font-semibold cursor-not-allowed opacity-60">
                        Product Unavailable
                    </button>
                @endif
            </div>
        </div>
    </div>
    
    <!-- Related Products -->
    @if($relatedProducts->count() > 0)
        <div class="mt-12">
            <h2 class="text-3xl font-serif font-bold mb-6 text-[#524438]">Related Products</h2>
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
                @php
                    $cart = session()->get('cart', []);
                @endphp
                @foreach($relatedProducts as $relatedProduct)
                    <x-product-card :product="$relatedProduct" :cartQuantity="$cart[$relatedProduct->id]['quantity'] ?? 0" />
                @endforeach
            </div>
        </div>
    @endif
</div>
@endsection

@push('modals')
<!-- Inquiry Form Modal -->
<x-modal id="inquiry-modal" title="Contact to Order" size="md">
    <form id="inquiry-form" class="space-y-4">
        @csrf
        <input type="hidden" name="product_id" value="{{ $product->id }}">
        <div>
            <label for="inquiry-name" class="block text-sm font-semibold mb-2 text-[#645443]">Name</label>
            <input type="text" id="inquiry-name" name="name" required class="w-full px-4 py-3 border-2 border-[#e8ddd0] rounded-xl focus:ring-2 focus:ring-[#9d8566] focus:border-[#9d8566] transition-all outline-none text-[#524438]">
        </div>
        <div>
            <label for="inquiry-email" class="block text-sm font-semibold mb-2 text-[#645443]">Email</label>
            <input type="email" id="inquiry-email" name="email" required class="w-full px-4 py-3 border-2 border-[#e8ddd0] rounded-xl focus:ring-2 focus:ring-[#9d8566] focus:border-[#9d8566] transition-all outline-none text-[#524438]">
        </div>
        <div>
            <label for="inquiry-message" class="block text-sm font-semibold mb-2 text-[#645443]">Message</label>
            <textarea id="inquiry-message" name="message" rows="4" required class="w-full px-4 py-3 border-2 border-[#e8ddd0] rounded-xl focus:ring-2 focus:ring-[#9d8566] focus:border-[#9d8566] transition-all outline-none text-[#524438] resize-none"></textarea>
        </div>
        <button type="submit" class="w-full bg-[#7d6a52] text-white px-6 py-3 rounded-full hover:bg-[#9d8566] transition-all font-semibold shadow-lg hover:shadow-xl transform hover:scale-105">
            Submit Inquiry
        </button>
    </form>
</x-modal>
@endpush

@push('modals')
<!-- Image Lightbox -->
<div id="lightbox-modal" class="fixed inset-0 bg-black bg-opacity-90 hidden z-50 flex items-center justify-center p-4" onclick="closeModal('lightbox-modal')">
    <div class="max-w-6xl w-full">
        <button onclick="closeModal('lightbox-modal')" class="absolute top-4 right-4 text-white hover:text-gray-300 z-10">
            <svg class="w-8 h-8" 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"></path>
            </svg>
        </button>
        <img id="lightbox-image" src="" alt="Product Image" class="max-w-full max-h-[90vh] mx-auto object-contain">
    </div>
</div>
@endpush

@push('scripts')
<script>
function changeMainImage(src) {
    document.getElementById('main-image').src = src;
}

function openLightbox(src) {
    document.getElementById('lightbox-image').src = src;
    openModal('lightbox-modal');
}

document.getElementById('inquiry-form')?.addEventListener('submit', async function(e) {
    e.preventDefault();
    const formData = new FormData(this);
    const response = await fetch('{{ route("inquiries.store") }}', {
        method: 'POST',
        body: formData,
        headers: {
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
        }
    });
    const data = await response.json();
    if (data.success) {
        showToast(data.message, 'success');
        closeModal('inquiry-modal');
        this.reset();
    } else {
        showToast(data.message || 'Submission failed. Please try again.', 'error');
    }
});

// Share Product Functionality
function shareProduct() {
    const productName = '{{ $product->name }}';
    const productUrl = window.location.href;
    const shareText = `Check out ${productName} at Memorycloset Media!`;
    
    if (navigator.share) {
        navigator.share({
            title: productName,
            text: shareText,
            url: productUrl
        }).catch(err => console.log('Error sharing', err));
    } else {
        // Fallback: Copy to clipboard
        navigator.clipboard.writeText(productUrl).then(() => {
            showToast('Product link copied to clipboard!', 'success');
        }).catch(() => {
            // Fallback: Show share options
            openShareModal();
        });
    }
}

function openShareModal() {
    const productName = '{{ $product->name }}';
    const productUrl = window.location.href;
    const shareText = encodeURIComponent(`Check out ${productName} at Memorycloset Media!`);
    
    const html = `
        <div class="space-y-4">
            <p class="text-[#645443] mb-4">Share this product:</p>
            <div class="flex flex-wrap gap-3">
                <a href="https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(productUrl)}" target="_blank" class="flex items-center gap-2 bg-[#1877f2] text-white px-4 py-2 rounded-lg hover:bg-[#166fe5] transition-colors">
                    <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 24 24">
                        <path d="M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z"/>
                    </svg>
                    Facebook
                </a>
                <a href="https://twitter.com/intent/tweet?text=${shareText}&url=${encodeURIComponent(productUrl)}" target="_blank" class="flex items-center gap-2 bg-[#1da1f2] text-white px-4 py-2 rounded-lg hover:bg-[#1a91da] transition-colors">
                    <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 24 24">
                        <path d="M23.953 4.57a10 10 0 01-2.825.775 4.958 4.958 0 002.163-2.723c-.951.555-2.005.959-3.127 1.184a4.92 4.92 0 00-8.384 4.482C7.69 8.095 4.067 6.13 1.64 3.162a4.822 4.822 0 00-.666 2.475c0 1.71.87 3.213 2.188 4.096a4.904 4.904 0 01-2.228-.616v.06a4.923 4.923 0 003.946 4.827 4.996 4.996 0 01-2.212.085 4.936 4.936 0 004.604 3.417 9.867 9.867 0 01-6.102 2.105c-.39 0-.779-.023-1.17-.067a13.995 13.995 0 007.557 2.209c9.053 0 13.998-7.496 13.998-13.985 0-.21 0-.42-.015-.63A9.935 9.935 0 0024 4.59z"/>
                    </svg>
                    Twitter
                </a>
                <a href="https://wa.me/?text=${shareText}%20${encodeURIComponent(productUrl)}" target="_blank" class="flex items-center gap-2 bg-[#25d366] text-white px-4 py-2 rounded-lg hover:bg-[#20ba5a] transition-colors">
                    <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 24 24">
                        <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413Z"/>
                    </svg>
                    WhatsApp
                </a>
                <button onclick="navigator.clipboard.writeText('${productUrl}'); showToast('Link copied to clipboard!', 'success'); closeModal('share-modal');" class="flex items-center gap-2 bg-[#7d6a52] text-white px-4 py-2 rounded-lg hover:bg-[#9d8566] transition-colors">
                    <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="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"></path>
                    </svg>
                    Copy Link
                </button>
            </div>
        </div>
    `;
    
    // Create or update share modal
    let shareModal = document.getElementById('share-modal');
    if (!shareModal) {
        shareModal = document.createElement('div');
        shareModal.id = 'share-modal';
        shareModal.className = 'fixed inset-0 bg-black/60 backdrop-blur-sm hidden z-50 flex items-center justify-center p-4';
        shareModal.innerHTML = `
            <div class="bg-white rounded-2xl max-w-md w-full shadow-2xl border border-[#e8ddd0] animate-slideUp">
                <div class="flex items-center justify-between p-6 border-b border-[#e8ddd0]">
                    <h3 class="text-2xl font-serif font-bold text-[#524438]">Share Product</h3>
                    <button onclick="closeModal('share-modal')" class="text-[#9d8566] hover:text-[#7d6a52] transition-colors p-2 hover:bg-[#f5f0e8] rounded-full">
                        <svg class="w-6 h-6" 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"></path>
                        </svg>
                    </button>
                </div>
                <div class="p-6" id="share-modal-content"></div>
            </div>
        `;
        document.body.appendChild(shareModal);
    }
    
    document.getElementById('share-modal-content').innerHTML = html;
    openModal('share-modal');
}

function updateCartQuantity(productId, quantity) {
    if (quantity < 0) quantity = 0;
    
    if (quantity === 0) {
        // Remove from cart
        fetch(`/cart/${productId}`, {
                method: 'DELETE',
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                    'Accept': 'application/json'
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    location.reload();
                } else {
                    showToast(data.message || 'Failed to update cart', 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showToast('Failed to update cart', 'error');
            });
        }
        return;
    }

    fetch(`/cart/${productId}`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
            'Accept': 'application/json'
        },
        body: JSON.stringify({ quantity: parseInt(quantity) })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            location.reload();
        } else {
            showToast(data.message || 'Failed to update cart', 'error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showToast('Failed to update cart', 'error');
    });
}

// Keyboard Navigation
document.addEventListener('keydown', function(e) {
    // Escape key closes modals
    if (e.key === 'Escape') {
        const openModals = document.querySelectorAll('.fixed:not(.hidden)');
        openModals.forEach(modal => {
            if (modal.id && modal.id.includes('modal')) {
                closeModal(modal.id);
            }
        });
    }
    
    // Ctrl/Cmd + K for search (if search exists)
    if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
        e.preventDefault();
        const searchInput = document.querySelector('input[name="search"]');
        if (searchInput) {
            searchInput.focus();
        }
    }
});
</script>
@endpush

