// Paste on https://ui.perfetto.dev/ (home, not the recording page), then close Console.
// Uses the official Perfetto UI extension. Maximum duration: 120 seconds.
(() => {
  const extensionId = 'lfmkphfpdbjijhpomgecfikhfohaoine';
  const request = atob('CqkECgYIgIAGIAEKBQiAECACCgYIgIABIAES0QEKzgEKC3RyYWNrX2V2ZW50EACKB7sBCgEqEgh0b3BsZXZlbBINdG9wbGV2ZWwuZmxvdxIScmVuZGVyZXIuc2NoZWR1bGVyEgJ2OBIKdjguZXhlY3V0ZRIHdjgud2FzbRIRZGV2dG9vbHMudGltZWxpbmUSAmNjEgNncHUSBWF1ZGlvEgh3ZWJhdWRpbxIZZGlzYWJsZWQtYnktZGVmYXVsdC12OC5nYxImY29uZmlnLnNjaGVkdWxlci5yZWNvcmRfdGFza19wb3N0X3RpbWVAARIiCiAKHG9yZy5jaHJvbWl1bS50cmFjZV9tZXRhZGF0YTIQARIqCigKC3RyYWNrX2V2ZW50EAGKBxYKASoSEWJsaW5rLnVzZXJfdGltaW5nEsEBCr4BCgxsaW51eC5mdHJhY2UQAqIGqgEKEnNjaGVkL3NjaGVkX3N3aXRjaAoSc2NoZWQvc2NoZWRfd2FraW5nChhzY2hlZC9zY2hlZF9wcm9jZXNzX2V4aXQKGHNjaGVkL3NjaGVkX3Byb2Nlc3NfZnJlZQoRdGFzay90YXNrX25ld3Rhc2sKEHRhc2svdGFza19yZW5hbWUKE3Bvd2VyL2NwdV9mcmVxdWVuY3kKDnBvd2VyL2NwdV9pZGxlYgIIARIeChwKE2xpbnV4LnByb2Nlc3Nfc3RhdHMQAboGAhABGMCpB6oBAwj0Aw==');
  document.getElementById('g3-system-reproduction')?.remove();
  const panel = document.createElement('div'); panel.id = 'g3-system-reproduction';
  panel.style.cssText = 'position:fixed;inset:24px;z-index:2147483647;background:white;color:black;padding:24px;border:3px solid #356;overflow:auto;font:18px sans-serif';
  const title = document.createElement('h2'); title.textContent = 'G3 Chrome + OS trace';
  const start = document.createElement('button'); start.textContent = 'Start tracing';
  const stop = document.createElement('button'); stop.textContent = 'Stop and save'; stop.disabled = true;
  for (const button of [start,stop]) button.style.cssText = 'font-size:20px;padding:12px;margin-right:12px';
  const status = document.createElement('pre'); status.style.whiteSpace = 'pre-wrap';
  status.textContent = 'Ready. Close Console, then start tracing. Auto stop: maximum 120 seconds.';
  // Perfetto redraws body; keep these controls outside its managed root.
  panel.append(title,start,stop,status); document.documentElement.append(panel);
  start.onclick = () => {
    start.disabled = true; stop.disabled = false;
    status.textContent = 'Recording requested. Reproduce playback in another tab, then return here and press Stop and save.';
    const parts = []; let port, finished = false, timer;
    function end(message) {
      if (finished) return; finished = true; clearTimeout(timer); stop.disabled = true;
      status.textContent = message;
      try { port?.postMessage({method:'FreeBuffers',requestData:''}); } catch {}
      setTimeout(() => { try { port?.disconnect(); } catch {} }, 100);
    }
    try {
      port = chrome.runtime.connect(extensionId);
      timer = setTimeout(() => end('Timed out waiting for trace. Copy this status.'), 180000);
      stop.onclick = () => {
        stop.disabled = true; status.textContent = 'Stopping and reading trace. Wait for download.';
        port.postMessage({method:'DisableTracing',requestData:''});
      };
      port.onDisconnect.addListener(() => {
        const error = chrome.runtime.lastError?.message;
        if (!finished) end('Extension disconnected: ' + (error ?? 'unknown reason'));
      });
      port.onMessage.addListener(message => {
        if (message.type === 'ChromeExtensionError') { end(message.error); return; }
        if (message.type === 'EnableTracingResponse') {
          stop.disabled = true; status.textContent = 'Recording ended. Reading trace; wait for download.';
          port.postMessage({method:'ReadBuffers',requestData:''});
        }
        if (message.type === 'ReadBuffersResponse') for (const slice of message.slices) {
          parts.push(Uint8Array.from(slice.data, c => c.charCodeAt(0)));
          if (slice.lastSliceForPacket) {
            const bytes = parts.reduce((n,p) => n + p.length, 0);
            if (!bytes) { end('Empty trace received.'); return; }
            const gzip = parts[0]?.[0] === 31 && parts[0]?.[1] === 139;
            const link = document.createElement('a');
            link.href = URL.createObjectURL(new Blob(parts,{type:'application/octet-stream'}));
            link.download = 'g3-system-reproduction.perfetto-trace' + (gzip ? '.gz' : '');
            link.textContent = 'Download trace again'; panel.append(document.createElement('br'),link);
            link.click(); end('Saved ' + bytes + ' bytes. Save the player diagnostics JSON from the same run.');
          }
        }
      });
      // Intentionally skip recording-page metadata/category discovery.
      port.postMessage({method:'EnableTracing',requestData:request});
    } catch (error) { end(String(error)); }
  };
})();
