import { Text } from '@tarojs/components';
import Taro from '@tarojs/taro';
import { splitLogisticsText } from '../lib/order-logistics-utils';
import { toast } from '../lib/api';

type LogisticsRichTextProps = {
  text: string;
  className?: string;
  phoneClassName?: string;
};

export default function LogisticsRichText({
  text,
  className = '',
  phoneClassName = 'order-logistics-phone-link',
}: LogisticsRichTextProps) {
  const segments = splitLogisticsText(text);

  function dial(phone: string) {
    const normalized = phone.replace(/-/g, '');
    Taro.makePhoneCall({ phoneNumber: normalized }).catch(() => toast('无法拨打电话'));
  }

  return (
    <Text className={className}>
      {segments.map((segment, index) =>
        segment.type === 'phone' ? (
          <Text
            key={`${segment.value}-${index}`}
            className={phoneClassName}
            onClick={(e) => {
              e.stopPropagation();
              dial(segment.value);
            }}
          >
            {segment.value}
          </Text>
        ) : (
          <Text key={`${index}-text`}>{segment.value}</Text>
        ),
      )}
    </Text>
  );
}
