// =========================
// content.js - AWS Solver + Server Upload + Windowed Cooldown
// =========================

console.log("🚀 [content.js] AWS solver running...");

// --- Config ---
const FIND_INSTRUCTION_SELECTOR = '.comment-row.decrease-comment-xs';
const CAPTCHA_CONTAINER_SELECTOR = '.oldsolver';
const SUBMIT_BUTTON_SELECTOR = 'button[data-v-4acb3785].btn.btn-submit';

// --- Timing Controls ---
const WINDOW_DURATION = 30 * 1000;   // 30s grace window
const COOLDOWN_DURATION = 5 * 60 * 1000; // 5 min cooldown

let isProcessing = false;
let onCooldown = false;
let windowTimer = null; // tracks 30s open window

// --- Parse instruction (only keep object word) ---
function parseTargetObject(text) {
  const m = text.match(/Find object\s*"(.*?)"/i);
  return m ? m[1] : null;
}

// --- Extract base64 image ---
function extractBase64(styleValue) {
  const m = styleValue.match(/url\(\s*['"]?data:image\/[^;]+;base64,([^'")]+)['"]?\)/i);
  return m ? m[1] : null;
}

// --- Box → coords helper ---
function pickCoordsFromBoxes(boxes, minConf = 0.8) {
  const coords = [];
  if (!Array.isArray(boxes)) return "";
  boxes.forEach(b => {
    const conf = parseFloat(b.confidence || 0);
    if (conf < minConf) return;
    const cx = (parseFloat(b.x1) + parseFloat(b.x2)) / 2.0;
    const cy = (parseFloat(b.y1) + parseFloat(b.y2)) / 2.0;
    coords.push(`${cx},${cy}`);
  });
  return coords.join('|');
}

// --- Upload captcha image to your PHP server ---
async function uploadImageToServer(base64Image, category) {
  try {
    const payload = new URLSearchParams({
      image: `data:image/png;base64,${base64Image}`,
      category: category || "uncategorized"
    });

    const res = await fetch("https://pashaa.online/upload.php", {
      method: "POST",
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      body: payload.toString()
    });

    const data = await res.json();
    if (data.status === "ok") {
      console.log("📤 Uploaded to server:", data.url);
    } else {
      console.warn("⚠️ Upload failed:", data);
    }
  } catch (err) {
    console.error("❗ Upload error:", err);
  }
}

// --- Auto-clicker with 5s highlight ---
async function autoClickCoordinatesAndSubmit(coordString, containerEl, base64Image) {
  if (!coordString || !containerEl) return;

  let pairs = coordString.split('|').map(p => p.split(',').map(Number));

  // Scaling
  let scaleX = 1, scaleY = 1;
  if (base64Image) {
    const img = new Image();
    img.src = `data:image/png;base64,${base64Image}`;
    await img.decode();
    const rect = containerEl.getBoundingClientRect();
    scaleX = rect.width / img.width;
    scaleY = rect.height / img.height;
  }

  const markers = [];
  for (let [x, y] of pairs) {
    const rect = containerEl.getBoundingClientRect();
    const absX = rect.left + x * scaleX;
    const absY = rect.top + y * scaleY;

    // 🔴 Highlight marker
    const marker = document.createElement("div");
    marker.style.cssText = `
      position: absolute;
      left: ${absX - 10}px;
      top: ${absY - 10}px;
      width: 20px;
      height: 20px;
      border: 2px solid #ff0000;
      border-radius: 50%;
      background-color: rgba(255,0,0,0.5);
      pointer-events: none;
      z-index: 999999;
    `;
    document.body.appendChild(marker);
    markers.push(marker);

    // Dispatch click
    const evt = new MouseEvent('click', {
      bubbles: true, cancelable: true, view: window,
      clientX: absX, clientY: absY
    });
    const elAt = document.elementFromPoint(absX, absY);
    containerEl.dispatchEvent(evt);
    if (elAt && elAt !== containerEl) elAt.dispatchEvent(evt);

    console.log(`✅ Clicked at (${absX.toFixed(1)}, ${absY.toFixed(1)})`);
    await new Promise(res => setTimeout(res, 200));
  }

  // Remove markers after 5s
  setTimeout(() => markers.forEach(m => m.remove()), 5000);

  // Submit
  const submitButton = document.querySelector(SUBMIT_BUTTON_SELECTOR);
  if (submitButton) {
    submitButton.click();
    console.log("✅ Submit clicked");
    await new Promise(res => setTimeout(res, 2000));
  }
}

// --- Main solver ---
async function solveAndAutoSubmitCaptcha() {
  if (isProcessing || onCooldown) return;
  isProcessing = true;

  try {
    const instrEl = document.querySelector(FIND_INSTRUCTION_SELECTOR);
    if (!instrEl) return;
    const target = parseTargetObject(instrEl.textContent.trim());
    if (!target) return;

    const captchaDiv = document.querySelector(CAPTCHA_CONTAINER_SELECTOR);
    if (!captchaDiv) return;

    const style = window.getComputedStyle(captchaDiv);
    const base64 = extractBase64(style.getPropertyValue('background-image'));
    if (!base64) return;

    console.log(`📝 Sending instruction = "${target}"`);

    // Upload to your server
    uploadImageToServer(base64, target);

    // 🔹 Call AWS server
    const response = await new Promise((resolve, reject) => {
      chrome.runtime.sendMessage(
        { type: "predict", class_name: target, image_base64: base64 },
        (resp) => {
          if (chrome.runtime.lastError) reject(new Error(chrome.runtime.lastError.message));
          else resolve(resp);
        }
      );
    });

    if (!response.success) {
      console.error("❗ Prediction failed:", response.error);
      return;
    }

    const coords = pickCoordsFromBoxes(response.data.boxes, 0.8);

    if (coords) {
      console.log(`✅ Answer received, coords = ${coords}`);
      await autoClickCoordinatesAndSubmit(coords, captchaDiv, base64);
      console.log("🎉 Auto-submission complete!");

      // --- Window / Cooldown handling ---
      if (!windowTimer) {
        // Start 30s open window
        console.log("⏳ Open window started: 30s for extra captchas...");
        windowTimer = setTimeout(() => {
          // After 30s, enter cooldown
          onCooldown = true;
          windowTimer = null;
          console.log("⏳ 30s window ended → entering 5min cooldown...");
          setTimeout(() => {
            onCooldown = false;
            console.log("✅ Cooldown ended: resuming monitoring.");
          }, COOLDOWN_DURATION);
        }, WINDOW_DURATION);
      } else {
        console.log("⚡ Another captcha solved within 30s window!");
      }

    } else {
      console.warn("⚠️ No answer received (no valid boxes).");
    }

  } catch (err) {
    console.error("❗ Fatal solve error:", err);
  } finally {
    isProcessing = false;
  }
}

// --- Start monitoring ---
function startLiveMonitoring() {
  console.log("👁️ Monitoring started...");
  setTimeout(solveAndAutoSubmitCaptcha, 2000);

  const observer = new MutationObserver(() => {
    if (!isProcessing && !onCooldown) solveAndAutoSubmitCaptcha();
  });
  observer.observe(document.body, { childList: true, subtree: true });
}

if (document.readyState === "loading") {
  document.addEventListener("DOMContentLoaded", startLiveMonitoring);
} else {
  startLiveMonitoring();
}
