import { View, Text, Image } from '@tarojs/components';
import Taro from '@tarojs/taro';
import './UserTabBar.css';

import iconHome from '../assets/tabbar/home.png';
import iconHomeActive from '../assets/tabbar/home-active.png';
import iconStore from '../assets/tabbar/store.png';
import iconStoreActive from '../assets/tabbar/store-active.png';
import iconBenefit from '../assets/tabbar/benefit.png';
import iconBenefitActive from '../assets/icons/store-benefit-y.png';
import iconMine from '../assets/tabbar/mine.png';
import iconMineActive from '../assets/tabbar/mine-active.png';

export const USER_TABS = [
  {
    pagePath: '/pages/home/index',
    text: '首页',
    icon: iconHome,
    iconActive: iconHomeActive,
  },
  {
    pagePath: '/pages/stores/index',
    text: '门店',
    icon: iconStore,
    iconActive: iconStoreActive,
  },
  {
    pagePath: '/pages/benefit/index',
    text: '好客权益',
    icon: iconBenefit,
    iconActive: iconBenefitActive,
  },
  {
    pagePath: '/pages/mine/index',
    text: '我的',
    icon: iconMine,
    iconActive: iconMineActive,
  },
] as const;

type UserTabBarProps = {
  selected: number;
};

/** C 端底栏：本地 PNG 图标（weapp 无法加载 Material 字体） */
export default function UserTabBar({ selected }: UserTabBarProps) {
  return (
    <View className="u-tabbar">
      {USER_TABS.map((tab, index) => {
        const active = selected === index;
        return (
          <View
            key={tab.pagePath}
            className={`u-tabbar__item${active ? ' u-tabbar__item--active' : ''}`}
            onClick={() => {
              if (!active) Taro.switchTab({ url: tab.pagePath });
            }}
          >
            <Image
              className="u-tabbar__icon"
              src={active ? tab.iconActive : tab.icon}
              mode="aspectFit"
            />
            <Text className="u-tabbar__label">{tab.text}</Text>
          </View>
        );
      })}
    </View>
  );
}

/** weapp custom-tab-bar 选中态同步；H5 无 getTabBar 时忽略 */
export function syncTabBarSelected(index: number) {
  try {
    const page = Taro.getCurrentInstance().page as
      | { getTabBar?: () => { setSelected?: (i: number) => void } }
      | undefined;
    page?.getTabBar?.()?.setSelected?.(index);
  } catch {
    /* ignore */
  }
}

export function shouldRenderPageTabBar(): boolean {
  return process.env.TARO_ENV === 'h5';
}
