{% extends "base.html" %}
{% load i18n %}

{% block content %}
<div class="container mx-auto px-4 py-8">
    <div class="flex justify-between items-center mb-6">
        <h1 class="text-2xl font-bold">{% trans "Tags" %}</h1>
        <a href="{% url 'tag-create' %}" class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">
            {% trans "New Tag" %}
        </a>
    </div>

    <!-- Tag Cloud Section -->
    <div class="bg-white rounded-lg shadow-md p-6 mb-8">
        <h2 class="text-xl font-semibold mb-4">{% trans "Tag Cloud" %}</h2>
        <div id="tag-cloud-container" style="width: 100%; height: 400px;"></div>
    </div>

    <!-- Sort Controls and Filter -->
    <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 mb-6">
        <div class="flex flex-wrap gap-2">
            <span class="text-gray-700 font-medium self-center mr-2">{% trans "Sort by:" %}</span>
            <a href="?sort=name" class="sort-btn px-3 py-1 rounded text-sm {% if current_sort == 'name' %}bg-blue-500 text-white{% else %}bg-gray-200 text-gray-700 hover:bg-gray-300{% endif %}">
                {% trans "Name (A-Z)" %}
            </a>
            <a href="?sort=name_desc" class="sort-btn px-3 py-1 rounded text-sm {% if current_sort == 'name_desc' %}bg-blue-500 text-white{% else %}bg-gray-200 text-gray-700 hover:bg-gray-300{% endif %}">
                {% trans "Name (Z-A)" %}
            </a>
            <a href="?sort=count" class="sort-btn px-3 py-1 rounded text-sm {% if current_sort == 'count' %}bg-blue-500 text-white{% else %}bg-gray-200 text-gray-700 hover:bg-gray-300{% endif %}">
                {% trans "Most Used" %}
            </a>
            <a href="?sort=count_asc" class="sort-btn px-3 py-1 rounded text-sm {% if current_sort == 'count_asc' %}bg-blue-500 text-white{% else %}bg-gray-200 text-gray-700 hover:bg-gray-300{% endif %}">
                {% trans "Least Used" %}
            </a>
        </div>

        <!-- Quick Filter Input -->
        <div class="w-full sm:w-64 relative">
            <input type="text" id="filter-tags-input" placeholder="{% trans 'Filter tags...' %}"
                   class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent">
            <div class="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none">
                <svg class="h-4 w-4 text-gray-400" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
                    <path fill-rule="evenodd" d="M8 4a4 4 0 100 8 4 4 0 000-8zM2 8a6 6 0 1110.89 3.476l4.817 4.817a1 1 0 01-1.414 1.414l-4.816-4.816A6 6 0 012 8z" clip-rule="evenodd" />
                </svg>
            </div>
        </div>
    </div>

    <div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4" id="tags-grid">
        {% for tag in tags %}
        <a href="{% url 'tag-detail' tag.slug %}" class="block group tag-item" data-tag-name="{{ tag.name|lower }}">
            <div
                class="tag-card rounded-lg p-2 h-full flex flex-col items-center justify-center text-center shadow-md hover:shadow-lg transition-all duration-200">
                <div class="mb-2">
                    {% with icon_classes="w-8 h-8 mx-auto" %}
                    {% if forloop.counter|divisibleby:5 %}
                    <svg class="{{ icon_classes }}" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"
                        stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                            d="M7 8h10M7 12h4m1 8l-4-4H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-3l-4 4z" />
                    </svg>
                    {% elif forloop.counter|divisibleby:4 %}
                    <svg class="{{ icon_classes }}" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"
                        stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                            d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
                    </svg>
                    {% elif forloop.counter|divisibleby:3 %}
                    <svg class="{{ icon_classes }}" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"
                        stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                            d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                    </svg>
                    {% elif forloop.counter|divisibleby:2 %}
                    <svg class="{{ icon_classes }}" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"
                        stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                            d="M8 7v8a2 2 0 002 2h6M8 7V5a2 2 0 012-2h4.586a1 1 0 01.707.293l4.414 4.414a1 1 0 01.293.707V15a2 2 0 01-2 2h-2M8 7H6a2 2 0 00-2 2v10a2 2 0 002 2h8a2 2 0 002-2v-2" />
                    </svg>
                    {% else %}
                    <svg class="{{ icon_classes }}" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"
                        stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                            d="M5 5a2 2 0 012-2h10a2 2 0 012 2v16l-7-3.5L5 21V5z" />
                    </svg>
                    {% endif %}
                    {% endwith %}
                </div>
                <h2 class="text-lg font-semibold mb-1">{{ tag.name }}</h2>
                <div class="mt-1">
                    <span
                        class="inline-flex items-center justify-center bg-white bg-opacity-30 text-xs font-medium px-2 py-1 rounded-full">
                        {{ tag.total_count }} {% trans "uses" %}
                    </span>
                </div>
            </div>
        </a>
        {% empty %}
        <div class="col-span-full text-center py-8 text-gray-500">
            {% trans "No tags found." %}
        </div>
        {% endfor %}
    </div>

    <!-- No results message (hidden by default) -->
    <div id="no-results-message" class="hidden col-span-full text-center py-8 text-gray-500">
        {% trans "No matching tags found." %}
    </div>
