@php
    $settingsSection = isset($settingsSection) && is_string($settingsSection) ? $settingsSection : null;
    /** @var \App\Models\UpdateSetting|null $updateSettings */
    $updateSettings = $updateSettings instanceof \App\Models\UpdateSetting ? $updateSettings : null;
    /** @var \Illuminate\Support\Collection<int, \App\Models\UpdateCheck> $updateChecks */
    $updateChecks = ($updateChecks ?? collect()) instanceof \Illuminate\Support\Collection ? $updateChecks : collect($updateChecks ?? []);
    /** @var \Illuminate\Support\Collection<int, \App\Models\UpdateInstallation> $updateInstallations */
    $updateInstallations = ($updateInstallations ?? collect()) instanceof \Illuminate\Support\Collection ? $updateInstallations : collect($updateInstallations ?? []);

    $defaultFeedUrl = \App\Support\UpdateCenterManager::DEFAULT_FEED_URL;
    $feedUrl = old('feed_url', (string) ($updateSettings?->feed_url ?: $defaultFeedUrl));
    $currentVersion = old('current_version', (string) ($updateSettings?->current_version ?: config('app.version', '1.005')));
    $channel = old('channel', (string) ($updateSettings?->channel ?: 'stable'));
    $isActive = old('is_active', (bool) ($updateSettings?->is_active ?? true));
    $autoCheckEnabled = old('auto_check_enabled', (bool) ($updateSettings?->auto_check_enabled ?? true));
    $checkInterval = (int) old('check_interval_minutes', (int) ($updateSettings?->check_interval_minutes ?? 720));
    $requestTimeout = (int) old('request_timeout_seconds', (int) ($updateSettings?->request_timeout_seconds ?? 8));
    $verifyTls = old('verify_tls', (bool) ($updateSettings?->verify_tls ?? true));
    $metaValue = old('meta', $updateSettings?->meta ? json_encode($updateSettings->meta, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) : '');

    $channelOptions = [
        'stable' => __('Stable'),
        'beta' => __('Beta'),
        'nightly' => __('Nightly'),
    ];
    $latestAvailableCheck = $updateChecks->first(static fn ($check) => $check->status === 'success' && $check->is_update_available);
    $pendingVersion = (string) ($latestAvailableCheck?->remote_version ?: ($updateSettings?->last_remote_version ?: ''));
    $pendingBuild = (string) ($latestAvailableCheck?->remote_build ?: ($updateSettings?->last_remote_build ?: ''));
    $hasPendingUpdate = $pendingVersion !== '' && version_compare($pendingVersion, (string) ($updateSettings?->current_version ?: $currentVersion), '>');
    $activeStatuses = ['queued', 'checking', 'downloading', 'extracting', 'backing_up', 'installing', 'finalizing'];
    $activeInstallation = $updateInstallations->first(static fn ($installation) => in_array((string) $installation->status, $activeStatuses, true));
    $activeInstallationPayload = $activeInstallation
        ? (new \App\Http\Resources\UpdateInstallationResource($activeInstallation->loadMissing('actor:id,name,email')))->toArray(request())
        : null;
    $installationStatusUrlTemplate = route('profile.updates.installations.show', ['installation' => '__INSTALLATION__']);
@endphp

