@php $fmt = app(\App\Services\Formatter::class); @endphp

<div>
    <x-ui.page-header
        title="Plans &amp; pricing"
        subtitle="Editing a plan never downgrades a shop already on it — entitlements are frozen at purchase."
    />

    <x-resource.toolbar placeholder="Plan name…" create-label="New plan" :can-create="$this->canManage()">
        <x-slot:filters>
            <select wire:model.live="productId" class="field-input w-auto py-1.5 text-xs">
                <option value="">All products</option>
                @foreach ($products as $id => $name)
                    <option value="{{ $id }}">{{ $name }}</option>
                @endforeach
            </select>
        </x-slot:filters>
    </x-resource.toolbar>

    <x-ui.card :padded="false">
        @if ($rows->isEmpty())
            <x-ui.empty
                icon="layers"
                title="No plans yet"
                message="Every product needs at least one trial plan and one paid plan before anyone can subscribe."
            />
        @else
            <x-ui.table>
                <x-slot:head>
                    <tr>
                        <x-ui.th sortable="{{ $sortField }}" field="name" :direction="$sortDirection">Plan</x-ui.th>
                        <th>Product</th>
                        <x-ui.th sortable="{{ $sortField }}" field="monthly_price" :direction="$sortDirection" align="right">Monthly</x-ui.th>
                        <x-ui.th sortable="{{ $sortField }}" field="annual_price" :direction="$sortDirection" align="right">Annual</x-ui.th>
                        <th class="num">Features</th>
                        <th class="num">Subscribers</th>
                        <th>Visibility</th>
                        <th></th>
                    </tr>
                </x-slot:head>

                @foreach ($rows as $plan)
                    <tr>
                        <td>
                            <p class="font-medium">
                                {{ $plan->name }}
                                @if ($plan->is_trial) <x-ui.badge color="blue">Trial</x-ui.badge> @endif
                                @if ($plan->is_featured) <x-ui.badge color="purple">Featured</x-ui.badge> @endif
                            </p>
                            <p class="text-xs text-slate-500">{{ $plan->tagline }}</p>
                        </td>

                        <td class="text-xs">{{ $plan->product?->name ?? '—' }}</td>

                        <td class="num">
                            {{ $fmt->money($plan->monthly_price) }}
                            @if ($plan->is_trial)
                                <p class="text-[11px] text-slate-400">{{ $plan->trial_days }} day trial</p>
                            @endif
                        </td>

                        <td class="num">
                            {{ $fmt->money($plan->annual_price) }}
                            @if ($plan->annualSavingPercent() > 0)
                                <p class="text-[11px] text-emerald-600">saves {{ $plan->annualSavingPercent() }}%</p>
                            @endif
                        </td>

                        <td class="num">{{ count($plan->features ?? []) }}</td>
                        <td class="num">{{ $plan->subscriptions_count }}</td>

                        <td>
                            @if (! $plan->is_active)
                                <x-ui.badge color="gray">Inactive</x-ui.badge>
                            @elseif ($plan->is_public)
                                <x-ui.badge color="green">Public</x-ui.badge>
                            @else
                                <x-ui.badge color="amber">Private</x-ui.badge>
                            @endif
                        </td>

                        <td>
                            <x-resource.row-actions :id="$plan->id"
                                                    :can-edit="$this->canManage()"
                                                    :can-delete="$this->canManage()" />
                        </td>
                    </tr>
                @endforeach
            </x-ui.table>

            <x-resource.pagination :rows="$rows" />
        @endif
    </x-ui.card>

    {{-- -------------------------------------------------------------- form --}}
    <x-ui.modal show="showForm" :title="$editingId ? 'Edit plan' : 'New plan'" width="3xl" close-action="closeForm">
        <div class="grid gap-3 sm:grid-cols-2">
            <x-ui.select label="Product" wire:model.live="form.saas_product_id" :options="$products"
                         placeholder="Choose a product" required :error="$errors->first('form.saas_product_id')" />

            <x-ui.input label="Plan name" wire:model.live="form.name" required :error="$errors->first('form.name')" />

            <x-ui.input label="Slug" wire:model="form.slug" hint="Used in URLs and API responses."
                        :error="$errors->first('form.slug')" />

            <x-ui.input label="Tagline" wire:model="form.tagline" :error="$errors->first('form.tagline')" />

            <div class="sm:col-span-2">
                <x-ui.textarea label="Description" wire:model="form.description" rows="2"
                               :error="$errors->first('form.description')" />
            </div>
        </div>

        {{-- ---------------------------------------------------------- price --}}
        <div class="mt-5 border-t border-slate-200 pt-4 dark:border-slate-800">
            <p class="mb-3 text-sm font-semibold">Price</p>

            <div class="grid gap-3 sm:grid-cols-3">
                <x-ui.input label="Monthly" type="number" step="0.01" wire:model.live="form.monthly_price"
                            :error="$errors->first('form.monthly_price')" />
                <x-ui.input label="Annual" type="number" step="0.01" wire:model.live="form.annual_price"
                            :error="$errors->first('form.annual_price')" />
                <x-ui.input label="Currency" wire:model="form.currency" :error="$errors->first('form.currency')" />
            </div>

            @php
                $monthly = (float) ($form['monthly_price'] ?? 0);
                $annual = (float) ($form['annual_price'] ?? 0);
                $saving = $monthly > 0 ? (int) round(100 - ($annual / ($monthly * 12) * 100)) : 0;
            @endphp

            @if ($monthly > 0 && $annual > 0)
                <p class="mt-2 text-xs text-slate-500">
                    Annual works out at <strong>{{ $fmt->money($annual / 12) }}</strong> a month —
                    @if ($saving > 0)
                        a {{ $saving }}% discount on paying monthly.
                    @elseif ($saving < 0)
                        <span class="text-amber-600">{{ abs($saving) }}% <em>more</em> than paying monthly. Check the figures.</span>
                    @else
                        the same as paying monthly.
                    @endif
                </p>
            @endif

            <div class="mt-3 grid gap-3 sm:grid-cols-2">
                <x-ui.toggle wire:model.live="form.is_trial" label="This is the free trial plan"
                             hint="New signups land here. Only one per product." />

                @if ($form['is_trial'] ?? false)
                    <x-ui.input label="Trial length (days)" type="number" wire:model="form.trial_days"
                                :error="$errors->first('form.trial_days')" />
                @endif
            </div>
        </div>

        {{-- ------------------------------------------------------- features --}}
        <div class="mt-5 border-t border-slate-200 pt-4 dark:border-slate-800">
            <p class="mb-1 text-sm font-semibold">What this plan unlocks</p>
            <p class="mb-3 text-xs text-slate-500">
                These keys come from the product's own configuration — anything not ticked is hidden
                inside the application, not merely unadvertised.
            </p>

            @if (empty($catalogue['features']))
                <p class="rounded-lg bg-amber-50 p-2.5 text-xs text-amber-800 dark:bg-amber-950 dark:text-amber-200">
                    Pick a product first. If you have picked one and still see this, the product's slug has no
                    block in <code>config/thinkrax.php</code>.
                </p>
            @else
                <div class="grid gap-1.5 sm:grid-cols-2">
                    @foreach ($catalogue['features'] as $key => $label)
                        <label class="flex items-start gap-2 rounded-lg border border-slate-200 p-2 text-sm hover:bg-slate-50 dark:border-slate-700 dark:hover:bg-slate-800">
                            <input type="checkbox" value="{{ $key }}" wire:model="selectedFeatures"
                                   class="mt-0.5 rounded border-slate-300">
                            <span>
                                {{ $label }}
                                <span class="block text-[11px] text-slate-400">{{ $key }}</span>
                            </span>
                        </label>
                    @endforeach
                </div>
            @endif
        </div>

        {{-- --------------------------------------------------------- limits --}}
        @if (! empty($catalogue['limits']))
            <div class="mt-5 border-t border-slate-200 pt-4 dark:border-slate-800">
                <p class="mb-1 text-sm font-semibold">Caps</p>
                <p class="mb-3 text-xs text-slate-500">Leave a box empty for unlimited.</p>

                <div class="grid gap-3 sm:grid-cols-3">
                    @foreach ($catalogue['limits'] as $key => $label)
                        <x-ui.input :label="$label" type="number" min="0"
                                    wire:model="limitValues.{{ $key }}" placeholder="Unlimited" />
                    @endforeach
                </div>
            </div>
        @endif

        {{-- ----------------------------------------------------- marketing --}}
        <div class="mt-5 border-t border-slate-200 pt-4 dark:border-slate-800">
            <p class="mb-3 text-sm font-semibold">Pricing page</p>

            <x-ui.textarea label="Selling points (one per line)" wire:model="form.highlights" rows="4"
                           :error="$errors->first('form.highlights')"
                           placeholder="Unlimited invoices&#10;WhatsApp support&#10;Free setup &amp; data import" />

            <div class="mt-3 grid gap-3 sm:grid-cols-2">
                <x-ui.toggle wire:model="form.is_public" label="Show on the pricing page" />
                <x-ui.toggle wire:model="form.is_featured" label="Highlight as the recommended plan" />
                <x-ui.toggle wire:model="form.is_active" label="Active"
                             hint="Inactive plans stay valid for existing shops but cannot be bought." />
                <x-ui.input label="Sort order" type="number" wire:model="form.sort_order" />
            </div>
        </div>

        <x-slot:footer>
            <x-ui.button wire:click="closeForm">Cancel</x-ui.button>
            <x-ui.button variant="primary" wire:click="saveResource" loading="saveResource">Save plan</x-ui.button>
        </x-slot:footer>
    </x-ui.modal>

    <x-resource.delete-confirm label="plan" />
</div>
