@php
    use App\Support\Badges\BadgeCatalog;
    use App\Support\Badges\BadgeDomain;

    /** @var \App\Models\Workspace $workspace */
    $workspace = $this->workspace;
    $customerHealthDecision = $this->customerHealthDecision();
    $tenants = $this->workspaceTenants();
    $runs = $this->recentRuns();
    $commercialLifecycle = $this->workspaceCommercialLifecycleSummary();
    $commercialBadge = BadgeCatalog::spec(BadgeDomain::CommercialLifecycleState, $commercialLifecycle['state'] ?? null);
    $commercialActionDecisions = is_array($commercialLifecycle['action_decisions'] ?? null) ? $commercialLifecycle['action_decisions'] : [];
    $activationLifecycleDecision = $commercialActionDecisions['managed_tenant_activation'] ?? null;
    $reviewPackLifecycleDecision = $commercialActionDecisions['review_pack_start'] ?? null;
    $readOnlyLifecycleDecision = $commercialActionDecisions['generated_pack_read'] ?? null;
    $workspaceEntitlementSummary = $this->workspaceEntitlementSummary();
    $planProfile = $workspaceEntitlementSummary['plan_profile'] ?? null;
    $entitlementDecisions = $workspaceEntitlementSummary['decisions'] ?? [];
    $managedTenantDecision = $entitlementDecisions['managed_tenant_activation_limit'] ?? null;
    $reviewPackDecision = $entitlementDecisions['review_pack_generation_enabled'] ?? null;
@endphp

