import { NAV_INNER_PX } from '../../utils/navMetrics';

const { statusBarHeight } = wx.getWindowInfo();
const NAV_BLOCK_HEIGHT = statusBarHeight + NAV_INNER_PX;

type FavoritesTab = 'favorites' | 'downloads';

type FavoriteItem =
    | {
          id: string;
          variant: 'standard';
          title: string;
          metaLine: string;
          stars: number;
          timeBadge: string;
          thumb: string;
      }
    | {
          id: string;
          variant: 'featured';
          title: string;
          metaLine: string;
          tags: string[];
      };

type DownloadRow = {
    id: string;
    title: string;
    time: string;
    status: string;
    statusHighlight: boolean;
    thumb?: string;
    placeholder?: 'draw';
};

type DownloadSection = {
    key: string;
    label: string;
    items: DownloadRow[];
};

const MOCK_FAVORITES: FavoriteItem[] = [
    {
        id: '1',
        variant: 'standard',
        title: '10以内加法',
        metaLine: '数学启蒙 · 4-6岁 · ',
        stars: 2,
        timeBadge: '收藏于 3 天前',
        thumb: 'https://lh3.googleusercontent.com/aida-public/AB6AXuD7khp0rJABfa9yFrMt9ZgIhAPyN44XmJ2pXNBgCzbgBvwA5ptFZVty013JedVzbE9_VvCQnToN7QETLDKjtiX22igzK-a5h4E8wjKrembFW4eVuk1RsJIbHjx3_cCz0hJ7_t76hF8t-Qdod_5R9sNMor1ZEjf6dGNp6UI_eIBjsN9b22iCTJ2VB-IEh0Rmil6_iC4Og-4I03IcQDV2rTHYIXcZxjiay1IiYGXw3wJ3bfo2SF2N7ZFT00akTgYU-9JyF7xJ6n15Yzc',
    },
    {
        id: '2',
        variant: 'standard',
        title: '图形连连看',
        metaLine: '逻辑思维 · 3-5岁 · ',
        stars: 1,
        timeBadge: '收藏于 5 天前',
        thumb: 'https://lh3.googleusercontent.com/aida-public/AB6AXuBY_0Rr153ZBT4IHcMyFtrcgl-y2ZRyVnOuGecnn7f4PZKoAx2lOuCorsMmfRa72s0JmbXrt4XT3QU1x7cIbZUyhv_EXwCfMaNxtkHc-ymIBIQ5jqm5oiQebrEWH4kjv14JdkCiziT4xzac4TdVN5yqpk7Wlg80QBl_ldDmAQqIgcUeN2PvlVvhmpOYmFeWE2HS3I_e4vV1J8s_cfV9_4g7y8SbxlSfnTmgQNeXrVbcdwaNEAGQWp92Iif0d2pVIqdfuUHO1pTw8oQ',
    },
    {
        id: '3',
        variant: 'standard',
        title: '拼音字母认读',
        metaLine: '语文基础 · 5-7岁 · ',
        stars: 3,
        timeBadge: '收藏于 1 周前',
        thumb: 'https://lh3.googleusercontent.com/aida-public/AB6AXuC54mXQ8620XwIsWmUHBHJGdmpF8uE4cSYxwR2NLJTsa6gYdTCHz2tqrKbGOye-y0CGgCPPWwJXzEuB2ZYrQ3CWWPlamvbjhTUDYf8yoA9Lyapll1t2w17AqzSHrbBPNFrq931IUCis64b51kslQZoq3c0KslZsBQiky-YSnuE7xUuNsgiF4hOak_ReFFufWE53h1sPkjHFeRM-H34b-e1MCNxGObGPhI0mNlJ_qz0c8aCuS-jdnDocSvIYda-iVcJLWcIT-mO6klw',
    },
    {
        id: '4',
        variant: 'featured',
        title: '趣味英语单词卡',
        metaLine: '语言学习 · 4-8岁 · ⭐⭐⭐',
        tags: ['畅销经典', '全彩打印'],
    },
];

