---
interface Props {
	class?: string;
	style?: string;
	tabindex?: string;
	'data-language'?: string;
	[key: string]: any;
}

const props = Astro.props;
const uniqueId = `code-${Math.random().toString(36).substr(2, 9)}`;
---

<div class="code-block-wrapper" data-code-id={uniqueId}>
	<button class="copy-button" data-copy-btn={uniqueId}>
		Copy
	</button>
	<pre {...props}><slot /></pre>
</div>

<style>
	.code-block-wrapper {
		position: relative;
		margin: 1rem 0;
	}

	.copy-button {
		position: absolute;
		top: 0.5rem;
		right: 0.5rem;
		padding: 0.25rem 0.5rem;
		background-color: rgba(255, 255, 255, 0.1);
		border: 1px solid rgba(255, 255, 255, 0.2);
		border-radius: 4px;
		color: white;
		cursor: pointer;
		font-size: 0.875rem;
		opacity: 0;
		transition: opacity 0.2s, background-color 0.2s;
		z-index: 10;
	}

	.code-block-wrapper:hover .copy-button {
		opacity: 1;
	}

	.copy-button:hover {
		background-color: rgba(255, 255, 255, 0.2);
	}

	.copy-button.copied {
		background-color: rgba(34, 197, 94, 0.3);
	}
</style>

<script>
	function setupCopyButtons() {
		const buttons = document.querySelectorAll('[data-copy-btn]');
		
		buttons.forEach((button) => {
			if (button.hasAttribute('data-initialized')) return;
			button.setAttribute('data-initialized', 'true');
			
			button.addEventListener('click', async () => {
				const wrapper = button.closest('.code-block-wrapper');
				const pre = wrapper?.querySelector('pre');
				const code = pre?.textContent || '';
				
				try {
					await navigator.clipboard.writeText(code);
					button.textContent = 'Copied!';
					button.classList.add('copied');
					
					setTimeout(() => {
						button.textContent = 'Copy';
						button.classList.remove('copied');
					}, 2000);
				} catch (err) {
					console.error('Failed to copy:', err);
					button.textContent = 'Failed';
					setTimeout(() => {
						button.textContent = 'Copy';
					}, 2000);
				}
			});
		});
	}
	setupCopyButtons();
	document.addEventListener('astro:page-load', setupCopyButtons);
</script>