<?php
$pageEdit = $page ?? null;
$formAction = !empty($pageEdit) ? '/admin/pages/' . (int)$pageEdit['id'] . '/update' : '/admin/pages/store';
$isEdit = !empty($pageEdit);
$enabledLangs = $enabledLangs ?? [];
$defaultLang = $defaultLang ?? 'en';
$translations = $translations ?? [];

$langTabs = [];
foreach ($enabledLangs as $lang) {
    $code = $lang['code'];
    $isDefault = ($code === $defaultLang);
    $hasTrans = isset($translations[$code]);
    $langTabs[] = [
        'code' => $code,
        'name' => $lang['name'] ?? strtoupper($code),
        'native' => $lang['native_name'] ?? $lang['name'] ?? strtoupper($code),
        'flag' => Translator::flagCode($code),
        'isDefault' => $isDefault,
        'hasTrans' => $hasTrans || $isDefault,
    ];
}
?>

<style>
.lang-tabs { display: flex; gap: 4px; flex-wrap: wrap; margin-bottom: 16px; }
.lang-tab { display: inline-flex; align-items: center; gap: 6px; padding: 6px 14px; border-radius: 8px; font-size: 13px; font-weight: 500; cursor: pointer; border: 1px solid #e5e7eb; background: #fff; color: #6b7280; transition: all .15s; }
.lang-tab:hover { border-color: #3b82f6; color: #3b82f6; }
.lang-tab.active { background: #eff6ff; border-color: #3b82f6; color: #1d4ed8; }
.lang-tab .badge { font-size: 10px; padding: 1px 6px; border-radius: 10px; font-weight: 600; }
.lang-tab .badge-default { background: #dbeafe; color: #1e40af; }
.lang-tab .badge-translated { background: #d1fae5; color: #065f46; }
.lang-panel { display: none; }
.lang-panel.active { display: block; }
.seo-panel { display: none; }
.seo-panel.active { display: block; }
.seo-preview { background: #f9fafb; border: 1px solid #e5e7eb; border-radius: 8px; padding: 12px; margin-top: 8px; }
.seo-preview__title { color: #1a0dab; font-size: 16px; font-weight: 400; line-height: 1.3; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.seo-preview__url { color: #006621; font-size: 12px; margin-top: 2px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.seo-preview__desc { color: #545454; font-size: 12px; line-height: 1.4; margin-top: 2px; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
.char-count { font-size: 11px; text-align: right; margin-top: 2px; color: #9ca3af; }
.char-count.warn { color: #d97706; }
.char-count.over { color: #dc2626; }
.copy-btn { display: inline-flex; align-items: center; gap: 4px; padding: 2px 8px; font-size: 11px; color: #6b7280; background: #f3f4f6; border: 1px solid #e5e7eb; border-radius: 4px; cursor: pointer; transition: all .15s; }
.copy-btn:hover { background: #e5e7eb; color: #374151; }
.editor-toggle { display: inline-flex; border: 1px solid #e5e7eb; border-radius: 6px; overflow: hidden; }
.editor-toggle button { padding: 4px 12px; font-size: 12px; font-weight: 500; border: none; background: #fff; color: #6b7280; cursor: pointer; transition: all .15s; display: inline-flex; align-items: center; gap: 4px; }
.editor-toggle button:not(:last-child) { border-right: 1px solid #e5e7eb; }
.editor-toggle button.active { background: #1d4ed8; color: #fff; }
.editor-toggle button:hover:not(.active) { background: #f3f4f6; }
.html-editor { display: none; width: 100%; min-height: 250px; padding: 12px; border: 1px solid #d1d5db; border-radius: 8px; font-family: 'SF Mono', 'Fira Code', 'Consolas', monospace; font-size: 13px; line-height: 1.6; color: #1f2937; background: #f8fafc; resize: vertical; outline: none; tab-size: 2; }
.html-editor:focus { border-color: #3b82f6; box-shadow: 0 0 0 3px rgba(59,130,246,.15); }
</style>

<form method="POST" action="<?= htmlspecialchars($formAction) ?>" id="pageForm">
    <?= Router::csrfField() ?>

    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        
        <div class="lg:col-span-2 space-y-6">

            <?php if (count($langTabs) > 1): ?>
            <div class="lang-tabs">
                <?php foreach ($langTabs as $i => $lt): ?>
                <button type="button" class="lang-tab<?= $i === 0 ? ' active' : '' ?>" data-lang="<?= $lt['code'] ?>" onclick="switchLangTab('<?= $lt['code'] ?>')">
                    <span class="fi fi-<?= $lt['flag'] ?> fis" style="font-size:14px;"></span>
                    <?= strtoupper($lt['code']) ?>
                    <?php if ($lt['isDefault']): ?>
                        <span class="badge badge-default">Default</span>
                    <?php elseif ($lt['hasTrans']): ?>
                        <span class="badge badge-translated">&#10003;</span>
                    <?php endif; ?>
                </button>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>

            <?php foreach ($langTabs as $i => $lt):
                $code = $lt['code'];
                $isDefault = $lt['isDefault'];
                $prefix = $isDefault ? '' : "trans_{$code}_";
                $trans = $translations[$code] ?? null;
                if ($isDefault) {
                    $fTitle = $pageEdit['title'] ?? '';
                    $fSlug = $pageEdit['slug'] ?? '';
                    $fBody = $pageEdit['body'] ?? '';
                } else {
                    $fTitle = $trans['title'] ?? '';
                    $fSlug = $trans['slug'] ?? '';
                    $fBody = $trans['body'] ?? '';
                }
            ?>
            <div class="lang-panel<?= $i === 0 ? ' active' : '' ?>" data-lang-panel="<?= $code ?>">
                <div class="bg-white rounded-lg shadow-sm border border-gray-200">
                    <div class="px-4 py-3 border-b border-gray-100 flex items-center justify-between">
                        <h3 class="text-sm font-semibold text-gray-700 flex items-center gap-2">
                            <span class="fi fi-<?= $lt['flag'] ?> fis"></span>
                            Content — <?= htmlspecialchars($lt['native']) ?>
                            <?php if ($isDefault): ?><span class="text-xs text-blue-600 font-normal">(Default)</span><?php endif; ?>
                        </h3>
                        <?php if (!$isDefault): ?>
                        <button type="button" class="copy-btn" onclick="copyFromDefault('<?= $code ?>')" title="Copy all fields from default language">
                            <i class="fa-solid fa-copy"></i> Copy from default
                        </button>
                        <?php endif; ?>
                    </div>
                    <div class="p-4 space-y-4">
                        <div>
                            <label for="<?= $prefix ?>title" class="block text-sm font-medium text-gray-700 mb-1">Title</label>
                            <input type="text" id="<?= $prefix ?>title" name="<?= $prefix ?>title" value="<?= htmlspecialchars($fTitle) ?>"
                                   <?= $isDefault ? 'required' : '' ?>
                                   class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none"
                                   data-lang="<?= $code ?>" data-field="title">
                        </div>
                        <div>
                            <label for="<?= $prefix ?>slug" class="block text-sm font-medium text-gray-700 mb-1">Slug <span class="text-xs text-gray-400 font-normal">/...</span></label>
                            <input type="text" id="<?= $prefix ?>slug" name="<?= $prefix ?>slug" value="<?= htmlspecialchars($fSlug) ?>"
                                   class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none"
                                   data-lang="<?= $code ?>" data-field="slug">
                            <p class="mt-1 text-xs text-gray-500">Leave empty to auto-generate from title.</p>
                        </div>
                        <div>
                            <div class="flex items-center justify-between mb-1">
                                <label class="block text-sm font-medium text-gray-700">Content</label>
                                <div class="editor-toggle" data-editor-toggle="<?= $code ?>">
                                    <button type="button" class="active" data-mode="visual" onclick="setEditorMode('<?= $code ?>', 'visual')"><i class="fa-solid fa-pen-to-square" style="font-size:11px;"></i> Visual</button>
                                    <button type="button" data-mode="html" onclick="setEditorMode('<?= $code ?>', 'html')"><i class="fa-solid fa-code" style="font-size:11px;"></i> HTML</button>
                                </div>
                            </div>
                            <div id="editor_wrap_<?= $code ?>">
                                <textarea id="editor_<?= $code ?>" name="<?= $prefix ?>body" rows="15"
                                          class="tinymce-editor w-full px-3 py-2 border border-gray-300 rounded-lg text-sm min-h-[200px] sm:min-h-[300px] resize-y"
                                          data-lang="<?= $code ?>" data-field="body"><?= htmlspecialchars($fBody) ?></textarea>
                                <textarea id="html_editor_<?= $code ?>" class="html-editor" data-lang="<?= $code ?>"><?= htmlspecialchars($fBody) ?></textarea>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>

            
            <div class="bg-white rounded-lg shadow-sm border border-gray-200 px-4 py-2.5">
                <div class="flex items-center gap-2 flex-wrap">
                    <span class="text-xs font-semibold text-gray-500 inline-flex items-center gap-1.5 mr-0.5 shrink-0">
                        <i class="fa-solid fa-puzzle-piece" style="font-size:11px;"></i> Insert widget
                    </span>
                    <?php foreach (Shortcode::widgets() as $wCode => $w): ?>
                    <button type="button" onclick="insertWidget('[<?= htmlspecialchars($wCode) ?>]', this)"
                            title="<?= htmlspecialchars($w['desc']) ?> &mdash; [<?= htmlspecialchars($wCode) ?>]"
                            class="inline-flex items-center gap-1.5 px-2.5 py-1 bg-gray-50 hover:bg-blue-600 hover:text-white hover:border-blue-600 border border-gray-200 rounded-full text-xs font-medium text-gray-700 transition-colors">
                        <i class="<?= htmlspecialchars($w['icon']) ?>" style="font-size:11px;"></i>
                        <?= htmlspecialchars($w['name']) ?>
                    </button>
                    <?php endforeach; ?>
                    <span class="text-[11px] text-gray-400 ml-auto hidden sm:inline">Adds it where your cursor is</span>
                </div>
            </div>

        </div>

        
        <div class="space-y-6">
            
            <div class="bg-white rounded-lg shadow-sm border border-gray-200">
                <div class="px-4 py-3 border-b border-gray-100">
                    <h3 class="text-sm font-semibold text-gray-700">Publish</h3>
                </div>
                <div class="p-4 space-y-4">
                    <div>
                        <label for="status" class="block text-sm font-medium text-gray-700 mb-1">Status</label>
                        <select id="status" name="status" class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none">
                            <option value="draft" <?= (($pageEdit['status'] ?? '') === 'draft') ? 'selected' : '' ?>>Draft</option>
                            <option value="published" <?= (($pageEdit['status'] ?? '') === 'published') ? 'selected' : '' ?>>Published</option>
                        </select>
                    </div>
                    <div class="flex items-center gap-2">
                        <input type="checkbox" id="show_in_footer" name="show_in_footer" value="1" class="w-4 h-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                            <?php if (!empty($pageEdit['show_in_footer'])): ?> checked<?php endif; ?>>
                        <label for="show_in_footer" class="text-sm text-gray-700">Show in footer</label>
                    </div>
                </div>
                <div class="px-4 py-3 border-t border-gray-100 space-y-2">
                    <button type="submit" class="w-full inline-flex items-center justify-center px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded-lg hover:bg-blue-700 transition-colors">
                        <i class="fa-solid fa-check mr-2"></i>
                        <?= $isEdit ? 'Update Page' : 'Create Page' ?>
                    </button>
                    <a href="/admin/pages" class="w-full inline-flex items-center justify-center px-4 py-2 bg-white text-gray-700 text-sm font-medium rounded-lg border border-gray-300 hover:bg-gray-50 transition-colors">Cancel</a>
                </div>
            </div>

            
            <div class="bg-white rounded-lg shadow-sm border border-gray-200">
                <div class="px-4 py-3 border-b border-gray-100">
                    <h3 class="text-sm font-semibold text-gray-700 flex items-center gap-2">
                        <i class="fa-solid fa-magnifying-glass text-gray-400" style="font-size:12px;"></i> SEO
                    </h3>
                </div>
                <?php foreach ($langTabs as $i => $lt):
                    $code = $lt['code'];
                    $isDefault = $lt['isDefault'];
                    $prefix = $isDefault ? '' : "trans_{$code}_";
                    $trans = $translations[$code] ?? null;
                    $fMetaTitle = $isDefault ? ($pageEdit['meta_title'] ?? '') : ($trans['meta_title'] ?? '');
                    $fMetaDesc = $isDefault ? ($pageEdit['meta_description'] ?? '') : ($trans['meta_description'] ?? '');
                ?>
                <div class="seo-panel<?= $i === 0 ? ' active' : '' ?>" data-seo-panel="<?= $code ?>">
                    <div class="p-4 space-y-3">
                        <?php if (count($langTabs) > 1): ?>
                        <div class="text-xs text-gray-500 flex items-center gap-1">
                            <span class="fi fi-<?= $lt['flag'] ?> fis" style="font-size:11px;"></span> <?= strtoupper($code) ?>
                        </div>
                        <?php endif; ?>
                        <div>
                            <label for="<?= $prefix ?>meta_title" class="block text-xs font-medium text-gray-700 mb-1">Meta Title</label>
                            <input type="text" id="<?= $prefix ?>meta_title" name="<?= $prefix ?>meta_title" value="<?= htmlspecialchars($fMetaTitle) ?>"
                                   maxlength="255" class="w-full px-2.5 py-1.5 border border-gray-300 rounded-lg text-xs focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none"
                                   data-lang="<?= $code ?>" data-field="meta_title"
                                   oninput="updateCharCount(this, 60); updateSeoPreview('<?= $code ?>')">
                            <div class="char-count" id="cc_<?= $prefix ?>meta_title">0/60</div>
                        </div>
                        <div>
                            <label for="<?= $prefix ?>meta_description" class="block text-xs font-medium text-gray-700 mb-1">Meta Description</label>
                            <textarea id="<?= $prefix ?>meta_description" name="<?= $prefix ?>meta_description" rows="2"
                                      maxlength="500" class="w-full px-2.5 py-1.5 border border-gray-300 rounded-lg text-xs focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none resize-y"
                                      data-lang="<?= $code ?>" data-field="meta_description"
                                      oninput="updateCharCount(this, 160); updateSeoPreview('<?= $code ?>')"><?= htmlspecialchars($fMetaDesc) ?></textarea>
                            <div class="char-count" id="cc_<?= $prefix ?>meta_description">0/160</div>
                        </div>
                        <div class="seo-preview">
                            <div class="seo-preview__title" id="seo_title_<?= $code ?>">Page Title</div>
                            <div class="seo-preview__url" id="seo_url_<?= $code ?>"><?= htmlspecialchars(rtrim(Setting::get('site_url', 'https://example.com'), '/')) ?>/...</div>
                            <div class="seo-preview__desc" id="seo_desc_<?= $code ?>">Description...</div>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>
</form>

<script src="https://cdnjs.cloudflare.com/ajax/libs/tinymce/7.6.1/tinymce.min.js" referrerpolicy="origin"></script>
<script>
(function() {
    const defaultLang = <?= json_encode($defaultLang) ?>;
    const siteUrl = <?= json_encode(rtrim(Setting::get('site_url', 'https://example.com'), '/')) ?>;
    let currentLang = defaultLang;
    let activeEditorId = null;
    const editorModes = {};
    let pendingContent = {};

    function initEditor(langCode) {
        if (editorModes[langCode] === 'html') return;
        const editorId = 'editor_' + langCode;
        const el = document.getElementById(editorId);
        if (!el) return;
        const existing = tinymce.get(editorId);
        if (existing) { existing.save(); existing.remove(); }
        tinymce.init({
            selector: '#' + editorId,
            plugins: 'lists link image table code fullscreen wordcount',
            toolbar: 'undo redo | blocks | bold italic underline strikethrough | alignleft aligncenter alignright | bullist numlist | link image table | code fullscreen',
            height: 400, menubar: false, branding: false, promotion: false, content_css: false,
            content_style: 'body{font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;font-size:14px;line-height:1.6;color:#1f2937;padding:8px;}',
            setup: function(editor) {
                editor.on('init', function() {
                    if (pendingContent[langCode] !== undefined) {
                        editor.setContent(pendingContent[langCode]);
                        delete pendingContent[langCode];
                    }
                });
                editor.on('change keyup', function() { editor.save(); });
            }
        });
        activeEditorId = editorId;
    }

    window.setEditorMode = function(langCode, mode) {
        const editorId = 'editor_' + langCode;
        const tmcEditor = tinymce.get(editorId);
        const textarea = document.getElementById(editorId);
        const htmlEditor = document.getElementById('html_editor_' + langCode);
        const toggleBtns = document.querySelector('[data-editor-toggle="' + langCode + '"]');
        toggleBtns.querySelectorAll('button').forEach(b => b.classList.remove('active'));
        toggleBtns.querySelector('[data-mode="' + mode + '"]').classList.add('active');
        if (mode === 'html') {
            let content = '';
            if (tmcEditor) { tmcEditor.save(); content = tmcEditor.getContent(); tmcEditor.remove(); }
            else { content = textarea.value; }
            htmlEditor.value = content;
            textarea.value = content;
            textarea.style.display = 'none';
            htmlEditor.style.display = 'block';
            activeEditorId = null;
        } else {
            const htmlContent = htmlEditor.value;
            textarea.value = htmlContent;
            pendingContent[langCode] = htmlContent;
            textarea.style.display = '';
            htmlEditor.style.display = 'none';
            initEditor(langCode);
        }
        editorModes[langCode] = mode;
    };

    window.switchLangTab = function(langCode) {
        if (activeEditorId) { const ed = tinymce.get(activeEditorId); if (ed) { ed.save(); ed.remove(); } }
        if (editorModes[currentLang] === 'html') {
            const htmlEd = document.getElementById('html_editor_' + currentLang);
            const ta = document.getElementById('editor_' + currentLang);
            if (htmlEd && ta) ta.value = htmlEd.value;
        }
        document.querySelectorAll('.lang-tab').forEach(t => t.classList.remove('active'));
        document.querySelectorAll('.lang-panel').forEach(p => p.classList.remove('active'));
        document.querySelectorAll('.seo-panel').forEach(p => p.classList.remove('active'));
        document.querySelector('.lang-tab[data-lang="' + langCode + '"]').classList.add('active');
        document.querySelector('[data-lang-panel="' + langCode + '"]').classList.add('active');
        document.querySelector('[data-seo-panel="' + langCode + '"]').classList.add('active');
        currentLang = langCode;
        if (editorModes[langCode] !== 'html') { setTimeout(() => initEditor(langCode), 50); }
    };

    window.copyFromDefault = function(targetCode) {
        ['title', 'slug', 'meta_title', 'meta_description'].forEach(field => {
            const src = document.querySelector('[data-lang="' + defaultLang + '"][data-field="' + field + '"]');
            const dst = document.querySelector('[data-lang="' + targetCode + '"][data-field="' + field + '"]');
            if (src && dst) { dst.value = src.value; dst.dispatchEvent(new Event('input')); }
        });
        const srcEditor = tinymce.get('editor_' + defaultLang);
        const srcTa = document.getElementById('editor_' + defaultLang);
        const dstEditor = tinymce.get('editor_' + targetCode);
        const dstTa = document.getElementById('editor_' + targetCode);
        let body = srcEditor ? srcEditor.getContent() : (srcTa ? srcTa.value : '');
        if (dstEditor) { dstEditor.setContent(body); dstEditor.save(); }
        else if (dstTa) { dstTa.value = body; }
    };

    
    window.insertWidget = function(code, btn) {
        const lang = currentLang;
        if (editorModes[lang] === 'html') {
            const ta = document.getElementById('html_editor_' + lang);
            if (!ta) return;
            const s = ta.selectionStart != null ? ta.selectionStart : ta.value.length;
            const e = ta.selectionEnd != null ? ta.selectionEnd : ta.value.length;
            ta.value = ta.value.slice(0, s) + code + ta.value.slice(e);
            const mirror = document.getElementById('editor_' + lang);
            if (mirror) mirror.value = ta.value;
            ta.focus();
            ta.selectionStart = ta.selectionEnd = s + code.length;
        } else {
            const ed = tinymce.get('editor_' + lang);
            if (ed) { ed.insertContent(code); ed.save(); ed.focus(); }
            else { const ta = document.getElementById('editor_' + lang); if (ta) { ta.value += code; } }
        }
        if (btn) {
            const html = btn.innerHTML;
            btn.innerHTML = '<i class="fa-solid fa-check" style="font-size:11px;"></i> Added';
            btn.style.background = '#16a34a'; btn.style.color = '#fff'; btn.style.borderColor = '#16a34a';
            setTimeout(function(){ btn.innerHTML = html; btn.style.background = ''; btn.style.color = ''; btn.style.borderColor = ''; }, 1100);
        }
    };

    window.updateCharCount = function(el, max) {
        const len = el.value.length;
        const cc = document.getElementById('cc_' + el.name);
        if (!cc) return;
        cc.textContent = len + '/' + max;
        cc.className = 'char-count' + (len > max ? ' over' : len > max * 0.83 ? ' warn' : '');
    };

    window.updateSeoPreview = function(langCode) {
        const pfx = (langCode === defaultLang) ? '' : 'trans_' + langCode + '_';
        const mt = document.getElementById(pfx + 'meta_title');
        const sl = document.getElementById(pfx + 'slug');
        const md = document.getElementById(pfx + 'meta_description');
        const pt = document.getElementById(pfx + 'title');
        const st = document.getElementById('seo_title_' + langCode);
        const su = document.getElementById('seo_url_' + langCode);
        const sd = document.getElementById('seo_desc_' + langCode);
        if (st) st.textContent = (mt && mt.value) ? mt.value : (pt ? pt.value : 'Page Title') || 'Page Title';
        if (su) su.textContent = siteUrl + ((langCode !== defaultLang) ? '/' + langCode : '') + '/' + ((sl && sl.value) ? sl.value : 'page-slug');
        if (sd) sd.textContent = (md && md.value) ? md.value : 'Description...';
    };

    document.getElementById('pageForm').addEventListener('submit', function() {
        tinymce.triggerSave();
        document.querySelectorAll('.html-editor').forEach(h => {
            if (editorModes[h.dataset.lang] === 'html') {
                const ta = document.getElementById('editor_' + h.dataset.lang);
                if (ta) ta.value = h.value;
            }
        });
    });

    document.querySelectorAll('input[data-field="meta_title"]').forEach(el => { updateCharCount(el, 60); el.addEventListener('input', () => updateSeoPreview(el.dataset.lang)); });
    document.querySelectorAll('textarea[data-field="meta_description"]').forEach(el => { updateCharCount(el, 160); el.addEventListener('input', () => updateSeoPreview(el.dataset.lang)); });
    document.querySelectorAll('input[data-field="title"], input[data-field="slug"]').forEach(el => { el.addEventListener('input', () => updateSeoPreview(el.dataset.lang)); });
    <?php foreach ($langTabs as $lt): ?>updateSeoPreview('<?= $lt['code'] ?>');<?php endforeach; ?>

    initEditor(<?= json_encode($langTabs[0]['code'] ?? $defaultLang) ?>);
})();
</script>
