<?php ob_start(); ?>

<?php
/**
 * Renders the section text color dropdown.
 * Values: '' (theme default), 'black', 'white', 'theme' (theme primary color).
 */
function render_section_text_color_field(array $data): void {
    $current = $data['section_text_color'] ?? '';
    ?>
    <div class="form-group" style="margin:0;">
        <label><?= __('admin.homepage.section_text_color') ?></label>
        <select name="section_text_color">
            <option value=""><?= __('admin.homepage.text_color_default') ?></option>
            <option value="black" <?= $current === 'black' ? 'selected' : '' ?>><?= __('admin.homepage.text_color_black') ?></option>
            <option value="white" <?= $current === 'white' ? 'selected' : '' ?>><?= __('admin.homepage.text_color_white') ?></option>
            <option value="theme" <?= $current === 'theme' ? 'selected' : '' ?>><?= __('admin.homepage.text_color_theme') ?></option>
        </select>
    </div>
    <?php
}
?>

<div class="content-header">
    <h2><?= __('admin.homepage.title') ?></h2>
    <p style="margin:.25rem 0 0; color:#888; font-size:.9rem;">
        <?= __('admin.homepage.configure_text') ?>
    </p>
</div>

<?php if (empty($sections)): ?>
<div class="form-card">
    <p class="text-muted"><?= __('admin.homepage.no_sections') ?></p>
</div>
<?php endif; ?>

<?php
// ── Build section_key → plugin-slug map from installed plugins ─────────────
// This map resolves the correct plugin slug for a given section_key, even when
// the slug convention differs (e.g. section_key "feature_showcase" → slug
// "feature-showcase-section"). Without this map, only the simple underscore-
// to-dash conversion is used, which fails for plugins where the slug does not
// exactly match the section_key with dashes instead of underscores.
$_pluginBaseDir = (defined('BASE_PATH') ? BASE_PATH : dirname(__DIR__, 3)) . '/plugins';
$_sectionKeyToSlug = [];
if (is_dir($_pluginBaseDir)) {
    foreach (scandir($_pluginBaseDir) as $_pDir) {
        if ($_pDir[0] === '.' || !is_dir($_pluginBaseDir . '/' . $_pDir)) {
            continue;
        }
        $_pJson = $_pluginBaseDir . '/' . $_pDir . '/plugin.json';
        if (is_file($_pJson)) {
            $_pMeta = @json_decode(@file_get_contents($_pJson), true);
            if (is_array($_pMeta) && !empty($_pMeta['section_key'])) {
                $_sectionKeyToSlug[$_pMeta['section_key']] = $_pMeta['slug'] ?? $_pDir;
            }
        }
    }
}
?>

<?php foreach ($sections as $_sIdx => $section): ?>
<?php $data = $section['data']; ?>

