(async () => {
  try {
    // Random delay between 10 and 16 seconds before starting
    const delay = 10000 + Math.random() * 4000;
    await new Promise(r => setTimeout(r, delay));
    console.log(`Waited ${Math.round(delay)} ms before starting.`);

    const captchaDiv = document.querySelector("#codigooo");
    if (!captchaDiv) return console.error("Captcha div not found");

    const captchaText = captchaDiv.textContent.trim();
    if (!captchaText) return console.error("Captcha text empty");

    const input = document.querySelector("#captcha_text");
    if (input) {
      input.focus();
      input.value = ""; // Clear existing input before typing

      // Simulate human-like typing one character at a time
      for (const char of captchaText) {
        input.value += char;
        input.dispatchEvent(new Event("input", { bubbles: true }));
        input.dispatchEvent(new Event("change", { bubbles: true }));

        // Random delay between keystrokes: 100ms to 300ms
        const charDelay = 100 + Math.random() * 200;
        await new Promise(r => setTimeout(r, charDelay));
      }
      console.log("Finished typing captcha.");
    } else {
      console.warn("Captcha input not found");
    }

    function simulateMouseClick(element) {
      const rect = element.getBoundingClientRect();
      const x = rect.left + rect.width / 2;
      const y = rect.top + rect.height / 2;

      element.dispatchEvent(new MouseEvent('mouseover', { bubbles: true, clientX: x, clientY: y }));
      element.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, clientX: x, clientY: y }));
      element.dispatchEvent(new MouseEvent('mouseup', { bubbles: true, clientX: x, clientY: y }));
      element.dispatchEvent(new MouseEvent('click', { bubbles: true, clientX: x, clientY: y }));
    }

    async function tryClickLoginButton() {
      let attempts = 0;
      const maxAttempts = 5;

      return new Promise((resolve) => {
        const interval = setInterval(() => {
          const btn = document.querySelector("button.g-recaptcha.button_generic");
          attempts++;

          if (btn && !btn.disabled && btn.offsetParent !== null) {
            // Random delay before click between 100ms and 800ms
            setTimeout(() => {
              simulateMouseClick(btn);
              console.log("Login button clicked.");
              clearInterval(interval);
              resolve(true);
            }, 100 + Math.random() * 700);
          } else if (attempts >= maxAttempts) {
            clearInterval(interval);
            console.warn("Login button not clickable after multiple attempts.");
            resolve(false);
          }
        }, 1000);
      });
    }

    await tryClickLoginButton();

  } catch (e) {
    console.error("Captcha autofill error:", e);
  }
})();