</div>

<!-- ECharts (CDN — page-specific, benefits from edge proximity) -->
<script src="https://cdn.jsdelivr.net/npm/echarts@5.6.0/dist/echarts.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/echarts-wordcloud@2.1.0/dist/echarts-wordcloud.min.js"></script>

<script>
    document.addEventListener('DOMContentLoaded', function () {
        // Define colors for tags - using colors from the image
        const tagColors = [
            '#3498db', // blue
            '#2ecc71', // green
            '#e74c3c', // red
            '#f39c12', // orange
            '#9b59b6', // purple
            '#1abc9c', // teal
            '#d35400', // dark orange
            '#34495e', // navy
            '#16a085', // dark green
            '#27ae60', // medium green
            '#8e44ad', // violet
            '#f1c40f'  // yellow
        ];

        // Apply colors to tag cards
        const tagCards = document.querySelectorAll('.tag-card');

        tagCards.forEach((card, index) => {
            const randomColor = tagColors[Math.floor(Math.random() * tagColors.length)];
            card.style.backgroundColor = randomColor;
            card.style.color = 'white';
        });

        // Initialize ECharts instance
        const chartDom = document.getElementById('tag-cloud-container');
        const myChart = echarts.init(chartDom);

        // Prepare data for word cloud
        const tagCloudData = [];
        {% for tag in tag_cloud %}
        tagCloudData.push({
            name: '{{ tag.name }}',
            value: {{ tag.count }},
            slug: '{{ tag.slug }}'
        });
        {% endfor %}

        // Configure word cloud options
        const option = {
            series: [{
                type: 'wordCloud',
                shape: 'circle',
                left: 'center',
                top: 'center',
                width: '100%',
                height: '100%',
                right: null,
                bottom: null,
                sizeRange: [14, 60],  // Increased max size for better visibility
                rotationRange: [0, 0],  // No rotation for better readability like in the image
                rotationStep: 0,
                gridSize: 15,  // Increased grid size for better spacing
                drawOutOfBound: false,
                layoutAnimation: true,  // Enable animation when rendering
                textStyle: {
                    fontFamily: 'sans-serif',
                    fontWeight: 'bold',
                    color: function () {
                        return tagColors[Math.floor(Math.random() * tagColors.length)];
                    }
                },
                emphasis: {
                    textStyle: {
                        fontWeight: 'bold',
                        shadowBlur: 10,
                        shadowColor: '#333'
                    }
                },
                data: tagCloudData
            }]
        };

        // Set configuration and render chart
        myChart.setOption(option);

        // Add click event to navigate to tag detail page
        myChart.on('click', function(params) {
            const clickedTag = tagCloudData.find(tag => tag.name === params.name);
            if (clickedTag) {
                window.location.href = `/ui/tags/${clickedTag.slug}/`;
            }
        });

        // Make chart responsive
        window.addEventListener('resize', function() {
            myChart.resize();
        });
    });

    // Quick filter functionality
    document.addEventListener('DOMContentLoaded', function() {
        const filterInput = document.getElementById('filter-tags-input');
        const tagItems = document.querySelectorAll('.tag-item');
        const noResultsMessage = document.getElementById('no-results-message');

        if (filterInput && tagItems.length > 0) {
            filterInput.addEventListener('keyup', function() {
                const filterTerm = this.value.toLowerCase().trim();
                let visibleCount = 0;

                tagItems.forEach(function(item) {
                    const tagName = item.getAttribute('data-tag-name');

                    if (tagName && tagName.includes(filterTerm)) {
                        item.style.display = '';
                        visibleCount++;
                    } else {
                        item.style.display = 'none';
                    }
                });

                // Show/hide no results message
                if (visibleCount === 0 && filterTerm.length > 0) {
                    noResultsMessage.classList.remove('hidden');
                } else {
                    noResultsMessage.classList.add('hidden');
                }
            });
        }
    });
</script>
{% endblock %}
