@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);
    $workspaceClosurePosture = $workspace->isClosed() ? 'closed' : 'open';
    $workspaceClosureBadge = BadgeCatalog::spec(BadgeDomain::WorkspaceClosurePosture, $workspaceClosurePosture);
    $commercialSourceDescriptor = ($commercialLifecycle['fallback_status'] ?? true) ? 'fallback-backed' : 'subscription-backed';
    $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;
    $supportAccess = $this->supportAccessSummary();
@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 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</p>
                    <div class="mt-2">
                        <x-filament::badge :color="$workspaceClosureBadge->color" :icon="$workspaceClosureBadge->icon">
                            {{ $workspaceClosureBadge->label }}
                        </x-filament::badge>
                    </div>
                    <p class="mt-2 text-sm text-gray-500 dark:text-gray-400">
                        @if ($workspace->isClosed())
                            Closed {{ $workspace->closed_at?->diffForHumans() ?? '' }}. Active selection and new mutations are blocked.
                        @else
                            Eligible for workspace selection and normal tenant operations.
                        @endif
                    </p>
                </div>
            </div>

            @if ($workspace->isClosed())
                <div class="mt-4 rounded-lg border border-danger-200 bg-danger-50 px-4 py-3 text-sm text-danger-800 dark:border-danger-500/30 dark:bg-danger-500/10 dark:text-danger-200">
                    <p class="font-semibold">Closed workspace</p>
                    <p class="mt-1">{{ $workspace->closureReason() ?? 'No closure reason recorded.' }}</p>
                </div>
            @endif

            <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">
                Support access
            </x-slot>

            <x-slot name="description">
                Workspace-scoped support access stays separate from break-glass recovery.
            </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 posture</p>
                    <div class="mt-2 flex flex-wrap items-center gap-2">
                        <x-filament::badge :color="$supportAccess['status_color']">
                            {{ $supportAccess['status_label'] }}
                        </x-filament::badge>

                        @if ($supportAccess['scope_label'])
                            <x-filament::badge color="gray">
                                {{ $supportAccess['scope_label'] }}
                            </x-filament::badge>
                        @endif
                    </div>

                    <p class="mt-2 text-sm text-gray-500 dark:text-gray-400">
                        @if ($supportAccess['reason'])
                            {{ $supportAccess['reason'] }}
                        @else
                            No platform support grant is currently active or pending for this workspace.
                        @endif
                    </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">Governance detail</p>
                    @if ($supportAccess['grant_id'])
                        <dl class="mt-2 grid grid-cols-1 gap-2 text-sm text-gray-600 dark:text-gray-300">
                            <div>
                                <dt class="font-medium text-gray-950 dark:text-white">Requester</dt>
                                <dd>{{ $supportAccess['requester_label'] }}</dd>
                            </div>
                            <div>
                                <dt class="font-medium text-gray-950 dark:text-white">Approval</dt>
                                <dd>
                                    {{ $supportAccess['approval_label'] }}
                                    @if ($supportAccess['approver_label'])
                                        by {{ $supportAccess['approver_label'] }}
                                    @endif
                                </dd>
                            </div>
                            <div>
                                <dt class="font-medium text-gray-950 dark:text-white">TTL</dt>
                                <dd>
                                    {{ $supportAccess['requested_ttl_label'] }}
                                    @if ($supportAccess['expires_label'])
                                        · expires {{ $supportAccess['expires_label'] }}
                                    @endif
                                </dd>
                            </div>
                            @if ($supportAccess['needs_break_glass'])
                                <div>
                                    <dt class="font-medium text-gray-950 dark:text-white">Recovery boundary</dt>
                                    <dd>Owner repair still requires active break-glass mode.</dd>
                                </div>
                            @endif
                        </dl>
                    @else
                        <p class="mt-2 text-sm text-gray-500 dark:text-gray-400">Request ordinary audit review access here, or request recovery access when owner repair needs a customer-visible approval path.</p>
                    @endif
                </div>
            </div>
        </x-filament::section>

        <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">Workspace subscription</p>
                    <div class="mt-2 flex items-center gap-2">
                        <x-filament::badge :color="($commercialLifecycle['fallback_status'] ?? true) ? 'gray' : 'info'">
                            {{ $commercialSourceDescriptor }}
                        </x-filament::badge>
                        <span class="text-sm text-gray-500 dark:text-gray-400">{{ $commercialLifecycle['subscription_state_label'] ?? 'No current subscription record' }}</span>
                    </div>

                    @if (($commercialLifecycle['subscription_key_date_label'] ?? null) !== null && ($commercialLifecycle['subscription_key_date'] ?? null) instanceof \Carbon\CarbonInterface)
                        <p class="mt-2 text-sm text-gray-500 dark:text-gray-400">
                            {{ $commercialLifecycle['subscription_key_date_label'] }}: {{ $commercialLifecycle['subscription_key_date']->toDayDateTimeString() }}
                        </p>
                    @endif

                    @if (($commercialLifecycle['fallback_status'] ?? true) === false)
                        @if (($commercialLifecycle['subscription_needs_review'] ?? false) === true)
                            <p class="mt-2 text-sm text-warning-700 dark:text-warning-300">This subscription record needs review before the next commercial change is applied.</p>
                        @endif
                        @if (($commercialLifecycle['subscription_billing_reference'] ?? null) !== null)
                            <p class="mt-2 text-sm text-gray-500 dark:text-gray-400">Reference: {{ $commercialLifecycle['subscription_billing_reference'] }}</p>
                        @endif
                    @else
                        <p class="mt-2 text-sm text-gray-500 dark:text-gray-400">No current subscription record is stored. The workspace still follows the explicit lifecycle fallback or the default active-paid posture.</p>
                    @endif
                </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">Derived commercial lifecycle</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>
                    <p class="mt-2 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($tenant->isRemovedFromWorkspace() ? \App\Support\Badges\BadgeDomain::TenantWorkspacePosture : \App\Support\Badges\BadgeDomain::TenantStatus, $tenant->isRemovedFromWorkspace() ? 'removed_from_workspace' : (string) $tenant->status)->color"
                            >
                                {{ \App\Support\Badges\BadgeRenderer::spec($tenant->isRemovedFromWorkspace() ? \App\Support\Badges\BadgeDomain::TenantWorkspacePosture : \App\Support\Badges\BadgeDomain::TenantStatus, $tenant->isRemovedFromWorkspace() ? 'removed_from_workspace' : (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>
