const API_BASE = 'https://privo.fyi'; const urlInput = document.getElementById('urlInput'); const shortenBtn = document.getElementById('shortenBtn'); const resultArea = document.getElementById('resultArea'); const shortLinkText = document.getElementById('shortLinkText'); const copyBtn = document.getElementById('copyBtn'); const errorMsg = document.getElementById('errorMsg'); shortenBtn.addEventListener('click', async () => { let url = urlInput.value.trim(); errorMsg.style.display = 'none'; resultArea.style.display = 'none'; if (!url) { showError('Please enter a URL.'); return; } if (!url.startsWith('http://') && !url.startsWith('https://')) { url = 'https://' + url; } shortenBtn.disabled = true; shortenBtn.textContent = '...'; try { const res = await fetch(`${API_BASE}/api/link`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ url }) }); const data = await res.json(); if (!res.ok) { throw new Error(data.error || 'Failed to shorten link'); } shortLinkText.href = data.short_url; shortLinkText.textContent = data.short_url; resultArea.style.display = 'block'; urlInput.value = ''; urlInput.focus(); } catch (err) { showError(err.message); } finally { shortenBtn.disabled = false; shortenBtn.textContent = 'Shorten'; } }); urlInput.addEventListener('keypress', (e) => { if (e.key === 'Enter') { shortenBtn.click(); } }); copyBtn.addEventListener('click', () => { navigator.clipboard.writeText(shortLinkText.textContent).then(() => { copyBtn.textContent = '✓ Copied!'; setTimeout(() => { copyBtn.textContent = 'Copy'; }, 2000); }).catch(() => { const range = document.createRange(); range.selectNode(shortLinkText); window.getSelection().removeAllRanges(); window.getSelection().addRange(range); document.execCommand('copy'); window.getSelection().removeAllRanges(); copyBtn.textContent = '✓ Copied!'; setTimeout(() => { copyBtn.textContent = 'Copy'; }, 2000); }); }); function showError(msg) { errorMsg.textContent = msg; errorMsg.style.display = 'block'; }