<div class="form-card" id="section-<?= (int) $section['id'] ?>" style="margin-bottom:1.5rem;">

    <!-- Section header bar -->
    <div style="display:flex; align-items:center; justify-content:space-between; margin-bottom:.75rem;">
        <div style="display:flex; align-items:center; gap:.75rem;">
            <span class="badge <?= $section['is_active'] ? 'badge-success' : 'badge-draft' ?>"
                  style="font-size:.8rem;">
                <?= $section['is_active'] ? __('admin.homepage.section_active') : __('admin.homepage.section_inactive') ?>
            </span>
            <h4 style="margin:0;">
                <span style="color:#999;font-weight:normal;font-size:.85em;">#<?= $_sIdx + 1 ?></span>
                <?= e($section['title']) ?>
                <small style="font-weight:normal; color:#aaa; font-size:.8em;">[<?= e($section['section_key']) ?>]</small>
            </h4>
        </div>
        <div style="display:flex; gap:.5rem; align-items:center;">
            <!-- Move section up/down -->
            <form method="POST" action="/admin/homepage/section/<?= (int) $section['id'] ?>/move" class="inline-form" style="display:inline;">
                <?= $csrf->field() ?>
                <input type="hidden" name="direction" value="up">
                <button type="submit" class="btn btn-xs" title="Move section up" aria-label="Move section up">&uarr;</button>
            </form>
            <form method="POST" action="/admin/homepage/section/<?= (int) $section['id'] ?>/move" class="inline-form" style="display:inline;">
                <?= $csrf->field() ?>
                <input type="hidden" name="direction" value="down">
                <button type="submit" class="btn btn-xs" title="Move section down" aria-label="Move section down">&darr;</button>
            </form>
            <span style="width:1px;height:1.5rem;background:#ddd;margin:0 .25rem;"></span>
            <!-- Toggle active state -->
            <form method="POST" action="/admin/homepage/section/<?= (int) $section['id'] ?>/toggle" class="inline-form">
                <?= $csrf->field() ?>
                <button type="submit" class="btn btn-sm <?= $section['is_active'] ? 'btn-secondary' : 'btn-primary' ?>">
                    <?= $section['is_active'] ? __('admin.homepage.deactivate') : __('admin.homepage.activate') ?>
                </button>
            </form>
            <!-- Toggle edit form -->
            <button class="btn btn-sm btn-secondary"
                    onclick="toggleSection('section-form-<?= (int) $section['id'] ?>')">
                <?= __('admin.homepage.edit') ?>
            </button>
        </div>
    </div>

    <!-- Quick preview of current content -->
    <div style="font-size:.85rem; color:#666; margin-bottom:.5rem;">
        <?php if (!empty($data['title'])): ?>
        <strong><?= __('admin.homepage.preview_title') ?>:</strong> <?= e($data['title']) ?>
        <?php endif; ?>
        <?php if (!empty($data['subtitle'])): ?>
        · <strong><?= __('admin.homepage.preview_subtitle') ?>:</strong> <?= e($data['subtitle']) ?>
        <?php endif; ?>
        <?php if (!empty($data['text'])): ?>
        · <strong><?= __('admin.homepage.preview_text') ?>:</strong> <?= e(mb_substr($data['text'], 0, 80)) ?><?= mb_strlen($data['text'] ?? '') > 80 ? '…' : '' ?>
        <?php endif; ?>
        <?php if ($section['section_key'] === 'features' && !empty($data['items'])): ?>
        · <strong><?= __('admin.homepage.preview_items', [':count' => count($data['items'])]) ?></strong>
        <?php endif; ?>
        <?php if (isset($data['cta_text']) && $data['cta_text'] !== ''): ?>
        · <strong><?= __('admin.homepage.preview_cta') ?>:</strong> <?= e($data['cta_text']) ?> → <?= e($data['cta_url'] ?? '') ?>
        <?php endif; ?>
        <?php if (isset($data['count'])): ?>
        · <strong><?= __('admin.homepage.preview_count') ?>:</strong> <?= (int) $data['count'] ?>
        <?php endif; ?>
    </div>

    <!-- Edit form (hidden by default) -->
    <div id="section-form-<?= (int) $section['id'] ?>" style="display:none; padding-top:1rem; border-top:1px solid #e9ecef; margin-top:.75rem;">
        <form method="POST" action="/admin/homepage/section/<?= (int) $section['id'] ?>/save" class="admin-form">
            <?= $csrf->field() ?>

            <!-- Section display title (editable) -->
            <div class="form-group">
                <label><?= __('admin.homepage.section_display_title') ?></label>
                <input type="text" name="section_title" value="<?= e($section['title']) ?>">
                <small class="form-hint"><?= __('admin.homepage.internal_label_hint') ?></small>
            </div>

            <?php if ($section['section_key'] === 'hero'): ?>
            <?php
            // Theme Admin Partial Override: allow premium themes to provide
            // their own admin form for this section. Falls back to core form.
            $_theme_hero_partial = theme_admin_partial('hero');
            if ($_theme_hero_partial):
                include $_theme_hero_partial;
            else:
            ?>
            <!-- ── Hero v2: Inhalt ──────────────────────────────────────── -->
            <h5 style="margin:0 0 1rem;font-size:.85rem;text-transform:uppercase;letter-spacing:.06em;color:#888;">
                Inhalt
            </h5>
            <div class="form-group">
                <label>Eyebrow-Text <small style="font-weight:normal;color:#aaa;">(optional, klein über dem Titel)</small></label>
                <input type="text" name="eyebrow" value="<?= e($data['eyebrow'] ?? '') ?>"
                       placeholder="z.B. Willkommen bei ITSWEBER">
            </div>
            <div class="form-group">
                <label>Hero Headline</label>
                <input type="text" name="title" value="<?= e($data['title'] ?? '') ?>"
                       placeholder="Your main headline">
            </div>
            <div class="form-group">
                <label>Subtitle / Tagline</label>
                <input type="text" name="subtitle" value="<?= e($data['subtitle'] ?? '') ?>"
                       placeholder="A short supporting line">
            </div>
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:.75rem 1.25rem;">
                <div class="form-group" style="margin:0;">
                    <label>CTA Button Text</label>
                    <input type="text" name="cta_text" value="<?= e($data['cta_text'] ?? '') ?>"
                           placeholder="e.g. Learn More">
                </div>
                <div class="form-group" style="margin:0;">
                    <label>CTA Button URL</label>
                    <input type="text" name="cta_url" value="<?= e($data['cta_url'] ?? '') ?>"
                           placeholder="/about">
                </div>
                <div class="form-group" style="margin:0;">
                    <label>2. Button Text <small style="font-weight:normal;color:#aaa;">(optional)</small></label>
                    <input type="text" name="cta2_text" value="<?= e($data['cta2_text'] ?? '') ?>"
                           placeholder="z.B. Portfolio ansehen">
                </div>
                <div class="form-group" style="margin:0;">
                    <label>2. Button URL</label>
                    <input type="text" name="cta2_url" value="<?= e($data['cta2_url'] ?? '') ?>"
                           placeholder="/gallery">
                </div>
            </div>

            <!-- ── Hero v2: Medien ──────────────────────────────────────── -->
            <hr style="margin:1.5rem 0;border:none;border-top:1px solid #e9ecef;">
            <h5 style="margin:0 0 1rem;font-size:.85rem;text-transform:uppercase;letter-spacing:.06em;color:#888;">
                Medien
            </h5>
            <div class="form-group">
                <label>Hintergrundbild <small style="font-weight:normal;color:#aaa;">(optional)</small></label>
                <input type="text" name="image" value="<?= e($data['image'] ?? '') ?>"
                       placeholder="filename.jpg (relative to /uploads/)">
                <small class="form-hint">Pfad relativ zu /uploads/ (z.B. <code>media/abc123.jpg</code>). Pfade im <a href="/admin/media" target="_blank">Media Manager</a>. Bei Boxed-Layout: Bild wird innerhalb der Box angezeigt.</small>
            </div>
            <div class="form-group">
                <label>Portrait-/Personenbild <small style="font-weight:normal;color:#aaa;">(optional)</small></label>
                <input type="text" name="portrait_image" value="<?= e($data['portrait_image'] ?? '') ?>"
                       placeholder="media/portrait.jpg">
                <small class="form-hint">Bei Split-Layout: Text links, Portrait rechts. Bei anderen Layout-Modi: zentriertes Portrait über dem Text.</small>
            </div>
            <div class="form-group">
                <label>Portrait-Bild Alt-Text</label>
                <input type="text" name="portrait_alt" value="<?= e($data['portrait_alt'] ?? '') ?>"
                       placeholder="Name oder Beschreibung des Portraits">
            </div>

            <!-- ── Hero v2: Darstellung ─────────────────────────────────── -->
            <hr style="margin:1.5rem 0;border:none;border-top:1px solid #e9ecef;">
            <h5 style="margin:0 0 1rem;font-size:.85rem;text-transform:uppercase;letter-spacing:.06em;color:#888;">
                Darstellung
                <small style="font-weight:normal;text-transform:none;letter-spacing:0;color:#bbb;">— leer lassen = Theme-Standard</small>
            </h5>

            <div style="display:grid;grid-template-columns:1fr 1fr;gap:.75rem 1.25rem;">

                <div class="form-group" style="margin:0;">
                    <label>Layout</label>
                    <select name="layout_mode">
                        <option value="">Center (Standard)</option>
                        <option value="full"  <?= ($data['layout_mode'] ?? '') === 'full'  ? 'selected' : '' ?>>Full – volle Breite</option>
                        <option value="boxed" <?= ($data['layout_mode'] ?? '') === 'boxed' ? 'selected' : '' ?>>Boxed – Karte mit eigenem Hintergrund</option>
                        <option value="split" <?= ($data['layout_mode'] ?? '') === 'split' ? 'selected' : '' ?>>Split – Text + Portrait zweispaltig</option>
                    </select>
                    <small class="form-hint">Boxed: Inhalt und Hintergrundbild innerhalb der Karte. Split: erfordert Portrait.</small>
                </div>

                <div class="form-group" style="margin:0;">
                    <label>Textausrichtung</label>
                    <select name="text_align">
                        <option value="">Center (Standard)</option>
                        <option value="left"  <?= ($data['text_align'] ?? '') === 'left'  ? 'selected' : '' ?>>Links</option>
                        <option value="right" <?= ($data['text_align'] ?? '') === 'right' ? 'selected' : '' ?>>Rechts</option>
                    </select>
                </div>

                <div class="form-group" style="margin:0;">
                    <label>Textfarbe</label>
                    <select name="text_color">
                        <option value="">Theme-Standard</option>
                        <option value="auto"  <?= ($data['text_color'] ?? '') === 'auto'  ? 'selected' : '' ?>>Automatisch (Theme-Standard)</option>
                        <option value="white" <?= ($data['text_color'] ?? '') === 'white' ? 'selected' : '' ?>>Weiß (#ffffff)</option>
                        <option value="black" <?= ($data['text_color'] ?? '') === 'black' ? 'selected' : '' ?>>Schwarz (#000000)</option>
                        <option value="red"   <?= ($data['text_color'] ?? '') === 'red'   ? 'selected' : '' ?>>Rot (#dc2626)</option>
                        <option value="green" <?= ($data['text_color'] ?? '') === 'green' ? 'selected' : '' ?>>Grün (#16a34a)</option>
                        <option value="blue"  <?= ($data['text_color'] ?? '') === 'blue'  ? 'selected' : '' ?>>Blau (#2563eb)</option>
                        <optgroup label="Legacy (1.0.9)">
                        <option value="light" <?= ($data['text_color'] ?? '') === 'light' ? 'selected' : '' ?>>Hell – legacy (→ white)</option>
                        <option value="dark"  <?= ($data['text_color'] ?? '') === 'dark'  ? 'selected' : '' ?>>Dunkel – legacy (→ black)</option>
                        </optgroup>
                    </select>
                </div>

                <div class="form-group" style="margin:0;">
                    <label>Hintergrund-Overlay</label>
                    <select name="overlay_strength">
                        <option value="">Kein Overlay</option>
                        <option value="light"  <?= ($data['overlay_strength'] ?? '') === 'light'  ? 'selected' : '' ?>>Leicht (25 %)</option>
                        <option value="medium" <?= ($data['overlay_strength'] ?? '') === 'medium' ? 'selected' : '' ?>>Mittel (45 %)</option>
                        <option value="heavy"  <?= ($data['overlay_strength'] ?? '') === 'heavy'  ? 'selected' : '' ?>>Stark (65 %)</option>
                    </select>
                    <small class="form-hint">Verdunkelt das Hintergrundbild für bessere Lesbarkeit. Bei Boxed: Overlay nur innerhalb der Karte.</small>
                </div>

                <div class="form-group" style="margin:0;">
                    <label>Überschrift-Größe</label>
                    <select name="heading_size">
                        <option value="">Standard</option>
                        <option value="sm" <?= ($data['heading_size'] ?? '') === 'sm' ? 'selected' : '' ?>>Klein</option>
                        <option value="md" <?= ($data['heading_size'] ?? '') === 'md' ? 'selected' : '' ?>>Mittel</option>
                        <option value="lg" <?= ($data['heading_size'] ?? '') === 'lg' ? 'selected' : '' ?>>Groß</option>
                        <option value="xl" <?= ($data['heading_size'] ?? '') === 'xl' ? 'selected' : '' ?>>Extra-Groß</option>
                    </select>
                </div>

                <div class="form-group" style="margin:0;">
                    <label>Überschrift-Gewicht</label>
                    <select name="heading_weight">
                        <option value="">Theme-Standard</option>
                        <option value="normal" <?= ($data['heading_weight'] ?? '') === 'normal' ? 'selected' : '' ?>>Normal (400)</option>
                        <option value="medium" <?= ($data['heading_weight'] ?? '') === 'medium' ? 'selected' : '' ?>>Medium (600)</option>
                        <option value="bold"   <?= ($data['heading_weight'] ?? '') === 'bold'   ? 'selected' : '' ?>>Bold (700)</option>
                        <option value="black"  <?= ($data['heading_weight'] ?? '') === 'black'  ? 'selected' : '' ?>>Black (900)</option>
                    </select>
                </div>

                <div class="form-group" style="margin:0;">
                    <label>Fließtext-Größe</label>
                    <select name="body_size">
                        <option value="">Standard</option>
                        <option value="sm" <?= ($data['body_size'] ?? '') === 'sm' ? 'selected' : '' ?>>Klein</option>
                        <option value="md" <?= ($data['body_size'] ?? '') === 'md' ? 'selected' : '' ?>>Mittel</option>
                        <option value="lg" <?= ($data['body_size'] ?? '') === 'lg' ? 'selected' : '' ?>>Groß</option>
                    </select>
                </div>

                <div class="form-group" style="margin:0;">
                    <label>Hero-Höhe</label>
                    <select name="hero_height">
                        <option value="">Standard</option>
                        <option value="tall" <?= ($data['hero_height'] ?? '') === 'tall' ? 'selected' : '' ?>>Tall (80 vh)</option>
                    </select>
                </div>

                <div class="form-group" style="margin:0;">
                    <label>Portrait-Form</label>
                    <select name="portrait_shape">
                        <option value="">Standard (aus Theme)</option>
                        <option value="circle"  <?= ($data['portrait_shape'] ?? '') === 'circle'  ? 'selected' : '' ?>>Kreis</option>
                        <option value="rounded" <?= ($data['portrait_shape'] ?? '') === 'rounded' ? 'selected' : '' ?>>Abgerundet</option>
                        <option value="square"  <?= ($data['portrait_shape'] ?? '') === 'square'  ? 'selected' : '' ?>>Quadrat</option>
                    </select>
                </div>

                <div class="form-group" style="margin:0;">
                    <label>Portrait-Schatten</label>
                    <select name="portrait_style">
                        <option value="">Standard</option>
                        <option value="elevated" <?= ($data['portrait_style'] ?? '') === 'elevated' ? 'selected' : '' ?>>Erhöht</option>
                        <option value="flat"     <?= ($data['portrait_style'] ?? '') === 'flat'     ? 'selected' : '' ?>>Kein Schatten</option>
                    </select>
                </div>

                <div class="form-group" style="margin:0;">
                    <label>CTA-Layout</label>
                    <select name="cta_layout">
                        <option value="">Nebeneinander (Standard)</option>
                        <option value="stacked" <?= ($data['cta_layout'] ?? '') === 'stacked' ? 'selected' : '' ?>>Untereinander</option>
                    </select>
                </div>

            </div>
            <!-- ── end Hero v2 Darstellung ─────────────────────────────── -->
            <?php endif; /* end theme_admin_partial fallback */ ?>

            <?php elseif ($section['section_key'] === 'intro'): ?>
            <?php $_theme_intro_partial = theme_admin_partial('intro'); if ($_theme_intro_partial): ?>
            <?php include $_theme_intro_partial; ?>
            <?php else: ?>
            <!-- Intro fields -->
            <div class="form-group">
                <label>Heading</label>
                <input type="text" name="title" value="<?= e($data['title'] ?? '') ?>"
                       placeholder="e.g. Welcome">
            </div>
            <div class="form-group">
                <label>Subtitle</label>
                <input type="text" name="subtitle" value="<?= e($data['subtitle'] ?? '') ?>"
                       placeholder="e.g. Optional subtitle">
            </div>
            <div class="form-group">
                <label>Intro Text</label>
                <textarea name="text" rows="5" placeholder="Write a short introduction…"><?= e($data['text'] ?? '') ?></textarea>
                <small class="form-hint">Line breaks are preserved in the frontend.</small>
            </div>
            <div class="form-group">
                <label>CTA Button Text</label>
                <input type="text" name="cta_text" value="<?= e($data['cta_text'] ?? '') ?>"
                       placeholder="e.g. Get Started">
                <small class="form-hint">Leave blank to hide the CTA button.</small>
            </div>
            <div class="form-group">
                <label>CTA Button URL</label>
                <input type="text" name="cta_url" value="<?= e($data['cta_url'] ?? '') ?>"
                       placeholder="/about">
            </div>
            <!-- ── Presentation Config ──── -->
            <hr style="margin:1.25rem 0;border:none;border-top:1px solid #e9ecef;">
            <h5 style="margin:0 0 .75rem;font-size:.85rem;text-transform:uppercase;letter-spacing:.06em;color:#888;">Presentation <small style="font-weight:normal;text-transform:none;letter-spacing:0;color:#bbb;">— leer = Theme-Standard</small></h5>
            <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:.75rem 1.25rem;">
                <div class="form-group" style="margin:0;">
                    <label>Farbschema</label>
                    <select name="color_scheme">
                        <option value="">Theme-Standard</option>
                        <option value="alt"     <?= ($data['color_scheme'] ?? '') === 'alt'     ? 'selected' : '' ?>>Alt (Sekundärhintergrund)</option>
                        <option value="primary" <?= ($data['color_scheme'] ?? '') === 'primary' ? 'selected' : '' ?>>Primary (Akzentfarbe)</option>
                        <option value="dark"    <?= ($data['color_scheme'] ?? '') === 'dark'    ? 'selected' : '' ?>>Dunkel (Invertiert)</option>
                        <option value="none"    <?= ($data['color_scheme'] ?? '') === 'none'    ? 'selected' : '' ?>>Keiner (Transparent)</option>
                    </select>
                </div>
                <?php render_section_text_color_field($data); ?>
                <div class="form-group" style="margin:0;">
                    <label>Textausrichtung</label>
                    <select name="text_align">
                        <option value="">Theme-Standard (Zentriert)</option>
                        <option value="left" <?= ($data['text_align'] ?? '') === 'left' ? 'selected' : '' ?>>Links</option>
                    </select>
                </div>
                <div class="form-group" style="margin:0;">
                    <label>Textbreite</label>
                    <select name="max_width">
                        <option value="">Theme-Standard</option>
                        <option value="sm" <?= ($data['max_width'] ?? '') === 'sm' ? 'selected' : '' ?>>Schmal (sm)</option>
                        <option value="md" <?= ($data['max_width'] ?? '') === 'md' ? 'selected' : '' ?>>Mittel (md)</option>
                        <option value="lg" <?= ($data['max_width'] ?? '') === 'lg' ? 'selected' : '' ?>>Weit (lg)</option>
                    </select>
                </div>
            </div>
            <?php endif; /* end intro theme_admin_partial fallback */ ?>

            <?php elseif ($section['section_key'] === 'features'): ?>
            <?php $_theme_features_partial = theme_admin_partial('features'); if ($_theme_features_partial): ?>
            <?php include $_theme_features_partial; ?>
            <?php else: ?>
            <!-- Features section -->
            <div class="form-group">
                <label>Section Heading</label>
                <input type="text" name="title" value="<?= e($data['title'] ?? '') ?>"
                       placeholder="e.g. What We Offer">
            </div>
            <div class="form-group">
                <label>Section Subtitle</label>
                <input type="text" name="subtitle" value="<?= e($data['subtitle'] ?? '') ?>"
                       placeholder="Optional subtitle under heading">
            </div>
            <div class="form-group">
                <label>Feature Items</label>
                <div id="feature-items-<?= (int) $section['id'] ?>" class="section-items-sortable">
                    <?php $existingItems = $data['items'] ?? []; ?>
                    <?php if (empty($existingItems)): ?>
                    <?php $existingItems = [['icon' => '', 'title' => '', 'text' => '', 'url' => '']]; ?>
                    <?php endif; ?>
                    <?php foreach ($existingItems as $fi): ?>
                    <div class="feature-item-row section-item-sortable" style="background:#f8f9fa;border:1px solid #e9ecef;border-radius:6px;padding:.75rem;margin-bottom:.5rem;">
                        <div style="display:grid;grid-template-columns:auto 80px 1fr 1fr auto auto;gap:.5rem;margin-bottom:.4rem;align-items:start;">
                            <div class="item-move-buttons" style="display:flex;flex-direction:column;gap:.2rem;">
                                <button type="button" class="btn btn-xs item-move-up" title="Move up">▲</button>
                                <button type="button" class="btn btn-xs item-move-down" title="Move down">▼</button>
                            </div>
                            <input type="text" name="item_icon[]" value="<?= e($fi['icon'] ?? '') ?>"
                                   placeholder="Icon/Emoji">
                            <input type="text" name="item_title[]" value="<?= e($fi['title'] ?? '') ?>"
                                   placeholder="Feature title">
                            <input type="text" name="item_url[]" value="<?= e($fi['url'] ?? '') ?>"
                                   placeholder="Link URL (optional)">
                            <button type="button" class="btn btn-sm btn-danger"
                                    onclick="this.closest('.feature-item-row').remove()">✕</button>
                        </div>
                        <div style="display:grid;grid-template-columns:1fr;gap:.5rem;">
                            <input type="text" name="item_text[]" value="<?= e($fi['text'] ?? '') ?>"
                                   placeholder="Short description">
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
                <button type="button" class="btn btn-sm btn-secondary" style="margin-top:.5rem;"
                        onclick="addFeatureItem(<?= (int) $section['id'] ?>)">+ Feature hinzufügen</button>
                <small class="form-hint">Icon: Emoji oder Text (z.B. ⚡ 🎯 💡). Link-URL ist optional.</small>
            </div>
            <!-- ── Presentation Config ──── -->
            <hr style="margin:1.25rem 0;border:none;border-top:1px solid #e9ecef;">
            <h5 style="margin:0 0 .75rem;font-size:.85rem;text-transform:uppercase;letter-spacing:.06em;color:#888;">Presentation <small style="font-weight:normal;text-transform:none;letter-spacing:0;color:#bbb;">— leer = Theme-Standard</small></h5>
            <div style="display:grid;grid-template-columns:1fr 1fr 1fr 1fr;gap:.75rem 1.25rem;">
                <div class="form-group" style="margin:0;">
                    <label>Farbschema</label>
                    <select name="color_scheme">
                        <option value="">Theme-Standard</option>
                        <option value="alt"     <?= ($data['color_scheme'] ?? '') === 'alt'     ? 'selected' : '' ?>>Alt (Sekundärhintergrund)</option>
                        <option value="primary" <?= ($data['color_scheme'] ?? '') === 'primary' ? 'selected' : '' ?>>Primary</option>
                        <option value="dark"    <?= ($data['color_scheme'] ?? '') === 'dark'    ? 'selected' : '' ?>>Dunkel</option>
                        <option value="none"    <?= ($data['color_scheme'] ?? '') === 'none'    ? 'selected' : '' ?>>Keiner</option>
                    </select>
                </div>
                <?php render_section_text_color_field($data); ?>
                <div class="form-group" style="margin:0;">
                    <label>Textausrichtung</label>
                    <select name="text_align">
                        <option value="">Theme-Standard</option>
                        <option value="left" <?= ($data['text_align'] ?? '') === 'left' ? 'selected' : '' ?>>Links</option>
                    </select>
                </div>
                <div class="form-group" style="margin:0;">
                    <label>Karten-Stil</label>
                    <select name="card_style">
                        <option value="">Theme-Standard</option>
                        <option value="bordered" <?= ($data['card_style'] ?? '') === 'bordered' ? 'selected' : '' ?>>Umrandet</option>
                        <option value="flat"     <?= ($data['card_style'] ?? '') === 'flat'     ? 'selected' : '' ?>>Flach (kein Schatten)</option>
                    </select>
                </div>
                <div class="form-group" style="margin:0;">
                    <label>Spaltenanzahl</label>
                    <select name="columns">
                        <option value="">Auto (Standard)</option>
                        <option value="2" <?= ($data['columns'] ?? '') === '2' ? 'selected' : '' ?>>2 Spalten</option>
                        <option value="3" <?= ($data['columns'] ?? '') === '3' ? 'selected' : '' ?>>3 Spalten</option>
                        <option value="4" <?= ($data['columns'] ?? '') === '4' ? 'selected' : '' ?>>4 Spalten</option>
                    </select>
                </div>
            </div>
            <?php endif; /* end features theme_admin_partial fallback */ ?>

            <?php elseif ($section['section_key'] === 'gallery_preview'): ?>
            <?php $_theme_gp_partial = theme_admin_partial('gallery_preview'); if ($_theme_gp_partial): ?>
            <?php include $_theme_gp_partial; ?>
            <?php else: ?>
            <!-- Gallery preview fields -->
            <div class="form-group">
                <label>Section Heading</label>
                <input type="text" name="title" value="<?= e($data['title'] ?? '') ?>"
                       placeholder="e.g. Our Work">
            </div>
            <div class="form-group">
                <label>Section Subtitle <small style="font-weight:normal;color:#aaa;">(optional)</small></label>
                <input type="text" name="subtitle" value="<?= e($data['subtitle'] ?? '') ?>"
                       placeholder="e.g. Browse our latest projects">
            </div>
            <div class="form-group">
                <label>Number of albums to show</label>
                <input type="number" name="count" value="<?= (int)($data['count'] ?? 6) ?>" min="1" max="24" style="width:100px;">
                <small class="form-hint">Only visible albums are shown. Section is hidden automatically when no albums exist.</small>
            </div>
            <div class="form-group">
                <label>CTA Button Text</label>
                <input type="text" name="cta_text" value="<?= e($data['cta_text'] ?? '') ?>"
                       placeholder="e.g. View All Albums">
                <small class="form-hint">Leave blank to hide the CTA button.</small>
            </div>
            <div class="form-group">
                <label>CTA Button URL</label>
                <input type="text" name="cta_url" value="<?= e($data['cta_url'] ?? '') ?>"
                       placeholder="/gallery">
            </div>
            <div class="form-group">
                <label>
                    <input type="hidden" name="show_image_count" value="0">
                    <input type="checkbox" name="show_image_count" value="1" <?= !empty($data['show_image_count']) ? 'checked' : '' ?>>
                    Show image count per album
                </label>
            </div>
            <p class="form-hint">
                Manage gallery albums at <a href="/admin/gallery" target="_blank">Gallery &rarr;</a>
            </p>
            <!-- ── Presentation Config ──── -->
            <hr style="margin:1.25rem 0;border:none;border-top:1px solid #e9ecef;">
            <h5 style="margin:0 0 .75rem;font-size:.85rem;text-transform:uppercase;letter-spacing:.06em;color:#888;">Presentation <small style="font-weight:normal;text-transform:none;letter-spacing:0;color:#bbb;">— leer = Theme-Standard</small></h5>
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:.75rem 1.25rem;">
                <div class="form-group" style="margin:0;">
                    <label>Farbschema</label>
                    <select name="color_scheme">
                        <option value="">Theme-Standard</option>
                        <option value="alt"     <?= ($data['color_scheme'] ?? '') === 'alt'     ? 'selected' : '' ?>>Alt (Sekundärhintergrund)</option>
                        <option value="primary" <?= ($data['color_scheme'] ?? '') === 'primary' ? 'selected' : '' ?>>Primary</option>
                        <option value="dark"    <?= ($data['color_scheme'] ?? '') === 'dark'    ? 'selected' : '' ?>>Dunkel</option>
                        <option value="none"    <?= ($data['color_scheme'] ?? '') === 'none'    ? 'selected' : '' ?>>Keiner</option>
                    </select>
                </div>
                <?php render_section_text_color_field($data); ?>
                <div class="form-group" style="margin:0;">
                    <label>Textausrichtung</label>
                    <select name="text_align">
                        <option value="">Theme-Standard</option>
                        <option value="left" <?= ($data['text_align'] ?? '') === 'left' ? 'selected' : '' ?>>Links</option>
                    </select>
                </div>
            </div>
            <?php endif; /* end gallery_preview theme_admin_partial fallback */ ?>

            <?php elseif ($section['section_key'] === 'blog_preview'): ?>
            <?php $_theme_bp_partial = theme_admin_partial('blog_preview'); if ($_theme_bp_partial): ?>
            <?php include $_theme_bp_partial; ?>
            <?php else: ?>
            <!-- Blog preview fields -->
            <div class="form-group">
                <label>Section Heading</label>
                <input type="text" name="title" value="<?= e($data['title'] ?? '') ?>"
                       placeholder="e.g. Latest News">
            </div>
            <div class="form-group">
                <label>Section Subtitle <small style="font-weight:normal;color:#aaa;">(optional)</small></label>
                <input type="text" name="subtitle" value="<?= e($data['subtitle'] ?? '') ?>"
                       placeholder="e.g. Stay up to date with our latest articles">
            </div>
            <div class="form-group">
                <label>Number of posts to show</label>
                <input type="number" name="count" value="<?= (int)($data['count'] ?? 3) ?>" min="1" max="12" style="width:100px;">
                <small class="form-hint">Only published posts are shown. Section is hidden automatically when no posts exist.</small>
            </div>
            <div class="form-group">
                <label>CTA Button Text</label>
                <input type="text" name="cta_text" value="<?= e($data['cta_text'] ?? '') ?>"
                       placeholder="e.g. Read all posts">
                <small class="form-hint">Leave blank to hide the CTA button.</small>
            </div>
            <div class="form-group">
                <label>CTA Button URL</label>
                <input type="text" name="cta_url" value="<?= e($data['cta_url'] ?? '') ?>"
                       placeholder="/blog">
            </div>
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:.75rem 1.25rem;margin-bottom:1rem;">
                <div class="form-group" style="margin:0;">
                    <label>
                        <input type="hidden" name="show_date" value="0">
                        <input type="checkbox" name="show_date" value="1" <?= !empty($data['show_date']) ? 'checked' : '' ?>>
                        Show publish date
                    </label>
                </div>
                <div class="form-group" style="margin:0;">
                    <label>
                        <input type="hidden" name="show_category" value="0">
                        <input type="checkbox" name="show_category" value="1" <?= !empty($data['show_category']) ? 'checked' : '' ?>>
                        Show category badge
                    </label>
                </div>
            </div>
            <p class="form-hint">
                Manage blog posts at <a href="/admin/blog" target="_blank">Blog &rarr;</a>
            </p>
            <!-- ── Presentation Config ──── -->
            <hr style="margin:1.25rem 0;border:none;border-top:1px solid #e9ecef;">
            <h5 style="margin:0 0 .75rem;font-size:.85rem;text-transform:uppercase;letter-spacing:.06em;color:#888;">Presentation <small style="font-weight:normal;text-transform:none;letter-spacing:0;color:#bbb;">— leer = Theme-Standard</small></h5>
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:.75rem 1.25rem;">
                <div class="form-group" style="margin:0;">
                    <label>Farbschema</label>
                    <select name="color_scheme">
                        <option value="">Theme-Standard</option>
                        <option value="alt"     <?= ($data['color_scheme'] ?? '') === 'alt'     ? 'selected' : '' ?>>Alt (Sekundärhintergrund)</option>
                        <option value="primary" <?= ($data['color_scheme'] ?? '') === 'primary' ? 'selected' : '' ?>>Primary</option>
                        <option value="dark"    <?= ($data['color_scheme'] ?? '') === 'dark'    ? 'selected' : '' ?>>Dunkel</option>
                        <option value="none"    <?= ($data['color_scheme'] ?? '') === 'none'    ? 'selected' : '' ?>>Keiner</option>
                    </select>
                </div>
                <?php render_section_text_color_field($data); ?>
                <div class="form-group" style="margin:0;">
                    <label>Textausrichtung</label>
                    <select name="text_align">
                        <option value="">Theme-Standard</option>
                        <option value="left" <?= ($data['text_align'] ?? '') === 'left' ? 'selected' : '' ?>>Links</option>
                    </select>
                </div>
            </div>
            <?php endif; /* end blog_preview theme_admin_partial fallback */ ?>

            <?php elseif ($section['section_key'] === 'events_preview'): ?>
            <?php $_theme_ep_partial = theme_admin_partial('events_preview'); if ($_theme_ep_partial): ?>
            <?php include $_theme_ep_partial; ?>
            <?php else: ?>
            <!-- Events preview fields -->
            <div class="form-group">
                <label>Section Heading</label>
                <input type="text" name="title" value="<?= e($data['title'] ?? '') ?>"
                       placeholder="e.g. Upcoming Events">
            </div>
            <div class="form-group">
                <label>Section Subtitle <small style="font-weight:normal;color:#aaa;">(optional)</small></label>
                <input type="text" name="subtitle" value="<?= e($data['subtitle'] ?? '') ?>"
                       placeholder="e.g. Don't miss our next events">
            </div>
            <div class="form-group">
                <label>Number of events to show</label>
                <input type="number" name="count" value="<?= (int)($data['count'] ?? 3) ?>" min="1" max="12" style="width:100px;">
                <small class="form-hint">Default: 3. Only published upcoming events are shown. Postponed / cancelled events are visually flagged.</small>
            </div>
            <div class="form-group">
                <label>CTA Button Text</label>
                <input type="text" name="cta_text" value="<?= e($data['cta_text'] ?? '') ?>"
                       placeholder="e.g. View all events">
                <small class="form-hint">Leave blank to hide the CTA button.</small>
            </div>
            <div class="form-group">
                <label>CTA Button URL</label>
                <input type="text" name="cta_url" value="<?= e($data['cta_url'] ?? '') ?>"
                       placeholder="/events">
            </div>
            <div class="form-group">
                <label>
                    <input type="hidden" name="show_image" value="0">
                    <input type="checkbox" name="show_image" value="1" <?= !empty($data['show_image']) ? 'checked' : '' ?>>
                    Show event images
                </label>
            </div>
            <p class="form-hint">
                Manage events at <a href="/admin/events" target="_blank">Events &rarr;</a>
            </p>
            <!-- ── Presentation Config ──── -->
            <hr style="margin:1.25rem 0;border:none;border-top:1px solid #e9ecef;">
            <h5 style="margin:0 0 .75rem;font-size:.85rem;text-transform:uppercase;letter-spacing:.06em;color:#888;">Presentation <small style="font-weight:normal;text-transform:none;letter-spacing:0;color:#bbb;">— leer = Theme-Standard</small></h5>
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:.75rem 1.25rem;">
                <div class="form-group" style="margin:0;">
                    <label>Farbschema</label>
                    <select name="color_scheme">
                        <option value="">Theme-Standard</option>
                        <option value="alt"     <?= ($data['color_scheme'] ?? '') === 'alt'     ? 'selected' : '' ?>>Alt (Sekundärhintergrund)</option>
                        <option value="primary" <?= ($data['color_scheme'] ?? '') === 'primary' ? 'selected' : '' ?>>Primary</option>
                        <option value="dark"    <?= ($data['color_scheme'] ?? '') === 'dark'    ? 'selected' : '' ?>>Dunkel</option>
                        <option value="none"    <?= ($data['color_scheme'] ?? '') === 'none'    ? 'selected' : '' ?>>Keiner</option>
                    </select>
                </div>
                <?php render_section_text_color_field($data); ?>
                <div class="form-group" style="margin:0;">
                    <label>Textausrichtung</label>
                    <select name="text_align">
                        <option value="">Theme-Standard</option>
                        <option value="left" <?= ($data['text_align'] ?? '') === 'left' ? 'selected' : '' ?>>Links</option>
                    </select>
                </div>
            </div>
            <?php endif; /* end events_preview theme_admin_partial fallback */ ?>

            <?php elseif ($section['section_key'] === 'cta'): ?>
            <?php $_theme_cta_partial = theme_admin_partial('cta'); if ($_theme_cta_partial): ?>
            <?php include $_theme_cta_partial; ?>
            <?php else: ?>
            <!-- CTA fields -->
            <div class="form-group">
                <label>Eyebrow</label>
                <input type="text" name="eyebrow" value="<?= e($data['eyebrow'] ?? '') ?>"
                       placeholder="e.g. Ready to start?">
            </div>
            <div class="form-group">
                <label>CTA Heading</label>
                <input type="text" name="title" value="<?= e($data['title'] ?? '') ?>"
                       placeholder="e.g. Get in Touch">
            </div>
            <div class="form-group">
                <label>Supporting Text</label>
                <textarea name="text" rows="3" placeholder="A short message encouraging action…"><?= e($data['text'] ?? '') ?></textarea>
                <small class="form-hint">Line breaks are preserved in the frontend.</small>
            </div>
            <div class="form-group">
                <label>Button Text</label>
                <input type="text" name="cta_text" value="<?= e($data['cta_text'] ?? '') ?>"
                       placeholder="e.g. Contact Us">
            </div>
            <div class="form-group">
                <label>Button URL</label>
                <input type="text" name="cta_url" value="<?= e($data['cta_url'] ?? '') ?>"
                       placeholder="/contact">
            </div>
            <div class="form-group">
                <label>Second Button Text</label>
                <input type="text" name="cta2_text" value="<?= e($data['cta2_text'] ?? '') ?>"
                       placeholder="e.g. Learn more">
                <small class="form-hint">Optional second CTA button.</small>
            </div>
            <div class="form-group">
                <label>Second Button URL</label>
                <input type="text" name="cta2_url" value="<?= e($data['cta2_url'] ?? '') ?>"
                       placeholder="/about">
            </div>
            <div class="form-group">
                <label>Background Image</label>
                <input type="text" name="image" value="<?= e($data['image'] ?? '') ?>"
                       placeholder="path/to/image.jpg">
                <small class="form-hint">Relative to /uploads/. Leave blank for solid background.</small>
            </div>
            <!-- ── Presentation Config ──── -->
            <hr style="margin:1.25rem 0;border:none;border-top:1px solid #e9ecef;">
            <h5 style="margin:0 0 .75rem;font-size:.85rem;text-transform:uppercase;letter-spacing:.06em;color:#888;">Presentation <small style="font-weight:normal;text-transform:none;letter-spacing:0;color:#bbb;">— leer = Theme-Standard</small></h5>
            <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:.75rem 1.25rem;">
                <div class="form-group" style="margin:0;">
                    <label>Farbschema</label>
                    <select name="color_scheme">
                        <option value="">Theme-Standard</option>
                        <option value="alt"     <?= ($data['color_scheme'] ?? '') === 'alt'     ? 'selected' : '' ?>>Alt (Sekundärhintergrund)</option>
                        <option value="primary" <?= ($data['color_scheme'] ?? '') === 'primary' ? 'selected' : '' ?>>Primary</option>
                        <option value="dark"    <?= ($data['color_scheme'] ?? '') === 'dark'    ? 'selected' : '' ?>>Dunkel</option>
                        <option value="none"    <?= ($data['color_scheme'] ?? '') === 'none'    ? 'selected' : '' ?>>Keiner</option>
                    </select>
                </div>
                <?php render_section_text_color_field($data); ?>
                <div class="form-group" style="margin:0;">
                    <label>Textausrichtung</label>
                    <select name="text_align">
                        <option value="">Theme-Standard (Zentriert)</option>
                        <option value="left" <?= ($data['text_align'] ?? '') === 'left' ? 'selected' : '' ?>>Links</option>
                    </select>
                </div>
                <div class="form-group" style="margin:0;">
                    <label>Hintergrund-Overlay</label>
                    <select name="overlay_strength">
                        <option value="">Kein Overlay</option>
                        <option value="light"  <?= ($data['overlay_strength'] ?? '') === 'light'  ? 'selected' : '' ?>>Leicht (25%)</option>
                        <option value="medium" <?= ($data['overlay_strength'] ?? '') === 'medium' ? 'selected' : '' ?>>Mittel (45%)</option>
                        <option value="heavy"  <?= ($data['overlay_strength'] ?? '') === 'heavy'  ? 'selected' : '' ?>>Stark (65%)</option>
                    </select>
                </div>
            </div>

            <?php endif; /* end cta theme_admin_partial fallback */ ?>

            <?php elseif ($section['section_key'] === 'topic_cards'): ?>
            <?php $_theme_tc_partial = theme_admin_partial('topic_cards'); if ($_theme_tc_partial): ?>
            <?php include $_theme_tc_partial; ?>
            <?php else: ?>
            <!-- Topic Cards fields -->
            <div class="form-group">
                <label>Section Heading</label>
                <input type="text" name="title" value="<?= e($data['title'] ?? '') ?>"
                       placeholder="z.B. Was wir anbieten">
            </div>
            <div class="form-group">
                <label>Section Subtitle</label>
                <input type="text" name="subtitle" value="<?= e($data['subtitle'] ?? '') ?>"
                       placeholder="Optional subtitle under heading">
            </div>
            <div class="form-group">
                <label>Karten</label>
                <div id="tc-items-<?= (int) $section['id'] ?>" class="section-items-sortable">
                    <?php $tcItems = $data['items'] ?? [['icon' => '', 'title' => '', 'text' => '', 'url' => '']]; ?>
                    <?php foreach ($tcItems as $tci): ?>
                    <div class="tc-item-row section-item-sortable" style="background:#f8f9fa;border:1px solid #e9ecef;border-radius:6px;padding:.75rem;margin-bottom:.5rem;">
                        <div style="display:grid;grid-template-columns:auto 80px 1fr 1fr;gap:.5rem;margin-bottom:.4rem;align-items:start;">
                            <div class="item-move-buttons" style="display:flex;flex-direction:column;gap:.2rem;">
                                <button type="button" class="btn btn-xs item-move-up" title="Move up">▲</button>
                                <button type="button" class="btn btn-xs item-move-down" title="Move down">▼</button>
                            </div>
                            <input type="text" name="tc_icon[]" value="<?= e($tci['icon'] ?? '') ?>"
                                   placeholder="Emoji/Icon">
                            <input type="text" name="tc_title[]" value="<?= e($tci['title'] ?? '') ?>"
                                   placeholder="Titel (Pflicht)">
                            <input type="text" name="tc_url[]" value="<?= e($tci['url'] ?? '') ?>"
                                   placeholder="Link-URL (optional)">
                        </div>
                        <div style="display:grid;grid-template-columns:1fr auto;gap:.5rem;align-items:start;">
                            <input type="text" name="tc_text[]" value="<?= e($tci['text'] ?? '') ?>"
                                   placeholder="Beschreibungstext">
                            <button type="button" class="btn btn-sm btn-danger"
                                    onclick="this.closest('.tc-item-row').remove()">✕</button>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
                <button type="button" class="btn btn-sm btn-secondary" style="margin-top:.5rem;"
                        onclick="addTcItem(<?= (int) $section['id'] ?>)">+ Karte hinzufügen</button>
                <small class="form-hint">Icon: Emoji oder Text (z.B. 🌐 🎨 ⚡). URL ist optional – ohne URL ist die Karte nicht verlinkt.</small>
            </div>
            <!-- ── Presentation Config ──── -->
            <hr style="margin:1.25rem 0;border:none;border-top:1px solid #e9ecef;">
            <h5 style="margin:0 0 .75rem;font-size:.85rem;text-transform:uppercase;letter-spacing:.06em;color:#888;">Presentation <small style="font-weight:normal;text-transform:none;letter-spacing:0;color:#bbb;">— leer = Theme-Standard</small></h5>
            <div style="display:grid;grid-template-columns:1fr 1fr 1fr 1fr;gap:.75rem 1.25rem;">
                <div class="form-group" style="margin:0;">
                    <label>Farbschema</label>
                    <select name="color_scheme">
                        <option value="">Theme-Standard</option>
                        <option value="alt"     <?= ($data['color_scheme'] ?? '') === 'alt'     ? 'selected' : '' ?>>Alt</option>
                        <option value="primary" <?= ($data['color_scheme'] ?? '') === 'primary' ? 'selected' : '' ?>>Primary</option>
                        <option value="dark"    <?= ($data['color_scheme'] ?? '') === 'dark'    ? 'selected' : '' ?>>Dunkel</option>
                        <option value="none"    <?= ($data['color_scheme'] ?? '') === 'none'    ? 'selected' : '' ?>>Keiner</option>
                    </select>
                </div>
                <?php render_section_text_color_field($data); ?>
                <div class="form-group" style="margin:0;">
                    <label>Textausrichtung</label>
                    <select name="text_align">
                        <option value="">Theme-Standard</option>
                        <option value="left" <?= ($data['text_align'] ?? '') === 'left' ? 'selected' : '' ?>>Links</option>
                    </select>
                </div>
                <div class="form-group" style="margin:0;">
                    <label>Karten-Stil</label>
                    <select name="card_style">
                        <option value="">Theme-Standard</option>
                        <option value="bordered" <?= ($data['card_style'] ?? '') === 'bordered' ? 'selected' : '' ?>>Umrandet</option>
                        <option value="flat"     <?= ($data['card_style'] ?? '') === 'flat'     ? 'selected' : '' ?>>Flach</option>
                    </select>
                </div>
                <div class="form-group" style="margin:0;">
                    <label>Spaltenanzahl</label>
                    <select name="columns">
                        <option value="">Auto (Standard)</option>
                        <option value="2" <?= ($data['columns'] ?? '') === '2' ? 'selected' : '' ?>>2 Spalten</option>
                        <option value="3" <?= ($data['columns'] ?? '') === '3' ? 'selected' : '' ?>>3 Spalten</option>
                        <option value="4" <?= ($data['columns'] ?? '') === '4' ? 'selected' : '' ?>>4 Spalten</option>
                    </select>
                </div>
            </div>
            <?php endif; /* end topic_cards theme_admin_partial fallback */ ?>

            <?php elseif ($section['section_key'] === 'highlight_grid'): ?>
            <?php $_theme_hg_partial = theme_admin_partial('highlight_grid'); if ($_theme_hg_partial): ?>
            <?php include $_theme_hg_partial; ?>
            <?php else: ?>
            <!-- Highlight Grid fields -->
            <div class="form-group">
                <label>Section Heading</label>
                <input type="text" name="title" value="<?= e($data['title'] ?? '') ?>"
                       placeholder="z.B. Im Fokus">
            </div>
            <div class="form-group">
                <label>Section Subtitle</label>
                <input type="text" name="subtitle" value="<?= e($data['subtitle'] ?? '') ?>"
                       placeholder="Optional subtitle under heading">
            </div>
            <div class="form-group">
                <label>Einträge</label>
                <div id="hg-items-<?= (int) $section['id'] ?>" class="section-items-sortable">
                    <?php $hgItems = $data['items'] ?? [['icon' => '', 'title' => '', 'text' => '', 'source' => '', 'url' => '']]; ?>
                    <?php foreach ($hgItems as $hgi): ?>
                    <div class="hg-item-row section-item-sortable" style="background:#f8f9fa;border:1px solid #e9ecef;border-radius:6px;padding:.75rem;margin-bottom:.5rem;">
                        <div style="display:grid;grid-template-columns:auto 80px 1fr 1fr;gap:.5rem;margin-bottom:.4rem;align-items:start;">
                            <div class="item-move-buttons" style="display:flex;flex-direction:column;gap:.2rem;">
                                <button type="button" class="btn btn-xs item-move-up" title="Move up">▲</button>
                                <button type="button" class="btn btn-xs item-move-down" title="Move down">▼</button>
                            </div>
                            <input type="text" name="hg_icon[]" value="<?= e($hgi['icon'] ?? '') ?>"
                                   placeholder="Icon">
                            <input type="text" name="hg_title[]" value="<?= e($hgi['title'] ?? '') ?>"
                                   placeholder="Titel (Pflicht)">
                            <input type="text" name="hg_url[]" value="<?= e($hgi['url'] ?? '') ?>"
                                   placeholder="Link-URL (optional)">
                        </div>
                        <div style="display:grid;grid-template-columns:1fr 1fr auto;gap:.5rem;align-items:start;">
                            <input type="text" name="hg_text[]" value="<?= e($hgi['text'] ?? '') ?>"
                                   placeholder="Beschreibung">
                            <input type="text" name="hg_source[]" value="<?= e($hgi['source'] ?? '') ?>"
                                   placeholder="Zusatzinfo/Quelle (optional)">
                            <button type="button" class="btn btn-sm btn-danger"
                                    onclick="this.closest('.hg-item-row').remove()">✕</button>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
                <button type="button" class="btn btn-sm btn-secondary" style="margin-top:.5rem;"
                        onclick="addHgItem(<?= (int) $section['id'] ?>)">+ Eintrag hinzufügen</button>
                <small class="form-hint">Icon ist optional. Hintergrundfarbe über Farbschema steuerbar.</small>
            </div>
            <!-- ── Presentation Config ──── -->
            <hr style="margin:1.25rem 0;border:none;border-top:1px solid #e9ecef;">
            <h5 style="margin:0 0 .75rem;font-size:.85rem;text-transform:uppercase;letter-spacing:.06em;color:#888;">Presentation <small style="font-weight:normal;text-transform:none;letter-spacing:0;color:#bbb;">— leer = Theme-Standard</small></h5>
            <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:.75rem 1.25rem;">
                <div class="form-group" style="margin:0;">
                    <label>Farbschema</label>
                    <select name="color_scheme">
                        <option value="">Theme-Standard</option>
                        <option value="alt"     <?= ($data['color_scheme'] ?? '') === 'alt'     ? 'selected' : '' ?>>Alt</option>
                        <option value="primary" <?= ($data['color_scheme'] ?? '') === 'primary' ? 'selected' : '' ?>>Primary</option>
                        <option value="dark"    <?= ($data['color_scheme'] ?? '') === 'dark'    ? 'selected' : '' ?>>Dunkel</option>
                        <option value="none"    <?= ($data['color_scheme'] ?? '') === 'none'    ? 'selected' : '' ?>>Keiner</option>
                    </select>
                </div>
                <?php render_section_text_color_field($data); ?>
                <div class="form-group" style="margin:0;">
                    <label>Textausrichtung</label>
                    <select name="text_align">
                        <option value="">Theme-Standard</option>
                        <option value="left" <?= ($data['text_align'] ?? '') === 'left' ? 'selected' : '' ?>>Links</option>
                    </select>
                </div>
                <div class="form-group" style="margin:0;">
                    <label>Spaltenanzahl</label>
                    <select name="columns">
                        <option value="">Auto (Standard)</option>
                        <option value="2" <?= ($data['columns'] ?? '') === '2' ? 'selected' : '' ?>>2 Spalten</option>
                        <option value="3" <?= ($data['columns'] ?? '') === '3' ? 'selected' : '' ?>>3 Spalten</option>
                        <option value="4" <?= ($data['columns'] ?? '') === '4' ? 'selected' : '' ?>>4 Spalten</option>
                    </select>
                </div>
            </div>
            <?php endif; /* end highlight_grid theme_admin_partial fallback */ ?>

            <?php else: ?>
            <?php
            // ── Plugin-based section type ────────────────────────────────
            // Check whether the responsible plugin is installed and active.
            $_sKey = $section['section_key'];
            $_pluginDir = (defined('BASE_PATH') ? BASE_PATH : dirname(__DIR__, 3)) . '/plugins';
            // Resolve slug: prefer the section_key→slug map (from plugin.json),
            // fall back to simple underscore-to-dash conversion for legacy plugins.
            $_possibleSlug = $_sectionKeyToSlug[$_sKey] ?? str_replace('_', '-', $_sKey);
            $_pluginInstalled = is_dir($_pluginDir . '/' . $_possibleSlug);
            $_activeSlugs = class_exists('\\App\\Services\\PluginLoader')
                ? \App\Services\PluginLoader::getActiveSlugs(defined('BASE_PATH') ? BASE_PATH : dirname(__DIR__, 3))
                : [];
            $_pluginActive = in_array($_possibleSlug, $_activeSlugs, true);

            // Try to render the plugin admin form via hook
            $pluginFormRendered = false;
            if ($_pluginActive && function_exists('run_hook')) {
                ob_start();
                run_hook('homepage.admin_form', $section, $data, $csrf);
                $pluginForm = ob_get_clean();
                if (trim($pluginForm) !== '') {
                    echo $pluginForm;
                    $pluginFormRendered = true;
                }
            }

            if (!$pluginFormRendered):
                if (!$_pluginInstalled): ?>
            <!-- Plugin not installed -->
            <div class="alert alert-warning" style="margin:0;">
                <strong><?= __('admin.homepage.plugin_not_installed_title') ?></strong>
                <?= __('admin.homepage.plugin_not_installed_text', [':key' => e($_sKey), ':slug' => e($_possibleSlug)]) ?>
                <div style="margin-top:.5rem;">
                    <a href="/admin/plugins" class="btn btn-sm btn-secondary"><?= __('admin.nav.plugins') ?> &rarr;</a>
                </div>
            </div>
                <?php elseif (!$_pluginActive): ?>
            <!-- Plugin installed but inactive -->
            <div class="alert alert-warning" style="margin:0;">
                <strong><?= __('admin.homepage.plugin_inactive_title') ?></strong>
                <?= __('admin.homepage.plugin_inactive_text', [':slug' => e($_possibleSlug)]) ?>
                <div style="margin-top:.5rem;">
                    <a href="/admin/plugins" class="btn btn-sm btn-primary"><?= __('admin.homepage.activate_plugin') ?></a>
                </div>
            </div>
                <?php else: ?>
            <!-- Plugin active but provided no admin form – show raw JSON fallback -->
            <div class="form-group">
                <label>Content (JSON)</label>
                <textarea name="content_raw" rows="8"
                          style="font-family:monospace;"><?= e($section['content'] ?? '{}') ?></textarea>
                <small class="form-hint"><?= __('admin.homepage.raw_json_hint') ?></small>
            </div>
                <?php endif; ?>
            <?php endif; ?>

            <?php
            // Premium theme extra fields for plugin sections:
            // If the active premium theme provides an admin partial for this
            // plugin section key, include it AFTER the plugin's own form.
            // This allows premium themes to add surface/atmosphere options
            // without replacing the plugin's core form.
            $_theme_plugin_partial = theme_admin_partial($section['section_key']);
            if ($_theme_plugin_partial) {
                include $_theme_plugin_partial;
            }
            ?>
            <?php endif; ?>

            <div style="display:flex; gap:.75rem; margin-top:1rem;">
                <button type="submit" class="btn btn-primary"><?= __('admin.homepage.save_section') ?></button>
                <button type="button" class="btn btn-secondary"
                        onclick="toggleSection('section-form-<?= (int) $section['id'] ?>')"><?= __('admin.homepage.cancel') ?></button>
            </div>
        </form>
    </div>
</div>

<?php endforeach; ?>

<script>
function toggleSection(id) {
    const el = document.getElementById(id);
    if (el) el.style.display = el.style.display === 'none' ? 'block' : 'none';
}

function addFeatureItem(sectionId) {
    const container = document.getElementById('feature-items-' + sectionId);
    if (!container) return;
    const row = document.createElement('div');
    row.className = 'feature-item-row section-item-sortable';
    row.style.cssText = 'background:#f8f9fa;border:1px solid #e9ecef;border-radius:6px;padding:.75rem;margin-bottom:.5rem;';
    row.innerHTML = '<div style="display:grid;grid-template-columns:auto 80px 1fr 1fr auto auto;gap:.5rem;margin-bottom:.4rem;align-items:start;">'
        + '<div class="item-move-buttons" style="display:flex;flex-direction:column;gap:.2rem;">'
        + '<button type="button" class="btn btn-xs item-move-up" title="Move up">▲</button>'
        + '<button type="button" class="btn btn-xs item-move-down" title="Move down">▼</button>'
        + '</div>'
        + '<input type="text" name="item_icon[]" placeholder="Icon/Emoji">'
        + '<input type="text" name="item_title[]" placeholder="Feature title">'
        + '<input type="text" name="item_url[]" placeholder="Link URL (optional)">'
        + '<button type="button" class="btn btn-sm btn-danger" onclick="this.closest(\'.feature-item-row\').remove()">✕</button>'
        + '</div><div style="display:grid;grid-template-columns:1fr;gap:.5rem;">'
        + '<input type="text" name="item_text[]" placeholder="Short description">'
        + '</div>';
    container.appendChild(row);
    attachItemSortHandlers(container);
}

function addTcItem(sectionId) {
    const container = document.getElementById('tc-items-' + sectionId);
    if (!container) return;
    const row = document.createElement('div');
    row.className = 'tc-item-row section-item-sortable';
    row.style.cssText = 'background:#f8f9fa;border:1px solid #e9ecef;border-radius:6px;padding:.75rem;margin-bottom:.5rem;';
    row.innerHTML = '<div style="display:grid;grid-template-columns:auto 80px 1fr 1fr;gap:.5rem;margin-bottom:.4rem;align-items:start;">'
        + '<div class="item-move-buttons" style="display:flex;flex-direction:column;gap:.2rem;">'
        + '<button type="button" class="btn btn-xs item-move-up" title="Move up">▲</button>'
        + '<button type="button" class="btn btn-xs item-move-down" title="Move down">▼</button>'
        + '</div>'
        + '<input type="text" name="tc_icon[]" placeholder="Emoji/Icon">'
        + '<input type="text" name="tc_title[]" placeholder="Titel (Pflicht)">'
        + '<input type="text" name="tc_url[]" placeholder="Link-URL (optional)">'
        + '</div><div style="display:grid;grid-template-columns:1fr auto;gap:.5rem;align-items:start;">'
        + '<input type="text" name="tc_text[]" placeholder="Beschreibungstext">'
        + '<button type="button" class="btn btn-sm btn-danger" onclick="this.closest(\'.tc-item-row\').remove()">✕</button>'
        + '</div>';
    container.appendChild(row);
    attachItemSortHandlers(container);
}

function addHgItem(sectionId) {
    const container = document.getElementById('hg-items-' + sectionId);
    if (!container) return;
    const row = document.createElement('div');
    row.className = 'hg-item-row section-item-sortable';
    row.style.cssText = 'background:#f8f9fa;border:1px solid #e9ecef;border-radius:6px;padding:.75rem;margin-bottom:.5rem;';
    row.innerHTML = '<div style="display:grid;grid-template-columns:auto 80px 1fr 1fr;gap:.5rem;margin-bottom:.4rem;align-items:start;">'
        + '<div class="item-move-buttons" style="display:flex;flex-direction:column;gap:.2rem;">'
        + '<button type="button" class="btn btn-xs item-move-up" title="Move up">▲</button>'
        + '<button type="button" class="btn btn-xs item-move-down" title="Move down">▼</button>'
        + '</div>'
        + '<input type="text" name="hg_icon[]" placeholder="Icon">'
        + '<input type="text" name="hg_title[]" placeholder="Titel (Pflicht)">'
        + '<input type="text" name="hg_url[]" placeholder="Link-URL (optional)">'
        + '</div><div style="display:grid;grid-template-columns:1fr 1fr auto;gap:.5rem;align-items:start;">'
        + '<input type="text" name="hg_text[]" placeholder="Beschreibung">'
        + '<input type="text" name="hg_source[]" placeholder="Zusatzinfo/Quelle (optional)">'
        + '<button type="button" class="btn btn-sm btn-danger" onclick="this.closest(\'.hg-item-row\').remove()">✕</button>'
        + '</div>';
    container.appendChild(row);
    attachItemSortHandlers(container);
}

/**
 * Attach move handlers to all sortable item containers.
 * Called on page load and whenever new items are added.
 */
function attachItemSortHandlers(container) {
    container.querySelectorAll('.item-move-up').forEach(btn => {
        btn.addEventListener('click', function(e) {
            e.preventDefault();
            const item = this.closest('.section-item-sortable');
            const prev = item.previousElementSibling;
            if (prev && prev.classList.contains('section-item-sortable')) {
                container.insertBefore(item, prev);
            }
        });
    });
    container.querySelectorAll('.item-move-down').forEach(btn => {
        btn.addEventListener('click', function(e) {
            e.preventDefault();
            const item = this.closest('.section-item-sortable');
            const next = item.nextElementSibling;
            if (next && next.classList.contains('section-item-sortable')) {
                container.insertBefore(next, item);
            }
        });
    });
}

// Auto-open the section that was just saved (based on URL hash)
document.addEventListener('DOMContentLoaded', function () {
    // Attach move handlers to all sortable containers on page load
    document.querySelectorAll('.section-items-sortable').forEach(container => {
        attachItemSortHandlers(container);
    });

    if (window.location.hash) {
        const sectionCard = document.querySelector(window.location.hash);
        if (sectionCard) {
            // Find and open the edit form
            const formId = 'section-form-' + window.location.hash.replace('#section-', '');
            const form = document.getElementById(formId);
            // Don't auto-open after save – just scroll to the card
            sectionCard.scrollIntoView({ behavior: 'smooth', block: 'start' });
        }
    }
});
</script>

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