<!DOCTYPE html>
<html lang="<?= current_locale() ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= e($pageTitle ?? 'Admin') ?> – ITSWEBER CMS</title>
    <meta name="csrf-token" content="<?= csrf_token() ?>">
    <link rel="stylesheet" href="/admin/assets/css/tokens.css?v=<?= cms_version() ?>">
    <link rel="stylesheet" href="/admin/assets/css/admin.css?v=<?= cms_version() ?>-<?= @filemtime($_SERVER['DOCUMENT_ROOT'].'/admin/assets/css/admin.css') ?: cms_version() ?>">
    <link rel="stylesheet" href="/admin/assets/css/components.css?v=<?= cms_version() ?>">
    <link rel="stylesheet" href="/admin/assets/css/icon-picker.css?v=<?= cms_version() ?>">
    <script>window.IW_ADMIN = '<?= e(admin_url()) ?>';</script>
</head>
<body class="admin-body">
    <a href="#admin-main-content" class="skip-link"><?= __('admin.topbar.skip_to_content') ?></a>
    <aside class="admin-sidebar" id="adminSidebar" aria-label="Admin sidebar">
        <div class="sidebar-header">
            <a href="<?= admin_url() ?>" class="sidebar-logo" title="<?= __('admin.nav.dashboard') ?>">
                <?php
                // Admin sidebar always shows the ITSWEBER CMS logo (white-filtered).
                // Theme-specific branding is intentionally NOT used here.
                ?>
                <img src="/admin/assets/images/brand/itsweber-cms-logo.png"
                     alt="ITSWEBER CMS"
                     class="sidebar-brand-logo"
                     onerror="this.style.display='none';this.nextElementSibling.style.display='inline'">
                <span style="display:none">ITSWEBER CMS</span>
            </a>
        </div>
        <nav class="sidebar-nav" aria-label="Main navigation">
            <a href="<?= admin_url('dashboard') ?>" class="nav-item <?= ($pageTitle ?? '') === __('admin.nav.dashboard') ? 'active' : '' ?>">
                <span class="nav-icon"><?= icon('layout-dashboard', 18) ?></span> <?= __('admin.nav.dashboard') ?>
            </a>
            <a href="<?= admin_url('pages') ?>" class="nav-item <?= str_contains($pageTitle ?? '', __('admin.nav.pages')) ? 'active' : '' ?>">
                <span class="nav-icon"><?= icon('file-text', 18) ?></span> <?= __('admin.nav.pages') ?>
            </a>
            <div class="nav-group <?= str_contains($pageTitle ?? '', __('admin.nav.blog')) || ($pageTitle ?? '') === __('admin.nav.categories') || ($pageTitle ?? '') === __('admin.nav.tags') ? 'open' : '' ?>">
                <button type="button" class="nav-item nav-group-toggle <?= str_contains($pageTitle ?? '', __('admin.nav.blog')) ? 'active' : '' ?>">
                    <span class="nav-icon"><?= icon('pen-line', 18) ?></span> <?= __('admin.nav.blog') ?>
                    <span class="nav-group-chevron"></span>
                </button>
                <div class="nav-group-children">
                    <a href="<?= admin_url('blog') ?>" class="nav-item nav-sub-item <?= ($pageTitle ?? '') === __('admin.blog.title') ? 'active' : '' ?>">
                        <span class="nav-icon"><?= icon('minus', 14) ?></span> <?= __('admin.blog.title') ?>
                    </a>
                    <a href="<?= admin_url('blog/categories') ?>" class="nav-item nav-sub-item <?= ($pageTitle ?? '') === __('admin.nav.categories') ? 'active' : '' ?>">
                        <span class="nav-icon"><?= icon('minus', 14) ?></span> <?= __('admin.nav.categories') ?>
                    </a>
                    <a href="<?= admin_url('blog/tags') ?>" class="nav-item nav-sub-item <?= ($pageTitle ?? '') === __('admin.nav.tags') ? 'active' : '' ?>">
                        <span class="nav-icon"><?= icon('minus', 14) ?></span> <?= __('admin.nav.tags') ?>
                    </a>
                </div>
            </div>
            <a href="<?= admin_url('gallery') ?>" class="nav-item <?= str_contains($pageTitle ?? '', __('admin.nav.gallery')) ? 'active' : '' ?>">
                <span class="nav-icon"><?= icon('image', 18) ?></span> <?= __('admin.nav.gallery') ?>
            </a>
            <div class="nav-group <?= str_contains($pageTitle ?? '', __('admin.nav.events')) || str_contains($pageTitle ?? '', __('admin.event_categories.title')) ? 'open' : '' ?>">
                <button type="button" class="nav-item nav-group-toggle <?= str_contains($pageTitle ?? '', __('admin.nav.events')) ? 'active' : '' ?>">
                    <span class="nav-icon"><?= icon('calendar', 18) ?></span> <?= __('admin.nav.events') ?>
                    <span class="nav-group-chevron"></span>
                </button>
                <div class="nav-group-children">
                    <a href="<?= admin_url('events') ?>" class="nav-item nav-sub-item <?= ($pageTitle ?? '') === __('admin.events.title') ? 'active' : '' ?>">
                        <span class="nav-icon"><?= icon('minus', 14) ?></span> <?= __('admin.events.title') ?>
                    </a>
                    <a href="<?= admin_url('events/categories') ?>" class="nav-item nav-sub-item <?= str_contains($pageTitle ?? '', __('admin.event_categories.title')) ? 'active' : '' ?>">
                        <span class="nav-icon"><?= icon('minus', 14) ?></span> <?= __('admin.event_categories.title') ?>
                    </a>
                </div>
            </div>
            <div class="nav-group <?= str_contains($pageTitle ?? '', __('admin.nav.downloads')) || str_contains($pageTitle ?? '', __('admin.download_categories.title')) ? 'open' : '' ?>">
                <button type="button" class="nav-item nav-group-toggle <?= str_contains($pageTitle ?? '', __('admin.nav.downloads')) ? 'active' : '' ?>">
                    <span class="nav-icon"><?= icon('download', 18) ?></span> <?= __('admin.nav.downloads') ?>
                    <span class="nav-group-chevron"></span>
                </button>
                <div class="nav-group-children">
                    <a href="<?= admin_url('downloads') ?>" class="nav-item nav-sub-item <?= ($pageTitle ?? '') === __('admin.downloads.title') ? 'active' : '' ?>">
                        <span class="nav-icon"><?= icon('minus', 14) ?></span> <?= __('admin.downloads.title') ?>
                    </a>
                    <a href="<?= admin_url('downloads/categories') ?>" class="nav-item nav-sub-item <?= str_contains($pageTitle ?? '', __('admin.download_categories.title')) ? 'active' : '' ?>">
                        <span class="nav-icon"><?= icon('minus', 14) ?></span> <?= __('admin.download_categories.title') ?>
                    </a>
                </div>
            </div>
            <a href="<?= admin_url('media') ?>" class="nav-item <?= str_contains($pageTitle ?? '', __('admin.nav.media')) ? 'active' : '' ?>">
                <span class="nav-icon"><?= icon('folder-open', 18) ?></span> <?= __('admin.nav.media') ?>
            </a>
            <a href="<?= admin_url('menus') ?>" class="nav-item <?= str_contains($pageTitle ?? '', __('admin.nav.menus')) ? 'active' : '' ?>">
                <span class="nav-icon"><?= icon('menu', 18) ?></span> <?= __('admin.nav.menus') ?>
            </a>
            <a href="<?= admin_url('pagebuilder') ?>" class="nav-item <?= str_contains($pageTitle ?? '', __('admin.nav.pagebuilder')) ? 'active' : '' ?>">
                <span class="nav-icon"><?= icon('layout-template', 18) ?></span> <?= __('admin.nav.pagebuilder') ?>
            </a>
            <?php
            $_iw_cfUnread = 0;
            try {
                if (class_exists('\\App\\Models\\ContactSubmission')) {
                    $_iw_cfUnread = \App\Models\ContactSubmission::countUnread();
                }
            } catch (\Throwable $e) { /* table may not exist yet on old installs */ }
            ?>
            <a href="<?= admin_url('contact-form') ?>" class="nav-item <?= str_contains($pageTitle ?? '', __('admin.nav.contact_form')) ? 'active' : '' ?>">
                <span class="nav-icon"><?= icon('mail', 18) ?></span> <?= __('admin.nav.contact_form') ?>
                <?php if ($_iw_cfUnread > 0): ?>
                <span class="nav-badge nav-badge--info"><?= $_iw_cfUnread ?></span>
                <?php endif; ?>
            </a>

            <div class="nav-divider"></div>

            <div class="nav-section-label"><?= __('admin.nav.system_section') ?? 'System' ?></div>

            <a href="<?= admin_url('themes') ?>" class="nav-item <?= str_contains($pageTitle ?? '', __('admin.nav.themes')) ? 'active' : '' ?>">
                <span class="nav-icon"><?= icon('sun', 18) ?></span> <?= __('admin.nav.themes') ?>
            </a>
            <a href="<?= admin_url('plugins') ?>" class="nav-item <?= str_contains($pageTitle ?? '', __('admin.nav.plugins')) ? 'active' : '' ?>">
                <span class="nav-icon"><?= icon('puzzle', 18) ?></span> <?= __('admin.nav.plugins') ?>
            </a>
            <?php
            $_iw_reqPath = parse_url($_SERVER['REQUEST_URI'] ?? '', PHP_URL_PATH) ?: '';
            $_iw_mpClient = str_contains($_iw_reqPath, '/marketplace') && !str_contains($_iw_reqPath, '/marketplace-server');
            $_iw_mpServer = str_contains($_iw_reqPath, '/marketplace-server');
            ?>
            <a href="<?= admin_url('marketplace') ?>" class="nav-item <?= $_iw_mpClient ? 'active' : '' ?>">
                <span class="nav-icon"><?= icon('store', 18) ?></span> <?= __('admin.nav.marketplace') ?>
            </a>
            <?php \App\Core\Hooks::run('admin.sidebar.after_marketplace', $_iw_mpServer); ?>
            <a href="<?= admin_url('users') ?>" class="nav-item <?= str_contains($pageTitle ?? '', __('admin.nav.users')) ? 'active' : '' ?>">
                <span class="nav-icon"><?= icon('users', 18) ?></span> <?= __('admin.nav.users') ?>
            </a>
            <?php if (\App\Models\Setting::get('totp_2fa_available', '0') === '1'): ?>
            <a href="<?= admin_url('2fa') ?>" class="nav-item <?= str_contains($pageTitle ?? '', __('admin.totp.title')) ? 'active' : '' ?>">
                <span class="nav-icon"><?= icon('shield', 18) ?></span> <?= __('admin.nav.two_factor') ?>
            </a>
            <?php endif; ?>
            <div class="nav-group <?= str_contains($pageTitle ?? '', __('admin.nav.settings')) || str_contains($pageTitle ?? '', __('admin.site_notice.title')) || str_contains($pageTitle ?? '', __('admin.mail.title')) ? 'open' : '' ?>">
                <button type="button" class="nav-item nav-group-toggle <?= str_contains($pageTitle ?? '', __('admin.nav.settings')) ? 'active' : '' ?>">
                    <span class="nav-icon"><?= icon('settings', 18) ?></span> <?= __('admin.nav.settings') ?>
                    <span class="nav-group-chevron"></span>
                </button>
                <div class="nav-group-children">
                    <a href="<?= admin_url('settings') ?>" class="nav-item nav-sub-item <?= ($pageTitle ?? '') === __('admin.nav.settings') || ($pageTitle ?? '') === 'Settings' ? 'active' : '' ?>">
                        <span class="nav-icon"><?= icon('minus', 14) ?></span> <?= __('admin.settings.general') ?>
                    </a>
                    <a href="<?= admin_url('settings/site-notice') ?>" class="nav-item nav-sub-item <?= str_contains($pageTitle ?? '', __('admin.site_notice.title')) ? 'active' : '' ?>">
                        <span class="nav-icon"><?= icon('minus', 14) ?></span> <?= __('admin.site_notice.nav_label') ?>
                    </a>
                    <a href="<?= admin_url('settings/mail') ?>" class="nav-item nav-sub-item <?= str_contains($pageTitle ?? '', __('admin.mail.title')) ? 'active' : '' ?>">
                        <span class="nav-icon"><?= icon('minus', 14) ?></span> <?= __('admin.nav.mail') ?>
                    </a>
                </div>
            </div>
            <a href="<?= admin_url('consent') ?>" class="nav-item <?= str_contains($pageTitle ?? '', __('admin.nav.consent')) ? 'active' : '' ?>">
                <span class="nav-icon"><?= icon('shield-check', 18) ?></span> <?= __('admin.nav.consent') ?>
            </a>
            <?php
            $_iw_bp = defined('BASE_PATH') ? BASE_PATH : dirname(__DIR__, 3);
            $_iw_maintUser   = is_file($_iw_bp . '/storage/.maintenance_mode');
            $_iw_maintSystem = is_file($_iw_bp . '/storage/.maintenance');
            $_iw_maintActive = $_iw_maintUser || $_iw_maintSystem;
            ?>
            <a href="<?= admin_url('maintenance') ?>" class="nav-item <?= str_contains($pageTitle ?? '', __('admin.nav.maintenance')) ? 'active' : '' ?> <?= $_iw_maintActive ? 'nav-item--warn' : '' ?>">
                <span class="nav-icon"><?= icon('wrench', 18) ?></span> <?= __('admin.nav.maintenance') ?><?= $_iw_maintActive ? ' <span class="nav-badge nav-badge--warn">' . __('admin.maintenance.nav_active') . '</span>' : '' ?>
            </a>
            <a href="<?= admin_url('system') ?>" class="nav-item <?= str_contains($pageTitle ?? '', __('admin.nav.system')) ? 'active' : '' ?>">
                <span class="nav-icon"><?= icon('monitor', 18) ?></span> <?= __('admin.nav.system') ?>
            </a>
            <a href="<?= admin_url('system/error-log') ?>" class="nav-item <?= str_contains($pageTitle ?? '', __('admin.system.error_log_title')) ? 'active' : '' ?>">
                <span class="nav-icon"><?= icon('alert-triangle', 18) ?></span> <?= __('admin.system.error_log_title') ?>
            </a>
            <a href="<?= admin_url('backup') ?>" class="nav-item <?= str_contains($pageTitle ?? '', __('admin.nav.backup')) ? 'active' : '' ?>">
                <span class="nav-icon"><?= icon('hard-drive', 18) ?></span> <?= __('admin.nav.backup') ?>
            </a>
            <?php if (setting('activity_log_enabled', '1') === '1'): ?>
            <a href="<?= admin_url('activity-log') ?>" class="nav-item <?= str_contains($pageTitle ?? '', __('admin.activity_log.title')) ? 'active' : '' ?>">
                <span class="nav-icon"><?= icon('activity', 18) ?></span> <?= __('admin.activity_log.title') ?>
            </a>
            <?php endif; ?>
            <?php if (setting('redirect_manager_enabled', '1') === '1'): ?>
            <a href="<?= admin_url('redirects') ?>" class="nav-item <?= str_contains($pageTitle ?? '', __('admin.redirects.title')) ? 'active' : '' ?>">
                <span class="nav-icon"><?= icon('arrow-right-left', 18) ?></span> <?= __('admin.redirects.title') ?>
            </a>
            <?php endif; ?>
        </nav>
        <div class="sidebar-footer">
            <span class="sidebar-version">v<?= e(cms_version()) ?></span>
        </div>
    </aside>

    <div class="sidebar-backdrop" id="sidebarBackdrop" aria-hidden="true"></div>

    <main class="admin-main">
        <header class="admin-topbar">
            <button class="sidebar-toggle" id="sidebarToggle" aria-label="<?= __('admin.topbar.open_menu') ?>" aria-expanded="false" aria-controls="adminSidebar">☰</button>
            <div class="topbar-title"><?= e($pageTitle ?? 'Admin') ?></div>
            <div class="topbar-actions">
                <a href="/" class="topbar-link" target="_blank"><?= __('admin.topbar.view_site') ?></a>
                <form method="POST" action="<?= admin_url('settings/language') ?>" class="topbar-language-form">
                    <?= csrf_field() ?>
                    <select name="language" onchange="this.form.submit()" class="topbar-lang-select">
                        <option value="de" <?= current_locale() === 'de' ? 'selected' : '' ?>>Deutsch</option>
                        <option value="en" <?= current_locale() === 'en' ? 'selected' : '' ?>>English</option>
                    </select>
                </form>
                <span class="topbar-user"><?= e($auth->userName() ?? 'Admin') ?></span>
                <a href="<?= admin_url('logout') ?>" class="topbar-link"><?= __('admin.topbar.logout') ?></a>
            </div>
        </header>

        <div class="admin-content" id="admin-main-content">
            <?php $flashSuccess = flash('success'); ?>
            <?php if ($flashSuccess): ?>
            <div class="alert alert-success" role="status" aria-live="polite"><?= e($flashSuccess) ?></div>
            <?php endif; ?>

            <?php $flashWarning = flash('warning'); ?>
            <?php if ($flashWarning): ?>
            <div class="alert alert-warning" role="status" aria-live="polite"><?= e($flashWarning) ?></div>
            <?php endif; ?>

            <?php $flashError = flash('error'); ?>
            <?php if ($flashError): ?>
            <div class="alert alert-error" role="alert" aria-live="assertive"><?= e($flashError) ?></div>
            <?php endif; ?>

            <?php
            // Persistent theme-fallback warning (ADR-088): shown on every admin page
            // as long as the configured theme is missing from the filesystem.
            $_iw_themeFallback = isset($_SESSION['_iw_theme_fallback']) ? (string) $_SESSION['_iw_theme_fallback'] : '';
            ?>
            <?php if ($_iw_themeFallback !== ''): ?>
            <div class="alert alert-warning" role="alert" aria-live="polite" style="border-left:4px solid #d97706;">
                ⚠ <strong><?= __('admin.theme_fallback.title') ?></strong>
                <?= __('admin.theme_fallback.text', ['theme' => e($_iw_themeFallback)]) ?>
                <a href="<?= admin_url('themes') ?>" style="margin-left:0.5rem;font-weight:600;"><?= __('admin.theme_fallback.link') ?></a>
            </div>
            <?php endif; ?>

            <?php
            // Plugin load error warning (Phase 2.4.1 hardening):
            // Shows which plugins failed to load and were auto-deactivated.
            if (class_exists('\\App\\Services\\PluginLoader')) {
                $_iw_pluginErrors = \App\Services\PluginLoader::getLoadErrors(defined('BASE_PATH') ? BASE_PATH : dirname(__DIR__, 3));
                if (!empty($_iw_pluginErrors)):
            ?>
            <div class="alert alert-error" role="alert" aria-live="assertive" style="border-left:4px solid #dc2626;">
                <strong><?= __('admin.plugins.load_error_title') ?></strong> <?= __('admin.plugins.load_error_text') ?>
                <ul style="margin:0.5rem 0 0;padding-left:1.25rem;">
                <?php foreach ($_iw_pluginErrors as $_iw_pSlug => $_iw_pErr): ?>
                    <li><strong><?= e($_iw_pSlug) ?></strong>: <?= e($_iw_pErr) ?></li>
                <?php endforeach; ?>
                </ul>
                <div style="margin-top:0.5rem;">
                    <a href="<?= admin_url('plugins') ?>" style="font-weight:600;"><?= __('admin.nav.plugins') ?> &rarr;</a>
                </div>
            </div>
            <?php
                endif;
                // Safe mode indicator
                if (\App\Services\PluginLoader::isSafeMode(defined('BASE_PATH') ? BASE_PATH : dirname(__DIR__, 3))):
            ?>
            <div class="alert alert-warning" role="alert" aria-live="polite" style="border-left:4px solid #d97706;">
                <strong><?= __('admin.plugins.safe_mode_title') ?></strong> <?= __('admin.plugins.safe_mode_text') ?>
            </div>
            <?php
                endif;
            }
            ?>

            <?= $content ?? '' ?>
        </div>
    </main>

    <script>
    window.iwT = <?= json_encode([
        'search_images'   => __('admin.js.search_images'),
        'folder_label'    => __('admin.js.folder_label'),
        'all_media'       => __('admin.js.all_media'),
        'unassigned'      => __('admin.js.unassigned'),
        'loading'         => __('admin.js.loading'),
        'no_images'       => __('admin.js.no_images'),
        'load_failed'     => __('admin.js.load_failed'),
        'select_image'    => __('admin.js.select_image'),
        'upload_btn'      => __('admin.js.upload_btn'),
        'search'          => __('admin.js.search'),
        'file_too_large'  => __('admin.js.file_too_large'),
        'csrf_missing'    => __('admin.js.csrf_missing'),
        'uploading'       => __('admin.js.uploading'),
        'upload_failed'   => __('admin.js.upload_failed'),
        'upload_http_err' => __('admin.js.upload_http_err'),
        'network_error'   => __('admin.js.network_error'),
        'upload_timeout'  => __('admin.js.upload_timeout'),
        'media_library'   => __('admin.js.media_library'),
        'close'           => __('admin.js.close'),
        'no_videos'       => __('admin.js.no_videos'),
        'select_video'    => __('admin.js.select_video'),
        'loading_short'   => __('admin.js.loading_short'),
        'uploading_short' => __('admin.js.uploading_short'),
        'upload_failed_short' => __('admin.js.upload_failed_short'),
        'file_too_large_short' => __('admin.js.file_too_large_short'),
        'load_failed_short'    => __('admin.js.load_failed_short'),
    ], JSON_UNESCAPED_UNICODE | JSON_HEX_TAG) ?>;
    </script>
    <script src="/admin/assets/js/vendor/Sortable.min.js"></script>
    <script src="/admin/assets/js/admin.js?v=<?= cms_version() ?>-<?= @filemtime($_SERVER['DOCUMENT_ROOT'].'/admin/assets/js/admin.js') ?: cms_version() ?>"></script>
    <script>window.__lucideIcons = <?= json_encode(get_lucide_icon_catalogue(), JSON_UNESCAPED_UNICODE | JSON_HEX_TAG) ?>;</script>
    <script src="/admin/assets/js/icon-picker.js?v=<?= cms_version() ?>"></script>
    <script src="/admin/assets/js/bulk-actions.js?v=<?= cms_version() ?>" defer></script>
    <script>
    /* ── Content Revisions Modal (v3.3.0) ────────────────────────────────── */
    var _revType = '', _revId = 0;
    function loadRevisions(type, id) {
        _revType = type; _revId = id;
        var overlay = document.getElementById('revisionsOverlay');
        if (!overlay) {
            overlay = document.createElement('div');
            overlay.id = 'revisionsOverlay';
            overlay.className = 'modal-overlay';
            overlay.style.cssText = 'display:flex;position:fixed;inset:0;z-index:9999;background:rgba(0,0,0,0.5);align-items:center;justify-content:center';
            overlay.innerHTML = '<div style="background:var(--surface-primary,#fff);border-radius:var(--radius-lg,12px);width:90%;max-width:640px;box-shadow:var(--shadow-lg,0 8px 32px rgba(0,0,0,0.2));overflow:hidden">'
                + '<div style="display:flex;justify-content:space-between;align-items:center;padding:1rem 1.25rem;border-bottom:1px solid var(--border-primary,#e5e7eb)">'
                + '<h3 style="margin:0;font-size:1.125rem"><?= icon('history', 18) ?> <?= __('admin.revisions.title') ?></h3>'
                + '<button type="button" onclick="closeRevisions()" style="background:none;border:none;font-size:1.5rem;cursor:pointer;color:var(--text-secondary,#6b7280);padding:0;line-height:1" aria-label="Close">&times;</button>'
                + '</div>'
                + '<div id="revisionsBody" style="padding:1.25rem;max-height:500px;overflow-y:auto">'
                + '<p class="text-muted" style="text-align:center;padding:2rem"><?= __('admin.common.loading') ?></p>'
                + '</div></div>';
            overlay.addEventListener('click', function(e) { if (e.target === overlay) closeRevisions(); });
            document.body.appendChild(overlay);
        }
        overlay.style.display = 'flex';
        document.getElementById('revisionsBody').innerHTML = '<p class="text-muted" style="text-align:center;padding:2rem"><?= __('admin.common.loading') ?></p>';
        fetch(window.IW_ADMIN + '/revisions/' + type + '/' + id)
            .then(function(r) { return r.json(); })
            .then(function(data) {
                var body = document.getElementById('revisionsBody');
                if (!data.ok || !data.revisions.length) {
                    body.innerHTML = '<p class="text-muted" style="text-align:center;padding:2rem"><?= __('admin.revisions.no_revisions') ?></p>';
                    return;
                }
                var html = '';
                data.revisions.forEach(function(rev) {
                    html += '<div style="display:flex;justify-content:space-between;align-items:center;padding:0.75rem 0;border-bottom:1px solid var(--border-primary,#e5e7eb)">'
                        + '<div>'
                        + '<strong>' + escHtml(rev.title || '–') + '</strong>'
                        + '<br><small style="color:var(--text-tertiary,#9ca3af)">' + escHtml(rev.created_at) + ' · ' + escHtml(rev.changed_by) + '</small>'
                        + '</div>'
                        + '<div style="display:flex;gap:0.5rem;flex-shrink:0">'
                        + '<button class="btn btn-sm btn-secondary" onclick="viewRevision(' + rev.id + ')"><?= icon('eye', 14) ?> <?= __('admin.revisions.view_diff') ?></button>'
                        + '<button class="btn btn-sm btn-primary" onclick="restoreRevision(' + rev.id + ')"><?= icon('rotate-ccw', 14) ?> <?= __('admin.revisions.restore') ?></button>'
                        + '</div></div>';
                });
                body.innerHTML = html;
            })
            .catch(function() {
                document.getElementById('revisionsBody').innerHTML = '<p class="text-muted" style="text-align:center;padding:2rem">Fehler beim Laden.</p>';
            });
    }
    function viewRevision(revId) {
        var body = document.getElementById('revisionsBody');
        body.innerHTML = '<p class="text-muted" style="text-align:center;padding:2rem"><?= __('admin.common.loading') ?></p>';
        fetch(window.IW_ADMIN + '/revisions/view/' + revId)
            .then(function(r) { return r.json(); })
            .then(function(data) {
                if (!data.ok) { body.innerHTML = '<p>Revision nicht gefunden.</p>'; return; }
                var html = '<p style="margin-bottom:1rem"><a href="#" onclick="loadRevisions(_revType,_revId);return false" style="color:var(--interactive-primary,#3b82f6);text-decoration:none"><?= icon('arrow-left', 14) ?> <?= __('admin.revisions.title') ?></a></p>';
                if (data.field_count === 0) {
                    html += '<p class="text-muted"><?= __('admin.revisions.no_revisions') ?></p>';
                } else {
                    html += '<p style="margin-bottom:1rem;font-weight:600">' + data.field_count + ' Feld(er) geändert</p>';
                    for (var field in data.diff) {
                        var oldVal = String(data.diff[field].old || '');
                        var newVal = String(data.diff[field]['new'] || '');
                        html += '<div style="margin-bottom:0.75rem;padding:0.75rem;border-radius:var(--radius-sm,6px);background:var(--surface-secondary,#f8f9fa);border:1px solid var(--border-primary,#e5e7eb)">'
                            + '<div style="font-weight:600;margin-bottom:0.5rem;text-transform:capitalize">' + escHtml(field.replace(/_/g, ' ')) + '</div>'
                            + '<div style="font-size:0.875rem;padding:0.375rem 0.5rem;background:var(--feedback-danger-bg,#fef2f2);border-radius:4px;margin-bottom:0.25rem;color:var(--feedback-danger,#dc2626);word-break:break-word">'
                            + '<strong>−</strong> ' + escHtml(oldVal.substring(0, 300)) + (oldVal.length > 300 ? '…' : '')
                            + '</div>'
                            + '<div style="font-size:0.875rem;padding:0.375rem 0.5rem;background:var(--feedback-success-bg,#f0fdf4);border-radius:4px;color:var(--feedback-success,#16a34a);word-break:break-word">'
                            + '<strong>+</strong> ' + escHtml(newVal.substring(0, 300)) + (newVal.length > 300 ? '…' : '')
                            + '</div></div>';
                    }
                }
                body.innerHTML = html;
            })
            .catch(function() {
                body.innerHTML = '<p>Fehler beim Laden der Unterschiede.</p>';
            });
    }
    function restoreRevision(revId) {
        if (!confirm('<?= __('admin.revisions.restore_confirm') ?>')) return;
        fetch(window.IW_ADMIN + '/revisions/restore/' + revId, {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded', 'X-Requested-With': 'XMLHttpRequest'},
            body: '_csrf_token=' + encodeURIComponent(document.querySelector('input[name="_csrf_token"]')?.value || '')
        }).then(function(r) { return r.json(); }).then(function(data) {
            if (data.ok) location.reload();
        });
    }
    function closeRevisions() {
        var o = document.getElementById('revisionsOverlay');
        if (o) o.style.display = 'none';
    }
    function escHtml(s) { var d = document.createElement('div'); d.textContent = s; return d.innerHTML; }
    </script>
</body>
</html>
