<x-app-layout title="Plans" heading="Care plans">
    @php
        $proPerBranch = number_format($proPricePerBranchMinor / 100, 0);
        $enterprisePerBranch = number_format($enterprisePricePerBranchMinor / 100, 0);
        $initialBranches = max(1, (int) $branchCount);
    @endphp

    <div class="mx-auto max-w-5xl space-y-6"
         x-data="{
            billing: 'monthly',
            branches: {{ $initialBranches }},
            proPerBranch: {{ (int) $proPricePerBranchMinor }},
            entPerBranch: {{ (int) $enterprisePricePerBranchMinor }},
            minBranches: {{ $initialBranches }},
            proTotal() {
                return this.proPerBranch * Math.max(this.minBranches, parseInt(this.branches) || this.minBranches);
            },
            entTotal() {
                return this.entPerBranch * Math.max(this.minBranches, parseInt(this.branches) || this.minBranches);
            },
            branchCount() {
                return Math.max(this.minBranches, parseInt(this.branches) || this.minBranches);
            },
            fmt(minor) {
                return (minor / 100).toLocaleString();
            }
         }">
        @if (session('success'))
            <div class="rounded-xl border border-emerald-200 bg-emerald-50 px-4 py-3 text-sm text-emerald-800">{{ session('success') }}</div>
        @endif
        @if (session('error'))
            <div class="rounded-xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-800">{{ session('error') }}</div>
        @endif
        @if (session('upsell'))
            <div class="rounded-xl border border-indigo-200 bg-indigo-50 px-4 py-3 text-sm text-indigo-900">{{ session('upsell') }}</div>
        @endif

        <div class="rounded-2xl border border-slate-200 bg-white px-6 py-5">
            <h1 class="text-2xl font-bold text-slate-900">Choose your Care plan</h1>
            <p class="mt-1 text-sm text-slate-600">
                Pay monthly from your Ladill wallet, or prepay 6/12/24 months via Paystack.
                Pro and Enterprise are billed per branch — set how many branches to include below.
                Enterprise includes dedicated onboarding — <a href="{{ $salesUrl }}" class="font-medium text-indigo-600 hover:text-indigo-800" target="_blank" rel="noopener">contact sales</a> for multi-site deployments.
            </p>
            <div class="mt-4 flex flex-wrap items-center gap-2">
                <button type="button" @click="billing = 'monthly'"
                        :class="billing === 'monthly' ? 'bg-indigo-600 text-white' : 'bg-slate-100 text-slate-700 hover:bg-slate-200'"
                        class="rounded-lg px-3 py-1.5 text-sm font-medium transition">Monthly · wallet</button>
                @foreach ($prepaidMonths as $months)
                    <button type="button" @click="billing = '{{ $months }}'"
                            :class="billing === '{{ $months }}' ? 'bg-indigo-600 text-white' : 'bg-slate-100 text-slate-700 hover:bg-slate-200'"
                            class="rounded-lg px-3 py-1.5 text-sm font-medium transition">{{ $months }} months · Paystack</button>
                @endforeach

                <label class="inline-flex items-center gap-2 rounded-lg border border-slate-200 bg-slate-50 px-3 py-1.5 text-sm text-slate-700">
                    <span class="font-medium text-slate-600">Branches</span>
                    <input type="number"
                           min="{{ $initialBranches }}"
                           max="999"
                           x-model.number="branches"
                           @change="if (branches < minBranches) branches = minBranches"
                           class="w-16 rounded-md border-slate-300 py-0.5 text-center text-sm focus:border-indigo-500 focus:ring-indigo-500">
                </label>
            </div>
            <p class="mt-2 text-xs text-slate-500">
                Minimum is your current active branch count ({{ $initialBranches }}). Totals update live for Pro and Enterprise.
            </p>
        </div>

        <div class="grid gap-5 lg:grid-cols-3">
            {{-- Free --}}
            <div class="flex flex-col rounded-2xl border border-slate-200 bg-white p-6 {{ $planKey === 'free' ? 'ring-2 ring-indigo-500' : '' }}">
                <p class="text-xs font-semibold uppercase tracking-wide text-slate-500">Free</p>
                <p class="mt-2 text-3xl font-bold text-slate-900">GHS 0</p>
                <p class="mt-1 text-sm text-slate-500">1 branch</p>
                <ul class="mt-5 flex-1 space-y-2 text-sm text-slate-700">
                    <li>Core patient records</li>
                    <li>Appointments & consults</li>
                    <li>Basic workflows</li>
                </ul>
                @if ($planKey === 'free')
                    <p class="mt-6 text-sm font-medium text-indigo-700">Current plan</p>
                @endif
            </div>

            {{-- Pro --}}
            <div class="flex flex-col rounded-2xl border border-slate-200 bg-white p-6 {{ $planKey === 'pro' ? 'ring-2 ring-indigo-500' : '' }}">
                <p class="text-xs font-semibold uppercase tracking-wide text-indigo-600">Pro</p>
                <x-plan-tier-price
                    :currency="$currency"
                    :monthly-minor="$proPricePerBranchMinor"
                    :monthly-display="$proPerBranch"
                    monthly-suffix="/branch/mo"
                />
                <p class="mt-1 text-sm text-slate-500">
                    <span x-text="branchCount()"></span> branch(es) × {{ $currency }} {{ $proPerBranch }}/branch
                    = {{ $currency }} <span x-text="fmt(proTotal())"></span>/mo
                </p>
                <ul class="mt-5 flex-1 space-y-2 text-sm text-slate-700">
                    <li>Everything in Free</li>
                    <li>Full clinical workflows</li>
                    <li>Laboratory & pharmacy</li>
                    <li>Encounter billing</li>
                    <li>Your own Paystack / Flutterwave / Hubtel</li>
                    <li>In-app service queues</li>
                    <li>Unlimited branches (billed per branch)</li>
                </ul>
                <div class="mt-6">
                    @if ($planKey === 'pro')
                        <p class="text-sm text-slate-600">
                            Active
                            @if ($planExpiresAt)
                                until <strong>{{ $planExpiresAt->format('d M Y') }}</strong>
                            @endif
                            @if ($billedBranches > 0)
                                · billed for {{ $billedBranches }} {{ str('branch')->plural($billedBranches) }}
                            @endif
                            .
                        </p>
                    @elseif ($canManage)
                        <form x-show="billing === 'monthly'" method="post" action="{{ route('care.pro.subscribe') }}">
                            @csrf
                            <input type="hidden" name="branches" :value="branchCount()">
                            <button type="submit" class="btn-primary w-full"
                                    x-text="'Upgrade to Pro — {{ $currency }} ' + fmt(proTotal()) + '/mo'"></button>
                        </form>
                        <template x-for="months in @js($prepaidMonths)" :key="months">
                            <form x-show="billing == months" method="post" action="{{ route('care.pro.subscribe-prepaid') }}">
                                @csrf
                                <input type="hidden" name="plan" value="pro">
                                <input type="hidden" name="months" :value="months">
                                <input type="hidden" name="branches" :value="branchCount()">
                                <button type="submit" class="btn-primary w-full"
                                        x-text="'Pay ' + months + ' months via Paystack — {{ $currency }} ' + fmt(proTotal() * months)"></button>
                            </form>
                        </template>
                    @else
                        <p class="text-sm text-slate-500">Ask an admin to upgrade.</p>
                    @endif
                </div>
            </div>

            {{-- Enterprise --}}
            <div class="flex flex-col rounded-2xl border border-slate-200 bg-gradient-to-b from-slate-900 to-slate-800 p-6 text-white {{ $planKey === 'enterprise' ? 'ring-2 ring-amber-400' : '' }}">
                <p class="text-xs font-semibold uppercase tracking-wide text-amber-300">Enterprise</p>
                <x-plan-tier-price
                    :currency="$currency"
                    :monthly-minor="$enterprisePricePerBranchMinor"
                    :monthly-display="$enterprisePerBranch"
                    monthly-suffix="/branch/mo"
                    dark
                />
                <p class="mt-1 text-sm text-slate-300">
                    <span x-text="branchCount()"></span> branch(es) × {{ $currency }} {{ $enterprisePerBranch }}/branch
                    = {{ $currency }} <span x-text="fmt(entTotal())"></span>/mo
                </p>
                <ul class="mt-5 flex-1 space-y-2 text-sm text-slate-200">
                    <li>Everything in Pro</li>
                    <li>Custom multi-department workflow integration</li>
                    <li>Advanced data analytics</li>
                    <li>AI-assisted healthcare integration</li>
                    <li>Priority support & dedicated onboarding</li>
                </ul>
                <div class="mt-6 space-y-2">
                    @if ($planKey === 'enterprise')
                        <p class="text-sm text-slate-200">
                            Active
                            @if ($planExpiresAt)
                                until <strong class="text-white">{{ $planExpiresAt->format('d M Y') }}</strong>
                            @endif
                            @if ($billedBranches > 0)
                                · billed for {{ $billedBranches }} {{ str('branch')->plural($billedBranches) }}
                            @endif
                            .
                        </p>
                    @elseif ($canManage)
                        @if ($canSubscribeEnterprise)
                            <form x-show="billing === 'monthly'" method="post" action="{{ route('care.pro.subscribe-enterprise') }}">
                                @csrf
                                <input type="hidden" name="branches" :value="branchCount()">
                                <button type="submit" class="w-full rounded-xl bg-amber-400 px-4 py-2.5 text-sm font-semibold text-slate-900 hover:bg-amber-300"
                                        x-text="'Upgrade — {{ $currency }} ' + fmt(entTotal()) + '/mo'"></button>
                            </form>
                            <template x-for="months in @js($prepaidMonths)" :key="'ent-' + months">
                                <form x-show="billing == months" method="post" action="{{ route('care.pro.subscribe-prepaid') }}">
                                    @csrf
                                    <input type="hidden" name="plan" value="enterprise">
                                    <input type="hidden" name="months" :value="months">
                                    <input type="hidden" name="branches" :value="branchCount()">
                                    <button type="submit" class="w-full rounded-xl bg-amber-400 px-4 py-2.5 text-sm font-semibold text-slate-900 hover:bg-amber-300"
                                            x-text="'Pay ' + months + ' months via Paystack — {{ $currency }} ' + fmt(entTotal() * months)"></button>
                                </form>
                            </template>
                        @else
                            <p class="text-sm text-slate-300">Ask an admin to upgrade, or contact sales for custom onboarding.</p>
                        @endif
                        <a href="{{ $salesUrl }}" target="_blank" rel="noopener" class="block text-center text-xs text-amber-200 underline hover:text-white">Contact sales for onboarding & SLA</a>
                    @else
                        <p class="text-sm text-slate-300">Ask an admin to upgrade.</p>
                    @endif
                </div>
            </div>
        </div>

        <div class="rounded-2xl border border-sky-100 bg-sky-50 px-4 py-3 text-sm text-sky-900">
            <p class="font-medium">Queue devices vs clinical devices</p>
            <ul class="mt-1 list-disc space-y-1 pl-5 text-sky-800/90">
                <li><strong>Queue kiosk</strong> — walk-up ticket issue on a tablet (Pro).</li>
                <li><strong>Queue display</strong> — registers a waiting-room TV board URL (Pro).</li>
                <li><strong>Barcode / QR scanners</strong> — USB keyboard wedge in Patients and Lab (all plans).</li>
                <li><strong>Vitals / analyzers</strong> — Care Device Agent (Pro).</li>
            </ul>
        </div>
    </div>
</x-app-layout>
