import { notify } from '@/core/ui/toast-notify'

function translate(i18n, key, params, fallback) {
	try {
		return i18n ? i18n.t(key, params) : fallback
	} catch (_) {
		return fallback
	}
}

export function copyText(content, showContent = true, i18n) {
	const text = typeof content === 'string' ? content : String(content)

	// #ifndef H5
	uni.setClipboardData({
		data: text,
		success() {
			if (showContent) {
				notify(translate(i18n, 'common.copySuccessWithContent', { content: text }, `复制成功 ${text}`))
			} else {
				notify(translate(i18n, 'common.copySuccess', {}, '复制成功'))
			}
		},
		fail() {
			notify(translate(i18n, 'common.copyFailed', {}, '复制失败'))
		}
	})
	// #endif

	// #ifdef H5
	if (!document.queryCommandSupported('copy')) {
		notify(translate(i18n, 'common.browserNotSupported', {}, '浏览器不支持'))
		return
	}
	const node = document.createElement('textarea')
	node.value = text
	node.readOnly = true
	document.body.appendChild(node)
	node.select()
	node.setSelectionRange(0, text.length)
	const ok = document.execCommand('copy')
	node.remove()
	if (ok) {
		if (showContent) {
			notify(translate(i18n, 'common.copySuccessWithContent', { content: text }, `复制成功 ${text}`))
		} else {
			notify(translate(i18n, 'common.copySuccess', {}, '复制成功'))
		}
	} else {
		notify(translate(i18n, 'common.copyFailed', {}, '复制失败'))
	}
	// #endif
}