<x-filament-panels::page>
    <div class="space-y-6">
        <x-filament::section>
            <x-slot name="heading">
                {{ $workspace->name }}
            </x-slot>

            <x-slot name="description">
                Workspace #{{ (int) $workspace->getKey() }}
            </x-slot>

            <div class="grid grid-cols-1 gap-4 sm:grid-cols-3">
                <div class="rounded-lg bg-gray-50 px-4 py-3 dark:bg-white/5">
                    <p class="text-xs font-semibold uppercase tracking-wider text-gray-500 dark:text-gray-400">Tenants</p>
                    <p class="mt-1 text-2xl font-bold text-gray-950 dark:text-white">{{ number_format((int) $workspace->tenants_count) }}</p>
                </div>
            </div>

            <div class="mt-4">
                <x-filament::link :href="$this->adminWorkspaceUrl()" icon="heroicon-m-arrow-top-right-on-square">
                    Open in /admin
                </x-filament::link>
            </div>
        </x-filament::section>

        @if ($customerHealthDecision)
            @include('filament.system.pages.directory.partials.customer-health-decision-card', ['decision' => $customerHealthDecision])
        @endif

        <x-filament::section>
            <x-slot name="heading">
                Commercial lifecycle
            </x-slot>

            <div class="grid grid-cols-1 gap-4 sm:grid-cols-2">
                <div class="rounded-lg bg-gray-50 px-4 py-3 dark:bg-white/5">
                    <p class="text-xs font-semibold uppercase tracking-wider text-gray-500 dark:text-gray-400">Current state</p>
                    <div class="mt-2 flex items-center gap-2">
                        <x-filament::badge :color="$commercialBadge->color" :icon="$commercialBadge->icon">
                            {{ $commercialBadge->label }}
                        </x-filament::badge>
                        <span class="text-sm text-gray-500 dark:text-gray-400">{{ $commercialLifecycle['source_label'] ?? 'default active paid' }}</span>
                    </div>
                    <p class="mt-2 text-sm text-gray-500 dark:text-gray-400">{{ $commercialLifecycle['description'] ?? 'Commercial lifecycle state controls expansion and review-pack starts.' }}</p>
                </div>

                <div class="rounded-lg bg-gray-50 px-4 py-3 dark:bg-white/5">
                    <p class="text-xs font-semibold uppercase tracking-wider text-gray-500 dark:text-gray-400">Lifecycle rationale</p>
                    <p class="mt-1 text-base font-semibold text-gray-950 dark:text-white">{{ $commercialLifecycle['rationale'] ?? 'No explicit rationale recorded.' }}</p>
                    <p class="mt-1 text-sm text-gray-500 dark:text-gray-400">
                        {{ $commercialLifecycle['last_changed_by'] ?? 'System default' }}
                        @if (($commercialLifecycle['last_changed_at'] ?? null) instanceof \Carbon\CarbonInterface)
                            · {{ $commercialLifecycle['last_changed_at']->diffForHumans() }}
                        @endif
                    </p>
                </div>
            </div>

            <div class="mt-4 space-y-3">
                @foreach ([
                    'Managed tenant activation' => $activationLifecycleDecision,
                    'Review-pack starts' => $reviewPackLifecycleDecision,
                    'Read-only history and downloads' => $readOnlyLifecycleDecision,
                ] as $label => $decision)
                    @if (is_array($decision))
                        <div class="rounded-lg border border-gray-200 px-4 py-3 dark:border-white/10">
                            <div class="flex items-start justify-between gap-4">
                                <div>
                                    <p class="text-sm font-semibold text-gray-950 dark:text-white">{{ $label }}</p>
                                    <p class="mt-1 text-sm text-gray-500 dark:text-gray-400">{{ $decision['message'] ?? 'No lifecycle decision message available.' }}</p>
                                </div>
                                <x-filament::badge :color="match ($decision['outcome'] ?? null) {
                                    'block' => 'danger',
                                    'warn' => 'warning',
                                    'allow_read_only' => 'info',
                                    default => 'success',
                                }">
                                    {{ str_replace('_', ' ', (string) ($decision['outcome'] ?? 'allow')) }}
                                </x-filament::badge>
                            </div>
                        </div>
                    @endif
                @endforeach
            </div>
        </x-filament::section>

        @if (is_array($planProfile) && is_array($managedTenantDecision) && is_array($reviewPackDecision))
            <x-filament::section>
                <x-slot name="heading">
                    Workspace entitlements
                </x-slot>

                <div class="grid grid-cols-1 gap-4 sm:grid-cols-2">
                    <div class="rounded-lg bg-gray-50 px-4 py-3 dark:bg-white/5">
                        <p class="text-xs font-semibold uppercase tracking-wider text-gray-500 dark:text-gray-400">Plan profile</p>
                        <p class="mt-1 text-base font-semibold text-gray-950 dark:text-white">{{ $planProfile['label'] }}</p>
                        <p class="mt-1 text-sm text-gray-500 dark:text-gray-400">{{ $planProfile['description'] }}</p>
                    </div>

                    <div class="rounded-lg bg-gray-50 px-4 py-3 dark:bg-white/5">
                        <p class="text-xs font-semibold uppercase tracking-wider text-gray-500 dark:text-gray-400">Last changed</p>
                        <p class="mt-1 text-base font-semibold text-gray-950 dark:text-white">{{ $managedTenantDecision['last_changed_by'] ?? 'Not set' }}</p>
                        <p class="mt-1 text-sm text-gray-500 dark:text-gray-400">{{ $managedTenantDecision['last_changed_at']?->diffForHumans() ?? 'No entitlement override recorded yet.' }}</p>
                    </div>
                </div>

                <div class="mt-4 space-y-3">
                    <div class="rounded-lg border border-gray-200 px-4 py-3 dark:border-white/10">
                        <div class="flex items-center justify-between gap-4">
                            <div>
                                <p class="text-sm font-semibold text-gray-950 dark:text-white">Managed tenant activation limit</p>
                                <p class="text-sm text-gray-500 dark:text-gray-400">{{ $managedTenantDecision['current_usage'] }} active of {{ $managedTenantDecision['effective_value'] }} allowed</p>
                            </div>
                            <x-filament::badge :color="$managedTenantDecision['source'] === 'workspace_override' ? 'warning' : 'gray'">
                                {{ $managedTenantDecision['source'] === 'workspace_override' ? 'workspace override' : ($managedTenantDecision['plan_profile_label'].' plan profile') }}
                            </x-filament::badge>
                        </div>

                        <p class="mt-2 text-sm text-gray-500 dark:text-gray-400">{{ $managedTenantDecision['rationale'] }}</p>
                    </div>

                    <div class="rounded-lg border border-gray-200 px-4 py-3 dark:border-white/10">
                        <div class="flex items-center justify-between gap-4">
                            <div>
                                <p class="text-sm font-semibold text-gray-950 dark:text-white">Review pack generation</p>
                                <p class="text-sm text-gray-500 dark:text-gray-400">{{ $reviewPackDecision['effective_value'] ? 'Enabled' : 'Disabled' }}</p>
                            </div>
                            <x-filament::badge :color="$reviewPackDecision['source'] === 'workspace_override' ? 'warning' : 'gray'">
                                {{ $reviewPackDecision['source'] === 'workspace_override' ? 'workspace override' : ($reviewPackDecision['plan_profile_label'].' plan profile') }}
                            </x-filament::badge>
                        </div>

                        <p class="mt-2 text-sm text-gray-500 dark:text-gray-400">{{ $reviewPackDecision['rationale'] }}</p>
                    </div>
                </div>
            </x-filament::section>
        @endif

        <x-filament::section>
            <x-slot name="heading">
                Tenants summary
            </x-slot>

            @if ($tenants->isEmpty())
                <p class="text-sm text-gray-500 dark:text-gray-400">No tenants are attached to this workspace.</p>
            @else
                <div class="space-y-2">
                    @foreach ($tenants as $tenant)
                        <a
                            href="{{ \App\Support\System\SystemDirectoryLinks::tenantDetail($tenant) }}"
                            class="flex items-center justify-between rounded-lg border border-gray-200 px-4 py-3 hover:border-primary-400 hover:bg-gray-50 dark:border-white/10 dark:hover:border-primary-500 dark:hover:bg-white/5"
                        >
                            <span class="font-medium text-gray-950 dark:text-white">{{ $tenant->name }}</span>
                            <x-filament::badge
                                :color="\App\Support\Badges\BadgeRenderer::spec(\App\Support\Badges\BadgeDomain::TenantStatus, (string) $tenant->status)->color"
                            >
                                {{ \App\Support\Badges\BadgeRenderer::spec(\App\Support\Badges\BadgeDomain::TenantStatus, (string) $tenant->status)->label }}
                            </x-filament::badge>
                        </a>
                    @endforeach
                </div>
            @endif
        </x-filament::section>

        <x-filament::section>
            <x-slot name="heading">
                Recent operations
            </x-slot>

            @if ($runs->isEmpty())
                <p class="text-sm text-gray-500 dark:text-gray-400">No recent operation runs for this workspace.</p>
            @else
                <div class="space-y-2">
                    @foreach ($runs as $run)
                        <a
                            href="{{ $run['url'] }}"
                            class="block rounded-lg border border-gray-200 px-4 py-3 hover:border-primary-400 hover:bg-gray-50 dark:border-white/10 dark:hover:border-primary-500 dark:hover:bg-white/5"
                        >
                            <div class="flex items-center justify-between">
                                <span class="font-medium text-gray-950 dark:text-white">#{{ $run['id'] }} · {{ $run['label'] }}</span>
                                <span class="text-xs text-gray-500 dark:text-gray-400">{{ $run['started'] }}</span>
                            </div>
                        </a>
                    @endforeach
                </div>
            @endif

            <div class="mt-4">
                <x-filament::link :href="$this->runsUrl()" icon="heroicon-m-arrow-top-right-on-square">
                    Open operations runs
                </x-filament::link>
            </div>
        </x-filament::section>
    </div>
</x-filament-panels::page>
