@php

$badgeText = $data['badge_text'] ?? "";
$title = $data['title'] ?? "";
$subtitle = $data['subtitle'] ?? "";

$showDescription = $data['show_description'] ?? true;
$showFeatures = $data['show_features'] ?? true;
$showBadge = $data['show_badge'] ?? true;
$showTestsCount = $data['show_tests_count'] ?? true;
$showOldPrice = $data['show_old_price'] ?? true;
$cardHover = $data['card_hover_effect'] ?? true;
$aspectRatio = $data['image_aspect_ratio'] ?? 'video';
$buttonsConfig = $data['buttons'] ?? [];

// Currency Logic (Global vs Local)
$useGlobalCurrency = $data['use_global_currency'] ?? true;
$siteSettings = app(\App\Settings\SiteSettings::class);

if ($useGlobalCurrency) {
    $currencyType = $siteSettings->currency_type ?? 'text';
    $currencyText = $siteSettings->currency_text ?? 'ريال';
    $currencySvg = $siteSettings->currency_svg ?? '';
    $currencyImage = $siteSettings->currency_image ?? '';
    $currencyPos = $siteSettings->currency_position ?? 'after';
    $currencyIconSize = $siteSettings->currency_icon_size ?? 18;
    
    $priceTagBg = $siteSettings->price_tag_bg ?? '#FFFFFF';
    $priceTagColor = $siteSettings->price_tag_color ?? '#000000';
} else {
    $currencyType = $data['currency_type'] ?? 'text';
    $currencyText = $data['currency_text'] ?? 'ريال';
    $currencySvg = $data['currency_svg'] ?? '';
    $currencyImage = $data['currency_image'] ?? '';
    $currencyPos = $data['currency_position'] ?? 'after';
    $currencyIconSize = $data['currency_icon_size'] ?? 18; // Fallback or local
    
    $priceTagBg = $data['price_tag_bg'] ?? '#FFFFFF';
    $priceTagColor = $data['price_tag_text_color'] ?? '#000000';
}

$currencyHtml = '';
if ($currencyType === 'text') {
    $currencyHtml = '<span class="price-currency">' . e($currencyText) . '</span>';
} elseif ($currencyType === 'svg') {
    $currencyHtml = '<span class="currency-svg">' . $currencySvg . '</span>';
} elseif ($currencyType === 'image' && $currencyImage) {
    $currencyHtml = '<img src="' . asset('storage/' . $currencyImage) . '" class="currency-img" alt="currency">';
}

// Default legacy button fallback if no buttons repeater data
if (empty($buttonsConfig)) {
    $buttonsConfig = [
        ['text' => $data['button_text'] ?? "تفاصيل الباقة", 'action' => 'details', 'style' => 'primary'],
        ['text' => "التفاصيل", 'action' => 'details', 'style' => 'outline']
    ];
}

// Carousel settings
$carouselSpeed = ($data['carousel_speed'] ?? 10) * 1000;

// Get dynamic categories
$categories = collect($data['package_categories'] ?? []);
$hasAnyPackages = false;

// Gather all package IDs to fetch in one query
$allPackageIds = collect();
foreach ($categories as $category) {
    if (!empty($category['packages'])) {
        $allPackageIds = $allPackageIds->merge($category['packages']);
    }
}

// Fetch packages
$packagesData = \App\Models\Package::active()
    ->whereIn('id', $allPackageIds->unique())
    ->get()
    ->keyBy('id');

$hasAnyPackages = $categories->count() > 0 && $packagesData->count() > 0;

// Package images (fallback)
$pkgImages = [
    'https://images.unsplash.com/photo-1579684385127-1ef15d508118?w=400&q=80',
    'https://images.unsplash.com/photo-1530497610245-94d3c16cda28?w=400&q=80',
    'https://images.unsplash.com/photo-1505751172876-fa1923c5c528?w=400&q=80',
    'https://images.unsplash.com/photo-1584308666744-24d5c474f2ae?w=400&q=80',
    'https://images.unsplash.com/photo-1576091160399-112ba8d25d1d?w=400&q=80',
];
@endphp

@if($hasAnyPackages)