<section class="space-y-6">
    <header>
        <h2 class="inline-flex items-center gap-2 text-lg font-medium text-gray-900">
            <x-menu-icon name="fa-solid fa-arrows-rotate" class="h-5 w-5 text-gray-500" />
            {{ __('Updates') }}
        </h2>
        <p class="mt-1 text-sm text-gray-600">
            {{ __('Configure update source, run checks and monitor available versions.') }}
        </p>
    </header>

    <div class="grid grid-cols-1 gap-3 md:grid-cols-2 xl:grid-cols-4">
        <div class="rounded-lg border border-slate-200 bg-slate-50 px-3 py-2">
            <p class="text-xs uppercase tracking-wide text-slate-500">{{ __('Current version') }}</p>
            <p class="mt-1 text-sm font-semibold text-slate-900">{{ $updateSettings?->current_version ?: $currentVersion }}</p>
        </div>
        <div class="rounded-lg border border-slate-200 bg-slate-50 px-3 py-2">
            <p class="text-xs uppercase tracking-wide text-slate-500">{{ __('Last remote version') }}</p>
            <p class="mt-1 text-sm font-semibold text-slate-900">{{ $updateSettings?->last_remote_version ?: '—' }}</p>
        </div>
        <div class="rounded-lg border border-slate-200 bg-slate-50 px-3 py-2">
            <p class="text-xs uppercase tracking-wide text-slate-500">{{ __('Last check') }}</p>
            <p class="mt-1 text-sm font-semibold text-slate-900">{{ $updateSettings?->last_checked_at?->format('d.m.Y H:i') ?: '—' }}</p>
        </div>
        <div class="rounded-lg border border-slate-200 bg-slate-50 px-3 py-2">
            <p class="text-xs uppercase tracking-wide text-slate-500">{{ __('Status') }}</p>
            <p class="mt-1 text-sm font-semibold {{ ($updateSettings?->is_active ?? true) ? 'text-emerald-700' : 'text-slate-700' }}">
                {{ ($updateSettings?->is_active ?? true) ? __('Active') : __('Disabled') }}
            </p>
        </div>
    </div>

    @if (session('status') === 'updates-settings-updated')
        <p class="rounded-md border border-emerald-200 bg-emerald-50 px-3 py-2 text-sm text-emerald-700">
            {{ __('Update settings have been saved.') }}
        </p>
    @endif

    @if (session('status') === 'updates-check-completed')
        <p class="rounded-md border border-emerald-200 bg-emerald-50 px-3 py-2 text-sm text-emerald-700">
            {{ session('success', __('Update check has been completed.')) }}
        </p>
        @if (session('error'))
            <p class="mt-2 rounded-md border border-rose-200 bg-rose-50 px-3 py-2 text-sm text-rose-700">
                {{ session('error') }}
            </p>
        @endif
    @endif

    @if (session('status') === 'updates-install-completed')
        @if (session('success'))
            <p class="rounded-md border border-emerald-200 bg-emerald-50 px-3 py-2 text-sm text-emerald-700">
                {{ session('success') }}
            </p>
        @endif
        @if (session('error'))
            <p class="rounded-md border border-rose-200 bg-rose-50 px-3 py-2 text-sm text-rose-700">
                {{ session('error') }}
            </p>
        @endif
    @endif

    <form method="POST" action="{{ route('profile.updates.update') }}" class="space-y-4 rounded-lg border border-slate-200 bg-white p-4">
        @csrf
        @method('PATCH')
        @if ($settingsSection)
            <input type="hidden" name="_settings_section" value="{{ $settingsSection }}">
        @endif

        <div class="grid grid-cols-1 gap-4 md:grid-cols-2">
            <div>
                <label for="updates-feed-url" class="block text-sm font-medium text-slate-700">{{ __('Update source URL') }}</label>
                <input id="updates-feed-url" name="feed_url" type="text" value="{{ $feedUrl }}" placeholder="{{ $defaultFeedUrl }}" class="mt-1 w-full rounded-md border-slate-300 text-sm shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                <p class="mt-1 text-xs text-slate-500">{{ __('Default source: :url', ['url' => $defaultFeedUrl]) }}</p>
                <x-input-error class="mt-2" :messages="$errors->get('feed_url')" />
            </div>

            <div>
                <label for="updates-current-version" class="block text-sm font-medium text-slate-700">{{ __('Current version') }}</label>
                <input id="updates-current-version" name="current_version" type="text" value="{{ $currentVersion }}" class="mt-1 w-full rounded-md border-slate-300 text-sm shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                <x-input-error class="mt-2" :messages="$errors->get('current_version')" />
            </div>
        </div>

        <div class="grid grid-cols-1 gap-4 md:grid-cols-3">
            <div>
                <label for="updates-channel" class="block text-sm font-medium text-slate-700">{{ __('Channel') }}</label>
                <select id="updates-channel" name="channel" class="mt-1 w-full rounded-md border-slate-300 text-sm shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                    @foreach ($channelOptions as $optionKey => $optionLabel)
                        <option value="{{ $optionKey }}" @selected($channel === $optionKey)>{{ $optionLabel }}</option>
                    @endforeach
                </select>
                <x-input-error class="mt-2" :messages="$errors->get('channel')" />
            </div>

            <div>
                <label for="updates-check-interval" class="block text-sm font-medium text-slate-700">{{ __('Check interval (minutes)') }}</label>
                <input id="updates-check-interval" name="check_interval_minutes" type="number" min="5" max="10080" value="{{ $checkInterval }}" class="mt-1 w-full rounded-md border-slate-300 text-sm shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                <x-input-error class="mt-2" :messages="$errors->get('check_interval_minutes')" />
            </div>

            <div>
                <label for="updates-timeout" class="block text-sm font-medium text-slate-700">{{ __('Request timeout (seconds)') }}</label>
                <input id="updates-timeout" name="request_timeout_seconds" type="number" min="2" max="60" value="{{ $requestTimeout }}" class="mt-1 w-full rounded-md border-slate-300 text-sm shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                <x-input-error class="mt-2" :messages="$errors->get('request_timeout_seconds')" />
            </div>
        </div>

        <div class="grid grid-cols-1 gap-2 md:grid-cols-3">
            <label class="inline-flex items-center gap-2 text-sm text-slate-700">
                <input type="checkbox" name="is_active" value="1" class="rounded border-slate-300 text-indigo-600 shadow-sm focus:ring-indigo-500" @checked($isActive)>
                {{ __('Enable update module') }}
            </label>
            <label class="inline-flex items-center gap-2 text-sm text-slate-700">
                <input type="checkbox" name="auto_check_enabled" value="1" class="rounded border-slate-300 text-indigo-600 shadow-sm focus:ring-indigo-500" @checked($autoCheckEnabled)>
                {{ __('Enable automatic checks') }}
            </label>
            <label class="inline-flex items-center gap-2 text-sm text-slate-700">
                <input type="checkbox" name="verify_tls" value="1" class="rounded border-slate-300 text-indigo-600 shadow-sm focus:ring-indigo-500" @checked($verifyTls)>
                {{ __('Verify TLS certificate') }}
            </label>
        </div>

        <div>
            <label for="updates-meta" class="block text-sm font-medium text-slate-700">{{ __('Meta JSON') }}</label>
            <textarea id="updates-meta" name="meta" rows="3" class="mt-1 w-full rounded-md border-slate-300 text-xs font-mono shadow-sm focus:border-indigo-500 focus:ring-indigo-500">{{ $metaValue }}</textarea>
            <x-input-error class="mt-2" :messages="$errors->get('meta')" />
        </div>

        <div class="flex justify-end">
            <button type="submit" class="inline-flex items-center rounded-md bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-500">
                {{ __('Save update settings') }}
            </button>
        </div>
    </form>

    <div class="rounded-lg border border-slate-200 bg-white p-4">
        <div class="flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between">
            <div>
                <h3 class="text-sm font-semibold text-slate-900">{{ __('Update installation') }}</h3>
                <p class="mt-1 text-sm text-slate-600">
                    @if ($hasPendingUpdate)
                        {{ __('Available version: :version', ['version' => $pendingVersion]) }}
                        @if ($pendingBuild !== '')
                            <span class="text-xs text-slate-500">({{ $pendingBuild }})</span>
                        @endif
                    @else
                        {{ __('Check for updates and install the newest package with one button.') }}
                    @endif
                </p>
            </div>

            <div class="flex flex-wrap gap-2">
                <form method="POST" action="{{ route('profile.updates.check') }}" class="inline-flex">
                    @csrf
                    @if ($settingsSection)
                        <input type="hidden" name="_settings_section" value="{{ $settingsSection }}">
                    @endif
                    <button type="submit" class="inline-flex items-center rounded-md border border-slate-300 px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50">
                        {{ __('Check updates now') }}
                    </button>
                </form>

                <form method="POST" action="{{ route('profile.updates.install') }}" class="inline-flex" data-updates-install-form>
                    @csrf
                    @if ($settingsSection)
                        <input type="hidden" name="_settings_section" value="{{ $settingsSection }}">
                    @endif
                    <button type="submit" class="inline-flex items-center rounded-md bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-500 disabled:cursor-not-allowed disabled:opacity-70" data-updates-install-button>
                        {{ $hasPendingUpdate ? __('Get update :version', ['version' => $pendingVersion]) : __('Get and install updates') }}
                    </button>
                </form>
            </div>
        </div>
    </div>

    <div
        class="rounded-lg border border-slate-200 bg-white p-4 {{ $activeInstallationPayload ? '' : 'hidden' }}"
        data-updates-install-progress-root
        data-install-url="{{ route('profile.updates.install') }}"
        data-install-status-url-template="{{ $installationStatusUrlTemplate }}"
        data-active-installation='@json($activeInstallationPayload)'
    >
        <div class="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
            <div>
                <h3 class="text-sm font-semibold text-slate-900">{{ __('Installing update') }}</h3>
                <p class="mt-1 text-sm text-slate-600" data-updates-install-progress-summary>{{ __('Waiting for the update installer to start...') }}</p>
            </div>
            <div class="text-sm font-semibold text-slate-700" data-updates-install-progress-version></div>
        </div>

        <div class="mt-4 h-2 w-full overflow-hidden rounded-full bg-slate-100">
            <div class="h-full rounded-full bg-indigo-600 transition-all duration-300" style="width: 0%" data-updates-install-progress-bar></div>
        </div>

        <div class="mt-3 flex flex-wrap items-center gap-3 text-xs text-slate-500">
            <span data-updates-install-progress-status>{{ __('Queued') }}</span>
            <span data-updates-install-progress-percent>0%</span>
            <span data-updates-install-progress-message></span>
        </div>

        <div class="mt-4 rounded-lg border border-slate-200 bg-slate-50 p-3">
            <div class="mb-2 text-xs font-semibold uppercase tracking-wide text-slate-500">{{ __('Progress log') }}</div>
            <div class="space-y-2 text-sm text-slate-700" data-updates-install-progress-events></div>
        </div>
    </div>

    <div class="space-y-3">
        <h3 class="text-sm font-semibold text-slate-900">{{ __('Update check history') }}</h3>

        @if ($updateChecks->isEmpty())
            <p class="rounded-md border border-slate-200 bg-slate-50 px-3 py-2 text-sm text-slate-600">{{ __('No update checks yet.') }}</p>
        @else
            <div class="overflow-hidden rounded-lg border border-slate-200">
                <table class="min-w-full divide-y divide-slate-200">
                    <thead class="bg-slate-50">
                        <tr>
                            <th class="px-3 py-2 text-left text-xs font-semibold uppercase tracking-wide text-slate-600">{{ __('Checked at') }}</th>
                            <th class="px-3 py-2 text-left text-xs font-semibold uppercase tracking-wide text-slate-600">{{ __('Status') }}</th>
                            <th class="px-3 py-2 text-left text-xs font-semibold uppercase tracking-wide text-slate-600">{{ __('Version') }}</th>
                            <th class="px-3 py-2 text-left text-xs font-semibold uppercase tracking-wide text-slate-600">{{ __('Source') }}</th>
                            <th class="px-3 py-2 text-left text-xs font-semibold uppercase tracking-wide text-slate-600">{{ __('Message') }}</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-100 bg-white">
                        @foreach ($updateChecks as $check)
                            <tr>
                                <td class="px-3 py-2 text-sm text-slate-700">{{ $check->checked_at?->format('d.m.Y H:i:s') ?: '—' }}</td>
                                <td class="px-3 py-2 text-sm">
                                    <span class="inline-flex rounded-full px-2 py-0.5 text-xs font-semibold {{ $check->status === 'success' ? 'bg-emerald-100 text-emerald-700' : 'bg-rose-100 text-rose-700' }}">
                                        {{ $check->status === 'success' ? __('Success') : __('Failed') }}
                                    </span>
                                    @if ($check->is_update_available)
                                        <span class="ml-2 inline-flex rounded-full bg-amber-100 px-2 py-0.5 text-xs font-semibold text-amber-700">{{ __('Update available') }}</span>
                                    @endif
                                </td>
                                <td class="px-3 py-2 text-sm text-slate-700">
                                    {{ $check->remote_version ?: '—' }}
                                    @if ($check->remote_build)
                                        <span class="text-xs text-slate-500">({{ $check->remote_build }})</span>
                                    @endif
                                </td>
                                <td class="px-3 py-2 text-xs text-slate-600">{{ $check->endpoint_url ?: '—' }}</td>
                                <td class="px-3 py-2 text-sm text-slate-700">{{ $check->error_message ?: '—' }}</td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        @endif
    </div>

    <div class="space-y-3">
        <h3 class="text-sm font-semibold text-slate-900">{{ __('Update journal') }}</h3>

        @if ($updateInstallations->isEmpty())
            <p class="rounded-md border border-slate-200 bg-slate-50 px-3 py-2 text-sm text-slate-600">{{ __('No update installations yet.') }}</p>
        @else
            <div class="overflow-hidden rounded-lg border border-slate-200">
                <table class="min-w-full divide-y divide-slate-200">
                    <thead class="bg-slate-50">
                        <tr>
                            <th class="px-3 py-2 text-left text-xs font-semibold uppercase tracking-wide text-slate-600">{{ __('Started at') }}</th>
                            <th class="px-3 py-2 text-left text-xs font-semibold uppercase tracking-wide text-slate-600">{{ __('User') }}</th>
                            <th class="px-3 py-2 text-left text-xs font-semibold uppercase tracking-wide text-slate-600">{{ __('Status') }}</th>
                            <th class="px-3 py-2 text-left text-xs font-semibold uppercase tracking-wide text-slate-600">{{ __('Version') }}</th>
                            <th class="px-3 py-2 text-left text-xs font-semibold uppercase tracking-wide text-slate-600">{{ __('Package') }}</th>
                            <th class="px-3 py-2 text-left text-xs font-semibold uppercase tracking-wide text-slate-600">{{ __('Message') }}</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-100 bg-white">
                        @foreach ($updateInstallations as $installation)
                            @php
                                $badgeClass = match ($installation->status) {
                                    'installed' => 'bg-emerald-100 text-emerald-700',
                                    'no_update' => 'bg-slate-100 text-slate-700',
                                    'checking', 'installing' => 'bg-amber-100 text-amber-700',
                                    default => 'bg-rose-100 text-rose-700',
                                };
                            @endphp
                            <tr>
                                <td class="px-3 py-2 text-sm text-slate-700">{{ $installation->started_at?->format('d.m.Y H:i:s') ?: '—' }}</td>
                                <td class="px-3 py-2 text-sm text-slate-700">{{ $installation->actor?->name ?: '—' }}</td>
                                <td class="px-3 py-2 text-sm">
                                    <span class="inline-flex rounded-full px-2 py-0.5 text-xs font-semibold {{ $badgeClass }}">
                                        {{ str_replace('_', ' ', ucfirst((string) $installation->status)) }}
                                    </span>
                                </td>
                                <td class="px-3 py-2 text-sm text-slate-700">
                                    {{ $installation->target_version ?: '—' }}
                                    @if ($installation->target_build)
                                        <span class="text-xs text-slate-500">({{ $installation->target_build }})</span>
                                    @endif
                                </td>
                                <td class="px-3 py-2 text-xs text-slate-600">
                                    {{ $installation->package_name ?: '—' }}
                                    @if ($installation->backup_path)
                                        <div class="mt-1 text-[11px] text-slate-500">{{ __('Backup created') }}</div>
                                    @endif
                                </td>
                                <td class="px-3 py-2 text-sm text-slate-700">
                                    <div>{{ $installation->message ?: '—' }}</div>
                                    @if (is_array($installation->events) && $installation->events !== [])
                                        <div class="mt-1 space-y-1 text-xs text-slate-500">
                                            @foreach (collect($installation->events)->take(-3) as $event)
                                                <div>{{ $event['timestamp'] ?? '' }} · {{ $event['message'] ?? '' }}</div>
                                            @endforeach
                                        </div>
                                    @endif
                                </td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        @endif
    </div>
