const params = new URLSearchParams(window.location.search);
const requestId = params.get('id') || '';

const el = {
  status: document.querySelector('#status'),
  origin: document.querySelector('#origin'),
  address: document.querySelector('#address'),
  payloadSummary: document.querySelector('#payloadSummary'),
  approveBtn: document.querySelector('#approveBtn'),
  rejectBtn: document.querySelector('#rejectBtn'),
};

function request(method) {
  return new Promise((resolve, reject) => {
    chrome.runtime.sendMessage(
      {
        type: 'MAZEXCHAIN_SIGNATURE_APPROVAL',
        method,
        id: requestId,
      },
      (response) => {
        if (chrome.runtime.lastError) {
          reject(new Error(chrome.runtime.lastError.message));
          return;
        }
        if (response?.ok) {
          resolve(response.result);
          return;
        }
        reject(new Error(response?.error?.message || 'Signature approval request failed.'));
      },
    );
  });
}

function setStatus(value) {
  el.status.textContent = value;
}

function setBusy(isBusy) {
  el.approveBtn.disabled = isBusy;
  el.rejectBtn.disabled = isBusy;
}

function shortHash(value) {
  if (!value) return '--';
  return `${String(value).slice(0, 16)}...${String(value).slice(-10)}`;
}

function renderSummary(payload = {}) {
  const rows = Object.entries(payload).filter(([, value]) => value !== '' && value !== undefined && value !== null);
  el.payloadSummary.innerHTML = rows
    .map(([key, value]) => `<dt>${key}</dt><dd>${String(value).replace(/[<>&"]/g, '')}</dd>`)
    .join('');
}

async function load() {
  if (!requestId) {
    throw new Error('Missing signature request id.');
  }
  const pending = await request('getPendingSignature');
  el.origin.textContent = pending.origin || '--';
  el.address.textContent = pending.account?.address || '--';
  renderSummary({
    ...pending.payload,
    address: shortHash(pending.account?.address),
    expires_at: pending.expires_at,
  });
  setStatus('Review the request before signing. Approval returns a signature to the requesting site.');
}

el.approveBtn.addEventListener('click', async () => {
  try {
    setBusy(true);
    setStatus('Approving signature...');
    await request('approveSignature');
    setStatus('Signature approved. You can close this window.');
    setTimeout(() => window.close(), 450);
  } catch (error) {
    setStatus(`Approval failed: ${error.message}`);
    setBusy(false);
  }
});

el.rejectBtn.addEventListener('click', async () => {
  try {
    setBusy(true);
    setStatus('Rejecting signature...');
    await request('rejectSignature');
    setStatus('Signature rejected. You can close this window.');
    setTimeout(() => window.close(), 450);
  } catch (error) {
    setStatus(`Reject failed: ${error.message}`);
    setBusy(false);
  }
});

load().catch((error) => {
  setStatus(error.message);
  setBusy(true);
});
