<?php
ob_start();
$isEdit = !empty($page);
$isSystem = $isEdit && \App\Models\Page::isSystemPage($page);
$systemTypes = \App\Models\Page::systemPageTypes();
$typeLabels = [
    'home' => 'Homepage', 'contact' => 'Contact', 'gallery' => 'Gallery',
    'blog' => 'Blog', 'events' => 'Events', 'downloads' => 'Downloads',
];
?>
<link rel="stylesheet" href="/admin/assets/editor/jodit.min.css">

<div class="content-header">
    <h2><?= $isEdit ? __('admin.pages.edit') : __('admin.pages.create') ?></h2>
    <div style="display:flex;gap:0.5rem;align-items:center;">
        <?php if ($isEdit): ?>
        <a href="/admin/preview/page/<?= (int) $page['id'] ?>" target="_blank" class="btn btn-secondary btn-sm"><?= __('admin.common.preview') ?></a>
        <?php endif; ?>
        <?php if ($isEdit && ($page['status'] ?? '') === 'published' && !empty($page['slug'])): ?>
        <a href="/<?= e($page['slug']) ?>" target="_blank" class="btn btn-secondary btn-sm"><?= __('admin.pages.view_page') ?></a>
        <?php endif; ?>
        <a href="/admin/pages" class="btn btn-secondary"><?= __('admin.pages.back') ?></a>
    </div>
</div>

<?php if ($isSystem): ?>
<div class="alert alert-info" style="margin-bottom:1rem;">
    <strong><?= e($typeLabels[$page['page_type']] ?? ucfirst($page['page_type'])) ?> – System Page</strong><br>
    This is a system/module page. You can edit the title, intro content, SEO fields, and the show-title setting. The slug and template are managed by the CMS core.
</div>
<?php endif; ?>

