<?php $pageTitle = t('update_title'); ?>
<div class="page-header">
    <div class="page-header-left">
        <a href="/admin/settings" class="btn btn-ghost btn-sm">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16"><path d="M19 12H5M12 19l-7-7 7-7"/></svg>
            <?= t('system_settings') ?>
        </a>
        <h1 class="page-title"><?= t('update_title') ?> → <?= Helper::e($version) ?></h1>
    </div>
</div>

<div class="card" style="max-width:680px">
    <div class="card-header"><h2 class="card-title"><?= t('update_progress_title') ?></h2></div>
    <div class="card-body">
        <div id="update-log" style="
            background:#0f172a;color:#e2e8f0;font-family:monospace;font-size:.85rem;
            border-radius:6px;padding:1rem;min-height:160px;line-height:1.7;
            overflow-y:auto;max-height:360px;display:flex;flex-direction:column;gap:2px;
        "></div>
        <div id="update-status" style="margin-top:1rem;font-size:.9rem;color:var(--text-muted)"></div>
    </div>
</div>

<script nonce="<?= csp_nonce() ?>">
(async () => {
    const log    = document.getElementById('update-log');
    const status = document.getElementById('update-status');

    const ts = () => new Date().toLocaleTimeString('de-DE', {hour: '2-digit', minute: '2-digit', second: '2-digit'});

    const append = (text, color) => {
        const row  = document.createElement('div');
        row.style.cssText = 'display:flex;gap:.75rem;align-items:baseline';

        const time = document.createElement('span');
        time.style.cssText = 'color:#475569;flex-shrink:0;user-select:none';
        time.textContent = ts();

        const msg = document.createElement('span');
        if (color) msg.style.color = color;
        msg.textContent = text;

        row.appendChild(time);
        row.appendChild(msg);
        log.appendChild(row);
        log.scrollTop = log.scrollHeight;
    };

    const colorOf = (line) =>
        line.startsWith('✗') ? '#f87171' :
        line.startsWith('⚠') ? '#fbbf24' :
        line.startsWith('🎉') ? '#4ade80' :
        line.startsWith('✓') ? '#86efac' :
        null;

    append('<?= t('update_progress_starting') ?>', '#94a3b8');

    try {
        const res = await fetch('/admin/update/perform', {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded', 'X-Requested-With': 'XMLHttpRequest'},
            body: 'csrf_token=<?= Auth::generateCsrfToken() ?>'
        });

        const data = await res.json();
        log.innerHTML = '';

        const lines = data.log || [];
        lines.forEach((line, i) => {
            setTimeout(() => {
                append(line, colorOf(line));
                if (i === lines.length - 1) {
                    if (data.ok) {
                        let secs = 10;
                        const tick = () => {
                            status.textContent = '<?= t('update_redirect_in') ?> ' + secs + ' …';
                            if (secs-- > 0) setTimeout(tick, 1000);
                            else location.replace('<?= APP_BASE ?>/admin/settings?_=' + Date.now());
                        };
                        tick();
                    } else {
                        append((data.error || '<?= t('update_unknown_error') ?>'), '#f87171');
                        status.innerHTML = '<a href="/admin/settings" class="btn btn-ghost btn-sm"><?= t('back') ?></a>';
                    }
                }
            }, i * 120);
        });

    } catch (e) {
        append(e.message, '#f87171');
        status.innerHTML = '<a href="/admin/settings" class="btn btn-ghost btn-sm"><?= t('back') ?></a>';
    }
})();
</script>
