<x-app-layout>
    <x-slot name="header">
        <h2 class="font-semibold text-xl text-gray-800 dark:text-gray-200 leading-tight">
            {{ __('Subscription Plans') }}
        </h2>
    </x-slot>

    <div class="py-12">
        <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
            <div class="bg-white dark:bg-gray-800 overflow-hidden shadow-xl sm:rounded-lg">
                <div class="p-6 lg:p-8">
                    <h3 class="text-2xl font-semibold text-gray-900 dark:text-gray-100 mb-6 text-center">
                        Choose Your Plan
                    </h3>

                    @if (session('info'))
                        <div class="mb-4 p-4 text-sm text-blue-700 bg-blue-100 rounded-lg dark:bg-blue-700 dark:text-blue-300" role="alert">
                            {{ session('info') }}
                        </div>
                    @endif

                    @if($plans->isEmpty())
                        <p class="text-center text-gray-500 dark:text-gray-400">
                            There are currently no subscription plans available. Please check back later.
                        </p>
                    @else
                        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
                            @foreach ($plans as $plan)
                                <div class="border border-gray-200 dark:border-gray-700 rounded-lg p-6 flex flex-col shadow-lg hover:shadow-xl transition-shadow duration-300">
                                    <h4 class="text-xl font-bold text-gray-900 dark:text-gray-100 mb-2">{{ $plan->name }}</h4>
                                    <p class="text-3xl font-extrabold text-gray-900 dark:text-gray-100 mb-3">
                                        ${{ number_format($plan->price, 2) }}
                                        <span class="text-sm font-medium text-gray-500 dark:text-gray-400">/ {{ $plan->interval_count > 1 ? $plan->interval_count : '' }} {{ Str::plural($plan->interval, $plan->interval_count) }}</span>
                                    </p>
                                    <p class="text-gray-600 dark:text-gray-400 text-sm mb-4 min-h-[60px]">{{ $plan->description }}</p>

                                    @if($plan->features && count($plan->features) > 0)
                                        <div class="space-y-4 mb-6 text-sm text-gray-600 dark:text-gray-400 flex-grow">
                                            @php
                                                $groupedPlanFeatures = [];
                                                if (isset($moduleDefinitions) && is_array($moduleDefinitions) && $plan->features && is_array($plan->features)) {
                                                    // Create a flat map of feature definitions for easier lookup
                                                    $featureDefMap = [];
                                                    foreach ($moduleDefinitions as $moduleSystemName => $moduleData) {
                                                        if (isset($moduleData['features']) && is_array($moduleData['features'])) {
                                                            foreach ($moduleData['features'] as $featureKeyFromDef => $featureDetail) {
                                                                // Use the key as defined in module.json (which should match plan feature keys)
                                                                $featureDefMap[$featureKeyFromDef] = [
                                                                    'moduleDisplayName' => $moduleData['displayName'],
                                                                    'featureName' => $featureDetail['name']
                                                                ];
                                                            }
                                                        }
                                                    }

                                                    foreach ($plan->features as $planFeatureItem) {
                                                        $planFeatureKey = $planFeatureItem['key'];
                                                        $featureLimit = $planFeatureItem['limit'] ?? null;

                                                        if (isset($featureDefMap[$planFeatureKey])) {
                                                            $moduleDisplayName = $featureDefMap[$planFeatureKey]['moduleDisplayName'];
                                                            $featureName = $featureDefMap[$planFeatureKey]['featureName'];

                                                            if (!isset($groupedPlanFeatures[$moduleDisplayName])) {
                                                                $groupedPlanFeatures[$moduleDisplayName] = [
                                                                    'displayName' => $moduleDisplayName,
                                                                    'features' => []
                                                                ];
                                                            }
                                                            $groupedPlanFeatures[$moduleDisplayName]['features'][] = [
                                                                'name' => $featureName,
                                                                'limit' => $featureLimit
                                                            ];
                                                        } else { // Handle features whose definition might be missing
                                                            if (!isset($groupedPlanFeatures['OrphanedFeatures'])) {
                                                                $groupedPlanFeatures['OrphanedFeatures'] = ['displayName' => 'Additional Features', 'features' => []];
                                                            }
                                                            $groupedPlanFeatures['OrphanedFeatures']['features'][] = [
                                                                'name' => Str::title(str_replace(['_', '-'], ' ', $planFeatureKey)), // Best guess for name
                                                                'limit' => $featureLimit
                                                            ];
                                                        }
                                                    }
                                                }
                                            @endphp

                                            @foreach ($groupedPlanFeatures as $moduleGroupName => $moduleGroupData)
                                                <div class="mt-3">
                                                    <h5 class="font-semibold text-gray-700 dark:text-gray-300 mb-1">{{ $moduleGroupData['displayName'] }}</h5>
                                                    <ul class="space-y-1 pl-4">
                                                        @foreach ($moduleGroupData['features'] as $feature)
                                                            <li class="flex items-start">
                                                                <svg class="w-4 h-4 text-green-500 mr-2 mt-0.5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path></svg>
                                                                <span>
                                                                    {{ $feature['name'] ?? 'Feature details missing' }}
                                                                    @if(isset($feature['limit']))
                                                                        <span class="ml-1 text-xs text-gray-400 dark:text-gray-500">(Limit: {{ $feature['limit'] === 0 ? 'Unlimited' : $feature['limit'] }})</span>
                                                                    @endif
                                                                </span>
                                                            </li>
                                                        @endforeach
                                                    </ul>
                                                </div>
                                            @endforeach
                                        </div>
                                    @endif

                                    {{-- TODO: Ensure you have a route named 'subscription.checkout' that accepts the plan --}}
                                    @if($currentSubscription && $currentSubscription->subscription_plan_id == $plan->id)
                                        <button disabled
                                           class="mt-auto block w-full bg-green-500 text-white font-semibold py-3 px-4 rounded-lg text-center cursor-not-allowed">
                                            Currently Active
                                        </button>
                                    @else
                                        <a href="{{ route('subscription.checkout', $plan) }}"
                                           class="mt-auto block w-full bg-blue-600 hover:bg-blue-700 text-white font-semibold py-3 px-4 rounded-lg text-center transition duration-150 ease-in-out">
                                            {{ $currentSubscription ? 'Switch to this Plan' : 'Choose Plan' }}
                                        </a>
                                    @endif

                                    {{-- Show trial period info only if the plan has one AND it's not the currently active plan --}}
                                    @if($plan->trial_period_days > 0 && !($currentSubscription && $currentSubscription->subscription_plan_id == $plan->id))
                                        <p class="text-xs text-center text-gray-500 dark:text-gray-400 mt-2">{{ $plan->trial_period_days }}-day free trial</p>
                                    @endif
                                </div>
                            @endforeach
                        </div>
                    @endif
                </div>
            </div>
        </div>
    </div>
</x-app-layout>