{{-- Subscription Pricing Box (with billing cycle toggle) --}}
{{-- All data is prepared by ProductService - no business logic in theme --}}
@php use App\Support\PricingModelRegistry; @endphp

<div class="bg-white dark:bg-surface-dark border border-gray-200 dark:border-gray-800 rounded-2xl p-6 shadow-soft hover:shadow-soft-hover transition-shadow duration-300" data-cp-container="product">
    
    {{-- Inject Product Config for JS --}}
    @if(isset($pricingData['product_config']))
        <script>
            window.ProductConfig = @json($pricingData['product_config']);
        </script>
    @endif

    {{-- Billing Cycle Switcher --}}
    <div class="p-1 bg-gray-100 dark:bg-gray-800 rounded-xl mb-8 flex tier-switcher">
        @foreach($billingTiers as $cycleId => $tier)
            @if($tier)
                <button 
                    class="tier-btn @if(($pricingData['default_billing_cycle'] ?? '') == $cycleId) active bg-white dark:bg-surface-dark shadow-sm text-primary @else text-text-muted hover:text-primary @endif flex-1 py-2 text-xs font-bold rounded-lg transition-all" 
                    data-cp-action="select-cycle"
                    data-value="{{ $cycleId }}" 
                    type="button">
                    {{ $tier['billing_cycle_label'] }}
                </button>
            @endif
        @endforeach
    </div>

    <div class="space-y-4 mb-8">
        <p class="text-xs font-semibold text-text-muted uppercase tracking-wider mb-2">
            @lang('shop.Select Plan')
        </p>

        @foreach($pricingData['plans'] as $index => $plan)
            @php
                $planTiers = collect($plan['pricing_tiers']);
                $isDefault = $plan['is_default'] || ($index === 0 && !$pricingData['plans']->contains('is_default', true));
                
                // Get list of supported cycle IDs for this plan
                $supportedCycles = $planTiers->map(function($t) {
                    return $t['billing_cycle'] ?: 'onetime';
                })->implode(',');
            @endphp
            
            {{-- Plan Radio Card --}}
            <div class="relative" 
                data-cp-plan="{{ $plan['slug'] }}" 
                data-plan-cycles="{{ $supportedCycles }}" 
                data-value="{{ $plan['slug'] }}"
                @foreach($billingTiers as $cycleId => $tier)
                    @if($tier)
                        @php
                            // Match plan tier by Cycle ID
                            $planTier = $planTiers->first(function($t) use ($cycleId) {
                                $tCycleId = $t['billing_cycle'] ?: 'onetime';
                                return $tCycleId == $cycleId;
                            });
                            $tierPricingModel = $planTier['pricing_model'] ?? 'fixed';
                            $tierModelHandler = app(PricingModelRegistry::class)->resolve($tierPricingModel);
                            // JS reads data-price-{cycle} to calculateTotal(); per-unit models use per_unit_amount.
                            $tierDisplayPrice = $tierModelHandler->usesPerUnitAmount()
                                ? number_format($planTier['per_unit_amount'] ?? 0, 2, '.', '')
                                : ($planTier ? number_format($planTier['price'], 2, '.', '') : '0.00');
                        @endphp
                        data-price-{{ $cycleId }}="{{ $tierDisplayPrice }}"
                        data-tier-{{ $cycleId }}="{{ $planTier ? $planTier['id'] : '' }}"
                        data-pricing-model-{{ $cycleId }}="{{ $tierPricingModel }}"
                    @endif
                @endforeach
            >
                <label class="block cursor-pointer group">
                    <input 
                        class="plan-radio sr-only" 
                        name="plan_id" 
                        type="radio" 
                        value="{{ $plan['id'] }}" 
                        data-cp-action="select-plan" 
                        data-value="{{ $plan['slug'] }}"
                        @if($isDefault) checked @endif 
                    />
                    <div class="plan-card border border-gray-200 dark:border-gray-700 rounded-xl p-4 transition-all hover:border-primary/50">
                        <div class="flex justify-between items-start mb-4">
                            <div class="flex items-center gap-3">
                                <div class="check-circle size-5 rounded-full border border-gray-300 dark:border-gray-600 flex items-center justify-center text-transparent transition-colors">
                                    <span class="material-symbols-outlined text-[14px] font-bold">check</span>
                                </div>
                                <div>
                                    <h4 class="font-bold text-text-main dark:text-white">
                                        {{ $plan['name'] }}
                                        @if($plan['is_popular'] || $isDefault)
                                        <span class="bg-primary/10 text-primary text-[10px] px-1.5 py-0.5 rounded ml-1">@lang('shop.POPULAR')</span>
                                        @endif
                                    </h4>
                                    <p class="text-xs text-text-muted">{{ $plan['description'] ?? 'Perfect for you' }}</p>
                                </div>
                            </div>
                            <div class="text-right">
                                @php
                                    $defaultCycle = $pricingData['default_billing_cycle'];
                                    $activeTier = $planTiers->first(function($t) use ($defaultCycle) {
                                        $tCycleId = $t['billing_cycle'] ?: 'onetime';
                                        return $tCycleId == $defaultCycle;
                                    }) ?? $planTiers->first();
                                    $activePricingModel  = $activeTier['pricing_model'] ?? 'fixed';
                                    $activeModelHandler = app(PricingModelRegistry::class)->resolve($activePricingModel);
                                    $activeDisplayPrice = $activeModelHandler->usesPerUnitAmount()
                                        ? ($activeTier['per_unit_amount'] ?? 0)
                                        : ($activeTier['price'] ?? 0);
                                    $activeSuffix = $activeModelHandler->checkoutSuffix(
                                        (float) ($activeTier['per_unit_amount'] ?? 0),
                                        $activeTier['billing_cycle_label'] ?? null
                                    );
                                @endphp
                                <span class="price-display font-bold text-lg text-text-main dark:text-white" data-cp-target="price">
                                    @if($activeModelHandler->checkoutDisplayZero())
                                        <span class="text-sm font-medium">Usage-based</span>
                                    @else
                                        ${{ number_format($activeDisplayPrice, 2) }}
                                    @endif
                                </span>
                                <span class="text-sm font-normal text-text-muted duration-period">
                                    {{ $activeSuffix }}
                                </span>
                            </div>
                        </div>

                        @if(count($plan['features']) > 0)
                            {{-- Key Features (first 3) --}}
                            <ul class="pl-8 text-xs text-text-muted space-y-2 mb-4">
                                @foreach(array_slice($plan['features'], 0, 3) as $feature)
                                <li class="flex items-center gap-2">
                                    <span class="material-symbols-outlined text-[14px] text-green-500">check</span>
                                    {{ $feature }}
                                </li>
                                @endforeach
                            </ul>

                            @if(count($plan['features']) > 3)
                                {{-- Collapsible Extra Features --}}
                                <div class="extra-features hidden pl-8 text-xs text-text-muted space-y-2 mb-4 border-t border-gray-50 dark:border-gray-800 pt-4" data-cp-target="feature-list">
                                    @foreach(array_slice($plan['features'], 3) as $feature)
                                    <li class="flex items-center gap-2 @if($loop->first) pt-1 @endif">
                                        <span class="material-symbols-outlined text-[14px] text-green-500">check</span>
                                        {{ $feature }}
                                    </li>
                                    @endforeach
                                </div>

                                <div role="button"
                                    data-cp-action="toggle-features"
                                    data-expanded="false"
                                    class="toggle-features-btn relative z-10 w-full mt-2 py-2 text-[10px] font-bold uppercase tracking-wider text-primary/60 hover:text-primary transition-colors flex items-center justify-center gap-1 cursor-pointer">
                                    <span>@lang('shop.Show all features')</span>
                                    <span class="material-symbols-outlined text-[16px] transition-transform duration-200">expand_more</span>
                                </div>
                            @endif
                        @endif
                    </div>
                </label>
            </div>
        @endforeach
    </div>

    {{-- Seat Count Input (shown by JS when a per-seat plan is selected) --}}
    <div id="seat-count-container" class="mb-6 hidden" data-cp-target="seat-count-container">
        <p class="text-xs font-semibold text-text-muted uppercase tracking-wider mb-3">@lang('shop.Number of Seats')</p>
        <div class="flex items-center gap-3">
            <button type="button" id="seat-decrement"
                    class="size-9 rounded-lg border border-gray-200 dark:border-gray-700 flex items-center justify-center text-text-muted hover:border-primary hover:text-primary transition-colors"
                    onclick="(function(){var i=document.getElementById('seat-count-input');var v=Math.max(1,parseInt(i.value||1)-1);i.value=v;i.dispatchEvent(new Event('input',{bubbles:true}))})()">
                <span class="material-symbols-outlined text-[18px]">remove</span>
            </button>
            <input type="number"
                   id="seat-count-input"
                   name="seat_count"
                   value="1"
                   min="1"
                   data-cp-target="seat-count"
                   class="w-20 text-center bg-gray-50 dark:bg-background-dark border border-gray-200 dark:border-gray-700 rounded-lg py-2 text-sm font-bold focus:ring-primary focus:border-primary" />
            <button type="button" id="seat-increment"
                    class="size-9 rounded-lg border border-gray-200 dark:border-gray-700 flex items-center justify-center text-text-muted hover:border-primary hover:text-primary transition-colors"
                    onclick="(function(){var i=document.getElementById('seat-count-input');var v=parseInt(i.value||1)+1;i.value=v;i.dispatchEvent(new Event('input',{bubbles:true}))})()">
                <span class="material-symbols-outlined text-[18px]">add</span>
            </button>
            <span class="text-sm text-text-muted" data-cp-target="seat-unit-label">seats</span>
        </div>
    </div>

    {{-- Hidden input for selected pricing tier --}}
    @php
        // Find default tier ID based on default cycle
        $defaultTier = null;
        if ($pricingData['default_billing_cycle'] && isset($billingTiers[$pricingData['default_billing_cycle']])) {
             $defaultTier = $billingTiers[$pricingData['default_billing_cycle']];
        } elseif ($billingTiers->isNotEmpty()) {
             $defaultTier = $billingTiers->first();
        }
        $defaultTierId = $defaultTier ? $defaultTier['id'] : '';
    @endphp
    <input type="hidden" name="pricing_tier_id" id="selected-pricing-tier-id" value="{{ $defaultTierId }}">

    {{-- Enhanced Add-ons Section --}}
    @php
        $currentTierAddons = isset($pricingData['addons_by_tier'][$defaultTierId]) 
            ? $pricingData['addons_by_tier'][$defaultTierId] 
            : [];
    @endphp
    
    @if(count($pricingData['available_addons'] ?? []) > 0)
    <div class="space-y-3 mb-8 pt-6 border-t border-gray-100 dark:border-gray-700" id="addon-container" data-cp-target="addon-list" data-current-tier-id="{{ $defaultTier ? $defaultTier['id'] : '' }}">
        <p class="text-xs font-semibold text-text-muted uppercase tracking-wider mb-2">
            @lang('shop.Optional Add-ons')
        </p>
        
        @foreach($pricingData['available_addons'] as $addonId => $addon)
            @php
                $isAvailable = isset($addon['tier_pricing'][$defaultTier['id']]);
                $addonTierData = $isAvailable ? $addon['tier_pricing'][$defaultTier['id']] : null;
            @endphp
            
            <div class="addon-item" 
                 data-addon-id="{{ $addonId }}" 
                 data-tier-pricing="{{ json_encode($addon['tier_pricing']) }}"
                 style="display: {{ $isAvailable ? 'block' : 'none' }};">
                <label class="flex items-start gap-3 cursor-pointer group">
                    <input 
                        name="addons[]" 
                        value="{{ $addonId }}" 
                        data-id="{{ $addonId }}"
                        data-price="{{ $addonTierData ? $addonTierData['price'] : 0 }}"
                        data-cp-action="toggle-addon"
                        class="addon-checkbox mt-1 w-4 h-4 rounded border-gray-300 text-primary focus:ring-primary/20 dark:bg-surface-dark dark:border-gray-600" 
                        type="checkbox" 
                    />
                    <div class="flex-grow">
                        <div class="flex justify-between items-center">
                            <span class="text-sm font-medium text-text-main dark:text-white">{{ $addon['name'] }}</span>
                            <span class="addon-price text-sm font-medium text-text-muted">
                                +<span class="price-value" data-cp-target="addon-price">${{ $addonTierData ? number_format($addonTierData['price'], 0) : 0 }}</span>
                            </span>
                        </div>
                        @if($addon['description'])
                            <p class="text-xs text-text-muted">{{ $addon['description'] }}</p>
                        @endif
                    </div>
                </label>
            </div>
        @endforeach
    </div>
    @endif

    {{-- Total Due Today --}}
    @php
        $defaultPricingModel  = $defaultTier['pricing_model'] ?? 'fixed';
        $defaultModelHandler  = app(PricingModelRegistry::class)->resolve($defaultPricingModel);
        $initialTotal = $defaultModelHandler->checkoutDisplayZero()
            ? '0.00'
            : ($defaultModelHandler->usesPerUnitAmount()
                ? number_format($defaultTier['per_unit_amount'] ?? 0, 2)
                : ($defaultTier ? number_format($defaultTier['price'], 2) : '0.00'));
    @endphp
    <div class="bg-gray-50 dark:bg-background-dark p-4 rounded-xl mb-4">
        <div class="flex justify-between items-end mb-1">
            <span class="text-sm text-text-muted">@lang('shop.Total Due Today')</span>
            <span class="text-2xl font-bold text-text-main dark:text-white" id="total-due-price" data-cp-target="total">
                ${{ $initialTotal }}
            </span>
        </div>
        <p class="text-xs text-text-muted text-right" data-cp-target="renewal-text">@lang('shop.Renews automatically. Cancel anytime.')</p>
        <p class="text-xs text-text-muted text-right hidden" data-cp-target="metered-note">@lang('shop.$0 today — billed monthly based on usage.')</p>
    </div>

    {{-- Subscribe Button --}}
    <button type="button" data-cp-action="submit-cart"
        class="w-full bg-primary hover:bg-primary-dark text-white font-bold py-3.5 rounded-xl transition-all shadow-lg shadow-primary/20 hover:shadow-primary/40 flex items-center justify-center gap-2">
        <span data-cp-target="cta-text">@lang('shop.button|Subscribe Now')</span>
        <span class="material-symbols-outlined text-[20px]">arrow_forward</span>
    </button>

</div>
