{% extends "base.html" %}

{% block title %}{{ post.subject }} - {{ config.BBS_NAME }}{% endblock %}

{% block content %}
<!-- Original Post -->
<div class="card mb-3">
    <div class="card-header d-flex justify-content-between align-items-center">
        <span>
            {% if post.is_pinned %}<i class="bi bi-pin-angle-fill text-warning" title="Pinned"></i>{% endif %}
            {% if post.is_locked %}<i class="bi bi-lock-fill text-danger" title="Locked"></i>{% endif %}
            {{ post.subject }}
        </span>
        <small>{{ post.created_at.strftime('%Y-%m-%d %H:%M:%S') }}</small>
    </div>
    <div class="card-body">
        <button type="button" id="postToggleMd" class="btn btn-link btn-sm p-0 mb-2">
            <i class="bi bi-markdown"></i> Toggle Markdown view
        </button>
        <a href="{{ url_for('boards.view_post_ansi', post_id=post.id) }}" class="btn btn-link btn-sm p-0 mb-2 ms-2">
            <i class="bi bi-tv"></i> ANSI view
        </a>
        {% if current_user.is_authenticated %}
        <button type="button" class="btn btn-link btn-sm p-0 mb-2 ms-2"
                data-quote-author="{{ post.author.username }}"
                data-quote-target=""
                data-quote-text="{{ post.content | e }}">
            <i class="bi bi-quote"></i> Quote
        </button>
        {% endif %}
        <span class="ms-3">
            {% set msg_type = 'post' %}{% set msg_id = post.id %}
            {% include '_vote_buttons.html' %}
        </span>
        <div id="postBodyPlain" class="ansi-body" style="white-space: pre-wrap;">{{ post.content | msgbody_rich }}</div>
        <div id="postBodyMd" style="display:none;">{{ post.content | markdown }}</div>
        {% if post.author and post.author.signature %}
        <div class="mt-3 pt-2 small text-muted" style="border-top:1px dashed var(--theme-border); white-space: pre-wrap;">
            -- <br>{{ post.author.signature }}
        </div>
        {% endif %}
        <script>
        (function() {
            const btn = document.getElementById('postToggleMd');
            const plain = document.getElementById('postBodyPlain');
            const md = document.getElementById('postBodyMd');
            if (!btn || !plain || !md) return;
            btn.addEventListener('click', () => {
                const showMd = plain.style.display !== 'none';
                plain.style.display = showMd ? 'none' : '';
                md.style.display = showMd ? '' : 'none';
            });
        })();
        </script>
        <hr style="border-color: #00ff00;">
        <div class="d-flex justify-content-between align-items-center">
            <small>
                Posted by <a href="{{ url_for('profile.view_user', username=post.author.username) }}">{{ post.author.username }}</a>
                {% set _gm = (post.author.group_memberships.first() if post.author.group_memberships else None) %}
                {% if _gm and _gm.group and _gm.group.tag %}
                    <span class="badge bg-secondary" title="{{ _gm.group.name }}">{{ _gm.group.tag }}</span>
                {% endif %}
                in <a href="{{ url_for('boards.view_board', board_id=post.board.id) }}">{{ post.board.name }}</a>
            </small>
            {% if current_user.is_authenticated %}
            <div class="d-flex gap-2">
                {% if current_user.is_admin or (current_user.moderating and (current_user.moderating | selectattr('board_id', 'equalto', post.board_id) | list | length) > 0) %}
                <form method="POST" action="{{ url_for('boards.toggle_pin', post_id=post.id) }}" class="d-inline">
                    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                    <button class="btn btn-sm btn-outline-warning" title="Toggle pin">
                        <i class="bi bi-pin-angle"></i> {% if post.is_pinned %}Unpin{% else %}Pin{% endif %}
                    </button>
                </form>
                <form method="POST" action="{{ url_for('boards.toggle_lock', post_id=post.id) }}" class="d-inline">
                    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                    <button class="btn btn-sm btn-outline-danger" title="Toggle lock">
                        <i class="bi bi-lock"></i> {% if post.is_locked %}Unlock{% else %}Lock{% endif %}
                    </button>
                </form>
                {% endif %}
                {% if current_user.id == post.author_id or current_user.is_admin %}
                <form method="POST" action="{{ url_for('boards.delete_post', post_id=post.id) }}" class="d-inline" onsubmit="return confirm('Are you sure you want to delete this post?');">
                    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                    <button type="submit" class="btn btn-danger btn-sm">
                        <i class="bi bi-trash"></i> Delete
                    </button>
                </form>
                {% endif %}
            </div>
            {% endif %}
        </div>
    </div>
</div>

