/** 진입점: 이벤트 바인딩·초기 렌더·URL 모달 처리 */
import { state, productsData } from './state.js';
import {
    applyFilters,
    renderStatusChips,
    renderCategoryChips,
    bindCategoryFilter,
} from './filters.js';
import { renderProducts, changePage } from './productList.js';
import { openModal, closeModal } from './modal.js';
import { scrollToImage } from './carousel.js';

console.log('Total products loaded:', productsData.length);

// HTML onclick에서 사용
window.openModal = openModal;
window.closeModal = closeModal;
window.changePage = changePage;
window.scrollToImage = scrollToImage;

// 검색 입력
const searchInput = document.getElementById('search-input');
if (searchInput) {
    searchInput.addEventListener('input', (e) => {
        state.searchKeyword = e.target.value.trim().toLowerCase();
        applyFilters();
    });
}

// Escape로 모달 닫기
document.addEventListener('keydown', (e) => {
    if (e.key !== 'Escape') return;
    const modal = document.getElementById('product-modal');
    if (!modal || modal.classList.contains('hidden')) return;
    closeModal();
});

function checkUrlAndOpenModal() {
    const params = new URLSearchParams(window.location.search);
    const productId = params.get('id');
    if (productId) {
        const product = productsData.find((p) => String(p.id) === productId);
        if (product) {
            setTimeout(() => openModal(product.id), 100);
        }
    }
}

// 초기 테마 설정 확인
const themeToggleDarkIcon = document.getElementById('theme-toggle-dark-icon');
const themeToggleLightIcon = document.getElementById('theme-toggle-light-icon');
const themeToggleBtn = document.getElementById('theme-toggle');

// 1. 현재 테마 상태에 따라 아이콘 표시/숨김 처리
function updateIcons() {
    if (document.documentElement.classList.contains('dark')) {
        themeToggleLightIcon.classList.remove('hidden');
        themeToggleDarkIcon.classList.add('hidden');
    } else {
        themeToggleDarkIcon.classList.remove('hidden');
        themeToggleLightIcon.classList.add('hidden');
    }
}

// 2. 초기 로드 시 설정 (localStorage 또는 시스템 설정 확인)
if (localStorage.getItem('color-theme') === 'dark' || (!('color-theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
    document.documentElement.classList.add('dark');
} else {
    document.documentElement.classList.remove('dark');
}
updateIcons();

// 3. 버튼 클릭 이벤트
themeToggleBtn.addEventListener('click', function() {
    // 테마 토글
    if (document.documentElement.classList.contains('dark')) {
        document.documentElement.classList.remove('dark');
        localStorage.setItem('color-theme', 'light');
    } else {
        document.documentElement.classList.add('dark');
        localStorage.setItem('color-theme', 'dark');
    }
    updateIcons();
});

// 초기 렌더
renderCategoryChips(productsData);
bindCategoryFilter(productsData);
renderStatusChips();
applyFilters();

document.addEventListener('DOMContentLoaded', () => {
    renderProducts(state.currentPage);
    checkUrlAndOpenModal();
});

// 데이터용 새 ID 생성기
const newId = Math.random().toString(36).substring(2, 10);
console.log(`%c[NUMBER]: ${newId}`, 'color: #137fec; font-weight: bold; border: 1px solid #137fec; padding: 2px 5px; border-radius: 4px;');

