const startFadeIn = () => {
    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) entry.target.classList.add('is-visible');
        });
    }, { threshold: 0.1 });
    document.querySelectorAll('.fade-in').forEach(item => observer.observe(item));
};

document.addEventListener('DOMContentLoaded', () => {
    const gridContainer = document.querySelector('.grid-container');
    if (!gridContainer || typeof WORKS_DATA === 'undefined') return;

    const categoryFilter = document.getElementById('category-filter');

    const pathPrefix = '';

    // カテゴリーボタン
    if (categoryFilter) {
        const categories = [...new Set(WORKS_DATA.map(w => w.category))];
        let buttonsHtml = `<button class="category-btn active" onclick="displayWorks('All', this)">All</button>`;
        categories.forEach(cat => {
            buttonsHtml += `<button class="category-btn" onclick="displayWorks('${cat}', this)">${cat}</button>`;
        });
        categoryFilter.innerHTML = buttonsHtml;
    }

    // イラスト一覧
    gridContainer.innerHTML = WORKS_DATA.map(work => {
        const imgPath = pathPrefix + work.img;
        return `
        <div class="work-item fade-in" data-category="${work.category}">
            <a href="${work.movie || imgPath}" class="glightbox" data-title="${work.title}" data-description="${work.caption || ''}">
                <img src="${imgPath}" class="works-item-thumbnail" alt="${work.title}">
            </a>
        </div>`;
    }).join('');

    let lightbox = GLightbox({ selector: '.glightbox' });

    window.displayWorks = function (filter, btnElement) {
        document.querySelectorAll('.category-btn').forEach(btn => btn.classList.remove('active'));
        btnElement.classList.add('active');

        document.querySelectorAll('.work-item').forEach(item => {
            const isMatch = (filter === 'All' || item.getAttribute('data-category') === filter);
            item.style.display = isMatch ? 'block' : 'none';
            if (isMatch) item.classList.add('is-visible');
        });

        if (lightbox) lightbox.destroy();
        lightbox = GLightbox({ selector: '.work-item[style*="display: block"] .glightbox' });
    };

    startFadeIn();
});