document.addEventListener('DOMContentLoaded', () => {
const copyButtons = document.querySelectorAll('.copy-btn');
copyButtons.forEach(button => {
button.addEventListener('click', async () => {
const targetId = button.getAttribute('data-target');
const codeElement = document.getElementById(targetId);
const textToCopy = codeElement.textContent;
try {
await navigator.clipboard.writeText(textToCopy);
button.classList.add('copied');
const originalHTML = button.innerHTML;
button.innerHTML = `
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M13.78 4.22a.75.75 0 0 1 0 1.06l-7.25 7.25a.75.75 0 0 1-1.06 0L2.22 9.28a.75.75 0 0 1 1.06-1.06L6 10.94l6.72-6.72a.75.75 0 0 1 1.06 0Z" fill="currentColor"/>
</svg>
`;
setTimeout(() => {
button.classList.remove('copied');
button.innerHTML = originalHTML;
}, 2000);
} catch (err) {
console.error('Failed to copy:', err);
const tempInput = document.createElement('textarea');
tempInput.value = textToCopy;
tempInput.style.position = 'fixed';
tempInput.style.opacity = '0';
document.body.appendChild(tempInput);
tempInput.select();
try {
document.execCommand('copy');
button.classList.add('copied');
setTimeout(() => button.classList.remove('copied'), 2000);
} catch (fallbackErr) {
console.error('Fallback copy failed:', fallbackErr);
}
document.body.removeChild(tempInput);
}
});
});
});