{% extends 'gallery/base.html' %}

{% block content %}
<div class="container mx-auto px-4 py-8">
    <!-- 面包屑导航 -->
    <nav class="mb-8">
        <ol class="flex items-center space-x-2 text-sm text-gray-400">
            <li>
                <a href="{% url 'index' %}" class="hover:text-blue-400 transition-colors">Gallery</a>
            </li>
            <li>
                <span class="mx-2">/</span>
            </li>
            {% if artwork.category %}
            <li>
                <a href="{% url 'category' artwork.category.slug %}" class="hover:text-blue-400 transition-colors">
                    {{ artwork.category.name }}
                </a>
            </li>
            <li>
                <span class="mx-2">/</span>
            </li>
            {% endif %}
            <li class="text-gray-300">{{ artwork.title }}</li>
        </ol>
    </nav>

    <!-- 返回按钮 -->
    <div class="mb-6">
        <a href="{% url 'index' %}" class="inline-flex items-center text-blue-400 hover:text-blue-300 transition-colors">
            <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18"></path>
            </svg>
            返回 Gallery
        </a>
    </div>

    <!-- 作品详情内容 -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-8 lg:gap-12 animate-fade-in">
        <!-- 左侧：图片展示 -->
        <div class="space-y-6">
            <!-- 主图 -->
            <div class="relative overflow-hidden rounded-xl bg-dark-card">
                <img
                    src="{{ artwork.image.url }}"
                    alt="{{ artwork.title }}"
                    class="w-full h-auto max-w-full block"
                    loading="eager"
                >

                <!-- 图片信息 -->
                <div class="absolute bottom-4 left-4 right-4 flex justify-end items-center">
                    <div class="text-xs text-gray-400 bg-black/70 px-3 py-1 rounded-full backdrop-blur-sm">
                        {{ artwork.created_at|date:"Y年m月d日" }}
                        {% if artwork.view_count %}
                        · {{ artwork.view_count }} 次浏览
                        {% endif %}
                    </div>
                </div>
            </div>

            <!-- 缩略图导航（如果有多个图片） -->
            {% if prev_artwork or next_artwork %}
            <div class="flex justify-between items-center pt-4 border-t border-gray-800">
                {% if prev_artwork %}
                <a href="{% url 'artwork_detail' prev_artwork.slug %}" class="group flex items-center text-gray-400 hover:text-blue-400 transition-colors">
                    <svg class="w-5 h-5 mr-2 group-hover:-translate-x-1 transition-transform" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path>
                    </svg>
                    <div class="text-right">
                        <div class="text-xs text-gray-500">上一幅</div>
                        <div class="text-sm">{{ prev_artwork.title|truncatechars:20 }}</div>
                    </div>
                </a>
                {% else %}
                <div></div>
                {% endif %}

                {% if next_artwork %}
                <a href="{% url 'artwork_detail' next_artwork.slug %}" class="group flex items-center text-gray-400 hover:text-blue-400 transition-colors">
                    <div class="text-left mr-2">
                        <div class="text-xs text-gray-500">下一幅</div>
                        <div class="text-sm">{{ next_artwork.title|truncatechars:20 }}</div>
                    </div>
                    <svg class="w-5 h-5 group-hover:translate-x-1 transition-transform" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path>
                    </svg>
                </a>
                {% else %}
                <div></div>
                {% endif %}
            </div>
            {% endif %}
        </div>

        <!-- 右侧：作品信息 -->
        <div class="space-y-8">
            <!-- 标题和分类 -->
            <div>
                <h1 class="text-4xl md:text-5xl font-serif font-bold mb-4">{{ artwork.title }}</h1>

                {% if artwork.category %}
                <div class="inline-flex items-center mb-6">
                    <a href="{% url 'category' artwork.category.slug %}" class="px-4 py-2 bg-blue-600/20 text-blue-400 rounded-full hover:bg-blue-600/30 transition-colors">
                        {{ artwork.category.name }}
                    </a>
                    <span class="mx-4 text-gray-500">•</span>
                    <span class="text-gray-400">{{ artwork.created_at|date:"Y年m月d日" }}</span>
                </div>
                {% endif %}
            </div>

            <!-- 作品描述 -->
            <div class="prose prose-invert max-w-none">
                <div class="bg-dark-card rounded-xl p-6 border border-gray-800">
                    <h3 class="text-xl font-semibold mb-4 text-gray-300">作品描述</h3>
                    <div class="text-gray-300 leading-relaxed whitespace-pre-line">
                        {{ artwork.description|linebreaks }}
                    </div>
                </div>
            </div>

            <!-- 作品元数据 -->
            <div class="bg-dark-card rounded-xl p-6 border border-gray-800">
                <h3 class="text-xl font-semibold mb-4 text-gray-300">作品信息</h3>
                <div class="grid grid-cols-2 gap-4">
                    <div>
                        <div class="text-sm text-gray-500">作品编号</div>
                        <div class="text-gray-300 font-mono">ART-{{ artwork.id|stringformat:"04d" }}</div>
                    </div>
                    <div>
                        <div class="text-sm text-gray-500">上传时间</div>
                        <div class="text-gray-300">{{ artwork.created_at|date:"Y-m-d H:i" }}</div>
                    </div>
                    <div>
                        <div class="text-sm text-gray-500">最后更新</div>
                        <div class="text-gray-300">{{ artwork.updated_at|date:"Y-m-d H:i" }}</div>
                    </div>
                    <div>
                        <div class="text-sm text-gray-500">浏览次数</div>
                        <div class="text-gray-300">{{ artwork.view_count }}</div>
                    </div>
                    <div>
                        <div class="text-sm text-gray-500">排序序号</div>
                        <div class="text-gray-300">{{ artwork.order }}</div>
                    </div>
                </div>
            </div>

            <!-- 分享和操作 -->
            <div class="flex flex-wrap gap-4">
                <button onclick="shareArtwork()" class="flex-1 md:flex-none px-6 py-3 bg-gray-800 hover:bg-gray-700 text-gray-300 rounded-lg transition-colors flex items-center justify-center">
                    <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8.684 13.342C8.886 12.938 9 12.482 9 12c0-.482-.114-.938-.316-1.342m0 2.684a3 3 0 110-2.684m0 2.684l6.632 3.316m-6.632-6l6.632-3.316m0 0a3 3 0 105.367-2.684 3 3 0 00-5.367 2.684zm0 9.316a3 3 0 105.368 2.684 3 3 0 00-5.368-2.684z"></path>
                    </svg>
                    分享作品
                </button>

                <a href="{{ artwork.image.url }}" download class="flex-1 md:flex-none px-6 py-3 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors flex items-center justify-center">
                    <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"></path>
                    </svg>
                    下载原图
                </a>
            </div>
        </div>
    </div>

    <!-- 相关作品（同分类） -->
    {% if related_artworks %}
    <div class="mt-16 pt-12 border-t border-gray-800">
        <h2 class="text-2xl font-semibold mb-6">同分类作品</h2>
        <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
            {% for related in related_artworks %}
            <a href="{% url 'artwork_detail' related.slug %}" class="group">
                <div class="relative overflow-hidden rounded-lg bg-dark-card">
                    <img
                        data-src="{{ related.thumbnail.url|default:related.image.url }}"
                        alt="{{ related.title }}"
                        class="lazy-image w-full h-48 object-cover transition-transform duration-300 group-hover:scale-105"
                        loading="lazy"
                    >
                    <div class="absolute inset-0 bg-black/0 group-hover:bg-black/40 transition-all duration-300"></div>
                    <div class="p-3">
                        <h3 class="text-sm font-medium text-gray-300 group-hover:text-blue-400 transition-colors truncate">
                            {{ related.title }}
                        </h3>
                    </div>
                </div>
            </a>
            {% endfor %}
        </div>
    </div>
    {% endif %}

    <!-- 评论区域 -->
    <section class="mt-16 pt-12 border-t border-gray-800" id="comments">
        <div class="mb-6">
            <h2 class="text-2xl font-bold text-white mb-2">
                评论 <span class="text-gray-400">({{ comment_count }})</span>
            </h2>
            <p class="text-gray-400">分享您对这幅作品的看法</p>
        </div>

        <!-- 评论表单（登录用户可见） -->
        {% if user.is_authenticated %}
            {% include "gallery/comments/comment_form.html" %}
        {% else %}
            <div class="bg-gray-900 border border-gray-800 rounded-lg p-6 mb-8">
                <p class="text-white mb-4">请登录后发表评论</p>
                <a href="{% url 'login' %}"
                   class="inline-flex items-center px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition duration-200">
                    立即登录
                </a>
            </div>
        {% endif %}

        <!-- 评论列表 -->
        {% include "gallery/comments/comment_list.html" %}
    </section>
