/* AI Tools Directory - Frontend JS */
(function () {
    'use strict';

    let searchTimer = null;
    let activeCategory = '';
    let activeSort = 'newest';
    let activePage = 1;
    let categoriesExpanded = false;

    function setupCategoryVisibility() {
        const pillsWrap = document.getElementById('aitd-category-filters');
        if (!pillsWrap) return;

        const defaultVisible = parseInt(pillsWrap.dataset.defaultVisible || '4', 10);
        const buttons = Array.from(pillsWrap.querySelectorAll('.aitd-pill'));
        const categoryButtons = buttons.filter((btn, index) => index > 0);

        categoryButtons.forEach((btn, index) => {
            btn.classList.toggle('aitd-pill-hidden', !categoriesExpanded && index >= defaultVisible);
        });

        pillsWrap.classList.toggle('is-expanded', categoriesExpanded);
    }

    function toRgbString(r, g, b) {
        return [r, g, b].join(', ');
    }

    function applyAccentFromImage(container, image) {
        if (!container || !image || image.dataset.aitdAccentApplied === '1') return;

        const updateAccent = function () {
            if (!image.naturalWidth || !image.naturalHeight) return;

            const canvas = document.createElement('canvas');
            const context = canvas.getContext('2d', { willReadFrequently: true });

            if (!context) return;

            canvas.width = 24;
            canvas.height = 24;

            try {
                context.drawImage(image, 0, 0, canvas.width, canvas.height);
                const pixels = context.getImageData(0, 0, canvas.width, canvas.height).data;

                let red = 0;
                let green = 0;
                let blue = 0;
                let count = 0;

                for (let i = 0; i < pixels.length; i += 4) {
                    const alpha = pixels[i + 3];
                    const r = pixels[i];
                    const g = pixels[i + 1];
                    const b = pixels[i + 2];
                    const max = Math.max(r, g, b);
                    const min = Math.min(r, g, b);
                    const saturation = max - min;

                    if (alpha < 180 || max > 245 || saturation < 18) {
                        continue;
                    }

                    red += r;
                    green += g;
                    blue += b;
                    count++;
                }

                if (!count) return;

                const rgb = toRgbString(
                    Math.round(red / count),
                    Math.round(green / count),
                    Math.round(blue / count)
                );

                container.style.setProperty('--aitd-brand-rgb', rgb);
                image.dataset.aitdAccentApplied = '1';
            } catch (error) {
                image.dataset.aitdAccentApplied = '1';
            }
        };

        if (image.complete) {
            updateAccent();
        } else {
            image.addEventListener('load', updateAccent, { once: true });
        }
    }

    function applyBrandAccents(scope) {
        const root = scope || document;

        root.querySelectorAll('.aitd-card-item').forEach(card => {
            const image = card.querySelector('.aitd-logo img');
            applyAccentFromImage(card, image);
        });

        root.querySelectorAll('.aitd-single-wrap').forEach(panel => {
            const image = panel.querySelector('.aitd-single-logo img');
            applyAccentFromImage(panel, image);
        });
    }

    function fetchTools() {
        const search = document.getElementById('aitd-search')?.value || '';
        const results = document.getElementById('aitd-results');
        if (!results) return;

        results.innerHTML = '<div class="aitd-loading">Searching tools...</div>';

        const body = new FormData();
        body.append('action', 'aitd_filter');
        body.append('nonce', aitd_ajax.nonce);
        body.append('search', search);
        body.append('category', activeCategory);
        body.append('sort', activeSort);
        body.append('page', activePage);

        fetch(aitd_ajax.url, { method: 'POST', body })
            .then(r => r.json())
            .then(data => {
                if (data.success) {
                    results.innerHTML = data.data;

                    results.querySelectorAll('.aitd-card-item').forEach((card, i) => {
                        card.style.animationDelay = (i * 40) + 'ms';
                    });

                    applyBrandAccents(results);
                } else {
                    results.innerHTML = '<div class="aitd-loading">Unable to load tools right now.</div>';
                }
            })
            .catch(() => {
                results.innerHTML = '<div class="aitd-loading">Something went wrong. Please refresh.</div>';
            });
    }

    document.addEventListener('DOMContentLoaded', function () {
        const searchInput = document.getElementById('aitd-search');
        if (searchInput) {
            searchInput.addEventListener('input', function () {
                clearTimeout(searchTimer);
                searchTimer = setTimeout(fetchTools, 350);
            });

            searchInput.addEventListener('keydown', function (e) {
                if (e.key === 'Enter') {
                    clearTimeout(searchTimer);
                    fetchTools();
                }
            });
        }

        document.querySelectorAll('.aitd-pill').forEach(btn => {
            btn.addEventListener('click', function () {
                if (this.dataset.category === '' || this.dataset.category === '0') {
                    categoriesExpanded = true;
                    setupCategoryVisibility();
                }

                document.querySelectorAll('.aitd-pill').forEach(b => b.classList.remove('active'));
                this.classList.add('active');
                activeCategory = this.dataset.category;
                activePage = 1;
                fetchTools();
            });
        });

        const sortSelect = document.getElementById('aitd-sort');
        if (sortSelect) {
            sortSelect.addEventListener('change', function () {
                activeSort = this.value;
                activePage = 1;
                fetchTools();
            });
        }

        document.addEventListener('click', function (event) {
            const pageButton = event.target.closest('.aitd-page-btn');
            if (!pageButton || pageButton.disabled) return;

            activePage = parseInt(pageButton.dataset.page || '1', 10);
            fetchTools();
            document.getElementById('aitd-results')?.scrollIntoView({ behavior: 'smooth', block: 'start' });
        });

        setupCategoryVisibility();
        applyBrandAccents(document);
        fetchTools();
    });
})();
