<?php ob_start(); ?>

<?php admin_content_header(__('admin.settings.title'), 'settings'); ?>

<?php if ($flash = flash('success')): ?>
<div class="alert alert-success"><?= e($flash) ?></div>
<?php endif; ?>

<form method="POST" action="<?= admin_url('settings/save') ?>" class="admin-form" enctype="multipart/form-data">
    <?= $csrf->field() ?>

    <div class="form-grid">
        <div class="form-main">

            <!-- General -->
            <div class="form-card">
                <h4><?= __('admin.settings.general') ?></h4>
                <div class="form-group">
                    <label for="site_name"><?= __('admin.settings.site_name') ?></label>
                    <input type="text" id="site_name" name="site_name"
                           value="<?= e($settings['site_name'] ?? '') ?>" required>
                </div>
                <div class="form-group">
                    <label for="site_tagline"><?= __('admin.settings.tagline') ?></label>
                    <input type="text" id="site_tagline" name="site_tagline"
                           value="<?= e($settings['site_tagline'] ?? '') ?>">
                </div>
                <div class="form-group">
                    <label for="contact_email"><?= __('admin.settings.contact_email') ?></label>
                    <input type="email" id="contact_email" name="contact_email"
                           value="<?= e($settings['contact_email'] ?? '') ?>">
                </div>
                <div class="form-group">
                    <label for="contact_phone"><?= __('admin.settings.contact_phone') ?></label>
                    <input type="text" id="contact_phone" name="contact_phone"
                           value="<?= e($settings['contact_phone'] ?? '') ?>">
                </div>
                <div class="form-group">
                    <label for="footer_text"><?= __('admin.settings.footer_text') ?></label>
                    <textarea id="footer_text" name="footer_text" rows="3"><?= e($settings['footer_text'] ?? '') ?></textarea>
                    <small class="form-hint"><?= __('admin.settings.footer_text_help') ?></small>
                </div>
                <div class="form-group">
                    <label for="copyright"><?= __('admin.settings.copyright') ?></label>
                    <textarea id="copyright" name="copyright" rows="2"><?= e($settings['copyright'] ?? '') ?></textarea>
                    <small class="form-hint"><?= __('admin.settings.copyright_help') ?></small>
                </div>
                <div class="form-group">
                    <small class="form-hint" style="display:block;margin-top:0.5rem;">
                        <?= __('admin.settings.footer_menu_help') ?>
                        <a href="<?= admin_url('menus') ?>?location=footer" style="color:var(--admin-primary,#2563eb);text-decoration:none;">
                            <?= __('admin.settings.footer_menu_link') ?>
                        </a>
                    </small>
                </div>
                <div class="form-group">
                    <label for="system_language"><?= __('admin.settings.language_label') ?></label>
                    <select id="system_language" name="system_language">
                        <option value="de" <?= ($settings['system_language'] ?? 'de') === 'de' ? 'selected' : '' ?>>Deutsch (de)</option>
                        <option value="en" <?= ($settings['system_language'] ?? 'de') === 'en' ? 'selected' : '' ?>>English (en)</option>
                    </select>
                    <small class="form-hint"><?= __('admin.settings.language_help') ?></small>
                </div>
            </div>

            <!-- Display Options -->
            <div class="form-card">
                <h4><?= __('admin.settings.display_options') ?></h4>
                <div class="form-group">
                    <label class="toggle-label">
                        <input type="hidden" name="breadcrumbs_enabled" value="0">
                        <input type="checkbox" name="breadcrumbs_enabled" id="breadcrumbs_enabled" value="1"
                               <?= ($settings['breadcrumbs_enabled'] ?? '1') === '1' ? 'checked' : '' ?>>
                        <?= __('admin.settings.breadcrumbs_enabled') ?>
                    </label>
                    <small class="form-hint"><?= __('admin.settings.breadcrumbs_enabled_help') ?></small>
                </div>
                <div class="form-group">
                    <label class="toggle-label">
                        <input type="hidden" name="dark_mode_enabled" value="0">
                        <input type="checkbox" name="dark_mode_enabled" id="dark_mode_enabled" value="1"
                               <?= ($settings['dark_mode_enabled'] ?? '0') === '1' ? 'checked' : '' ?>>
                        <?= __('admin.settings.dark_mode_enabled') ?>
                    </label>
                    <small class="form-hint"><?= __('admin.settings.dark_mode_enabled_help') ?></small>
                </div>
                <div class="form-group">
                    <label class="toggle-label">
                        <input type="hidden" name="search_enabled" value="0">
                        <input type="checkbox" name="search_enabled" id="search_enabled" value="1"
                               <?= ($settings['search_enabled'] ?? '1') === '1' ? 'checked' : '' ?>>
                        <?= __('admin.settings.search_enabled') ?>
                    </label>
                    <small class="form-hint"><?= __('admin.settings.search_enabled_help') ?></small>
                </div>
                <div class="form-group">
                    <label class="toggle-label">
                        <input type="hidden" name="search_in_header" value="0">
                        <input type="checkbox" name="search_in_header" id="search_in_header" value="1"
                               <?= ($settings['search_in_header'] ?? '1') === '1' ? 'checked' : '' ?>>
                        <?= __('admin.settings.search_in_header') ?>
                    </label>
                    <small class="form-hint"><?= __('admin.settings.search_in_header_help') ?></small>
                </div>
                <div class="form-group">
                    <label class="toggle-label">
                        <input type="hidden" name="custom_css_js_enabled" value="0">
                        <input type="checkbox" name="custom_css_js_enabled" id="custom_css_js_enabled" value="1"
                               <?= ($settings['custom_css_js_enabled'] ?? '1') === '1' ? 'checked' : '' ?>>
                        <?= __('admin.settings.custom_css_js_enabled') ?>
                    </label>
                    <small class="form-hint"><?= __('admin.settings.custom_css_js_enabled_help') ?></small>
                </div>
                <div class="form-group">
                    <label class="toggle-label">
                        <input type="hidden" name="header_show_site_name" value="0">
                        <input type="checkbox" name="header_show_site_name" id="header_show_site_name" value="1"
                               <?= ($settings['header_show_site_name'] ?? '0') === '1' ? 'checked' : '' ?>>
                        <?= __('admin.settings.header_show_site_name') ?>
                    </label>
                    <small class="form-hint"><?= __('admin.settings.header_show_site_name_help') ?></small>
                </div>
                <div class="form-group">
                    <label class="toggle-label">
                        <input type="hidden" name="footer_show_address" value="0">
                        <input type="checkbox" name="footer_show_address" id="footer_show_address" value="1"
                               <?= ($settings['footer_show_address'] ?? '0') === '1' ? 'checked' : '' ?>>
                        <?= __('admin.settings.footer_show_address') ?>
                    </label>
                    <small class="form-hint"><?= __('admin.settings.footer_show_address_help') ?></small>
                </div>
                <div class="form-group">
                    <label class="toggle-label">
                        <input type="hidden" name="sticky_header_enabled" value="0">
                        <input type="checkbox" name="sticky_header_enabled" id="sticky_header_enabled" value="1"
                               <?= ($settings['sticky_header_enabled'] ?? '0') === '1' ? 'checked' : '' ?>>
                        <?= __('admin.settings.sticky_header_enabled') ?>
                    </label>
                    <small class="form-hint"><?= __('admin.settings.sticky_header_enabled_help') ?></small>
                </div>
                <div class="form-group">
                    <label class="toggle-label">
                        <input type="hidden" name="scroll_animations_enabled" value="0">
                        <input type="checkbox" name="scroll_animations_enabled" id="scroll_animations_enabled" value="1"
                               <?= ($settings['scroll_animations_enabled'] ?? '0') === '1' ? 'checked' : '' ?>>
                        <?= __('admin.settings.scroll_animations_enabled') ?>
                    </label>
                    <small class="form-hint"><?= __('admin.settings.scroll_animations_enabled_help') ?></small>
                </div>
                <div class="form-group">
                    <label class="toggle-label">
                        <input type="hidden" name="content_revisions_enabled" value="0">
                        <input type="checkbox" name="content_revisions_enabled" id="content_revisions_enabled" value="1"
                               <?= ($settings['content_revisions_enabled'] ?? '1') === '1' ? 'checked' : '' ?>>
                        <?= __('admin.settings.content_revisions_enabled') ?>
                    </label>
                    <small class="form-hint"><?= __('admin.settings.content_revisions_enabled_help') ?></small>
                </div>
                <div class="form-group">
                    <label class="toggle-label">
                        <input type="hidden" name="activity_log_enabled" value="0">
                        <input type="checkbox" name="activity_log_enabled" id="activity_log_enabled" value="1"
                               <?= ($settings['activity_log_enabled'] ?? '1') === '1' ? 'checked' : '' ?>>
                        <?= __('admin.settings.activity_log_enabled') ?>
                    </label>
                    <small class="form-hint"><?= __('admin.settings.activity_log_enabled_help') ?></small>
                </div>
                <div class="form-group">
                    <label class="toggle-label">
                        <input type="hidden" name="security_headers_enabled" value="0">
                        <input type="checkbox" name="security_headers_enabled" id="security_headers_enabled" value="1"
                               <?= ($settings['security_headers_enabled'] ?? '1') === '1' ? 'checked' : '' ?>>
                        <?= __('admin.settings.security_headers_enabled') ?>
                    </label>
                    <small class="form-hint"><?= __('admin.settings.security_headers_enabled_help') ?></small>
                </div>
                <div class="form-group">
                    <label class="toggle-label">
                        <input type="hidden" name="redirect_manager_enabled" value="0">
                        <input type="checkbox" name="redirect_manager_enabled" id="redirect_manager_enabled" value="1"
                               <?= ($settings['redirect_manager_enabled'] ?? '1') === '1' ? 'checked' : '' ?>>
                        <?= __('admin.settings.redirect_manager_enabled') ?>
                    </label>
                    <small class="form-hint"><?= __('admin.settings.redirect_manager_enabled_help') ?></small>
                </div>
                <div class="form-group">
                    <label class="toggle-label">
                        <input type="hidden" name="content_scheduling_enabled" value="0">
                        <input type="checkbox" name="content_scheduling_enabled" id="content_scheduling_enabled" value="1"
                               <?= ($settings['content_scheduling_enabled'] ?? '1') === '1' ? 'checked' : '' ?>>
                        <?= __('admin.settings.content_scheduling_enabled') ?>
                    </label>
                    <small class="form-hint"><?= __('admin.settings.content_scheduling_enabled_help') ?></small>
                </div>
                <div class="form-group">
                    <label class="toggle-label">
                        <input type="hidden" name="http_cache_enabled" value="0">
                        <input type="checkbox" name="http_cache_enabled" id="http_cache_enabled" value="1"
                               <?= ($settings['http_cache_enabled'] ?? '0') === '1' ? 'checked' : '' ?>>
                        <?= __('admin.settings.http_cache_enabled') ?>
                    </label>
                    <small class="form-hint"><?= __('admin.settings.http_cache_enabled_help') ?></small>
                </div>
                <div class="form-group" id="httpCacheTtlGroup" style="<?= ($settings['http_cache_enabled'] ?? '0') === '1' ? '' : 'display:none;' ?>">
                    <label for="http_cache_ttl"><?= __('admin.settings.http_cache_ttl') ?></label>
                    <input type="number" id="http_cache_ttl" name="http_cache_ttl"
                           value="<?= (int) ($settings['http_cache_ttl'] ?? 3600) ?>"
                           min="60" max="86400" step="60">
                    <small class="form-hint"><?= __('admin.settings.http_cache_ttl_help') ?></small>
                </div>
            </div>

            <!-- Performance (B2, B5) -->
            <div class="form-card">
                <h4><?= __('admin.settings.performance') ?></h4>
                <div class="form-group">
                    <label class="toggle-label">
                        <input type="hidden" name="page_cache_enabled" value="0">
                        <input type="checkbox" name="page_cache_enabled" id="page_cache_enabled" value="1"
                               <?= ($settings['page_cache_enabled'] ?? '0') === '1' ? 'checked' : '' ?>>
                        <?= __('admin.settings.page_cache_enabled') ?>
                    </label>
                    <small class="form-hint"><?= __('admin.settings.page_cache_enabled_help') ?></small>
                </div>
                <div class="form-group" id="pageCacheTtlGroup" style="<?= ($settings['page_cache_enabled'] ?? '0') === '1' ? '' : 'display:none;' ?>">
                    <label for="page_cache_ttl"><?= __('admin.settings.page_cache_ttl') ?></label>
                    <input type="number" id="page_cache_ttl" name="page_cache_ttl"
                           value="<?= (int) ($settings['page_cache_ttl'] ?? 3600) ?>"
                           min="60" max="86400" step="60">
                    <small class="form-hint"><?= __('admin.settings.page_cache_ttl_help') ?></small>
                </div>
                <div class="form-group" id="pageCacheClearGroup" style="<?= ($settings['page_cache_enabled'] ?? '0') === '1' ? '' : 'display:none;' ?>">
                    <form method="POST" action="<?= admin_url('settings/clear-page-cache') ?>" style="display:inline;">
                        <?= $csrf->field() ?>
                        <button type="submit" class="btn btn-secondary btn-xs"><?= __('admin.settings.clear_page_cache') ?></button>
                    </form>
                </div>
                <div class="form-group">
                    <label class="toggle-label">
                        <input type="hidden" name="asset_minification_enabled" value="0">
                        <input type="checkbox" name="asset_minification_enabled" id="asset_minification_enabled" value="1"
                               <?= ($settings['asset_minification_enabled'] ?? '0') === '1' ? 'checked' : '' ?>>
                        <?= __('admin.settings.asset_minification_enabled') ?>
                    </label>
                    <small class="form-hint"><?= __('admin.settings.asset_minification_enabled_help') ?></small>
                </div>
            </div>

            <!-- Upload Settings -->
            <div class="form-card">
                <h4><?= __('admin.settings.upload_settings') ?></h4>
                <div class="form-group">
                    <label for="upload_allowed_extensions"><?= __('admin.settings.upload_allowed_extensions') ?></label>
                    <input type="text" id="upload_allowed_extensions" name="upload_allowed_extensions"
                           value="<?= e($settings['upload_allowed_extensions'] ?? 'jpg,jpeg,png,gif,webp,svg,ico,mp4,webm,pdf') ?>"
                           placeholder="jpg,jpeg,png,gif,webp,svg,ico,mp4,webm,pdf">
                    <small class="form-hint"><?= __('admin.settings.upload_allowed_extensions_help') ?></small>
                </div>
                <div class="form-group">
                    <label for="upload_max_filesize_mb"><?= __('admin.settings.upload_max_filesize_mb') ?></label>
                    <input type="number" id="upload_max_filesize_mb" name="upload_max_filesize_mb"
                           value="<?= (int) ($settings['upload_max_filesize_mb'] ?? 5) ?>"
                           min="1" max="200" step="1">
                    <small class="form-hint"><?= __('admin.settings.upload_max_filesize_mb_help') ?></small>
                </div>
            </div>

            <!-- Security (B1) -->
            <div class="form-card">
                <h4><?= __('admin.settings.security') ?></h4>
                <div class="form-group">
                    <label class="toggle-label">
                        <input type="hidden" name="totp_2fa_available" value="0">
                        <input type="checkbox" name="totp_2fa_available" id="totp_2fa_available" value="1"
                               <?= ($settings['totp_2fa_available'] ?? '0') === '1' ? 'checked' : '' ?>>
                        <?= __('admin.settings.totp_2fa_available') ?>
                    </label>
                    <small class="form-hint"><?= __('admin.settings.totp_2fa_available_help') ?></small>
                </div>
                <div class="form-group">
                    <label class="toggle-label">
                        <input type="hidden" name="accessibility_audit_enabled" value="0">
                        <input type="checkbox" name="accessibility_audit_enabled" id="accessibility_audit_enabled" value="1"
                               <?= ($settings['accessibility_audit_enabled'] ?? '1') === '1' ? 'checked' : '' ?>>
                        <?= __('admin.settings.accessibility_audit_enabled') ?>
                    </label>
                    <small class="form-hint"><?= __('admin.settings.accessibility_audit_enabled_help') ?></small>
                </div>
                <div class="form-group">
                    <label for="admin_slug"><?= __('admin.settings.admin_slug') ?></label>
                    <div style="display:flex; align-items:center; gap:0.5rem;">
                        <span style="color:var(--sem-text-secondary,#64748b);">/</span>
                        <input type="text" id="admin_slug" name="admin_slug"
                               value="<?= e(setting('admin_slug', 'admin')) ?>"
                               pattern="[a-z0-9\-]+" placeholder="admin"
                               style="max-width: 300px;">
                    </div>
                    <small class="field-hint"><?= __('admin.settings.admin_slug_hint') ?></small>
                </div>
            </div>

            <!-- Schema.org / LocalBusiness (B4) -->
            <div class="form-card">
                <h4><?= __('admin.settings.schema_org') ?></h4>
                <div class="form-group">
                    <label class="toggle-label">
                        <input type="hidden" name="local_business_enabled" value="0">
                        <input type="checkbox" name="local_business_enabled" id="local_business_enabled" value="1"
                               <?= ($settings['local_business_enabled'] ?? '0') === '1' ? 'checked' : '' ?>>
                        <?= __('admin.settings.local_business_enabled') ?>
                    </label>
                    <small class="form-hint"><?= __('admin.settings.local_business_enabled_help') ?></small>
                </div>
                <div id="localBusinessFields" style="<?= ($settings['local_business_enabled'] ?? '0') === '1' ? '' : 'display:none;' ?>">
                    <div class="form-group">
                        <label for="local_business_type"><?= __('admin.settings.local_business_type') ?></label>
                        <select id="local_business_type" name="local_business_type">
                            <?php foreach (['LocalBusiness','Store','Restaurant','HealthAndBeautyBusiness','LegalService','FinancialService','EducationalOrganization','AutoRepair','Dentist','RealEstateAgent'] as $t): ?>
                            <option value="<?= $t ?>" <?= ($settings['local_business_type'] ?? 'LocalBusiness') === $t ? 'selected' : '' ?>><?= $t ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="local_business_street"><?= __('admin.settings.local_business_street') ?></label>
                        <input type="text" id="local_business_street" name="local_business_street"
                               value="<?= e($settings['local_business_street'] ?? '') ?>">
                    </div>
                    <div style="display:grid;grid-template-columns:1fr 1fr;gap:1rem;">
                        <div class="form-group">
                            <label for="local_business_postal"><?= __('admin.settings.local_business_postal') ?></label>
                            <input type="text" id="local_business_postal" name="local_business_postal"
                                   value="<?= e($settings['local_business_postal'] ?? '') ?>">
                        </div>
                        <div class="form-group">
                            <label for="local_business_city"><?= __('admin.settings.local_business_city') ?></label>
                            <input type="text" id="local_business_city" name="local_business_city"
                                   value="<?= e($settings['local_business_city'] ?? '') ?>">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="local_business_country"><?= __('admin.settings.local_business_country') ?></label>
                        <input type="text" id="local_business_country" name="local_business_country"
                               value="<?= e($settings['local_business_country'] ?? '') ?>" placeholder="DE">
                    </div>
                    <div style="display:grid;grid-template-columns:1fr 1fr;gap:1rem;">
                        <div class="form-group">
                            <label for="local_business_lat"><?= __('admin.settings.local_business_lat') ?></label>
                            <input type="text" id="local_business_lat" name="local_business_lat"
                                   value="<?= e($settings['local_business_lat'] ?? '') ?>" placeholder="50.9375">
                        </div>
                        <div class="form-group">
                            <label for="local_business_lng"><?= __('admin.settings.local_business_lng') ?></label>
                            <input type="text" id="local_business_lng" name="local_business_lng"
                                   value="<?= e($settings['local_business_lng'] ?? '') ?>" placeholder="6.9603">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="local_business_hours"><?= __('admin.settings.local_business_hours') ?></label>
                        <input type="text" id="local_business_hours" name="local_business_hours"
                               value="<?= e($settings['local_business_hours'] ?? '') ?>"
                               placeholder="Mo-Fr 09:00-17:00, Sa 10:00-14:00">
                        <small class="form-hint"><?= __('admin.settings.local_business_hours_help') ?></small>
                    </div>
                </div>
                <div class="form-group" style="margin-top:1rem;">
                    <label class="toggle-label">
                        <input type="hidden" name="faq_schema_enabled" value="0">
                        <input type="checkbox" name="faq_schema_enabled" id="faq_schema_enabled" value="1"
                               <?= ($settings['faq_schema_enabled'] ?? '1') === '1' ? 'checked' : '' ?>>
                        <?= __('admin.settings.faq_schema_enabled') ?>
                    </label>
                    <small class="form-hint"><?= __('admin.settings.faq_schema_enabled_help') ?></small>
                </div>
            </div>

            <!-- Blog Options -->
            <div class="form-card">
                <h4><?= __('admin.settings.blog_options') ?></h4>
                <div class="form-group">
                    <label class="toggle-label">
                        <input type="hidden" name="blog_reading_time" value="0">
                        <input type="checkbox" name="blog_reading_time" id="blog_reading_time" value="1"
                               <?= ($settings['blog_reading_time'] ?? '1') === '1' ? 'checked' : '' ?>>
                        <?= __('admin.settings.blog_reading_time') ?>
                    </label>
                    <small class="form-hint"><?= __('admin.settings.blog_reading_time_help') ?></small>
                </div>
                <div class="form-group">
                    <label class="toggle-label">
                        <input type="hidden" name="blog_toc" value="0">
                        <input type="checkbox" name="blog_toc" id="blog_toc" value="1"
                               <?= ($settings['blog_toc'] ?? '1') === '1' ? 'checked' : '' ?>>
                        <?= __('admin.settings.blog_toc') ?>
                    </label>
                    <small class="form-hint"><?= __('admin.settings.blog_toc_help') ?></small>
                </div>
                <div class="form-group">
                    <label class="toggle-label">
                        <input type="hidden" name="blog_related_posts" value="0">
                        <input type="checkbox" name="blog_related_posts" id="blog_related_posts" value="1"
                               <?= ($settings['blog_related_posts'] ?? '1') === '1' ? 'checked' : '' ?>>
                        <?= __('admin.settings.blog_related_posts') ?>
                    </label>
                    <small class="form-hint"><?= __('admin.settings.blog_related_posts_help') ?></small>
                </div>
            </div>

            <!-- SEO -->
            <div class="form-card">
                <h4><?= __('admin.settings.seo') ?></h4>
                <div class="form-group">
                    <label for="seo_title"><?= __('admin.settings.seo_title') ?></label>
                    <input type="text" id="seo_title" name="seo_title"
                           value="<?= e($settings['seo_title'] ?? '') ?>">
                    <small class="form-hint"><?= __('admin.settings.seo_title_help') ?></small>
                </div>
                <div class="form-group">
                    <label for="seo_description"><?= __('admin.settings.seo_description') ?></label>
                    <textarea id="seo_description" name="seo_description" rows="3"><?= e($settings['seo_description'] ?? '') ?></textarea>
                    <small class="form-hint"><?= __('admin.settings.seo_description_help') ?></small>
                </div>
                <div class="form-group">
                    <label class="toggle-label">
                        <input type="hidden" name="extended_seo_enabled" value="0">
                        <input type="checkbox" name="extended_seo_enabled" id="extended_seo_enabled" value="1"
                               <?= ($settings['extended_seo_enabled'] ?? '1') === '1' ? 'checked' : '' ?>>
                        <?= __('admin.settings.extended_seo_enabled') ?>
                    </label>
                    <small class="form-hint"><?= __('admin.settings.extended_seo_enabled_help') ?></small>
                </div>
            </div>

            <!-- Social -->
            <div class="form-card">
                <h4><?= __('admin.settings.social') ?></h4>
                <div class="form-group">
                    <label for="social_facebook"><?= __('admin.settings.social_facebook') ?></label>
                    <input type="url" id="social_facebook" name="social_facebook"
                           value="<?= e($settings['social_facebook'] ?? '') ?>" placeholder="https://facebook.com/…">
                </div>
                <div class="form-group">
                    <label for="social_instagram"><?= __('admin.settings.social_instagram') ?></label>
                    <input type="url" id="social_instagram" name="social_instagram"
                           value="<?= e($settings['social_instagram'] ?? '') ?>" placeholder="https://instagram.com/…">
                </div>
                <div class="form-group">
                    <label for="social_linkedin"><?= __('admin.settings.social_linkedin') ?></label>
                    <input type="url" id="social_linkedin" name="social_linkedin"
                           value="<?= e($settings['social_linkedin'] ?? '') ?>" placeholder="https://linkedin.com/in/…">
                </div>
                <div class="form-group">
                    <label for="social_x"><?= __('admin.settings.social_x') ?></label>
                    <input type="url" id="social_x" name="social_x"
                           value="<?= e($settings['social_x'] ?? '') ?>" placeholder="https://x.com/…">
                </div>
                <div class="form-group">
                    <label for="social_youtube"><?= __('admin.settings.social_youtube') ?></label>
                    <input type="url" id="social_youtube" name="social_youtube"
                           value="<?= e($settings['social_youtube'] ?? '') ?>" placeholder="https://youtube.com/@…">
                </div>
                <div class="form-group">
                    <label for="social_discord"><?= __('admin.settings.social_discord') ?></label>
                    <input type="url" id="social_discord" name="social_discord"
                           value="<?= e($settings['social_discord'] ?? '') ?>" placeholder="https://discord.gg/…">
                </div>
                <div class="form-group">
                    <label for="social_twitch"><?= __('admin.settings.social_twitch') ?></label>
                    <input type="url" id="social_twitch" name="social_twitch"
                           value="<?= e($settings['social_twitch'] ?? '') ?>" placeholder="https://twitch.tv/…">
                </div>
                <div class="form-group">
                    <label for="social_github"><?= __('admin.settings.social_github') ?></label>
                    <input type="url" id="social_github" name="social_github"
                           value="<?= e($settings['social_github'] ?? '') ?>" placeholder="https://github.com/…">
                </div>
                <div class="form-group">
                    <label for="social_tiktok"><?= __('admin.settings.social_tiktok') ?></label>
                    <input type="url" id="social_tiktok" name="social_tiktok"
                           value="<?= e($settings['social_tiktok'] ?? '') ?>" placeholder="https://tiktok.com/@…">
                </div>
            </div>

        </div><!-- /.form-main -->

        <div class="form-sidebar">

            <!-- Branding – Logo & Favicon ──────────────────────────────────── -->
            <div class="form-card">
                <h4><?= __('admin.settings.branding') ?></h4>

                <?php
                /**
                 * Renders the branding field widget.
                 *
                 * @param string      $key       Setting key (e.g. 'logo_header')
                 * @param string      $label     Display label
                 * @param string      $hint      Help text below
                 * @param string      $currentPath Current relative path (from settings)
                 * @param string      $fileField  Name for the file input (e.g. 'logo_header_file')
                 */
                function renderBrandingField(
                    string $key,
                    string $label,
                    string $hint,
                    string $currentPath,
                    string $fileField
                ): void {
                    $previewUrl = $currentPath !== '' ? '/uploads/' . ltrim($currentPath, '/') : '';
                    $isImage    = $previewUrl !== '' && !str_ends_with(strtolower($currentPath), '.ico');
                    ?>
                    <div class="form-group branding-field" id="branding-group-<?= e($key) ?>">
                        <label><?= e($label) ?></label>

                        <!-- Current preview -->
                        <div class="branding-preview-wrap">
                            <?php if ($isImage): ?>
                                <img src="<?= e($previewUrl) ?>"
                                     id="branding-preview-<?= e($key) ?>"
                                     class="branding-preview-img"
                                     alt="<?= e($label) ?>"
                                     onerror="this.style.display='none'">
                            <?php elseif ($currentPath !== ''): ?>
                                <div class="branding-no-preview" id="branding-preview-<?= e($key) ?>">
                                    <?= e(basename($currentPath)) ?>
                                </div>
                            <?php else: ?>
                                <div class="branding-no-preview" id="branding-preview-<?= e($key) ?>" style="display:flex">
                                    <?= __('admin.settings.branding_no_image') ?>
                                </div>
                            <?php endif; ?>
                        </div>

                        <?php if ($currentPath !== ''): ?>
                        <div class="branding-path-display" id="branding-path-display-<?= e($key) ?>">
                            <?= e($currentPath) ?>
                        </div>
                        <?php else: ?>
                        <div class="branding-path-display" id="branding-path-display-<?= e($key) ?>"></div>
                        <?php endif; ?>

                        <!-- Actions: Upload / Pick / Remove -->
                        <div class="branding-actions" style="margin-top:0.5rem;">
                            <label class="btn btn-secondary btn-xs" style="display:inline-block;margin:0;cursor:pointer;">
                                <?= __('admin.settings.branding_upload') ?>
                                <input type="file" name="<?= e($fileField) ?>"
                                       id="file-<?= e($key) ?>"
                                       class="branding-file-input"
                                       data-target="<?= e($key) ?>"
                                       accept="image/*,.ico"
                                       style="display:none">
                            </label>

                            <button type="button"
                                    class="btn btn-secondary btn-xs branding-picker-btn"
                                    data-target="<?= e($key) ?>">
                                <?= __('admin.settings.branding_from_media') ?>
                            </button>

                            <button type="button"
                                    class="branding-remove-btn"
                                    data-target="<?= e($key) ?>"
                                    onclick="clearBrandingField('<?= e($key) ?>')">
                                <?= __('admin.settings.branding_remove') ?>
                            </button>
                        </div>

                        <!-- Hidden path field (sent with form) -->
                        <input type="hidden" name="<?= e($key) ?>"
                               id="hidden-<?= e($key) ?>"
                               value="<?= e($currentPath) ?>">

                        <?php if ($hint): ?>
                        <small class="form-hint"><?= $hint ?></small>
                        <?php endif; ?>
                    </div>
                    <?php
                }
                ?>

                <?php renderBrandingField(
                    'logo_header',
                    __('admin.settings.branding_header_logo'),
                    __('admin.settings.branding_header_logo_hint'),
                    $settings['logo_header'] ?? '',
                    'logo_header_file'
                ); ?>

                <div class="form-group">
                    <label for="logo_header_mode"><?= __('admin.settings.branding_header_mode') ?></label>
                    <select id="logo_header_mode" name="logo_header_mode">
                        <option value="original" <?= ($settings['logo_header_mode'] ?? 'original') === 'original' ? 'selected' : '' ?>><?= __('admin.settings.branding_mode_original') ?></option>
                        <option value="filtered" <?= ($settings['logo_header_mode'] ?? '') === 'filtered' ? 'selected' : '' ?>><?= __('admin.settings.branding_mode_filtered_header') ?></option>
                    </select>
                    <small class="form-hint"><?= __('admin.settings.branding_mode_help') ?></small>
                </div>

                <?php renderBrandingField(
                    'logo_footer',
                    __('admin.settings.branding_footer_logo'),
                    __('admin.settings.branding_footer_logo_hint'),
                    $settings['logo_footer'] ?? '',
                    'logo_footer_file'
                ); ?>

                <div class="form-group">
                    <label for="logo_footer_mode"><?= __('admin.settings.branding_footer_mode') ?></label>
                    <select id="logo_footer_mode" name="logo_footer_mode">
                        <option value="original" <?= ($settings['logo_footer_mode'] ?? 'original') === 'original' ? 'selected' : '' ?>><?= __('admin.settings.branding_mode_original') ?></option>
                        <option value="filtered" <?= ($settings['logo_footer_mode'] ?? '') === 'filtered' ? 'selected' : '' ?>><?= __('admin.settings.branding_mode_filtered') ?></option>
                    </select>
                </div>

                <div class="form-group">
                    <label for="logo_alt"><?= __('admin.settings.branding_logo_alt') ?></label>
                    <input type="text" id="logo_alt" name="logo_alt"
                           value="<?= e($settings['logo_alt'] ?? '') ?>"
                           placeholder="<?= __('admin.settings.branding_logo_alt_placeholder') ?>">
                    <small class="form-hint"><?= __('admin.settings.branding_logo_alt_hint') ?></small>
                </div>

                <hr style="margin: 1rem 0; border-color: var(--border-color, #e5e7eb);">

                <?php renderBrandingField(
                    'logo',
                    __('admin.settings.branding_logo_general'),
                    __('admin.settings.branding_logo_general_hint'),
                    $settings['logo'] ?? '',
                    'logo_file'
                ); ?>

                <?php renderBrandingField(
                    'favicon',
                    __('admin.settings.branding_favicon'),
                    __('admin.settings.branding_favicon_hint'),
                    $settings['favicon'] ?? '',
                    'favicon_file'
                ); ?>

            </div>

            <button type="submit" class="btn btn-primary btn-full"><?= __('admin.settings.save') ?></button>
        </div><!-- /.form-sidebar -->
    </div><!-- /.form-grid -->
