import { useEffect } from 'react';
import Taro, { useDidShow } from '@tarojs/taro';
import { captureIosJssdkEntryUrl } from '@dukang/weixin-sdk';
import { applyWechatShare, type PageSharePayload } from '../lib/wechat-share';

/**
 * H5：进入页面时刷新微信分享卡片；
 * 小程序：开启右上角分享菜单。
 */
export default function WechatShareReady({ payload }: { payload?: PageSharePayload }) {
  useEffect(() => {
    if (process.env.TARO_ENV === 'h5') {
      captureIosJssdkEntryUrl();
    }
  }, []);

  useDidShow(() => {
    if (process.env.TARO_ENV === 'weapp') {
      void Taro.showShareMenu({
        withShareTicket: true,
        showShareItems: ['shareAppMessage', 'shareTimeline'],
      }).catch(() => {
        void Taro.showShareMenu({ withShareTicket: true }).catch(() => {});
      });
      return;
    }
    void applyWechatShare({
      title: payload?.title,
      desc: payload?.desc,
      imgUrl: payload?.imgUrl,
      link: payload?.link,
    }).catch(() => {});
  });

  useEffect(() => {
    if (process.env.TARO_ENV !== 'h5') return;
    void applyWechatShare({
      title: payload?.title,
      desc: payload?.desc,
      imgUrl: payload?.imgUrl,
      link: payload?.link,
    }).catch(() => {});
  }, [payload?.title, payload?.desc, payload?.imgUrl, payload?.link]);

  return null;
}
