import Taro from '@tarojs/taro'
import type { ProductType } from '@/types'
import { tapLight } from './feedback'

export function safeMiniappPath(value: unknown, fallback = '/pages/home/index') {
  const target = String(value || '').trim()
  if (!target) return fallback
  if (!target.startsWith('/pages/') || target.startsWith('//')) return fallback
  if (/[\u0000-\u001f]/.test(target)) return fallback
  return target.slice(0, 512)
}

export function go(url: string) {
  tapLight()
  Taro.navigateTo({ url: safeMiniappPath(url) })
}

export function toProduct(id: string) {
  if (id === 'consulting' || id.startsWith('consulting-')) {
    go('/pages/consulting/index')
    return
  }
  if (id.startsWith('data-')) {
    go(`/pages/data-service/detail/index?id=${encodeURIComponent(id)}`)
    return
  }
  go(`/pages/services/detail/index?id=${id}`)
}

export function toServiceList(type: ProductType) {
  if (type === 'consulting') {
    go('/pages/consulting/index')
    return
  }
  if (type === 'data') {
    go('/pages/data-service/index')
    return
  }
  go(`/pages/services/list/index?type=${type}`)
}

export function toast(title: string) {
  Taro.showToast({ title, icon: 'none' })
}