</form>

<!-- ── Branding Media Picker Overlay ───────────────────────────────────────── -->
<div id="brandingPickerOverlay" style="display:none;position:fixed;inset:0;z-index:9999;background:rgba(0,0,0,.5);align-items:center;justify-content:center;">
    <div class="branding-picker-modal">
        <div class="branding-picker-header">
            <span><?= __('admin.settings.branding_picker_title') ?></span>
            <button type="button" id="brandingPickerClose" title="<?= __('admin.settings.branding_picker_close') ?>">×</button>
        </div>
        <div id="brandingPickerBody" style="overflow-y:auto;flex:1;padding:1rem;">
            <p style="text-align:center;color:var(--gray-400);padding-top:3rem;"><?= __('admin.settings.branding_picker_loading') ?></p>
        </div>
    </div>
</div>

<script>
// ── Branding field logic ─────────────────────────────────────────────────────

var _iw_brandingStr = {
    noImage:    <?= json_encode(__('admin.settings.branding_no_image')) ?>,
    loading:    <?= json_encode(__('admin.settings.branding_picker_loading')) ?>,
    search:     <?= json_encode(__('admin.settings.branding_picker_search')) ?>,
    noImages:   <?= json_encode(__('admin.settings.branding_picker_no_images')) ?>,
    pickerErr:  <?= json_encode(__('admin.settings.branding_picker_error')) ?>
};

