const WebSocket = require('ws');

const targetId = '99E4CD414CCC9BA4FA79A23CB7746182';
const wsUrl = `ws://127.0.0.1:18800/devtools/page/${targetId}`;

const ws = new WebSocket(wsUrl);
let id = 1;

function sendCommand(method, params = {}) {
  return new Promise((resolve, reject) => {
    const commandId = id++;
    const handler = (data) => {
      const message = JSON.parse(data);
      if (message.id === commandId) {
        ws.removeListener('message', handler);
        if (message.error) {
          reject(new Error(message.error.message));
        } else {
          resolve(message.result);
        }
      }
    };
    ws.on('message', handler);
    ws.send(JSON.stringify({ id: commandId, method, params }));
  });
}

ws.on('open', async () => {
  try {
    console.log('Connected to Chrome');
    
    // Execute JavaScript to fill the form
    const script = `
      (function() {
        // Dismiss cookie banner
        const buttons = Array.from(document.querySelectorAll('button'));
        const dismissButton = buttons.find(btn => btn.textContent.includes('Dismiss'));
        if (dismissButton) {
          dismissButton.click();
          console.log('Clicked dismiss button');
        }
        
        // Wait for banner to dismiss
        setTimeout(() => {
          const email = 'jake@burtonmethod.com';
          const password = 'Mailchimp2026!Secure';
          
          // Find input fields by looking at all text/email inputs
          const inputs = document.querySelectorAll('input[type="text"], input[type="email"], input');
          const passwordInput = document.querySelector('input[type="password"]');
          
          let emailInput = null;
          let usernameInput = null;
          
          // Find the email and username inputs by their labels
          inputs.forEach(input => {
            const label = input.parentElement.querySelector('label, [role="label"], div');
            if (label && label.textContent.includes('Business email')) {
              emailInput = input;
            } else if (label && label.textContent.includes('Username')) {
              usernameInput = input;
            }
          });
          
          // Fill email
          if (emailInput) {
            emailInput.value = email;
            emailInput.dispatchEvent(new Event('input', { bubbles: true }));
            emailInput.dispatchEvent(new Event('change', { bubbles: true }));
            emailInput.dispatchEvent(new Event('blur', { bubbles: true }));
            console.log('Filled email field');
          } else {
            console.log('Email input not found');
          }
          
          // Fill username
          if (usernameInput) {
            usernameInput.value = email;
            usernameInput.dispatchEvent(new Event('input', { bubbles: true }));
            usernameInput.dispatchEvent(new Event('change', { bubbles: true }));
            usernameInput.dispatchEvent(new Event('blur', { bubbles: true }));
            console.log('Filled username field');
          } else {
            console.log('Username input not found');
          }
          
          // Fill password
          if (passwordInput) {
            passwordInput.value = password;
            passwordInput.dispatchEvent(new Event('input', { bubbles: true }));
            passwordInput.dispatchEvent(new Event('change', { bubbles: true }));
            passwordInput.dispatchEvent(new Event('blur', { bubbles: true }));
            console.log('Filled password field');
          } else {
            console.log('Password input not found');
          }
          
          // Click Sign up button after a delay
          setTimeout(() => {
            const signupButton = buttons.find(btn => btn.textContent.trim() === 'Sign up');
            if (signupButton) {
              signupButton.click();
              console.log('Clicked Sign up button');
            } else {
              console.log('Sign up button not found');
            }
          }, 1000);
          
        }, 1500);
        
        return 'Script executed';
      })();
    `;
    
    const result = await sendCommand('Runtime.evaluate', {
      expression: script,
      awaitPromise: false,
      returnByValue: true
    });
    
    console.log('Result:', result.result.value);
    console.log('Form filling script executed. Waiting for navigation...');
    
    // Wait a bit for the form to be submitted
    setTimeout(() => {
      ws.close();
      console.log('Done');
      process.exit(0);
    }, 10000);
    
  } catch (error) {
    console.error('Error:', error.message);
    ws.close();
    process.exit(1);
  }
});

ws.on('error', (error) => {
  console.error('WebSocket error:', error.message);
  process.exit(1);
});
