<template>
	<div class="relative rounded-lg border-2 border-gray-200 bg-gray-100 p-3">
		<div class="select-all break-all text-xs text-gray-800">
			<pre
				:class="{
					'whitespace-pre-wrap': breakLines,
					'overflow-x-auto': !breakLines
				}"
				:style="
					!breakLines
						? 'scrollbar-width: none; -ms-overflow-style: none; -webkit-scrollbar: none;'
						: ''
				"
				>{{ textContent }}</pre
			>
		</div>
		<button
			class="absolute right-2 top-2 rounded-sm border border-gray-200 bg-white p-1 text-xs text-gray-600"
			variant="outline"
			@click="copyTextContentToClipboard"
		>
			{{ copied ? $t('Copied') : $t('Copy') }}
		</button>
	</div>
</template>

<script>
import { toast } from 'vue-sonner';

export default {
	props: {
		textContent: {
			type: String,
			required: true
		},
		breakLines: {
			type: Boolean,
			default: true
		}
	},
	data() {
		return {
			copied: false
		};
	},
	methods: {
		async copyTextContentToClipboard() {
			try {
				// 优先使用现代的 Clipboard API
				if (navigator.clipboard && navigator.clipboard.writeText) {
					await navigator.clipboard.writeText(this.textContent);
					this.showCopySuccess();
				} else {
					// 降级方案：使用传统的 execCommand 方法
					this.fallbackCopyTextToClipboard(this.textContent);
				}
			} catch (error) {
				// 如果 Clipboard API 失败，尝试降级方案
				this.fallbackCopyTextToClipboard(this.textContent);
			}
		},
		fallbackCopyTextToClipboard(text) {
			const textArea = document.createElement('textarea');
			textArea.value = text;
			textArea.style.position = 'fixed';
			textArea.style.left = '-999999px';
			textArea.style.top = '-999999px';
			document.body.appendChild(textArea);
			textArea.focus();
			textArea.select();
			
			try {
				const successful = document.execCommand('copy');
				if (successful) {
					this.showCopySuccess();
				} else {
					toast.error(this.$t('Copy failed, please copy manually'));
				}
			} catch (err) {
				toast.error(this.$t('Copy failed, please copy manually'));
			} finally {
				document.body.removeChild(textArea);
			}
		},
		showCopySuccess() {
			this.copied = true;
			setTimeout(() => {
				this.copied = false;
			}, 4000);
			toast.success(this.$t('Copied to clipboard!'));
		}
	}
};
</script>