<!-- Replies -->
{% if replies %}
    <div class="card mb-3">
        <div class="card-header">
            <i class="bi bi-chat-dots"></i> Replies ({{ replies|length }})
        </div>
        <div class="card-body">
            {% for reply, depth in replies %}
                <div class="mb-3 p-3"
                     style="background-color:var(--theme-card-bg);
                            border:1px solid var(--theme-primary);
                            border-radius:5px;
                            margin-left:{{ (depth * 24) }}px;">
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <strong>
                            <a href="{{ url_for('profile.view_user', username=reply.author.username) }}">{{ reply.author.username }}</a>
                            {% if depth > 0 %}
                              <small class="text-muted">↳ depth {{ depth }}</small>
                            {% endif %}
                        </strong>
                        <small>{{ reply.created_at.strftime('%Y-%m-%d %H:%M:%S') }}</small>
                    </div>
                    <div class="ansi-body" style="white-space: pre-wrap;">{{ reply.content | msgbody_rich }}</div>
                    {% if reply.author and reply.author.signature %}
                    <div class="mt-2 pt-1 small text-muted" style="border-top:1px dashed var(--theme-border); white-space: pre-wrap;">
                        -- <br>{{ reply.author.signature }}
                    </div>
                    {% endif %}
                    <div class="d-flex gap-2">
                    {% if current_user.is_authenticated %}
                        <button type="button" class="btn btn-link btn-sm p-0"
                                onclick="document.getElementById('replyTo').value='{{ reply.id }}';
                                         document.getElementById('replyToLabel').textContent='Replying to {{ reply.author.username }}';
                                         document.getElementById('replyForm').scrollIntoView({behavior:'smooth'});">
                            <i class="bi bi-reply"></i> Reply
                        </button>
                        <button type="button" class="btn btn-link btn-sm p-0 ms-2"
                                data-quote-author="{{ reply.author.username }}"
                                data-quote-target="{{ reply.id }}"
                                data-quote-text="{{ reply.content | e }}">
                            <i class="bi bi-quote"></i> Quote
                        </button>
                    {% endif %}
                    {% if current_user.is_authenticated and (current_user.id == reply.author_id or current_user.is_admin) %}
                        <form method="POST" action="{{ url_for('boards.delete_post', post_id=reply.id) }}" class="d-inline" onsubmit="return confirm('Are you sure you want to delete this reply?');">
                            <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                            <button type="submit" class="btn btn-danger btn-sm">
                                <i class="bi bi-trash"></i> Delete
                            </button>
                        </form>
                    {% endif %}
                    </div>
                </div>
            {% endfor %}
        </div>
    </div>
{% endif %}

{% if current_user.is_authenticated %}
<div class="mb-3 d-flex gap-2 align-items-center flex-wrap">
    <form method="post" action="{{ url_for('saved.add') }}" class="d-inline-block">
        <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
        <input type="hidden" name="kind" value="post">
        <input type="hidden" name="target_id" value="{{ post.id }}">
        <button type="submit" class="btn btn-outline-warning btn-sm">
            <i class="bi bi-bookmark-star"></i> Save Post
        </button>
    </form>
    {% set reactions = (post.reactions | list) if post.reactions else [] %}
    {% set my_kinds = (reactions | selectattr('user_id', 'equalto', current_user.id) | map(attribute='kind') | list) %}
    {% set rcount = {} %}
    {% for r in reactions %}
        {% set _ = rcount.update({r.kind: rcount.get(r.kind, 0) + 1}) %}
    {% endfor %}
    {% for kind, label in [('like','👍'),('heart','❤️'),('lol','😂'),('wow','😮'),('sad','😢')] %}
    <form method="post" action="{{ url_for('boards.react', post_id=post.id) }}" class="d-inline-block">
        <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
        <input type="hidden" name="kind" value="{{ kind }}">
        <button type="submit" class="btn btn-sm {% if kind in my_kinds %}btn-warning{% else %}btn-outline-secondary{% endif %}">
            {{ label }} {{ rcount.get(kind, 0) }}
        </button>
    </form>
    {% endfor %}
</div>
{% endif %}

<!-- Reply Form -->
{% if post.is_locked and not current_user.is_admin %}
    <div class="card"><div class="card-body text-muted">
        <i class="bi bi-lock"></i> This thread is locked.
    </div></div>
{% elif current_user.is_authenticated %}
    <div class="card" id="replyForm">
        <div class="card-header d-flex justify-content-between">
            <span><i class="bi bi-reply"></i> Post Reply</span>
            <small id="replyToLabel" class="text-muted">Replying to thread</small>
        </div>
        <div class="card-body">
            <form method="POST" action="{{ url_for('boards.reply_post', post_id=post.id) }}">
                {{ form.hidden_tag() }}
                <input type="hidden" name="reply_to" id="replyTo" value="">

                <div class="mb-3">
                    {{ form.content(class="form-control", rows=5, placeholder="Write your reply...") }}
                    {% if form.content.errors %}
                        <div class="invalid-feedback d-block">
                            {% for error in form.content.errors %}{{ error }}{% endfor %}
                        </div>
                    {% endif %}
                </div>

                {{ form.submit(class="btn btn-primary") }}
                <button type="button" class="btn btn-link btn-sm"
                        onclick="document.getElementById('replyTo').value='';
                                 document.getElementById('replyToLabel').textContent='Replying to thread';">
                    Reset to top-level reply
                </button>
            </form>
        </div>
    </div>
{% else %}
    <div class="card">
        <div class="card-body text-center">
            <p>Please <a href="{{ url_for('auth.login') }}">login</a> to reply to this post.</p>
        </div>
    </div>
{% endif %}
<script>
(function() {
    document.querySelectorAll('[data-quote-text]').forEach(btn => {
        btn.addEventListener('click', () => {
            const ta = document.querySelector('#replyForm textarea');
            if (!ta) return;
            const author = btn.dataset.quoteAuthor || 'someone';
            const target = btn.dataset.quoteTarget || '';
            const txt = btn.dataset.quoteText || '';
            const quoted = txt.split(/\r?\n/).map(l => '> ' + l).join('\n');
            const insertion = (ta.value ? '\n\n' : '') +
                              author + ' wrote:\n' + quoted + '\n\n';
            ta.value = ta.value + insertion;
            if (target) {
                const rt = document.getElementById('replyTo');
                const lbl = document.getElementById('replyToLabel');
                if (rt) rt.value = target;
                if (lbl) lbl.textContent = 'Replying to ' + author;
            }
            ta.focus();
            ta.scrollIntoView({behavior:'smooth'});
        });
    });
})();
</script>
{% endblock %}
