{% load i18n %}
{% load blog_tags %}


<footer class="entry-meta">
    {% trans 'posted in' %}
    <a href="{{ article.category.get_absolute_url }}" rel="category tag">{{ article.category.name }}</a>
    {% if article.type == 'a' %}
        {% if article.tags.all %}

            {% trans 'and tagged' %}
            {% for t in article.tags.all %}
                <a href="{{ t.get_absolute_url }}" rel="tag">{{ t.name }}</a>
                {% if t != article.tags.all.last %}
                    ,
                {% endif %}
            {% endfor %}


        {% endif %}
    {% endif %}
    .{% trans 'by ' %}
    <span class="by-author">
        <span class="author vcard">
            <a class="url fn n" href="{{ article.author.get_absolute_url }}"
                    {% blocktranslate %}
               title="View all articles published by {{ article.author.username }}"
                    {% endblocktranslate %}
               rel="author">
            <span itemprop="author" itemscope itemtype="http://schema.org/Person">

            <span itemprop="name" itemprop="publisher">

            {{ article.author.username }}
        </span>
            </span>
    </a>
    {% if user.is_authenticated and user != article.author %}
        <button type="button" class="follow-btn {% if is_following %}following{% endif %}"
                data-author-id="{{ article.author.id }}"
                style="margin-left: 10px; padding: 5px 15px; border: 1px solid #ddd; border-radius: 15px; background: {% if is_following %}#28a745{% else %}white{% endif %}; color: {% if is_following %}white{% else %}#333{% endif %}; cursor: pointer; font-size: 12px; transition: all 0.3s;">
            <span class="follow-text">{% if is_following %}已关注{% else %}+ 关注{% endif %}</span>
        </button>
    {% endif %}


        </span>
{% trans 'on' %}
     <a href="{{ article.get_absolute_url }}"
        title="{% datetimeformat article.pub_time %}"
        itemprop="datePublished" content="{% datetimeformat article.pub_time %}"
        rel="bookmark">
        <time class="entry-date updated"
              datetime="{{ article.pub_time }}">
            {% datetimeformat article.pub_time %}
        </time>
    </a>
    {% if user.is_superuser %}
        <a href="{{ article.get_admin_url }}">{% trans 'edit' %}</a>
    {% endif %}
    </span>
</footer><!-- .entry-meta -->

<!-- 关注功能JavaScript -->
<script>
(function() {
    'use strict';

    // 获取CSRF Token
    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }

    // 使用事件委托，避免重复绑定
    document.addEventListener('DOMContentLoaded', function() {
        const followBtns = document.querySelectorAll('.follow-btn');

        followBtns.forEach(function(followBtn) {
            // 检查是否已经绑定过事件
            if (followBtn.hasAttribute('data-follow-bound')) {
                return;
            }
            followBtn.setAttribute('data-follow-bound', 'true');

            followBtn.addEventListener('click', async function(e) {
                e.preventDefault();
                e.stopPropagation();

                const btn = this;
                const authorId = btn.dataset.authorId;
                const isFollowing = btn.classList.contains('following');
                const url = isFollowing ? '{% url "blog:unfollow_user" %}' : '{% url "blog:follow_user" %}';

                // 禁用按钮，防止重复点击
                btn.disabled = true;

                console.log('关注请求:', { authorId, isFollowing, url });

                try {
                    const response = await fetch(url, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRFToken': getCookie('csrftoken'),
                            'X-Requested-With': 'XMLHttpRequest'
                        },
                        credentials: 'same-origin',
                        body: JSON.stringify({ user_id: parseInt(authorId) })
                    });

                    console.log('关注响应状态:', response.status);

                    // 检查是否需要登录
                    if (response.status === 401) {
                        alert('请先登录后再关注');
                        window.location.href = '{% url "account:login" %}?next=' + window.location.pathname;
                        return;
                    }

                    const data = await response.json();
                    console.log('关注响应数据:', data);

                    if (data.success) {
                        // 更新所有相同作者的关注按钮状态
                        const allFollowBtns = document.querySelectorAll(`.follow-btn[data-author-id="${authorId}"]`);

                        allFollowBtns.forEach(function(targetBtn) {
                            if (data.is_following) {
                                targetBtn.classList.add('following');
                                targetBtn.style.background = '#28a745';
                                targetBtn.style.color = 'white';
                                targetBtn.querySelector('.follow-text').textContent = '已关注';
                            } else {
                                targetBtn.classList.remove('following');
                                targetBtn.style.background = 'white';
                                targetBtn.style.color = '#333';
                                targetBtn.querySelector('.follow-text').textContent = '+ 关注';
                            }
                        });
                    } else {
                        // 只显示一次alert
                        alert(data.message || '操作失败');
                    }
                } catch (error) {
                    console.error('关注请求失败:', error);
                    alert('网络错误，请重试');
                } finally {
                    // 重新启用按钮
                    btn.disabled = false;
                }
            }, { once: false });
        });
    });
})();
</script>

