// pages/wiki/index.js
import { MOCK_WIKI } from '../../utils/mockData';

Page({
    data: {
        wikiList: [],
        displayedList: [],
        searchQuery: '',
        activeCategory: '全部',
        showIdentifyModal: false
    },

    onLoad() {
        this.setData({ wikiList: MOCK_WIKI });
        this.filterList();
    },

    onShow() {
        if (typeof this.getTabBar === 'function' &&
            this.getTabBar()) {
            this.getTabBar().setData({ selected: 3 });
        }
    },

    onSearchInput(e) {
        // TDesign search event: e.detail.value
        this.setData({ searchQuery: e.detail.value }, () => {
            this.filterList();
        });
    },

    setCategory(e) {
        this.setData({ activeCategory: e.currentTarget.dataset.cat }, () => {
            this.filterList();
        });
    },

    filterList() {
        const { wikiList, searchQuery, activeCategory } = this.data;
        let result = wikiList;

        if (searchQuery) {
            const q = searchQuery.toLowerCase();
            result = result.filter(item =>
                item.name.toLowerCase().includes(q) ||
                item.scientificName.toLowerCase().includes(q)
            );
        }

        if (activeCategory !== '全部') {
            result = result.filter(item => item.category.includes(activeCategory));
        }

        this.setData({ displayedList: result });
    },

    goToDetail(e) {
        const item = e.currentTarget.dataset.item;
        wx.navigateTo({
            url: `/pages/plant-detail/index?id=${item.id}&mode=wiki`
        });
    },

    openIdentifyModal() { this.setData({ showIdentifyModal: true }); },

    onPopupVisibleChange(e) {
        this.setData({
            showIdentifyModal: e.detail.visible
        });
    },

    closeIdentifyModal() { this.setData({ showIdentifyModal: false }); }
})
