/** 상태·카테고리·검색 필터 로직 및 UI */
import { state, productsData } from './state.js';
import { VISIBILITY_CONFIG, STATUS_FILTERS, STATUS_ORDER, STATUS_COLOR, SEARCH_CONFIG } 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;
    const keyword = state.searchKeyword.toLowerCase();

    state.visibleProducts = productsData
        .filter((product) => {
            // [1] 가시성 및 상태/카테고리 필터
            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);

            // [2] config 설정을 기반으로 한 동적 검색 매칭
            const searchMatch =
                keyword === '' ||
                (() => {
                    const searchPool = [];

                    if (SEARCH_CONFIG.USE_TITLE) searchPool.push(product.title);

                    if (SEARCH_CONFIG.USE_CUSTOM_TAG && product.customTag) searchPool.push(product.customTag);

                    if (SEARCH_CONFIG.USE_DESCRIPTION && product.description) searchPool.push(product.description);

                    if (SEARCH_CONFIG.USE_TAGS && product.tags) searchPool.push(...product.tags); // 배열 요소를 풀어서 추가

                    if (SEARCH_CONFIG.USE_FULL_DESCRIPTION && product.fullDescription) searchPool.push(...product.fullDescription);

                    // 검색 풀(Pool)에 있는 단어 중 키워드를 포함하는 게 하나라도 있는지 확인
                    return searchPool.some((text) => String(text).toLowerCase().includes(keyword));
                })();

            return statusMatch && categoryMatch && searchMatch;
        })
        .sort((a, b) => {
            const aOrder = STATUS_ORDER[a.status] ?? 999;
            const bOrder = STATUS_ORDER[b.status] ?? 999;
            return aOrder - bOrder;
        });

    renderTotalCount(state.visibleProducts.length);

    renderProducts(state.currentPage);
}

/** 총 개수를 화면에 표시하는 보조 함수 */
function renderTotalCount(count) {
    const totalCountElement = document.getElementById('total-count');
    if (totalCountElement) {
        totalCountElement.textContent = count.toLocaleString(); // 3자리마다 콤마
    }
}

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();
        });
    });
}

// 로고 클릭 시 초기화 로직
document.getElementById('logo-title')?.addEventListener('click', () => {
    // 1. 검색어 초기화
    state.searchKeyword = '';
    const searchInput = document.getElementById('search-input'); // 검색창 ID가 있다면
    if (searchInput) searchInput.value = '';

    // 2. 카테고리 초기화 (All 선택)
    state.activeCategories.clear();
    state.activeCategories.add('All');

    // 3. 상태 필터 초기화 (기본 활성화 상태로)
    state.activeStatuses.clear();
    STATUS_FILTERS.filter(f => f.defaultActive).forEach(f => state.activeStatuses.add(f.key));

    // 4. 필터 적용 및 UI 갱신
    applyFilters();
    renderStatusChips();
    renderCategoryChips(productsData);

    // 5. 페이지 최상단으로 스크롤 (선택 사항)
    window.scrollTo({ top: 0, behavior: 'smooth' });
});