function clearBrandingField(key) {
    document.getElementById('hidden-' + key).value = '';
    var preview = document.getElementById('branding-preview-' + key);
    var pathDisplay = document.getElementById('branding-path-display-' + key);
    if (preview) {
        preview.src = '';
        preview.style.display = 'none';
        preview.textContent = _iw_brandingStr.noImage;
        preview.style.display = 'flex';
    }
    if (pathDisplay) pathDisplay.textContent = '';
    // Clear file input
    var fileInput = document.getElementById('file-' + key);
    if (fileInput) fileInput.value = '';
}

function updateBrandingPreview(key, url, path) {
    var preview    = document.getElementById('branding-preview-' + key);
    var hiddenInp  = document.getElementById('hidden-' + key);
    var pathDisplay = document.getElementById('branding-path-display-' + key);

    if (hiddenInp) hiddenInp.value = path;
    if (pathDisplay) pathDisplay.textContent = path;

    if (preview) {
        if (preview.tagName === 'IMG') {
            preview.src = url;
            preview.style.display = '';
        } else {
            // Replace placeholder div with img
            var img = document.createElement('img');
            img.src = url;
            img.className = 'branding-preview-img';
            img.alt = key + ' Vorschau';
            preview.parentNode.replaceChild(img, preview);
            img.id = 'branding-preview-' + key;
        }
    }
}