const MOCK_DOWNLOADS: DownloadSection[] = [
    {
        key: 'today',
        label: '今天',
        items: [
            {
                id: 'd1',
                title: '拼音描红 · 声母表',
                time: '14:32',
                status: '已保存相册',
                statusHighlight: true,
                thumb: 'https://lh3.googleusercontent.com/aida-public/AB6AXuBCm6X4rhibw2_WxP-U0dDyOsiYol3y12OnEXHRkPONZYMQBUcr3Grqo1IbwH3sdWPg5jIUeIbr_AEwv_hFwUOMMz9jTIIMc6Pke1bzSvlQcgdDq-zMEIU4A--IQFX59ac-8BscCajXZcd4v8rE6JEZFf1-aztKclPTkE_Rrgj-nbVCy5V6bOE6yDOB67VdTbcqiOdaFN18ju_MgWVo3FQZLwIUZOBahkPl0vDIKA0mkiaGK9eiFpfnERYxkYG3eWJZ40umTYp46Jo',
            },
            {
                id: 'd2',
                title: '趣味口算题卡',
                time: '09:15',
                status: '已下载 PDF',
                statusHighlight: false,
                thumb: 'https://lh3.googleusercontent.com/aida-public/AB6AXuBxNORxN_vftYMLaMjZVscL-o9bZnBrfUi7IAqOrFATIztGV12_0ggwgae-fmk0cORWtysZWJJDcAzj0NEyniFxbREoGDuq9U4kytprJkA70_k0MCzPgStmq0bRwu1Gx1j4peglFam8PH6IlPvOMbiHQ7-fMFfYTSBtA1p7Dp06NDOzS2VrMlF8VxjEgihVmhHUrHePVvXlktUkXBKNzrXEXrogO3iOyouTUKyvJh0TeChKUv3KohMoD5ol7C3fjBhdHf7QD4StOQ4',
            },
        ],
    },
    {
        key: 'yesterday',
        label: '昨天',
        items: [
            {
                id: 'd3',
                title: '汉字笔画基础训练',
                time: '16:40',
                status: '已发送邮件',
                statusHighlight: false,
                placeholder: 'draw',
            },
        ],
    },
];

Page({
    data: {
        favScrollHeight: 0,
        activeTab: 'favorites' as FavoritesTab,
        favoriteList: MOCK_FAVORITES as FavoriteItem[],
        downloadSections: MOCK_DOWNLOADS as DownloadSection[],
    },

    onLoad() {
        const win = wx.getWindowInfo();
        this.setData({
            favScrollHeight: win.windowHeight - NAV_BLOCK_HEIGHT,
        });
    },

    onShow() {
        const tab = wx.getStorageSync('favorites_active_tab') as FavoritesTab;
        if (tab === 'downloads' || tab === 'favorites') {
            this.setData({ activeTab: tab });
            wx.removeStorageSync('favorites_active_tab');
        }
    },

    onTabSwitch(e: WechatMiniprogram.TouchEvent) {
        const tab = e.currentTarget.dataset.tab as FavoritesTab;
        if (tab !== 'favorites' && tab !== 'downloads') return;
        this.setData({ activeTab: tab });
    },

    onDiscoverTap() {
        wx.switchTab({ url: '/pages/home/home' });
    },

    onSearchTap() {
        wx.showToast({ title: '搜索功能开发中', icon: 'none' });
    },

    onRemoveFavorite(e: WechatMiniprogram.TouchEvent) {
        const id = e.currentTarget.dataset.id as string | undefined;
        if (!id) return;
        const list = (this.data.favoriteList as FavoriteItem[]).filter((item) => item.id !== id);
        this.setData({ favoriteList: list });
        wx.showToast({ title: '已取消收藏', icon: 'none' });
    },

    onClearHistory() {
        wx.showModal({
            title: '清空下载历史',
            content: '确定清空本地展示的历史记录吗？',
            success: (res) => {
                if (!res.confirm) return;
                this.setData({ downloadSections: [] });
                wx.showToast({ title: '已清空', icon: 'none' });
            },
        });
    },

    onDownloadMore(e: WechatMiniprogram.TouchEvent) {
        const id = e.currentTarget.dataset.id as string | undefined;
        wx.showToast({ title: id ? `更多操作：${id}` : '更多', icon: 'none' });
    },
});