<form method="POST" action="<?= $isEdit ? '/admin/pages/update/' . (int)$page['id'] : '/admin/pages/store' ?>" class="admin-form" id="pageForm">
    <?= $csrf->field() ?>

    <div class="form-grid">
        <div class="form-main">
            <div class="form-group">
                <label for="title"><?= __('admin.pages.page_title') ?> <span class="required">*</span></label>
                <input type="text" id="title" name="title"
                       value="<?= e($page['title'] ?? '') ?>"
                       required
                       placeholder="<?= __('admin.pages.page_title_placeholder') ?>">
            </div>

            <div class="form-group">
                <label for="slug"><?= __('admin.common.slug') ?></label>
                <div class="slug-preview-wrap">
                    <span class="slug-prefix">/</span>
                    <input type="text" id="slug" name="slug"
                           value="<?= e($page['slug'] ?? '') ?>"
                           placeholder="<?= __('admin.pages.slug_placeholder') ?>"
                           <?= $isSystem ? 'readonly style="background:#f0f0f0;cursor:not-allowed;"' : '' ?>>
                </div>
                <?php if ($isSystem): ?>
                <small class="form-hint">The slug of a system page cannot be changed.</small>
                <?php else: ?>
                <small class="form-hint"><?= __('admin.pages.slug_help') ?></small>
                <?php endif; ?>
            </div>

            <div class="form-group">
                <label for="content"><?= __('admin.pages.content') ?></label>
                <textarea id="content" name="content" rows="15"><?= e($page['content'] ?? '') ?></textarea>
                <div class="editor-footer-row">
                    <small class="form-hint editor-hint"><?= __('admin.pages.content_help') ?></small>
                    <button type="button" class="btn btn-secondary btn-sm media-picker-btn" id="mediaPickerBtn" data-media-picker data-editor-target="content"><?= __('admin.pages.insert_from_library') ?></button>
                </div>
            </div>
        </div>

        <div class="form-sidebar">
            <div class="form-card">
                <h4><?= __('admin.pages.publishing') ?></h4>
                <div class="form-group">
                    <label for="status"><?= __('admin.common.status') ?></label>
                    <select id="status" name="status">
                        <option value="draft"     <?= ($page['status'] ?? 'draft') === 'draft'     ? 'selected' : '' ?>><?= __('admin.common.draft') ?></option>
                        <option value="published" <?= ($page['status'] ?? '') === 'published'       ? 'selected' : '' ?>><?= __('admin.common.published') ?></option>
                    </select>
                </div>
                <?php if (!$isSystem): ?>
                <div class="form-group">
                    <label for="template"><?= __('admin.pages.template') ?></label>
                    <select id="template" name="template">
                        <option value="page"    <?= ($page['template'] ?? 'page') === 'page'    ? 'selected' : '' ?>><?= __('admin.pages.template_default') ?></option>
                        <option value="home"    <?= ($page['template'] ?? '') === 'home'         ? 'selected' : '' ?>><?= __('admin.pages.template_home') ?></option>
                        <option value="contact" <?= ($page['template'] ?? '') === 'contact'      ? 'selected' : '' ?>><?= __('admin.pages.template_contact') ?></option>
                    </select>
                    <small class="form-hint"><?= __('admin.pages.template_help') ?></small>
                </div>
                <?php else: ?>
                <input type="hidden" name="template" value="<?= e($page['template'] ?? 'page') ?>">
                <?php endif; ?>
                <div class="form-group">
                    <label for="sort_order"><?= __('admin.pages.order') ?></label>
                    <input type="number" id="sort_order" name="sort_order"
                           value="<?= (int)($page['sort_order'] ?? 0) ?>"
                           min="0" step="1">
                    <small class="form-hint"><?= __('admin.pages.sort_help') ?></small>
                </div>
                <?php if (!$isSystem || ($page['page_type'] ?? '') === 'home'): ?>
                <div class="form-group">
                    <label class="checkbox-label">
                        <input type="checkbox" name="is_homepage" value="1" <?= !empty($page['is_homepage']) ? 'checked' : '' ?>>
                        <?= __('admin.pages.set_homepage') ?>
                    </label>
                </div>
                <?php endif; ?>
                <div class="form-group">
                    <label class="checkbox-label">
                        <input type="hidden" name="show_title" value="0">
                        <input type="checkbox" name="show_title" value="1" <?= ($page['show_title'] ?? 1) ? 'checked' : '' ?>>
                        <?= __('admin.pages.show_title') ?>
                    </label>
                    <small class="form-hint"><?= __('admin.pages.show_title_help') ?></small>
                </div>
                <button type="submit" class="btn btn-primary btn-full" style="margin-top:0.5rem;">
                    <?= $isEdit ? __('admin.pages.update_page') : __('admin.pages.create_page') ?>
                </button>
            </div>

            <div class="form-card">
                <h4><?= __('admin.pages.seo') ?></h4>
                <div class="form-group">
                    <label for="seo_title"><?= __('admin.pages.seo_title') ?></label>
                    <input type="text" id="seo_title" name="seo_title"
                           value="<?= e($page['seo_title'] ?? '') ?>"
                           placeholder="<?= __('admin.pages.seo_title_default') ?>"
                           maxlength="120">
                    <div class="seo-counter" id="seo_title_counter">
                        <span id="seo_title_len">0</span><?= __('admin.pages.seo_title_hint') ?>
                    </div>
                </div>
                <div class="form-group">
                    <label for="seo_description"><?= __('admin.pages.seo_description') ?></label>
                    <textarea id="seo_description" name="seo_description" rows="3"
                              placeholder="<?= __('admin.pages.seo_description_default') ?>"
                              maxlength="320"><?= e($page['seo_description'] ?? '') ?></textarea>
                    <div class="seo-counter" id="seo_desc_counter">
                        <span id="seo_desc_len">0</span><?= __('admin.pages.seo_description_hint') ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</form>

<!-- ── Media Picker Modal ──────────────────────────────────────────────── -->
<div id="mediaPickerOverlay" class="media-picker-overlay" style="display:none;" role="dialog" aria-modal="true" aria-label="Image Library">
    <div class="media-picker-modal">
        <div class="media-picker-header">
            <h3><?= __('admin.pages.insert_image_title') ?></h3>
            <button type="button" class="media-picker-close" id="mediaPickerClose" aria-label="Close">&times;</button>
        </div>
        <div id="mediaPickerBody">
            <p class="text-muted" style="text-align:center; padding:2rem;"><?= __('admin.common.loading') ?></p>
        </div>
        <div class="media-picker-footer">
            <small class="form-hint"><?= __('admin.pages.insert_image_help') ?></small>
        </div>
    </div>