// ── File input preview (client-side) ─────────────────────────────────────────
document.querySelectorAll('.branding-file-input').forEach(function(input) {
    input.addEventListener('change', function() {
        var key  = this.dataset.target;
        var file = this.files[0];
        if (!file) return;

        // Immediate client-side preview via ObjectURL
        var url = URL.createObjectURL(file);
        var preview = document.getElementById('branding-preview-' + key);
        if (preview) {
            if (preview.tagName === 'IMG') {
                preview.src = url;
                preview.style.display = '';
            } else {
                var img = document.createElement('img');
                img.src = url;
                img.className = 'branding-preview-img';
                img.alt = key;
                preview.parentNode.replaceChild(img, preview);
                img.id = 'branding-preview-' + key;
            }
        }
        var pd = document.getElementById('branding-path-display-' + key);
        if (pd) pd.textContent = <?= json_encode(__('admin.settings.upload_pending', [':filename' => '__FILE__'])) ?>.replace('__FILE__', file.name);
        // Clear the hidden path field so the upload takes precedence
        var hiddenInp = document.getElementById('hidden-' + key);
        if (hiddenInp) hiddenInp.value = '';
    });
});

// ── Media Picker for branding ─────────────────────────────────────────────────
(function() {
    var overlay     = document.getElementById('brandingPickerOverlay');
    var closeBtn    = document.getElementById('brandingPickerClose');
    var body        = document.getElementById('brandingPickerBody');
    var currentTarget = null;
    var loaded      = false;

    if (!overlay) return;

    function openPicker(targetKey) {
        currentTarget = targetKey;
        overlay.style.display = 'flex';
        if (!loaded) {
            renderPickerGrid(body);
            loaded = true;
        }
    }

    function closePicker() {
        overlay.style.display = 'none';
        currentTarget = null;
    }

    closeBtn && closeBtn.addEventListener('click', closePicker);
    overlay.addEventListener('click', function(e) { if (e.target === overlay) closePicker(); });
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape' && overlay.style.display !== 'none') closePicker();
    });

    document.querySelectorAll('.branding-picker-btn').forEach(function(btn) {
        btn.addEventListener('click', function() { openPicker(this.dataset.target); });
    });

    function renderPickerGrid(container) {
        container.innerHTML =
            '<div style="display:flex;gap:0.5rem;margin-bottom:0.75rem;">' +
                '<input type="text" id="bpSearch" placeholder="' + _iw_brandingStr.search + '" autocomplete="off" style="flex:1;padding:0.4rem 0.65rem;border:1px solid var(--border-color,#e5e7eb);border-radius:6px;font-size:0.875rem;">' +
            '</div>' +
            '<div id="bpGrid" style="display:grid;grid-template-columns:repeat(auto-fill,minmax(110px,1fr));gap:0.6rem;">' +
                '<p style="grid-column:1/-1;text-align:center;color:var(--gray-400);padding:2rem 0;">' + _iw_brandingStr.loading + '</p>' +
            '</div>';

        var searchInput = container.querySelector('#bpSearch');
        var searchTimer;
        searchInput.addEventListener('input', function() {
            clearTimeout(searchTimer);
            searchTimer = setTimeout(function() { loadImages(searchInput.value); }, 300);
        });

        loadImages('');
    }

    function loadImages(q) {
        var grid = document.getElementById('bpGrid');
        if (!grid) return;
        grid.innerHTML = '<p style="grid-column:1/-1;text-align:center;color:var(--gray-400);padding:2rem 0;">' + _iw_brandingStr.loading + '</p>';

        fetch('<?= admin_url('media/picker-images') ?>?q=' + encodeURIComponent(q), {credentials:'same-origin'})
            .then(function(r) { return r.json(); })
            .then(function(data) {
                if (!data.images || !data.images.length) {
                    grid.innerHTML = '<p style="grid-column:1/-1;text-align:center;color:var(--gray-400);padding:2rem 0;">' + _iw_brandingStr.noImages + '</p>';
                    return;
                }
                var html = '';
                data.images.forEach(function(img) {
                    html += '<div class="bp-item" style="cursor:pointer;border-radius:6px;overflow:hidden;border:2px solid transparent;transition:border-color .15s;"' +
                            ' data-url="' + escHtml(img.url) + '"' +
                            ' data-path="' + escHtml(img.url.replace(/^\/uploads\//,'')) + '"' +
                            ' title="' + escHtml(img.name) + '">' +
                            '<img src="' + escHtml(img.thumb_url || img.url) + '" alt="' + escHtml(img.name) + '"' +
                            ' style="width:100%;height:80px;object-fit:cover;" loading="lazy">' +
                            '<div style="font-size:0.7rem;padding:0.2rem 0.3rem;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:var(--gray-600);">' +
                            escHtml(img.name) + '</div></div>';
                });
                grid.innerHTML = html;

                grid.querySelectorAll('.bp-item').forEach(function(item) {
                    item.addEventListener('mouseenter', function() { item.style.borderColor = 'var(--admin-primary,#2563eb)'; });
                    item.addEventListener('mouseleave', function() { item.style.borderColor = 'transparent'; });
                    item.addEventListener('click', function() {
                        if (currentTarget) {
                            updateBrandingPreview(currentTarget, item.dataset.url, item.dataset.path);
                        }
                        closePicker();
                    });
                });
            })
            .catch(function() {
                var grid = document.getElementById('bpGrid');
                if (grid) grid.innerHTML = '<p style="grid-column:1/-1;text-align:center;color:var(--admin-danger);padding:2rem 0;">' + _iw_brandingStr.pickerErr + '</p>';
            });
    }

    function escHtml(str) {
        return String(str).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
    }
}());

// ── Conditional field visibility ────────────────────────────────────────────
(function () {
    function toggle(cbId, targets) {
        var cb = document.getElementById(cbId);
        if (!cb) return;
        cb.addEventListener('change', function () {
            targets.forEach(function (id) {
                var el = document.getElementById(id);
                if (el) el.style.display = cb.checked ? '' : 'none';
            });
        });
    }
    toggle('http_cache_enabled', ['httpCacheTtlGroup']);
    toggle('page_cache_enabled', ['pageCacheTtlGroup', 'pageCacheClearGroup']);
    toggle('local_business_enabled', ['localBusinessFields']);
}());
</script>

<?php $content = ob_get_clean(); include dirname(__DIR__) . '/layouts/admin.php'; ?>
