// Popup script for axterminator recorder

let isRecording = false;
let actions = [];

// DOM elements
const recordBtn = document.getElementById('recordBtn');
const clearBtn = document.getElementById('clearBtn');
const copyBtn = document.getElementById('copyBtn');
const status = document.getElementById('status');
const actionsCount = document.getElementById('actionsCount');
const codeOutput = document.getElementById('codeOutput');

// Load saved state
chrome.storage.local.get(['isRecording', 'actions'], (result) => {
  isRecording = result.isRecording || false;
  actions = result.actions || [];
  updateUI();
  generateCode();
});

// Toggle recording
recordBtn.addEventListener('click', async () => {
  isRecording = !isRecording;

  // Save state
  chrome.storage.local.set({ isRecording });

  // Notify content script
  const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  if (tab) {
    chrome.tabs.sendMessage(tab.id, { type: 'toggleRecording', isRecording });
  }

  updateUI();
});

// Clear recordings
clearBtn.addEventListener('click', () => {
  actions = [];
  chrome.storage.local.set({ actions: [] });
  updateUI();
  generateCode();
});

// Copy code
copyBtn.addEventListener('click', () => {
  codeOutput.select();
  document.execCommand('copy');
  copyBtn.textContent = 'Copied!';
  setTimeout(() => {
    copyBtn.textContent = 'Copy Code';
  }, 1500);
});

// Listen for actions from content script
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.type === 'actionRecorded') {
    actions.push(message.action);
    chrome.storage.local.set({ actions });
    updateUI();
    generateCode();
  }
});

function updateUI() {
  if (isRecording) {
    recordBtn.textContent = 'Stop Recording';
    recordBtn.classList.add('recording');
    status.textContent = 'Recording... Click elements on the page';
    status.classList.remove('idle');
    status.classList.add('recording');
  } else {
    recordBtn.textContent = 'Start Recording';
    recordBtn.classList.remove('recording');
    status.textContent = 'Ready to record';
    status.classList.add('idle');
    status.classList.remove('recording');
  }

  actionsCount.textContent = `${actions.length} action${actions.length !== 1 ? 's' : ''} recorded`;
}

function generateCode() {
  if (actions.length === 0) {
    codeOutput.value = '# Start recording to generate code...';
    return;
  }

  let code = `#!/usr/bin/env python3
"""Generated by axterminator Recorder"""

import axterminator
from axterminator import BACKGROUND

def main():
    # Note: This script automates a web browser
    # For Safari automation, use:
    app = axterminator.app(name="Safari")

    # For Chrome, use:
    # app = axterminator.app(name="Google Chrome")

`;

  for (const action of actions) {
    const locator = generateLocator(action);

    if (action.type === 'click') {
      code += `    # Click: ${action.text || action.tag}\n`;
      code += `    app.find(${locator}).click()\n\n`;
    } else if (action.type === 'input') {
      code += `    # Type into: ${action.text || action.tag}\n`;
      code += `    element = app.find(${locator})\n`;
      code += `    element.type_text("${escapeString(action.value)}")\n\n`;
    }
  }

  code += `
if __name__ == "__main__":
    main()
`;

  codeOutput.value = code;
}

function generateLocator(action) {
  // Priority: data-testid > aria-label > id > text > tag
  if (action.testId) {
    return `"${action.testId}", strategy="data_testid"`;
  }
  if (action.ariaLabel) {
    return `"${action.ariaLabel}", strategy="aria_label"`;
  }
  if (action.id) {
    return `"${action.id}", strategy="identifier"`;
  }
  if (action.text && action.text.length < 50) {
    return `"${escapeString(action.text)}"`;
  }
  if (action.placeholder) {
    return `"${action.placeholder}"`;
  }
  // Fallback to role/tag
  return `"${action.tag}", role="AX${capitalize(action.tag)}"`;
}

function escapeString(str) {
  return str.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n');
}

function capitalize(str) {
  return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
}
