/** 상태·카테고리·검색 필터 로직 및 UI */
import { state, productsData } from './state.js';
import {
    VISIBILITY_CONFIG,
    STATUS_FILTERS,
    STATUS_ORDER,
    STATUS_COLOR,
} from './config.js';
import { renderProducts } from './productList.js';

function getStatusChipClass(status, isActive) {
    const base = STATUS_COLOR[status] ?? '';
    if (isActive) {
        return `${base} opacity-100 shadow-sm`;
    }
    return `bg-slate-50 text-slate-400 border-slate-200 opacity-30 grayscale hover:opacity-50`;
}

export function renderStatusChips() {
    const container = document.getElementById('status-chips');
    if (!container) return;
    container.innerHTML = '';

    STATUS_FILTERS.filter((f) => f.visible).forEach(({ key, label }) => {
        const isActive = state.activeStatuses.has(key);
        const chip = document.createElement('button');
        chip.className = `status-chip px-3 py-1.5 md:px-4 md:py-2 rounded-full text-xs md:text-sm font-medium transition-all duration-200 border ${getStatusChipClass(key, isActive)}`;
        chip.textContent = label;
        chip.onclick = () => toggleStatusFilter(key);
        container.appendChild(chip);
    });
}

function toggleStatusFilter(status) {
    if (state.activeStatuses.has(status)) {
        state.activeStatuses.delete(status);
    } else {
        state.activeStatuses.add(status);
    }
    if (state.activeStatuses.size === 0) {
        STATUS_FILTERS.filter((f) => f.defaultActive).forEach((f) => state.activeStatuses.add(f.key));
    }
    applyFilters();
    renderStatusChips();
}

export function applyFilters() {
    state.currentPage = 1;
    state.visibleProducts = productsData
        .filter((product) => {
            if (product.status === '미판매' && !VISIBILITY_CONFIG.showUnlisted) return false;
            if (product.status === '판매완료' && !VISIBILITY_CONFIG.showSold) return false;
            const statusMatch = state.activeStatuses.has(product.status);
            const categoryMatch = state.activeCategories.has('All') || state.activeCategories.has(product.category);
            const searchMatch = state.searchKeyword === '' || product.title.toLowerCase().includes(state.searchKeyword);
            return statusMatch && categoryMatch && searchMatch;
        })
        .sort((a, b) => {
            const aOrder = STATUS_ORDER[a.status] ?? 999;
            const bOrder = STATUS_ORDER[b.status] ?? 999;
            return aOrder - bOrder;
        });
    renderProducts(state.currentPage);
}

export function getCategories(products) {
    return ['All', ...new Set(products.map((p) => p.category))];
}

export function renderCategoryChips(products) {
    const container = document.getElementById('filter-chips');
    if (!container) return;
    const categories = ['All', ...new Set(products.map((p) => p.category))];
    container.innerHTML = '';

    categories.forEach((cat) => {
        const isActive = state.activeCategories.has(cat);
        const chip = document.createElement('button');
        chip.className = `filter-chip px-3 py-1.5 md:px-4 md:py-2 rounded-full text-xs md:text-sm font-medium transition border ${isActive ? 'bg-primary text-white border-primary' : 'bg-slate-50 text-slate-600 border-slate-200'}`;
        chip.textContent = cat;
        chip.dataset.category = cat;
        chip.onclick = () => toggleCategory(cat);
        container.appendChild(chip);
    });
}

export function toggleCategory(category) {
    if (category === 'All') {
        state.activeCategories.clear();
        state.activeCategories.add('All');
    } else {
        state.activeCategories.delete('All');
        state.activeCategories.has(category) ? state.activeCategories.delete(category) : state.activeCategories.add(category);
        if (state.activeCategories.size === 0) state.activeCategories.add('All');
    }
    renderCategoryChips(productsData);
    applyFilters();
}

export function bindCategoryFilter(products) {
    const chips = document.querySelectorAll('.filter-chip');
    chips.forEach((chip) => {
        chip.addEventListener('click', () => {
            const category = chip.dataset.category;
            if (category === 'All') {
                state.activeCategories.clear();
                state.activeCategories.add('All');
            } else {
                state.activeCategories.delete('All');
                if (state.activeCategories.has(category)) state.activeCategories.delete(category);
                else state.activeCategories.add(category);
                if (state.activeCategories.size === 0) state.activeCategories.add('All');
            }
            applyFilters();
        });
    });
}
