<?php ob_start(); ?>

<div class="content-header">
    <h2><?= __('admin.settings.title') ?></h2>
</div>

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

<form method="POST" action="/admin/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="2"><?= e($settings['footer_text'] ?? '') ?></textarea>
                </div>
                <div class="form-group">
                    <label for="copyright"><?= __('admin.settings.copyright') ?></label>
                    <input type="text" id="copyright" name="copyright"
                           value="<?= e($settings['copyright'] ?? '') ?>">
                </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>

            <!-- 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>

            <!-- 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>

        </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/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;');
    }
}());
</script>

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