@php
    use App\Helpers\FeatureHelper;
    use App\Services\PricingCalculatorService;

    $comparison = getContent('comparison.content', true);
    $pricingCalculator = app(PricingCalculatorService::class);
    $billingCycles = PricingCalculatorService::BILLING_CYCLES;

    // 1. Determine which categories to show
    // If a single $category is passed (e.g. from category page), use only that.
    // Otherwise, use the $categories collection passed from the controller.
    $displayCategories = isset($category) ? collect([$category]) : ($categories ?? collect());
    
    // 2. Determine the default billing cycle (longest available)
    $globalLongestCycle = 'monthly';
    if ($displayCategories->isNotEmpty()) {
        $maxMonths = 0;
        foreach($displayCategories as $cat) {
            foreach($cat->activeProducts as $p) {
                $pPricing = $pricingCalculator->getProductPricing($p);
                $lpCycle = $pPricing['longest_cycle'] ?? 'monthly';
                $lpMonths = $billingCycles[$lpCycle]['months'] ?? 1;
                if ($lpMonths > $maxMonths) {
                    $maxMonths = $lpMonths;
                    $globalLongestCycle = $lpCycle;
                }
            }
        }
    }

    $groupLabels = [
        'resources' => 'Resources',
        'features' => 'Features',
        'security' => 'Security',
        'performance' => 'Performance',
        'support' => 'Support',
        'other' => 'Additional Features',
    ];
    $groupOrder = ['resources', 'features', 'security', 'performance', 'support', 'other'];
@endphp

