{% extends "base.html" %}
{% load i18n static %}
{% block content %}
<style>
  /* ── Apple design tokens (same system as Files / Collections) ── */
  :root {
    --apple-blue: #0071e3; --apple-green: #27ae60; --apple-text: #1d1d1f;
    --apple-gray: #86868b; --apple-separator: rgba(0, 0, 0, 0.06);
    --apple-bg: #f5f5f7; --apple-radius-lg: 22px;
    --apple-ease: cubic-bezier(.25, .1, .25, 1);
    --apple-shadow-lift: 0 18px 44px rgba(0, 0, 0, 0.12);
  }

  .tags-page {
    max-width: 1080px; margin: 0 auto; padding: 2rem 1.25rem 3rem;
    color: var(--apple-text);
  }

  /* ── Header ── */
  .tags-header {
    display: flex; align-items: center; justify-content: space-between; gap: 1rem;
    margin-bottom: 1.4rem;
  }
  .tags-header h1 {
    font-size: 2.1rem; font-weight: 700; letter-spacing: -0.02em; margin: 0 0 0.2rem;
  }
  .tags-header .count { font-size: 0.9rem; color: var(--apple-gray); margin: 0; }
  .apple-btn {
    display: inline-flex; align-items: center; gap: 0.45rem;
    min-height: 40px; padding: 0.5rem 1.15rem; border-radius: 980px;
    font-size: 0.875rem; font-weight: 600; text-decoration: none; border: none; cursor: pointer;
    transition: background 0.25s ease, transform 0.2s var(--apple-ease), box-shadow 0.25s ease;
  }
  .apple-btn-primary { background: var(--apple-blue); color: #fff; box-shadow: 0 8px 22px rgba(0, 113, 227, 0.32); }
  .apple-btn-primary:hover { background: #2487e6; }
  .apple-btn-primary:active { transform: scale(0.96); }

  /* ── Apple card ── */
  .apple-card {
    background: #fff; border-radius: var(--apple-radius-lg);
    border: 1px solid rgba(0, 0, 0, 0.05);
    box-shadow: 0 4px 18px rgba(0, 0, 0, 0.05);
    padding: 1.4rem 1.5rem; margin-bottom: 1.25rem;
  }
  .apple-card h2 { font-size: 1.05rem; font-weight: 700; margin: 0 0 1rem; }

  /* ── Word cloud ── */
  #tag-cloud-container { width: 100%; height: 380px; }
  @media (max-width: 640px) { #tag-cloud-container { height: 300px; } }

  /* ── Toolbar: sort segmented + search ── */
  .tags-toolbar {
    display: flex; align-items: center; justify-content: space-between; gap: 0.9rem;
    margin-bottom: 1.1rem; flex-wrap: wrap;
  }
  .sort-segmented {
    display: inline-flex; padding: 3px; gap: 2px;
    background: rgba(0, 0, 0, 0.055); border-radius: 12px;
  }
  .sort-btn {
    padding: 0.42rem 0.85rem; border-radius: 9px;
    font-size: 0.8rem; font-weight: 600; color: var(--apple-text);
    text-decoration: none; white-space: nowrap;
    transition: background 0.2s ease, color 0.2s ease, box-shadow 0.2s ease;
  }
  .sort-btn:hover { background: rgba(0, 0, 0, 0.05); }
  .sort-btn.active { background: #fff; color: var(--apple-text); box-shadow: 0 1px 5px rgba(0, 0, 0, 0.12); }
  .tags-search { position: relative; flex: 1; min-width: 220px; max-width: 300px; }
  .tags-search svg {
    position: absolute; left: 0.85rem; top: 50%; transform: translateY(-50%);
    width: 1rem; height: 1rem; color: var(--apple-gray); pointer-events: none;
  }
  .tags-search input {
    width: 100%; height: 40px; padding: 0 1rem 0 2.35rem;
    border: 1px solid rgba(0, 0, 0, 0.07); border-radius: 12px;
    background: #fff; font-size: 0.875rem; color: var(--apple-text);
    transition: border-color 0.25s ease, box-shadow 0.25s ease;
  }
  .tags-search input::placeholder { color: var(--apple-gray); }
  .tags-search input:focus {
    outline: none; border-color: rgba(0, 113, 227, 0.45);
    box-shadow: 0 0 0 4px rgba(0, 113, 227, 0.12);
  }

  /* ── Tag grid ── */
  .tags-grid {
    display: grid; gap: 0.7rem;
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  }
  .tag-card {
    display: flex; align-items: center; gap: 0.6rem;
    background: #fff; border: 1px solid rgba(0, 0, 0, 0.06);
    border-radius: 16px; padding: 0.8rem 1rem;
    text-decoration: none; min-width: 0;
    transition: border-color 0.2s ease, box-shadow 0.2s ease, transform 0.2s var(--apple-ease);
  }
  .tag-card:hover {
    border-color: rgba(0, 113, 227, 0.35);
    box-shadow: 0 6px 20px rgba(0, 0, 0, 0.08);
    transform: translateY(-1px);
  }
  .tag-hash { font-size: 1.05rem; font-weight: 800; flex: none; }
  .tag-name {
    font-size: 0.9rem; font-weight: 600; color: var(--apple-text);
    overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1;
  }
  .tag-count {
    flex: none; display: inline-flex; align-items: center;
    min-width: 1.9rem; height: 1.5rem; padding: 0 0.5rem; justify-content: center;
    border-radius: 980px; font-size: 0.72rem; font-weight: 700;
    background: rgba(0, 0, 0, 0.055); color: var(--apple-gray);
  }
  .no-results { display: none; text-align: center; padding: 2.5rem 1rem; color: var(--apple-gray); font-size: 0.9rem; }

  @media (max-width: 640px) {
    .tags-page { padding: 1.35rem 1rem 2.5rem; }
    .tags-header h1 { font-size: 1.7rem; }
    .tags-grid { grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 0.55rem; }
    .tag-card { padding: 0.7rem 0.8rem; }
    .sort-segmented { overflow-x: auto; max-width: 100%; }
    .tags-search { max-width: 100%; }
  }
</style>

<div class="tags-page">
    <!-- Header -->
    <div class="tags-header">
        <div>
            <h1>{% trans "Tags" %}</h1>
            <p class="count">{{ tags|length }} {% trans "tags" %} · {% trans "click the cloud or a card to explore" %}</p>
        </div>
        <a href="{% url 'tag-create' %}" class="apple-btn apple-btn-primary">
            <svg width="15" height="15" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2.5" aria-hidden="true">
                <path stroke-linecap="round" stroke-linejoin="round" d="M12 5v14m-7-7h14"/>
            </svg>
            {% trans "New Tag" %}
        </a>
    </div>

    <!-- Tag Cloud (local echarts, no CDN) -->
    <div class="apple-card">
        <h2>{% trans "Tag Cloud" %}</h2>
        <div id="tag-cloud-container"></div>
    </div>

    <!-- Sort + filter -->
    <div class="tags-toolbar">
        <div class="sort-segmented" role="group" aria-label="{% trans 'Sort tags' %}">
            <a href="?sort=name" class="sort-btn {% if current_sort == 'name' %}active{% endif %}">{% trans "Name A–Z" %}</a>
            <a href="?sort=name_desc" class="sort-btn {% if current_sort == 'name_desc' %}active{% endif %}">{% trans "Z–A" %}</a>
            <a href="?sort=count" class="sort-btn {% if current_sort == 'count' %}active{% endif %}">{% trans "Most Used" %}</a>
            <a href="?sort=count_asc" class="sort-btn {% if current_sort == 'count_asc' %}active{% endif %}">{% trans "Least Used" %}</a>
        </div>
        <div class="tags-search">
            <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-4.35-4.35M17 10.5a6.5 6.5 0 11-13 0 6.5 6.5 0 0113 0z"/>
            </svg>
            <input type="text" id="filter-tags-input" placeholder="{% trans 'Filter tags…' %}" autocomplete="off">
        </div>
    </div>

    <!-- Tag cards -->
    <div class="tags-grid" id="tags-grid">
        {% for tag in tags %}
        <a href="{% url 'tag-detail' tag.slug %}" class="tag-card tag-item" data-tag-name="{{ tag.name|lower }}">
            <span class="tag-hash" aria-hidden="true">#</span>
            <span class="tag-name" title="{{ tag.name }}">{{ tag.name }}</span>
            <span class="tag-count">{{ tag.total_count }}</span>
        </a>
        {% empty %}
        <div class="no-results" style="display:block;grid-column:1/-1">{% trans "No tags found." %}</div>
        {% endfor %}
    </div>
    <div id="no-results-message" class="no-results">{% trans "No matching tags found." %}</div>
</div>

<script src="{% static 'vendor/echarts/echarts.min.js' %}"></script>
<script src="{% static 'vendor/echarts/echarts-wordcloud.min.js' %}"></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
    const tagColors = [
        '#3498db', '#2ecc71', '#e74c3c', '#f39c12', '#9b59b6',
        '#1abc9c', '#d35400', '#16a085', '#8e44ad', '#e91e63'
    ];
    // Stable per-name colour (hash) so cards don't repaint on every load
    const colorOf = name => tagColors[Math.abs([...name].reduce((h, c) => (h * 31 + c.charCodeAt(0)) >>> 0, 7)) % tagColors.length];
    document.querySelectorAll('.tag-item').forEach(card => {
        const name = card.dataset.tagName;
        card.querySelector('.tag-hash').style.color = colorOf(name || 'x');
    });

    // ── Word cloud (local echarts) ──
    const chartDom = document.getElementById('tag-cloud-container');
    const myChart = echarts.init(chartDom);
    const tagCloudData = [
        {% for tag in tag_cloud %}
        { name: '{{ tag.name|escapejs }}', value: {{ tag.count }}, slug: '{{ tag.slug|escapejs }}' },
        {% endfor %}
    ];
    myChart.setOption({
        tooltip: { show: true, formatter: p => p.name },
        series: [{
            type: 'wordCloud',
            shape: 'circle',
            left: 'center', top: 'center', width: '100%', height: '100%',
            sizeRange: [16, 60], rotationRange: [0, 0], gridSize: 16,
            drawOutOfBound: false, layoutAnimation: true,
            textStyle: {
                fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',
                fontWeight: 'bold',
                color: () => tagColors[Math.floor(Math.random() * tagColors.length)],
            },
            emphasis: { textStyle: { fontWeight: 'bold', shadowBlur: 12, shadowColor: 'rgba(0,0,0,0.25)' } },
            data: tagCloudData,
        }],
    });
    myChart.on('click', p => {
        const hit = tagCloudData.find(t => t.name === p.name);
        if (hit) window.location.href = `/ui/tags/${hit.slug}/`;
    });
    window.addEventListener('resize', () => myChart.resize());

    // ── Live filter ──
    const filterInput = document.getElementById('filter-tags-input');
    const tagItems = document.querySelectorAll('.tag-item');
    const noResults = document.getElementById('no-results-message');
    if (filterInput) {
        filterInput.addEventListener('input', () => {
            const term = filterInput.value.toLowerCase().trim();
            let visible = 0;
            tagItems.forEach(item => {
                const name = item.getAttribute('data-tag-name') || '';
                const match = name.includes(term);
                item.style.display = match ? '' : 'none';
                if (match) visible++;
            });
            noResults.style.display = (visible === 0 && term.length > 0) ? 'block' : 'none';
        });
    }
});
</script>
{% endblock %}
