(() => {
  const target = document.querySelector('#success-download');
  const message = document.querySelector('#success-message');
  const token = sessionStorage.getItem('mpcDownloadToken');
  const expiresAt = sessionStorage.getItem('mpcDownloadExpiresAt');
  if (!token || !/^[A-Za-z0-9_-]{30,100}$/.test(token)) {
    target.innerHTML = '<a class="primary-button inline-button" href="/">Return to secure checkout</a>';
    message.textContent = 'No unused download entitlement was found in this browser session.';
    return;
  }
  const form = document.createElement('form');
  form.method = 'post';
  form.action = `/download/${encodeURIComponent(token)}`;
  const button = document.createElement('button');
  button.type = 'submit';
  button.className = 'primary-button download-button';
  button.textContent = 'Download companion now';
  form.appendChild(button);
  target.appendChild(form);
  message.textContent = expiresAt ? `One download only. This secure entitlement expires at ${new Date(expiresAt).toLocaleString()}.` : 'One download only.';
  form.addEventListener('submit', () => {
    button.disabled = true;
    button.textContent = 'Starting secure download...';
    sessionStorage.removeItem('mpcDownloadToken');
    sessionStorage.removeItem('mpcDownloadExpiresAt');
  });
})();