</div>

<script src="/admin/assets/editor/jodit.min.js"></script>
<script>
(function () {
    // ── Jodit WYSIWYG Editor ──────────────────────────────────────────────
    var contentTextarea = document.getElementById('content');
    var joditEditor     = null;
    if (contentTextarea && typeof Jodit !== 'undefined') {
        joditEditor = Jodit.make(contentTextarea, {
            height: 480,
            language: 'en',
            toolbarSticky: true,
            toolbarStickyOffset: 56, // admin topbar height
            buttons: [
                'bold', 'italic', 'underline', 'strikethrough', 'eraser',
                '|',
                'paragraph', 'fontsize',
                '|',
                'ul', 'ol', 'indent', 'outdent',
                '|',
                'superscript', 'subscript',
                '|',
                'link', 'image',
                '|',
                'table', 'hr',
                '|',
                'align',
                '|',
                'undo', 'redo',
                '\n',
                'find',
                '|',
                'source',
                '|',
                'fullsize'
            ],
            // HTML Preservation – do not strip or modify existing HTML
            cleanHTML: {
                fillEmptyParagraph: false,
                replaceNBSP: false,
                removeEmptyElements: false,
                allowTags: false,
                denyTags: false
            },
            enter: 'P',
            allowResizeX: false,
            allowResizeY: true,
            minHeight: 300,
            // Keep HTML intact when pasting
            processPasteHTML: false,
            askBeforePasteHTML: false,
            askBeforePasteFromWord: false,
            defaultActionOnPaste: 'insert_as_html'
        });
        // Store instance on the element so admin.js can reach it via
        // [data-editor-target] without relying on a global variable.
        contentTextarea._joditEditor = joditEditor;
    }

    // ── Slug Auto-Generation ─────────────────────────────────────────────
    var titleInput = document.getElementById('title');
    var slugInput  = document.getElementById('slug');

    <?php if (!$isEdit): ?>
    if (titleInput && slugInput) {
        titleInput.addEventListener('input', function () {
            if (!slugInput._userEdited) {
                slugInput.value = slugifyTitle(this.value);
            }
        });
        slugInput.addEventListener('input', function () {
            this._userEdited = (this.value.trim() !== '');
        });
    }
    <?php endif; ?>

    function slugifyTitle(str) {
        var map = {
            'ä':'ae','ö':'oe','ü':'ue','Ä':'ae','Ö':'oe','Ü':'ue','ß':'ss',
            'à':'a','á':'a','â':'a','ã':'a','å':'a','æ':'ae',
            'ç':'c','è':'e','é':'e','ê':'e','ë':'e',
            'ì':'i','í':'i','î':'i','ï':'i',
            'ñ':'n','ò':'o','ó':'o','ô':'o','õ':'o','ø':'o',
            'ù':'u','ú':'u','û':'u',
            'ý':'y','þ':'th','ÿ':'y'
        };
        return str
            .replace(/[äöüÄÖÜßàáâãåæçèéêëìíîïñòóôõøùúûýþÿ]/g, function (c) { return map[c] || c; })
            .toLowerCase()
            .replace(/[^a-z0-9]+/g, '-')
            .replace(/^-+|-+$/g, '');
    }

    // ── SEO Character Counters ───────────────────────────────────────────
    function updateCounter(inputId, lenId, limit) {
        var el  = document.getElementById(inputId);
        var len = document.getElementById(lenId);
        if (!el || !len) return;
        function update() {
            var n = el.value.length;
            len.textContent = n;
            len.className = n > limit ? 'seo-over' : (n > limit * 0.9 ? 'seo-warn' : '');
        }
        el.addEventListener('input', update);
        update();
    }

    updateCounter('seo_title',       'seo_title_len', 60);
    updateCounter('seo_description', 'seo_desc_len',  160);

    // Media Picker is wired up by admin.js after it loads, via the
    // [data-media-picker] / [data-editor-target] attributes on the button.
})();
</script>

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