<?php
 
 

$letters = array_keys($groupedTags);
$alphabet = array_merge(['#'], range('A', 'Z'));
?>

<div class="section-title-row">
    <h1 class="section-title" style="text-transform:uppercase;"><?php echo __('page_title_tags'); ?></h1>
    <div class="section-title-row__search">
        <i class="fa-solid fa-magnifying-glass listing-search__icon"></i>
        <input type="text" class="listing-search__input" id="tagSearchInput" placeholder="<?php echo __('search_tags'); ?>" autocomplete="off">
    </div>
</div>


<nav class="tag-alphabet" id="tagAlphabet">
    <?php foreach ($alphabet as $l): ?>
        <?php if (in_array($l, $letters, true)): ?>
            <a href="#letter-<?php echo $l === '#' ? '0' : $l; ?>" class="tag-alphabet__letter"><?php echo $l; ?></a>
        <?php else: ?>
            <span class="tag-alphabet__letter tag-alphabet__letter--disabled"><?php echo $l; ?></span>
        <?php endif; ?>
    <?php endforeach; ?>
</nav>


<div class="empty-state" id="tagNoResults" style="display:none;">
    <div class="empty-state__icon"><i class="fa-light fa-magnifying-glass"></i></div>
    <p class="empty-state__text"><?php echo __('no_results_for'); ?> "<span id="tagNoResultsQuery"></span>"</p>
</div>


<div class="tag-sections-grid" id="tagGrid">
    <?php foreach ($groupedTags as $letter => $tags): ?>
        <div class="tag-section" id="letter-<?php echo $letter === '#' ? '0' : $letter; ?>" data-letter="<?php echo htmlspecialchars($letter); ?>">
            <div class="tag-section__header">
                <span class="tag-section__letter"><?php echo htmlspecialchars($letter); ?></span>
                <span class="tag-section__count"><?php echo count($tags); ?></span>
            </div>
            <div class="tag-section__tags">
                <?php foreach ($tags as $tag): ?>
                    <a href="<?php echo url('/tag/' . htmlspecialchars($tag['slug'])); ?>"
                       class="tag-link"
                       data-name="<?php echo htmlspecialchars(mb_strtolower($tag['name'])); ?>"
                       title="<?php echo htmlspecialchars($tag['name']); ?> — <?php echo (int)$tag['video_count'] !== 1 ? __('video_count_plural', [':count' => Format::number((int)$tag['video_count'])]) : __('video_count', [':count' => Format::number((int)$tag['video_count'])]); ?>">
                        <?php echo htmlspecialchars($tag['name']); ?>
                    </a>
                <?php endforeach; ?>
            </div>
        </div>
    <?php endforeach; ?>
</div>

<script>
(function() {
    const input = document.getElementById('tagSearchInput');
    const grid = document.getElementById('tagGrid');
    const sections = grid.querySelectorAll('.tag-section');
    const noResults = document.getElementById('tagNoResults');
    const noResultsQuery = document.getElementById('tagNoResultsQuery');
    const alphabetLinks = document.querySelectorAll('.tag-alphabet a.tag-alphabet__letter');

    
    alphabetLinks.forEach(function(link) {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            const target = document.querySelector(this.getAttribute('href'));
            if (target) {
                target.scrollIntoView({ behavior: 'smooth', block: 'start' });
            }
        });
    });

    
    input.addEventListener('input', function() {
        const q = this.value.trim().toLowerCase();
        let totalVisible = 0;

        sections.forEach(function(section) {
            const tags = section.querySelectorAll('.tag-link');
            let sectionVisible = 0;

            tags.forEach(function(tag) {
                const name = tag.getAttribute('data-name');
                if (q === '' || name.indexOf(q) !== -1) {
                    tag.style.display = '';
                    sectionVisible++;
                } else {
                    tag.style.display = 'none';
                }
            });

            
            const countBadge = section.querySelector('.tag-section__count');
            if (q !== '') {
                countBadge.textContent = sectionVisible;
            } else {
                countBadge.textContent = tags.length;
            }

            section.style.display = sectionVisible > 0 ? '' : 'none';
            totalVisible += sectionVisible;
        });

        if (q !== '' && totalVisible === 0) {
            noResultsQuery.textContent = this.value.trim();
            noResults.style.display = '';
        } else {
            noResults.style.display = 'none';
        }
    });
})();
</script>

<script>
(function(){
    var grid = document.getElementById('tagGrid');
    if (!grid) return;
    
    var sections = Array.prototype.slice.call(grid.querySelectorAll('.tag-section'));
    if (sections.length < 2) return;

    function colCount(){
        var w = window.innerWidth || document.documentElement.clientWidth || 1200;
        if (w <= 480) return 1;
        if (w <= 900) return 2;
        return 3;
    }

    function masonry(){
        var n = colCount();
        grid.classList.add('is-masonry');
        grid.innerHTML = '';
        var cols = [];
        for (var i = 0; i < n; i++){
            var c = document.createElement('div');
            c.className = 'tag-col';
            grid.appendChild(c);
            cols.push(c);
        }
        
        
        for (var s = 0; s < sections.length; s++){
            var min = 0;
            for (var i = 1; i < n; i++){ if (cols[i].offsetHeight < cols[min].offsetHeight) min = i; }
            cols[min].appendChild(sections[s]);
        }
    }

    masonry();
    var rt;
    window.addEventListener('resize', function(){ clearTimeout(rt); rt = setTimeout(masonry, 150); });
})();
</script>