</div>
{% endblock %}

{% block extra_js %}
<script>
    // 分享功能
    function shareArtwork() {
        if (navigator.share) {
            navigator.share({
                title: '{{ artwork.title|escapejs }} - YITAO-REN GALLERY',
                text: '{{ artwork.description|truncatechars:100|escapejs }}',
                url: window.location.href,
            })
            .then(() => console.log('分享成功'))
            .catch((error) => console.log('分享失败:', error));
        } else {
            // 复制链接到剪贴板
            navigator.clipboard.writeText(window.location.href)
                .then(() => alert('链接已复制到剪贴板！'))
                .catch(err => alert('复制失败，请手动复制链接。'));
        }
    }

    // 图片缩放功能
    const mainImage = document.querySelector('img[alt="{{ artwork.title }}"]');
    if (mainImage) {
        mainImage.addEventListener('click', function() {
            this.classList.toggle('cursor-zoom-out');
            this.classList.toggle('cursor-zoom-in');
            this.classList.toggle('scale-150');
            this.classList.toggle('origin-center');
        });
    }

    // 键盘导航
    document.addEventListener('keydown', function(e) {
        if (e.key === 'ArrowLeft' && {% if prev_artwork %}true{% else %}false{% endif %}) {
            window.location.href = "{% if prev_artwork %}{% url 'artwork_detail' prev_artwork.slug %}{% endif %}";
        } else if (e.key === 'ArrowRight' && {% if next_artwork %}true{% else %}false{% endif %}) {
            window.location.href = "{% if next_artwork %}{% url 'artwork_detail' next_artwork.slug %}{% endif %}";
        } else if (e.key === 'Escape') {
            window.location.href = "{% url 'index' %}";
        }
    });

    // 评论图片预览
    const commentImageInput = document.querySelector('input[name="image"]');
    if (commentImageInput) {
        const imagePreview = document.createElement('div');
        imagePreview.className = 'mt-4 hidden';
        imagePreview.innerHTML = `
            <p class="text-gray-400 text-sm mb-2">图片预览</p>
            <img class="max-w-full h-auto rounded-lg border border-gray-800 max-h-48 object-contain">
            <button type="button" class="mt-2 text-red-400 hover:text-red-300 text-sm">
                移除图片
            </button>
        `;
        commentImageInput.parentNode.insertBefore(imagePreview, commentImageInput.nextSibling);

        const previewImg = imagePreview.querySelector('img');
        const removeBtn = imagePreview.querySelector('button');

        commentImageInput.addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    previewImg.src = e.target.result;
                    imagePreview.classList.remove('hidden');
                };
                reader.readAsDataURL(file);
            } else {
                imagePreview.classList.add('hidden');
            }
        });

        removeBtn.addEventListener('click', function() {
            commentImageInput.value = '';
            imagePreview.classList.add('hidden');
        });
    }

    // 评论表单验证
    const commentForm = document.querySelector('form[action*="comment/add"]');
    if (commentForm) {
        commentForm.addEventListener('submit', function(e) {
            const textarea = this.querySelector('textarea[name="text"]');
            const fileInput = this.querySelector('input[name="image"]');

            if (!textarea.value.trim() && !fileInput.files.length) {
                e.preventDefault();
                alert('请填写评论内容或上传图片');
                textarea.focus();
            }
        });
    }

    // 滚动到评论区域（如果URL中有#comments）
    if (window.location.hash === '#comments') {
        const commentsSection = document.getElementById('comments');
        if (commentsSection) {
            setTimeout(() => {
                commentsSection.scrollIntoView({ behavior: 'smooth' });
            }, 100);
        }
    }

    // 评论删除确认
    document.addEventListener('submit', function(e) {
        if (e.target.action && e.target.action.includes('comment/delete')) {
            if (!confirm('确定要删除这条评论吗？此操作不可撤销。')) {
                e.preventDefault();
            }
        }
    });
</script>
{% endblock %}