@if($displayCategories->isNotEmpty())
<section id="comparison" class="relative pt-24 pb-16 lg:pt-32 lg:pb-20 bg-white dark:bg-slate-950 overflow-hidden transition-colors duration-300"
    x-data="{ 
        activeTab: {{ $displayCategories->first()->id }},
        billingCycle: '{{ $globalLongestCycle }}'
    }">
    {{-- Background Effects --}}
    <div class="absolute inset-0 pointer-events-none">
        <div class="absolute inset-0 bg-[url('data:image/svg+xml,%3Csvg%20viewBox%3D%220%200%20200%20200%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cfilter%20id%3D%22n%22%3E%3CfeTurbulence%20type%3D%22fractalNoise%22%20baseFrequency%3D%220.65%22%20numOctaves%3D%223%22%20stitchTiles%3D%22stitch%22%2F%3E%3C%2Ffilter%3E%3Crect%20width%3D%22100%25%22%20height%3D%22100%25%22%20filter%3D%22url(%23n)%22%2F%3E%3C%2Fsvg%3E')] opacity-[0.03] dark:opacity-10 mix-blend-soft-light"></div>
        <div class="absolute top-0 left-1/2 -translate-x-1/2 w-[700px] h-[400px] bg-primary-600/5 dark:bg-primary-600/20 rounded-full blur-[160px] mix-blend-screen"></div>
        <div class="absolute -top-24 -left-24 w-[400px] h-[400px] bg-primary-600/5 dark:bg-primary-600/10 rounded-full blur-[120px] mix-blend-screen"></div>
        <div class="absolute top-1/2 right-0 w-[350px] h-[350px] bg-primary-600/5 rounded-full blur-[100px] mix-blend-screen"></div>
    </div>

    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 relative z-10">
        {{-- Section Header --}}
        <div class="text-center mb-12">
            <h2 class="text-3xl sm:text-4xl font-extrabold text-slate-900 dark:text-white mb-5 tracking-tight">
                {!! purify(__(@$comparison->data_values->heading ?? 'Cloud Hosting <span class="text-transparent bg-clip-text bg-gradient-to-r from-primary-600 via-primary-600 to-primary-800 dark:from-primary-400 dark:via-primary-400 dark:to-primary-300">Plans & Pricing</span>')) !!}
            </h2>
            <p class="text-slate-500 dark:text-slate-400 text-lg sm:text-xl max-w-2xl mx-auto font-medium opacity-90 leading-relaxed">
                {{ __(@$comparison->data_values->subheading ?? 'Get premium features at no extra cost in every plan.') }}
            </p>
        </div>

        {{-- Category Tabs (Underline Style) --}}
        @if($displayCategories->count() > 1)
            @php
                $catTabs = [];
                foreach ($displayCategories as $cat) {
                    $catTabs[$cat->id] = $cat->name;
                }
            @endphp
            <x-theme.ui.tabs :tabs="$catTabs" model="activeTab" class="mb-10" />
        @endif

        {{-- Comparison Content --}}
        @foreach($displayCategories as $cat)
            @php
                $comparisonProducts = $cat->activeProducts()->with('pricing')->get();
                if ($comparisonProducts->isEmpty()) continue;

                $categoryFeatures = $cat->categoryFeatures()->get()->groupBy(fn($item) => $item->comparison_group ?: 'other');
                
                $activeFeatureGroups = $categoryFeatures->filter(function($features) use ($comparisonProducts) {
                    foreach($features as $feature) {
                        foreach($comparisonProducts as $product) {
                            if ($product->features->where('category_feature_id', $feature->id)->first()) return true;
                        }
                    }
                    return false;
                });

                $sortedFeatureGroups = $activeFeatureGroups->sortBy(function($features, $group) use ($groupOrder) {
                    $index = array_search($group, $groupOrder);
                    return $index !== false ? $index : 999;
                });
            @endphp
            
            <div x-show="activeTab === {{ $cat->id }}" 
                 x-transition:enter="transition ease-out duration-300"
                 x-transition:enter-start="opacity-0 translate-y-8"
                 x-transition:enter-end="opacity-100 translate-y-0"
                 x-data="{ activeGroup: '{{ $sortedFeatureGroups->keys()->first() }}' }"
                 class="space-y-8">
                
                {{-- Desktop Table View (hidden on mobile) --}}
                <div class="relative overflow-hidden rounded-2xl bg-slate-50 dark:bg-slate-900/40 border border-slate-200 dark:border-white/10 backdrop-blur-xl shadow-lg shadow-slate-200/50 dark:shadow-none hidden lg:block">
                    <div class="overflow-x-auto">
                        <table class="w-full text-left border-collapse min-w-[800px]">
                            <thead class="sticky top-0 z-20 bg-slate-100/95 dark:bg-slate-900/95 backdrop-blur-md">
                                <tr>
                                    <th class="p-6 bg-slate-100/50 dark:bg-slate-900/40 border-b border-slate-200 dark:border-white/10 sticky left-0 z-30 bg-slate-100 dark:bg-slate-950 backdrop-blur-md">
                                        <div class="flex flex-col">
                                            <span class="text-[10px] font-bold uppercase tracking-[0.2em] text-primary-600 dark:text-primary-500 mb-1">
                                                @lang('Feature List')
                                            </span>
                                            <span class="text-xl font-extrabold text-slate-900 dark:text-white">@lang('Comparison')</span>
                                        </div>
                                    </th>
                                    @foreach($comparisonProducts as $product)
                                        @php
                                            $pricingData = $pricingCalculator->getProductPricingForJs($product);
                                        @endphp
                                        <th class="p-6 bg-slate-100/50 dark:bg-slate-900/40 border-b border-slate-200 dark:border-white/10 text-center min-w-[220px] relative"
                                            x-data='{ pricing: @json($pricingData) }'>
                                            @if($product->is_recommended)
                                                <div class="absolute top-0 left-1/2 -translate-x-1/2 bg-primary-600 text-white text-[10px] font-bold px-4 py-1.5 rounded-b-xl uppercase tracking-widest shadow-lg shadow-primary-500/40 z-20">
                                                    @lang('Recommended')
                                                </div>
                                            @endif
                                            
                                            <h3 class="text-xl font-bold text-slate-900 dark:text-white mb-2">{{ __($product->name) }}</h3>
                                            
                                            <div class="mb-4 h-14 flex flex-col items-center justify-center">
                                                <template x-if="pricing.prices[billingCycle]">
                                                    <div class="flex flex-col items-center">
                                                        <div class="flex items-center gap-1">
                                                            <span class="text-xs font-bold text-slate-500 dark:text-slate-400 self-start mt-1">{{ gs('cur_sym') }}</span>
                                                            <span class="text-2xl font-extrabold text-slate-900 dark:text-white" x-text="pricing.prices[billingCycle].display_raw"></span>
                                                            <span class="text-xs text-slate-500 dark:text-slate-400 font-medium h-full flex items-end pb-1">/mo</span>
                                                        </div>
                                                        <div class="mt-1 flex items-center gap-2" x-show="pricing.prices[billingCycle].has_discount">
                                                            <span class="text-[10px] text-slate-400 dark:text-slate-500 line-through" x-text="pricing.prices[billingCycle].original"></span>
                                                            <span class="px-1.5 py-0.5 rounded text-[8px] font-bold uppercase bg-primary-100 dark:bg-primary-500/10 text-primary-600 dark:text-primary-400 border border-primary-200 dark:border-primary-500/20">
                                                                @lang('Save') <span x-text="pricing.prices[billingCycle].discount_badge"></span>
                                                            </span>
                                                        </div>
                                                    </div>
                                                </template>
                                                <template x-if="!pricing.prices[billingCycle]">
                                                    <span class="text-slate-300 dark:text-slate-600 font-bold uppercase tracking-widest text-sm">@lang('N/A')</span>
                                                </template>
                                            </div>
                                            
                                            <a :href="pricing.prices[billingCycle] ? '{{ route('products.order', [$cat->slug, $product->slug]) }}?billing_cycle=' + billingCycle : '#'" 
                                               :class="!pricing.prices[billingCycle] ? 'opacity-20 pointer-events-none' : ''"
                                               class="inline-flex items-center justify-center w-full h-11 rounded-xl font-bold transition-[background-color,color,transform] duration-300 active:scale-95 gap-2 {{ $product->is_recommended ? 'bg-primary-600 text-white hover:bg-primary-500 shadow-lg shadow-primary-600/20' : 'bg-slate-200 dark:bg-white/10 text-slate-900 dark:text-white hover:bg-slate-300 dark:hover:bg-white/20' }}">
                                                @lang('Order Now')
                                            </a>
                                        </th>
                                    @endforeach
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-100 dark:divide-white/5">
                                @foreach($sortedFeatureGroups as $groupKey => $features)
                                    @php
                                        $label = __($groupLabels[$groupKey] ?? ucfirst($groupKey));
                                    @endphp
                                    {{-- Group Header --}}
                                    <tr class="cursor-pointer transition-colors duration-300 bg-slate-50/50 dark:bg-slate-900/30 hover:bg-primary-600/5"
                                        @click="activeGroup = activeGroup === '{{ $groupKey }}' ? null : '{{ $groupKey }}'">
                                        <td colspan="{{ $comparisonProducts->count() + 1 }}" class="px-8 py-5">
                                            <div class="flex items-center justify-between">
                                                <div class="flex items-center gap-3">
                                                    <div class="w-8 h-8 rounded-lg flex items-center justify-center border border-slate-200 dark:border-white/10"
                                                         :class="activeGroup === '{{ $groupKey }}' ? 'bg-primary-600 text-white' : 'bg-slate-100 dark:bg-white/5 text-slate-400 dark:text-slate-500'">
                                                        <i class="ph ph-bold ph-caret-right transition-transform" :class="activeGroup === '{{ $groupKey }}' ? 'rotate-90' : ''"></i>
                                                    </div>
                                                    <h4 class="text-xs font-bold uppercase tracking-[0.2em]"
                                                        :class="activeGroup === '{{ $groupKey }}' ? 'text-slate-900 dark:text-white' : 'text-slate-500 dark:text-slate-400'">
                                                        {{ $label }}
                                                    </h4>
                                                </div>
                                            </div>
                                        </td>
                                    </tr>

                                    {{-- Feature Rows --}}
                                    @foreach($features as $feature)
                                        <tr x-show="activeGroup === '{{ $groupKey }}'" x-transition class="hover:bg-slate-50 dark:hover:bg-white/[0.02]">
                                            <td class="sticky left-0 z-10 bg-white/95 dark:bg-slate-900/95 backdrop-blur-sm px-8 py-4 text-sm font-medium text-slate-600 dark:text-slate-400 border-r border-slate-100 dark:border-white/10">
                                                <div class="flex items-center gap-2">
                                                    <span>{{ $feature->name }}</span>
                                                    @if($feature->tooltip_text)
                                                        <div class="group/tip relative flex items-center">
                                                            <i class="ph ph-info text-slate-400 dark:text-slate-600 hover:text-primary-600 dark:hover:text-primary-400 cursor-help text-xs"></i>
                                                            <div class="absolute left-0 bottom-full mb-2 hidden group-hover/tip:block w-48 p-2 bg-white dark:bg-slate-800 border border-slate-200 dark:border-white/10 rounded-lg text-[10px] text-slate-600 dark:text-slate-300 z-50 shadow-xl">
                                                                {{ $feature->tooltip_text }}
                                                            </div>
                                                        </div>
                                                    @endif
                                                </div>
                                            </td>
                                            @foreach($comparisonProducts as $product)
                                                @php
                                                    $pf = $product->features->where('category_feature_id', $feature->id)->first();
                                                @endphp
                                                <td class="px-6 py-4 text-center border-l border-slate-50 dark:border-white/[0.03]">
                                                    @if($pf)
                                                        <div class="flex items-center justify-center">
                                                            @if($pf->type === 'included')
                                                                <svg class="w-5 h-5 text-green-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="3" d="M5 13l4 4L19 7" />
                                                                </svg>
                                                            @elseif($pf->type === 'unlimited')
                                                                <span class="text-[10px] font-bold uppercase tracking-widest text-primary-600 dark:text-primary-500 bg-primary-100 dark:bg-primary-500/10 px-2 py-0.5 rounded border border-primary-200 dark:border-primary-500/20">@lang('Unlimited')</span>
                                                            @elseif($pf->type === 'excluded')
                                                                <svg class="w-5 h-5 text-red-500/20 dark:text-red-500/40" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="3" d="M6 18L18 6M6 6l12 12" />
                                                                </svg>
                                                            @else
                                                                <span class="text-sm font-bold text-slate-900 dark:text-white">{{ FeatureHelper::getCombinedValue($pf, false) }}</span>
                                                            @endif
                                                        </div>
                                                    @else
                                                        <span class="text-slate-200 dark:text-white/5 text-[10px] font-bold uppercase tracking-widest">@lang('N/A')</span>
                                                    @endif
                                                </td>
                                            @endforeach
                                        </tr>
                                    @endforeach
                                @endforeach

                            </tbody>
                        </table>
                    </div>
                </div>

                {{-- Feature Summary Cards --}}
                <div class="hidden lg:grid md:grid-cols-3 gap-6">
                    @foreach($comparisonProducts->take(3) as $product)
                        <div class="p-6 rounded-2xl bg-primary-50 dark:bg-primary-600/5 border border-primary-100 dark:border-primary-500/10 flex flex-col items-center text-center group hover:bg-primary-100 dark:hover:bg-primary-600/10 transition-[border-color,background-color,box-shadow] shadow-sm">
                            <h4 class="text-slate-900 dark:text-white font-bold mb-2 text-lg">{{ $product->name }}</h4>
                            <p class="text-slate-500 dark:text-slate-400 text-sm leading-relaxed mb-6">
                                {{ Str::limit(strip_tags($product->description), 100) }}
                            </p>
                            <a href="{{ route('products.order', [$cat->slug, $product->slug]) }}" class="text-primary-600 dark:text-primary-400 text-xs font-bold uppercase tracking-widest hover:text-primary-700 dark:hover:text-white transition-colors">
                                @lang('View Details') →
                            </a>
                        </div>
                    @endforeach
                </div>

                {{-- Mobile Card View (visible only on mobile/tablet) --}}
                <div class="lg:hidden space-y-6">
                    @foreach($comparisonProducts as $product)
                        @php
                            $pricingData = $pricingCalculator->getProductPricingForJs($product);
                        @endphp
                        <div class="rounded-2xl bg-white dark:bg-slate-900/60 border border-slate-200 dark:border-white/10 overflow-hidden shadow-md shadow-slate-200/30 dark:shadow-none"
                             x-data='{ pricing: @json($pricingData), expanded: {{ $product->is_recommended ? 'true' : 'false' }} }'>
                            {{-- Card Header --}}
                            <div class="p-6 {{ $product->is_recommended ? 'bg-primary-600 text-white' : 'bg-slate-50 dark:bg-slate-900/40' }}">
                                @if($product->is_recommended)
                                    <span class="inline-block text-[10px] font-bold uppercase tracking-[0.2em] text-white/80 mb-2">@lang('Recommended')</span>
                                @endif
                                <h4 class="text-lg font-bold {{ $product->is_recommended ? '' : 'text-slate-900 dark:text-white' }}">{{ __($product->name) }}</h4>
                                <div class="mt-3 flex items-baseline gap-1">
                                    <template x-if="pricing.prices[billingCycle]">
                                        <div class="flex items-baseline gap-1">
                                            <span class="text-sm font-bold {{ $product->is_recommended ? 'text-white/60' : 'text-slate-500 dark:text-slate-400' }}">{{ gs('cur_sym') }}</span>
                                            <span class="text-2xl font-extrabold {{ $product->is_recommended ? '' : 'text-slate-900 dark:text-white' }}" x-text="pricing.prices[billingCycle].display_raw"></span>
                                            <span class="text-sm font-medium {{ $product->is_recommended ? 'text-white/60' : 'text-slate-500 dark:text-slate-400' }}">/mo</span>
                                        </div>
                                    </template>
                                    <template x-if="!pricing.prices[billingCycle]">
                                        <span class="text-sm font-bold {{ $product->is_recommended ? 'text-white/60' : 'text-slate-500 dark:text-slate-400' }} uppercase tracking-widest">@lang('N/A')</span>
                                    </template>
                                </div>
                            </div>
                            
                            {{-- Toggle Features --}}
                            <button @click="expanded = !expanded" class="w-full px-6 py-3 flex items-center justify-between text-xs font-bold uppercase tracking-[0.15em] text-slate-500 dark:text-slate-400 hover:text-slate-900 dark:hover:text-white transition-colors border-b border-slate-100 dark:border-white/5"
                                    :aria-expanded="expanded">
                                <span x-text="expanded ? '{{ __('Hide Features') }}' : '{{ __('Show Features') }}'"></span>
                                <i class="ph ph-caret-down transition-transform" :class="expanded && 'rotate-180'" aria-hidden="true"></i>
                            </button>

                            {{-- Feature List --}}
                            <div x-show="expanded" x-collapse class="divide-y divide-slate-100 dark:divide-white/5">
                                @foreach($sortedFeatureGroups as $groupKey => $features)
                                    <div class="px-6 py-3 bg-slate-50/50 dark:bg-white/[0.02]">
                                        <span class="text-[10px] font-bold uppercase tracking-[0.2em] text-primary-600 dark:text-primary-500">{{ __($groupLabels[$groupKey] ?? ucfirst($groupKey)) }}</span>
                                    </div>
                                    @foreach($features as $feature)
                                        @php $pf = $product->features->where('category_feature_id', $feature->id)->first(); @endphp
                                        <div class="flex items-center justify-between px-6 py-3">
                                            <span class="text-sm text-slate-600 dark:text-slate-400">{{ $feature->name }}</span>
                                            <span class="flex-shrink-0 ml-3">
                                                @if($pf)
                                                    @if($pf->type === 'included')
                                                        <svg class="w-5 h-5 text-green-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="3" d="M5 13l4 4L19 7" /></svg>
                                                    @elseif($pf->type === 'unlimited')
                                                        <span class="text-[10px] font-bold uppercase tracking-widest text-primary-600 dark:text-primary-500">@lang('Unlimited')</span>
                                                    @elseif($pf->type === 'excluded')
                                                        <svg class="w-5 h-5 text-red-500/30" fill="none" viewBox="0 0 24 24" stroke="currentColor" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="3" d="M6 18L18 6M6 6l12 12" /></svg>
                                                    @else
                                                        <span class="text-sm font-bold text-slate-900 dark:text-white">{{ FeatureHelper::getCombinedValue($pf, false) }}</span>
                                                    @endif
                                                @else
                                                    <span class="text-slate-300 dark:text-white/10 text-[10px] font-bold uppercase">@lang('N/A')</span>
                                                @endif
                                            </span>
                                        </div>
                                    @endforeach
                                @endforeach
                            </div>

                            {{-- CTA --}}
                            <div class="p-6 border-t border-slate-100 dark:border-white/5">
                                <a :href="pricing.prices[billingCycle] ? '{{ route('products.order', [$cat->slug, $product->slug]) }}?billing_cycle=' + billingCycle : '#'" 
                                   :class="!pricing.prices[billingCycle] ? 'opacity-30 pointer-events-none' : ''"
                                   class="flex items-center justify-center w-full h-12 rounded-xl font-bold transition-[background-color,color,transform] active:scale-95 gap-2 {{ $product->is_recommended ? 'bg-primary-600 text-white shadow-lg shadow-primary-500/20' : 'bg-slate-100 dark:bg-white/10 text-slate-900 dark:text-white' }}">
                                    @lang('Order Now')
                                    <i class="ph ph-arrow-right" aria-hidden="true"></i>
                                </a>
                            </div>
                        </div>
                    @endforeach
                </div>
            </div>
        @endforeach
    </div>
</section>
@endif
@push('style')
{{-- Custom Scrollbar & Advanced Separators --}}
<style>
    [x-cloak] { display: none !important; }
    
    .scrollbar-thin::-webkit-scrollbar {
        height: 6px;
    }
    
    .scrollbar-thin::-webkit-scrollbar-track {
        background: rgba(255, 255, 255, 0.02);
        border-radius: 10px;
    }
    
    .scrollbar-thin::-webkit-scrollbar-thumb {
        background: rgba(255, 255, 255, 0.1);
        border-radius: 10px;
        border: 2px solid transparent;
        background-clip: padding-box;
    }
    
    .scrollbar-thin:hover::-webkit-scrollbar-thumb {
        background: rgba(255, 255, 255, 0.2);
        background-clip: padding-box;
    }

    {{-- Down line vertical separator effect --}}
    @media (min-width: 1024px) {
        .comparison-table-wrapper th[scope="col"]:not(:first-child),
        .comparison-table-wrapper td:not(:first-child) {
            position: relative;
        }
    }
</style>
@endpush