</section>

@once
    <script>
        document.addEventListener('DOMContentLoaded', () => {
            const progressRoot = document.querySelector('[data-updates-install-progress-root]');
            const installForm = document.querySelector('[data-updates-install-form]');
            const installButton = installForm?.querySelector('[data-updates-install-button]');

            if (!progressRoot || !installForm || !installButton) {
                return;
            }

            const summaryNode = progressRoot.querySelector('[data-updates-install-progress-summary]');
            const versionNode = progressRoot.querySelector('[data-updates-install-progress-version]');
            const statusNode = progressRoot.querySelector('[data-updates-install-progress-status]');
            const percentNode = progressRoot.querySelector('[data-updates-install-progress-percent]');
            const messageNode = progressRoot.querySelector('[data-updates-install-progress-message]');
            const eventsNode = progressRoot.querySelector('[data-updates-install-progress-events]');
            const barNode = progressRoot.querySelector('[data-updates-install-progress-bar]');
            const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') ?? '';
            const installUrl = progressRoot.dataset.installUrl ?? installForm.getAttribute('action') ?? '';
            const statusUrlTemplate = progressRoot.dataset.installStatusUrlTemplate ?? '';

            let pollHandle = null;
            let activeInstallation = null;
            try {
                activeInstallation = JSON.parse(progressRoot.dataset.activeInstallation || 'null');
            } catch {
                activeInstallation = null;
            }

            const terminalStatuses = new Set(['installed', 'no_update', 'failed']);

            const humanizeStatus = (status) => {
                const map = {
                    queued: 'Queued',
                    checking: 'Checking source',
                    downloading: 'Downloading package',
                    extracting: 'Extracting package',
                    backing_up: 'Creating backup',
                    installing: 'Deploying files',
                    finalizing: 'Finalizing',
                    installed: 'Installed',
                    no_update: 'No update',
                    failed: 'Failed',
                };

                return map[String(status || '')] || String(status || '');
            };

            const renderInstallation = (payload) => {
                if (!payload || typeof payload !== 'object') {
                    return;
                }

                activeInstallation = payload;
                progressRoot.classList.remove('hidden');

                const version = [payload.target_version || '', payload.target_build ? `(${payload.target_build})` : '']
                    .filter(Boolean)
                    .join(' ');

                if (summaryNode) {
                    summaryNode.textContent = payload.is_terminal
                        ? (payload.status === 'installed'
                            ? 'Update installed in background. Refresh the page when convenient.'
                            : 'Background update task completed.')
                        : 'The update is running in the background. You can stay on this page.';
                }

                if (versionNode) {
                    versionNode.textContent = version !== '' ? version : '';
                }

                if (statusNode) {
                    statusNode.textContent = humanizeStatus(payload.status);
                }

                if (percentNode) {
                    percentNode.textContent = `${Number(payload.progress_percent || 0)}%`;
                }

                if (messageNode) {
                    messageNode.textContent = String(payload.message || '');
                }

                if (barNode) {
                    barNode.style.width = `${Number(payload.progress_percent || 0)}%`;
                    barNode.classList.toggle('bg-rose-600', payload.status === 'failed');
                    barNode.classList.toggle('bg-emerald-600', payload.status === 'installed');
                    barNode.classList.toggle('bg-indigo-600', !['failed', 'installed'].includes(String(payload.status || '')));
                }

                if (eventsNode) {
                    const events = Array.isArray(payload.events) ? payload.events.slice(-8) : [];
                    eventsNode.innerHTML = events.map((event) => {
                        const timestamp = String(event?.timestamp || '').replace('T', ' ').replace('Z', '');
                        const message = String(event?.message || '');

                        return `<div class="flex items-start justify-between gap-3 rounded-md bg-white px-3 py-2"><span>${message}</span><span class="shrink-0 text-xs text-slate-400">${timestamp}</span></div>`;
                    }).join('');
                }

                const disableButton = !payload.is_terminal;
                installButton.disabled = disableButton;

                if (payload.is_terminal) {
                    stopPolling();
                }
            };

            const stopPolling = () => {
                if (pollHandle) {
                    window.clearInterval(pollHandle);
                    pollHandle = null;
                }
            };

            const pollInstallation = async () => {
                if (!activeInstallation?.id || !statusUrlTemplate) {
                    return;
                }

                const statusUrl = statusUrlTemplate.replace('__INSTALLATION__', String(activeInstallation.id));
                try {
                    const response = await window.fetch(statusUrl, {
                        headers: {
                            Accept: 'application/json',
                            'X-Requested-With': 'XMLHttpRequest',
                        },
                    });

                    if (!response.ok) {
                        if (messageNode) {
                            messageNode.textContent = 'Temporary connection issue while checking background update status. Retrying...';
                        }

                        return;
                    }

                    const json = await response.json().catch(() => null);
                    if (json?.data) {
                        renderInstallation(json.data);
                    }
                } catch (error) {
                    if (messageNode) {
                        messageNode.textContent = 'Connection to the background updater was interrupted. Retrying...';
                    }
                }
            };

            const startPolling = () => {
                stopPolling();
                pollInstallation().catch(() => {});
                pollHandle = window.setInterval(() => {
                    pollInstallation().catch(() => {});
                }, 1200);
            };

            installForm.addEventListener('submit', async (event) => {
                event.preventDefault();
                installButton.disabled = true;

                const response = await window.fetch(installUrl, {
                    method: 'POST',
                    headers: {
                        Accept: 'application/json',
                        'X-Requested-With': 'XMLHttpRequest',
                        'X-CSRF-TOKEN': csrfToken,
                    },
                    body: new FormData(installForm),
                });

                if (!response.ok) {
                    installButton.disabled = false;
                    if (messageNode) {
                        messageNode.textContent = 'Failed to start background update.';
                    }
                    return;
                }

                const json = await response.json().catch(() => null);
                if (json?.data) {
                    renderInstallation(json.data);
                    startPolling();
                    return;
                }

                installButton.disabled = false;
            });

            if (activeInstallation?.id && !terminalStatuses.has(String(activeInstallation.status || ''))) {
                renderInstallation(activeInstallation);
                startPolling();
            }
        });
    </script>
@endonce
