<?php
$L = \App\Helpers\Lang::class; ?>
<div class="fade-in" style="max-width: 1100px; margin: 0 auto;">
    <!-- Page Header -->
    <div style="display: flex; gap: 1rem; align-items: center; margin-bottom: 1.5rem; flex-wrap: wrap;">
        <div style="flex: 1; min-width: 0;">
            <h1 style="font-size: clamp(1.25rem, 4vw, 2rem); margin: 0 0 0.25rem; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;"><?= $L::t('create_discussion') ?></h1>
            <p style="color: var(--text-muted); margin: 0; font-size: 0.9rem;"><?= $L::t('discussion_desc') ?></p>
        </div>
        <div class="hotkey-hint" style="font-size: 0.78rem; color: var(--text-muted); padding: 0.5rem 0.75rem; background: var(--card); border-radius: 0.75rem; border: 1px solid var(--border); white-space: nowrap;">
            <kbd style="background: var(--bg); border: 1px solid var(--border); border-radius: 4px; padding: 2px 5px;">Ctrl</kbd>
            + <kbd style="background: var(--bg); border: 1px solid var(--border); border-radius: 4px; padding: 2px 5px;">Enter</kbd>
            — <?= $L::t('publish_topic_hint') ?>
        </div>
    </div>

    <div class="create-grid" style="display: grid; grid-template-columns: 1fr 280px; gap: 2rem; align-items: start;">
        <!-- Main Form -->
        <div class="card" style="padding: 0; overflow: hidden;">
            <form id="create-form" action="/post/store" method="POST">
                <?= \App\Core\CSRF::field() ?>

                <!-- Toolbar -->
                <div id="editor-toolbar" style="background: var(--bg); border-bottom: 1px solid var(--border); padding: 0.75rem 1.5rem; display: flex; align-items: center; gap: 0.5rem; flex-wrap: wrap;">
                    <span style="font-size: 0.75rem; color: var(--text-muted); margin-right: 0.5rem; font-weight: 600;"><?= $L::t('markdown_toolbar') ?></span>
                    <button type="button" class="md-btn" data-tooltip="Bold (Ctrl+B)" onclick="mdWrap('**','**')" style="font-weight: bold;">B</button>
                    <button type="button" class="md-btn" data-tooltip="Italic (Ctrl+I)" onclick="mdWrap('*','*')" style="font-style: italic;">I</button>
                    <button type="button" class="md-btn" data-tooltip="Code" onclick="mdWrap('`','`')"><i class="fas fa-code" style="font-size: 0.7rem;"></i></button>
                    <button type="button" class="md-btn" data-tooltip="Code Block" onclick="mdWrap('```\n','\n```')"><i class="fas fa-terminal" style="font-size: 0.7rem;"></i></button>
                    <button type="button" class="md-btn" data-tooltip="Blockquote" onclick="mdPrefix('> ')"><i class="fas fa-quote-right" style="font-size: 0.7rem;"></i></button>
                    <button type="button" class="md-btn" data-tooltip="Bullet List" onclick="mdPrefix('- ')"><i class="fas fa-list" style="font-size: 0.7rem;"></i></button>
                    <button type="button" class="md-btn" data-tooltip="Numbered List" onclick="mdPrefix('1. ')"><i class="fas fa-list-ol" style="font-size: 0.7rem;"></i></button>
                    <button type="button" class="md-btn" data-tooltip="Heading" onclick="mdPrefix('## ')"><i class="fas fa-heading" style="font-size: 0.7rem;"></i></button>
                    <button type="button" class="md-btn" data-tooltip="Link" onclick="mdLink()"><i class="fas fa-link" style="font-size: 0.7rem;"></i></button>
                    <button type="button" class="md-btn" data-tooltip="Horizontal Rule" onclick="insertAtCursor('\n---\n')"><i class="fas fa-minus" style="font-size: 0.7rem;"></i></button>
                    <div style="height: 20px; width: 1px; background: var(--border); margin: 0 0.5rem;"></div>
                    <!-- Emoji Quick Insert -->
                    <span style="font-size: 0.75rem; color: var(--text-muted); font-weight: 600; margin-right: 0.25rem;"><?= $L::t('emoji_toolbar') ?></span>
                    <?php foreach(['💡','🚀','🔥','✅','⚠️','❌','🎉','❓','📝'] as $e): ?>
                        <button type="button" class="md-btn emoji-btn" onclick="insertAtCursor('<?= $e ?>')" title="<?= $e ?>"><?= $e ?></button>
                    <?php endforeach; ?>
                </div>

                <div style="padding: 1.75rem 1.75rem 0 1.75rem;">
                    <!-- Title -->
                    <div class="form-group" style="margin-bottom: 1.5rem; position: relative;">
                        <label style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.75rem; font-weight: 700;">
                            <span><?= $L::t('post_title') ?></span>
                            <span id="title-chars" style="font-size: 0.75rem; font-weight: 400; color: var(--text-muted);">0 / 120</span>
                        </label>
                        <input type="text" id="post-title" name="title" class="form-control" placeholder="<?= $L::t('summarize_post') ?>" required maxlength="120" style="padding: 1rem 1.25rem; font-size: 1.05rem;">
                        <!-- Live title preview -->
                        <div id="title-preview" style="margin-top: 0.75rem; padding: 0.75rem 1rem; background: var(--primary-light); border-radius: 0.5rem; border-left: 3px solid var(--primary); display: none;">
                            <span style="font-size: 0.7rem; color: var(--text-muted); font-weight: 600; text-transform: uppercase;">Preview:</span>
                            <p id="title-preview-text" style="margin: 0.25rem 0 0; font-weight: 600; font-size: 1.05rem;"></p>
                        </div>
                    </div>

                    <!-- Category & Type Row -->
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; margin-bottom: 1.5rem;">
                        <div class="form-group">
                            <label style="display: block; margin-bottom: 0.75rem; font-weight: 700;"><?= $L::t('category') ?></label>
                            <select name="category_id" class="form-control" required style="padding: 1rem 1.25rem;">
                                <option value="" disabled selected><?= $L::t('select_category') ?></option>
                                <?php foreach ($categories as $cat): ?>
                                    <option value="<?= $cat['id'] ?>"><?= htmlspecialchars($cat['name']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="form-group">
                            <label style="display: block; margin-bottom: 0.75rem; font-weight: 700;"><?= $L::t('discussion_type') ?></label>
                            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 0.75rem;">
                                <label class="type-selector" style="margin: 0;">
                                    <input type="radio" name="type" value="reddit" checked style="display: none;">
                                    <div class="type-card-mini">
                                        <i class="fas fa-users"></i>
                                        <span><?= $L::t('community_post') ?></span>
                                    </div>
                                </label>
                                <label class="type-selector" style="margin: 0;">
                                    <input type="radio" name="type" value="question" style="display: none;">
                                    <div class="type-card-mini">
                                        <i class="fas fa-question-circle"></i>
                                        <span><?= $L::t('question_qa') ?></span>
                                    </div>
                                </label>
                            </div>
                        </div>
                    </div>

                    <!-- Dual Pane Editor -->
                    <div class="form-group">
                        <label style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.75rem; font-weight: 700;">
                            <span><?= $L::t('content') ?></span>
                            <div style="display: flex; gap: 0.5rem; align-items: center;">
                                <span id="word-count" style="font-size: 0.75rem; color: var(--text-muted);">0 words</span>
                                <span style="color: var(--border);">·</span>
                                <span style="font-size: 0.75rem; color: var(--primary); font-weight: 600;"><i class="fas fa-markdown" style="margin-right: 0.25rem;"></i>Markdown</span>
                            </div>
                        </label>
                        <div class="editor-dual-pane" style="display: grid; grid-template-columns: 1fr 1fr; border: 1px solid var(--border); border-radius: 1rem; overflow: hidden; background: var(--bg);">
                            <div style="position: relative;">
                                <textarea name="content" id="post-editor" class="form-control" rows="18" placeholder="<?= $L::t('write_content') ?>" required style="border: none; border-radius: 0; background: transparent; padding: 1.25rem; resize: none; border-right: 1px solid var(--border); height: 100%; min-height: 350px; font-family: 'JetBrains Mono', 'Fira Code', monospace; font-size: 0.9rem; line-height: 1.7;"></textarea>
                            </div>
                            <div id="markdown-preview" class="markdown-body editor-preview-pane" style="padding: 1.25rem; overflow-y: auto; max-height: 480px; min-height: 350px; position: relative;">
                                <div id="preview-placeholder" style="position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; flex-direction: column; gap: 0.5rem; color: var(--text-muted);">
                                    <i class="fas fa-eye" style="font-size: 2rem; opacity: 0.3;"></i>
                                    <p style="margin: 0; font-style: italic; font-size: 0.9rem;">Preview appears here...</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="create-actions" style="padding: 1rem 1.25rem; border-top: 1px solid var(--border); display: flex; gap: 0.75rem; justify-content: space-between; align-items: center; background: var(--bg); flex-wrap: wrap;">
                    <a href="/" class="btn" style="background: transparent; border: 1px solid var(--border); color: var(--text-muted); padding: 0.65rem 1rem; flex-shrink: 0;">
                        <i class="fas fa-trash-alt"></i> <span class="btn-label"><?= $L::t('discard_draft') ?></span>
                    </a>
                    <button type="submit" id="submit-btn" class="btn btn-primary" style="padding: 0.85rem 2rem; border-radius: 3rem; font-size: 1rem; flex: 1;">
                        <i class="fas fa-rocket"></i> <?= $L::t('publish_discussion') ?>
                    </button>
                </div>
            </form>
        </div>

        <!-- Side Panel: Markdown Cheatsheet + Tips -->
        <div style="display: flex; flex-direction: column; gap: 1.5rem; position: sticky; top: 2rem;">
            <div class="card" style="padding: 1.25rem;">
                <h4 style="margin: 0 0 1rem; font-size: 0.9rem; display: flex; align-items: center; gap: 0.5rem;"><i class="fas fa-info-circle" style="color: var(--primary);"></i> Markdown</h4>
                <div style="font-family: monospace; font-size: 0.8rem; display: flex; flex-direction: column; gap: 0.5rem; color: var(--text-muted);">
                    <div style="display: flex; justify-content: space-between;"><code style="color: var(--text);"># Heading</code><span>Title</span></div>
                    <div style="display: flex; justify-content: space-between;"><code style="color: var(--text);">**bold**</code><span><strong>bold</strong></span></div>
                    <div style="display: flex; justify-content: space-between;"><code style="color: var(--text);">*italic*</code><span><em>italic</em></span></div>
                    <div style="display: flex; justify-content: space-between;"><code style="color: var(--text);">`code`</code><span><code>code</code></span></div>
                    <div style="display: flex; justify-content: space-between;"><code style="color: var(--text);">> quote</code><span>Quote</span></div>
                    <div style="display: flex; justify-content: space-between;"><code style="color: var(--text);">- item</code><span>List</span></div>
                    <div style="display: flex; justify-content: space-between;"><code style="color: var(--text);">[text](url)</code><span>Link</span></div>
                    <div style="display: flex; justify-content: space-between;"><code style="color: var(--text);">```code```</code><span>Block</span></div>
                </div>
            </div>

            <!-- Keyboard Shortcuts -->
            <div class="card" style="padding: 1.25rem;">
                <h4 style="margin: 0 0 1rem; font-size: 0.9rem; display: flex; align-items: center; gap: 0.5rem;"><i class="fas fa-keyboard" style="color: var(--primary);"></i> <?= $L::t('hotkeys_title') ?></h4>
                <div style="display: flex; flex-direction: column; gap: 0.5rem; font-size: 0.8rem; color: var(--text-muted);">
                    <div style="display: flex; justify-content: space-between; align-items: center;"><span><?= $L::t('hotkey_publish') ?></span><code><kbd>Ctrl</kbd>+<kbd>Enter</kbd></code></div>
                    <div style="display: flex; justify-content: space-between; align-items: center;"><span><?= $L::t('hotkey_bold') ?></span><code><kbd>Ctrl</kbd>+<kbd>B</kbd></code></div>
                    <div style="display: flex; justify-content: space-between; align-items: center;"><span><?= $L::t('hotkey_italic') ?></span><code><kbd>Ctrl</kbd>+<kbd>I</kbd></code></div>
                    <div style="display: flex; justify-content: space-between; align-items: center;"><span><?= $L::t('hotkey_tab') ?></span><code><kbd>Tab</kbd></code></div>
                </div>
            </div>

            <!-- Writing Tips -->
            <div class="card" style="padding: 1.25rem; background: rgba(99, 102, 241, 0.05); border-color: rgba(99, 102, 241, 0.2);">
                <h4 style="margin: 0 0 1rem; font-size: 0.9rem; color: var(--primary); display: flex; align-items: center; gap: 0.5rem;"><i class="fas fa-lightbulb"></i> <?= $L::t('tips_title') ?></h4>
                <ul style="margin: 0; padding-left: 1.25rem; font-size: 0.8rem; color: var(--text-muted); display: flex; flex-direction: column; gap: 0.6rem;">
                    <li><?= $L::t('tip_specific_title') ?></li>
                    <li><?= $L::t('tip_code_blocks') ?></li>
                    <li><?= $L::t('tip_category') ?></li>
                    <li><?= $L::t('tip_add_context') ?></li>
                </ul>
            </div>
        </div>
    </div>
</div>

<style>
.md-btn {
    background: var(--card);
    border: 1px solid var(--border);
    color: var(--text);
    width: 32px;
    height: 32px;
    border-radius: 6px;
    cursor: pointer;
    transition: var(--transition);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 0.85rem;
}
.md-btn:hover {
    background: var(--primary);
    color: white;
    border-color: var(--primary);
}
.emoji-btn { font-size: 1rem; }

.type-card-mini {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 0.4rem;
    padding: 0.85rem;
    background: var(--card);
    border: 2px solid var(--border);
    border-radius: 0.75rem;
    transition: var(--transition);
    cursor: pointer;
    text-align: center;
}
.type-card-mini i { font-size: 1.25rem; color: var(--text-muted); }
.type-card-mini span { font-size: 0.75rem; font-weight: 600; }
.type-selector input:checked + .type-card-mini {
    border-color: var(--primary);
    background: var(--primary-light);
}
.type-selector input:checked + .type-card-mini i { color: var(--primary); }
.type-card-mini:hover { transform: translateY(-2px); box-shadow: var(--shadow); }

kbd {
    font-family: 'JetBrains Mono', monospace;
    font-size: 0.7em;
    background: var(--bg);
    border: 1px solid var(--border);
    border-radius: 4px;
    padding: 1px 5px;
}
</style>

<script>
const editor = document.getElementById('post-editor');
const preview = document.getElementById('markdown-preview');
const titleInput = document.getElementById('post-title');
const titlePreview = document.getElementById('title-preview');
const titlePreviewText = document.getElementById('title-preview-text');
const titleChars = document.getElementById('title-chars');
const wordCount = document.getElementById('word-count');
const previewPlaceholder = document.getElementById('preview-placeholder');
const form = document.getElementById('create-form');
const wordCountLabel = '<?= $L::t('words') ?>';
const publishingLabel = '<?= $L::t('publishing') ?>';
const linkPrompt = '<?= $L::t('link_url_prompt') ?>';

// Title character counter + live preview
if (titleInput) {
    titleInput.addEventListener('input', () => {
        const len = titleInput.value.length;
        titleChars.textContent = len + ' / 120';
        titleChars.style.color = len > 100 ? '#ef4444' : 'var(--text-muted)';
        if (titleInput.value.trim().length > 3) {
            titlePreview.style.display = 'block';
            titlePreviewText.textContent = titleInput.value;
        } else {
            titlePreview.style.display = 'none';
        }
    });
}

// Markdown live preview + word count
if (editor && preview) {
    editor.addEventListener('input', () => {
        const val = editor.value;
        if (val.trim()) {
            if (previewPlaceholder) previewPlaceholder.style.display = 'none';
            preview.innerHTML = marked.parse(val);
        } else {
            if (previewPlaceholder) previewPlaceholder.style.display = 'flex';
            // Clear content except placeholder
            Array.from(preview.childNodes).forEach(n => { if (n !== previewPlaceholder) n.remove(); });
        }
        // Word count
        const words = val.trim().split(/\s+/).filter(w => w.length > 0);
        wordCount.textContent = words.length + ' ' + wordCountLabel;
    });

    // Tab key for indentation
    editor.addEventListener('keydown', (e) => {
        if (e.key === 'Tab') {
            e.preventDefault();
            insertAtCursor('    ');
        }
        // Ctrl+B - Bold
        if (e.ctrlKey && e.key === 'b') { e.preventDefault(); mdWrap('**','**'); }
        // Ctrl+I - Italic
        if (e.ctrlKey && e.key === 'i') { e.preventDefault(); mdWrap('*','*'); }
    });
}

// Ctrl+Enter to submit
document.addEventListener('keydown', (e) => {
    if (e.ctrlKey && e.key === 'Enter' && document.activeElement !== document.body) {
        const btn = document.getElementById('submit-btn');
        if (btn) { btn.innerHTML = '<i class="fas fa-spinner fa-spin" style="margin-right: 0.5rem;"></i> ' + publishingLabel; form.submit(); }
    }
});

// Markdown helper functions
function insertAtCursor(text) {
    if (!editor) return;
    const start = editor.selectionStart;
    const end = editor.selectionEnd;
    editor.value = editor.value.substring(0, start) + text + editor.value.substring(end);
    editor.selectionStart = editor.selectionEnd = start + text.length;
    editor.dispatchEvent(new Event('input'));
    editor.focus();
}

function mdWrap(before, after) {
    if (!editor) return;
    const start = editor.selectionStart;
    const end = editor.selectionEnd;
    const selected = editor.value.substring(start, end);
    const replacement = before + (selected || 'text') + after;
    editor.value = editor.value.substring(0, start) + replacement + editor.value.substring(end);
    editor.selectionStart = start + before.length;
    editor.selectionEnd = start + before.length + (selected || 'text').length;
    editor.dispatchEvent(new Event('input'));
    editor.focus();
}

function mdPrefix(prefix) {
    if (!editor) return;
    const start = editor.selectionStart;
    const lineStart = editor.value.lastIndexOf('\n', start - 1) + 1;
    editor.value = editor.value.substring(0, lineStart) + prefix + editor.value.substring(lineStart);
    editor.selectionStart = editor.selectionEnd = start + prefix.length;
    editor.dispatchEvent(new Event('input'));
    editor.focus();
}

function mdLink() {
    const url = prompt(linkPrompt);
    if (url) mdWrap('[', '](' + url + ')');
}
</script>
