(function () {
  const params = new URLSearchParams(window.location.search);
  const username = params.get('u') || '';
  const password = params.get('p') || '';
  const url = params.get('url') || '';
  const tool = params.get('tool') || 'Tool';
  const customDes = params.get('des') || '';
  const sheetID = params.get('sheet') || '';

  document.getElementById('tool').textContent = tool + ' — login';
  document.getElementById('usernameField').value = username;
  document.getElementById('passwordField').value = password;
  document.getElementById('urlMeta').textContent = url;

  if (customDes && customDes !== 'null' && customDes !== 'test') {
    document.getElementById('desWrap').style.display = '';
    // Render plain text, auto-linkify any URLs
    const div = document.getElementById('des');
    const escaped = customDes.replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
    div.innerHTML = escaped.replace(/(https?:\/\/[^\s]+)/g, '<a href="$1" target="_blank">$1</a>');
  }

  if (sheetID) {
    document.getElementById('sheetWrap').style.display = '';
    const a = document.getElementById('sheetLink');
    a.href = sheetID; a.textContent = sheetID;
  }

  document.querySelectorAll('button.copy').forEach(b => {
    b.addEventListener('click', () => {
      const field = document.getElementById(b.dataset.copy);
      navigator.clipboard.writeText(field.value).then(() => {
        const tag = b.dataset.copy === 'usernameField' ? 'copiedUser' : 'copiedPass';
        const el = document.getElementById(tag);
        el.classList.add('show');
        setTimeout(() => el.classList.remove('show'), 1200);
      });
    });
  });

  document.getElementById('goBtn').addEventListener('click', () => {
    if (url) window.open(url, '_blank');
  });
})();