{{-- Packages Section CSS - matching prismad.html --}}
<style>
    .prisma-pkgs { font-family: 'Cairo', sans-serif; }
    .prisma-pkgs .section-container { max-width: 1300px; margin: 0 auto 80px; padding: 0 20px; }
    .prisma-pkgs .packages-intro {
        text-align: center; padding: 60px 24px;
        background: linear-gradient(135deg, rgba(0,153,255,0.06) 0%, rgba(123,0,255,0.04) 100%);
        border-radius: 30px; margin: 0 20px 50px; border: 1px solid rgba(0,153,255,0.12);
        display: flex; flex-direction: column; align-items: center; gap: 10px;
    }
    .prisma-pkgs .seasonal-badge {
        display: inline-flex; align-items: center; gap: 8px;
        background: linear-gradient(135deg, #0099FF 0%, #7B00FF 100%);
        color: #fff; padding: 10px 28px; border-radius: 50px; font-weight: 700;
        margin-bottom: 16px; font-size: 1rem; box-shadow: 0 6px 20px rgba(0,153,255,0.4);
    }
    .prisma-pkgs .section-title {
        display: flex; flex-direction: column; align-items: center; 
        text-align: center; width: 100%; gap: 15px;
    }
    .prisma-pkgs .section-title h2 {
        font-size: clamp(1.8rem, 5vw, 2.8rem); color: #2F4A5E; font-weight: 900;
        margin: 0; line-height: 1.2; letter-spacing: -0.01em; width: fit-content;
    }
    .prisma-pkgs .section-title h2::after {
        content: ''; display: block; width: 80px; height: 5px;
        background: linear-gradient(135deg,#0099FF 0%,#7B00FF 100%);
        margin: 14px auto 0; border-radius: 10px;
    }
    .prisma-pkgs .packages-sub { 
        color: #64748B; margin: 0; font-size: 1.15rem; font-weight: 500; 
        max-width: 800px; line-height: 1.6;
    }

    @media (max-width: 768px) {
        .prisma-pkgs .section-container { margin-bottom: 40px; }
        .prisma-pkgs .packages-intro { padding: 32px 16px; margin-bottom: 24px; }
        .prisma-pkgs .section-title h2 { font-size: 1.8rem; }
    }

    /* Tier Header Row */
    .prisma-pkgs .section-header-row {
        display: flex; justify-content: space-between; align-items: center;
        margin-bottom: 28px; padding: 18px 24px; background: #fff;
        border-radius: 16px; box-shadow: 0 4px 20px rgba(47,74,94,0.06);
        border-right: 4px solid #0099FF; flex-wrap: wrap; gap: 15px;
    }
    .prisma-pkgs .pkg-title-group h3 {
        font-size: 1.5rem; color: #2F4A5E; font-weight: 800;
        display: flex; align-items: center; gap: 12px; margin: 0;
    }
    .prisma-pkgs .pkg-title-group h3 i { color: #0099FF; }

    /* Carousel */
    .prisma-pkgs .carousel-container { position: relative; padding: 0 10px; }
    .prisma-pkgs .carousel-track {
        display: flex; gap: 25px; overflow-x: auto; scroll-snap-type: x mandatory;
        padding-bottom: 30px; scrollbar-width: none; -ms-overflow-style: none;
    }
    .prisma-pkgs .carousel-track::-webkit-scrollbar { display: none; }
    .prisma-pkgs .nav-btn {
        position: absolute; top: 40%; transform: translateY(-50%);
        width: 45px; height: 45px; border-radius: 50%; background: #fff;
        border: 1px solid #ddd; color: #2F4A5E; font-size: 1.2rem;
        cursor: pointer; box-shadow: 0 4px 10px rgba(0,0,0,0.1); z-index: 10;
        transition: all 0.3s; display: flex; align-items: center; justify-content: center;
    }
    .prisma-pkgs .nav-btn:hover { background: #2F4A5E; color: #fff; border-color: #2F4A5E; }
    .prisma-pkgs .nav-btn.prev { right: -25px; }
    .prisma-pkgs .nav-btn.next { left: -25px; }
    
    @media (max-width: 768px) {
        .prisma-pkgs .nav-btn { display: none !important; }
        .prisma-pkgs .section-header-row { flex-direction: column; align-items: flex-start; gap: 12px; padding: 15px; }
    }
    .prisma-pkgs .carousel-dots { display: flex; justify-content: center; gap: 8px; margin-top: 10px; }
    .prisma-pkgs .dot { width: 10px; height: 10px; border-radius: 50%; background: #cbd5e1; cursor: pointer; transition: 0.3s; }
    .prisma-pkgs .dot.active { background: linear-gradient(135deg,#0099FF 0%,#7B00FF 100%); width: 25px; border-radius: 10px; }

    /* Package Card */
    .prisma-pkgs .pkg-card {
        min-width: 300px; max-width: 300px; background: #fff; border-radius: 20px;
        box-shadow: 0 8px 32px rgba(47,74,94,0.08), 0 2px 8px rgba(0,0,0,0.04);
        scroll-snap-align: center; display: flex; flex-direction: column;
        overflow: hidden; border: 1px solid rgba(0,153,255,0.08);
        transition: all 0.3s cubic-bezier(0.4,0,0.2,1);
    }
    .prisma-pkgs .pkg-card:hover {
        border-color: rgba(0,153,255,0.3); transform: translateY(-8px);
        box-shadow: 0 24px 48px rgba(0,153,255,0.15), 0 8px 24px rgba(0,0,0,0.08);
    }

    @media (max-width: 480px) {
        .prisma-pkgs .section-container { padding: 0 10px; }
        .prisma-pkgs .pkg-card { min-width: 280px; max-width: 280px; margin: 0; }
        .prisma-pkgs .section-title h2 { font-size: 1.6rem !important; }
        .prisma-pkgs .pkg-title-group h3 { font-size: 1.2rem !important; }
        .prisma-pkgs .packages-intro { padding: 40px 15px; margin: 0 10px 30px; border-radius: 20px; }
        .prisma-pkgs .pkg-badge { font-size: 0.8rem; padding: 4px 10px; }
        .prisma-pkgs .pkg-price { font-size: 1.4rem; }
    }
    .prisma-pkgs .pkg-img-wrap {
        background: linear-gradient(135deg,#f1f5f9 0%,#e2e8f0 100%);
        position: relative; overflow: hidden;
    }
    .prisma-pkgs .pkg-img-wrap.aspect-video { aspect-ratio: 16/10; }
    .prisma-pkgs .pkg-img-wrap.aspect-square { aspect-ratio: 1/1; }
    .prisma-pkgs .pkg-img-wrap.aspect-auto { aspect-ratio: auto; }

    .prisma-pkgs .pkg-img-wrap img { width: 100%; height: 100%; object-fit: cover; transition: 0.5s; }
    .prisma-pkgs .pkg-card:hover .pkg-img-wrap img { transform: scale(1.06); }
    .prisma-pkgs .price-tag {
        position: absolute; bottom: 12px; left: 12px;
        background: {{ $priceTagBg }};
        color: {{ $priceTagColor }}; 
        padding: 8px 16px; border-radius: 24px;
        font-weight: 700; font-size: 0.95rem; 
        box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        display: flex; align-items: center; gap: 6px;
        border: 1px solid rgba(0,0,0,0.05);
    }
    .prisma-pkgs .currency-svg svg { width: {{ $currencyIconSize }}px !important; height: {{ $currencyIconSize }}px !important; fill: currentColor; display: block; }
    .prisma-pkgs .currency-img { width: {{ $currencyIconSize }}px !important; height: {{ $currencyIconSize }}px !important; min-width: {{ $currencyIconSize }}px !important; object-fit: contain; vertical-align: middle; }
    .prisma-pkgs .price-currency { font-size: 0.95rem; opacity: 0.9; font-weight: 600; }
    .prisma-pkgs .old-price-tag {
        position: absolute; top: 12px; right: 12px;
        background: rgba(239,68,68,0.9); color: #fff; padding: 4px 12px;
        border-radius: 12px; font-size: 0.8rem; font-weight: 600;
        text-decoration: line-through;
    }
    .prisma-pkgs .pkg-body { padding: 22px; flex: 1; display: flex; flex-direction: column; }
    .prisma-pkgs .pkg-title-text { font-weight: 800; font-size: 1.15rem; margin-bottom: 10px; color: #2F4A5E; line-height: 1.4; }
    .prisma-pkgs .pkg-desc {
        font-size: 0.9rem; color: #64748B; margin-bottom: 20px;
        display: -webkit-box; -webkit-line-clamp: 2; line-clamp: 2;
        -webkit-box-orient: vertical; overflow: hidden; flex: 1; line-height: 1.55;
    }
    .prisma-pkgs .pkg-actions { display: flex; gap: 10px; margin-top: auto; }
    .prisma-pkgs .btn {
        flex: 1; padding: 12px 14px; border-radius: 12px; font-weight: 700;
        font-size: 0.9rem; cursor: pointer; text-align: center; border: none;
        transition: 0.3s; display: flex; align-items: center; justify-content: center;
        gap: 6px; text-decoration: none; font-family: 'Cairo', sans-serif;
    }
    .prisma-pkgs .btn-primary { background: linear-gradient(135deg,#0099FF 0%,#7B00FF 100%); color: #fff; }
    .prisma-pkgs .btn-primary:hover { box-shadow: 0 6px 20px rgba(0,153,255,0.4); color: #fff; }
    .prisma-pkgs .btn-outline { background: #fff; border: 2px solid #2F4A5E; color: #2F4A5E; }
    .prisma-pkgs .btn-outline:hover { background: #2F4A5E; color: #fff; }

    @media(max-width:768px){
        .prisma-pkgs .nav-btn{width:36px;height:36px;font-size:1rem;}
        .prisma-pkgs .nav-btn.prev{right:4px;}
        .prisma-pkgs .nav-btn.next{left:4px;}
        .prisma-pkgs .pkg-card{min-width:260px;max-width:260px;}
    }
</style>

<div class="prisma-pkgs">
    {{-- Intro Section --}}
    <div class="packages-intro">
        @if($showBadge)
        <div class="seasonal-badge">
            <i class="fas fa-fire"></i> {{ $badgeText }}
        </div>
        @endif
        <div class="section-title">
            <h2>{{ $title }}</h2>
            <p class="packages-sub">{{ $subtitle }}</p>
        </div>
    </div>

    @foreach($categories as $categoryIndex => $category)
        @php
            $catPackages = collect($category['packages'] ?? [])
                ->map(fn($id) => $packagesData->get($id))
                ->filter();
            
            $iconClass = 'fas fa-' . ($category['icon'] ?? 'star');
            if ($category['icon'] === 'check') $iconClass = 'fas fa-check-circle';
        @endphp

        @if($catPackages->count() > 0)
        <section class="section-container">
            <div class="section-header-row">
                <div class="pkg-title-group">
                    <h3><i class="{{ $iconClass }}"></i> {{ $category['category_name'] ?? "" }}</h3>
                </div>
            </div>
            <div class="carousel-container" id="prisma-carousel-{{ $categoryIndex }}">
                <button class="nav-btn prev" aria-label="السابق"><i class="fas fa-chevron-right"></i></button>
                <div class="carousel-track">
                    @foreach($catPackages as $index => $package)
                    <div class="pkg-card">
                        <div class="pkg-img-wrap aspect-{{ $aspectRatio }}">
                            @if($package->image)
                                <img src="{{ asset('storage/' . $package->image) }}" alt="{{ $package->name }}" loading="lazy">
                            @else
                                <img src="{{ $pkgImages[$index % count($pkgImages)] }}" alt="{{ $package->name }}" loading="lazy">
                            @endif
                            <span class="price-tag">
                                @if($currencyPos === 'before') {!! $currencyHtml !!} @endif
                                {{ number_format($package->final_price) }}
                                @if($currencyPos === 'after') {!! $currencyHtml !!} @endif
                            </span>
                            @if($showOldPrice && $package->price > $package->final_price)
                                <span class="old-price-tag">
                                    @if($currencyPos === 'before') <span style="font-size: 0.7rem; margin-left: 2px;">{!! $currencyHtml !!}</span> @endif
                                    {{ number_format($package->price) }}
                                    @if($currencyPos === 'after') <span style="font-size: 0.7rem; margin-right: 2px;">{!! $currencyHtml !!}</span> @endif
                                </span>
                            @endif
                        </div>
                        <div class="pkg-body">
                            <h4 class="pkg-title-text">{{ $package->name }}</h4>
                            @if($showDescription && $package->description)
                                <p class="pkg-desc">{{ strip_tags($package->description) }}</p>
                            @endif
                            <div class="pkg-actions">
                                @foreach($buttonsConfig as $btn)
                                    @php
                                        $btnUrl = $btn['action'] === 'details' 
                                            ? route('package.show', $package->slug ?? $package->id) 
                                            : ($btn['url'] ?? '#');
                                        $btnClass = $btn['style'] === 'outline' ? 'btn-outline' : 'btn-primary';
                                        $btnStyle = !empty($btn['color']) 
                                            ? ($btn['style'] === 'outline' ? "border-color: {$btn['color']}; color: {$btn['color']};" : "background: {$btn['color']};") 
                                            : "";
                                    @endphp
                                    <a href="{{ $btnUrl }}" class="btn {{ $btnClass }}" style="{{ $btnStyle }}">{{ $btn['text'] }}</a>
                                @endforeach
                            </div>
                        </div>
                    </div>
                    @endforeach
                </div>
                <button class="nav-btn next" aria-label="التالي"><i class="fas fa-chevron-left"></i></button>
                <div class="carousel-dots">
                    @foreach($catPackages as $i => $p)
                        <div class="dot {{ $i === 0 ? 'active' : '' }}" data-index="{{ $i }}"></div>
                    @endforeach
                </div>
            </div>
        </section>
        @endif
    @endforeach
</div>

{{-- Carousel JavaScript (matching prismad.html logic) --}}
<script>
document.addEventListener('DOMContentLoaded', function() {
    const carouselSpeed = {{ $carouselSpeed }};
    const isRtl = document.documentElement.dir === 'rtl' || document.body.style.direction === 'rtl' || getComputedStyle(document.body).direction === 'rtl';
    const gap = 25;

    function initPrismaCarousel(containerId) {
        const container = document.getElementById(containerId);
        if (!container) return;

        const track = container.querySelector('.carousel-track');
        const dotsContainer = container.querySelector('.carousel-dots');
        const btnPrev = container.querySelector('.prev');
        const btnNext = container.querySelector('.next');
        const cards = track.querySelectorAll('.pkg-card');
        const totalCards = cards.length;

        if (totalCards === 0) return;

        function getStep() {
            const first = track.querySelector('.pkg-card');
            return first ? first.offsetWidth + gap : 325;
        }

        function scrollTrackToIndex(idx) {
            const step = getStep();
            const targetLeft = isRtl ? -(idx * step) : idx * step;
            track.scrollTo({ left: targetLeft, behavior: 'smooth' });
        }

        function updateDotsFromScroll() {
            const step = getStep();
            const scrollLeft = track.scrollLeft;
            const index = Math.min(
                totalCards - 1,
                Math.max(0, Math.round((isRtl ? -scrollLeft : scrollLeft) / step))
            );
            const dots = dotsContainer.querySelectorAll('.dot');
            dots.forEach(d => d.classList.remove('active'));
            if (dots[index]) dots[index].classList.add('active');
        }

        if (btnNext) btnNext.onclick = () => track.scrollBy({ left: -getStep(), behavior: 'smooth' });
        if (btnPrev) btnPrev.onclick = () => track.scrollBy({ left: getStep(), behavior: 'smooth' });

        track.addEventListener('scroll', updateDotsFromScroll);

        dotsContainer.querySelectorAll('.dot').forEach(dotEl => {
            const idx = parseInt(dotEl.getAttribute('data-index'), 10);
            dotEl.onclick = () => scrollTrackToIndex(idx);
        });

        // Auto-scroll
        setInterval(function() {
            const step = getStep();
            const scrollLeft = track.scrollLeft;
            const currentIndex = Math.min(
                totalCards - 1,
                Math.max(0, Math.round((isRtl ? -scrollLeft : scrollLeft) / step))
            );
            const nextIndex = (currentIndex + 1) % totalCards;
            scrollTrackToIndex(nextIndex);
        }, carouselSpeed);
    }

    // Initialize carousels for each valid dynamic category
    const categoryCount = {{ count($categories) }};
    for(let i = 0; i < categoryCount; i++) {
        initPrismaCarousel('prisma-carousel-' + i);
    }
});
</script>
@endif
