/**
 * content-wizard.js — Wizard Automation Content Script
 * Handles automation commands from background.js on:
 * - icloud-setan.texaproject.com (email generation, inbox, verification)
 * - figma.com/signup (form filling)
 * - weave.figma.com (Weavy login + token capture trigger)
 */

(function () {
  if (window.__wizardInjected) return;
  window.__wizardInjected = true;

  const hostname = window.location.hostname;
  const pathname = window.location.pathname;
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

  // Keep-alive port connection to prevent Service Worker suspension
  try {
    let port = chrome.runtime.connect({ name: "wizard-keepalive" });
    port.onDisconnect.addListener(() => {
      setTimeout(() => {
        try { port = chrome.runtime.connect({ name: "wizard-keepalive" }); } catch (e) {}
      }, 1000);
    });
    setInterval(() => {
      try { port.postMessage({ type: "ping" }); } catch (e) {}
    }, 8000);
  } catch (e) {}

  // ─── Message listener ──────────────────────────────────────────────────────
  chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
    if (!msg || !msg.action) return false;

    // Route based on action
    const handler = HANDLERS[msg.action];
    if (handler) {
      handler(msg, sendResponse);
      return true; // keep channel open for async
    }
    return false;
  });

  const HANDLERS = {};

  // ═══════════════════════════════════════════════════════════════════════════
  // iCloud Setan handlers
  // ═══════════════════════════════════════════════════════════════════════════

  if (hostname.includes("icloud-setan")) {
    // Login with voucher
    HANDLERS["WIZARD_LOGIN"] = async (msg, respond) => {
      try {
        const voucher = msg.voucher;
        if (!voucher) return respond({ ok: false, error: "No voucher provided" });

        const overlay = document.getElementById("login-overlay");
        if (overlay && overlay.classList.contains("hidden")) {
          return respond({ ok: true, msg: "Already logged in" });
        }

        const input = document.getElementById("login-code");
        const submit = document.getElementById("login-submit");
        if (!input || !submit) return respond({ ok: false, error: "Login form not found" });

        input.value = voucher;
        input.dispatchEvent(new Event("input", { bubbles: true }));
        await sleep(300);
        submit.click();

        // Wait for login success
        for (let i = 0; i < 30; i++) {
          await sleep(500);
          const btn = document.getElementById("btn-generate");
          if (btn) return respond({ ok: true, msg: "Login success" });
        }
        respond({ ok: false, error: "Login timeout" });
      } catch (e) {
        respond({ ok: false, error: e.message });
      }
    };

    // Generate random email
    HANDLERS["WIZARD_GENERATE_EMAIL"] = async (msg, respond) => {
      try {
        // Select server if specified
        if (msg.serverIndex !== undefined) {
          const picker = document.getElementById("account-picker");
          if (picker) {
            const options = picker.querySelectorAll("option");
            if (options[msg.serverIndex]) {
              picker.value = options[msg.serverIndex].value;
              picker.dispatchEvent(new Event("change", { bubbles: true }));
              await sleep(1000);
            }
          }
        }

        const btn = document.getElementById("btn-generate");
        if (!btn) return respond({ ok: false, error: "Generate button not found" });

        btn.click();
        await sleep(3000);

        // Check for limit modal
        const limitModal = document.getElementById("limit-modal");
        if (limitModal && !limitModal.classList.contains("hidden")) {
          const closeBtn = document.getElementById("limit-close");
          if (closeBtn) closeBtn.click();
          return respond({ ok: false, error: "LIMIT", msg: "Server limit reached" });
        }

        // Check for error message
        const msgEl = document.getElementById("message");
        if (msgEl && !msgEl.classList.contains("hidden") && msgEl.classList.contains("bg-red-100")) {
          return respond({ ok: false, error: "ERROR", msg: msgEl.textContent.trim() });
        }

        // Wait for reserve step
        const reserveStep = document.getElementById("step-reserve");
        if (!reserveStep) return respond({ ok: false, error: "Reserve step not found" });

        for (let i = 0; i < 20; i++) {
          await sleep(500);
          if (!reserveStep.classList.contains("hidden") || reserveStep.style.display !== "none") {
            const emailInput = document.getElementById("generated-email");
            if (emailInput && emailInput.value.includes("@icloud.com")) {
              return respond({ ok: true, email: emailInput.value });
            }
          }
        }
        respond({ ok: false, error: "Email generation timeout" });
      } catch (e) {
        respond({ ok: false, error: e.message });
      }
    };

    // Reserve (activate) the generated email
    HANDLERS["WIZARD_RESERVE_EMAIL"] = async (msg, respond) => {
      try {
        const labelInput = document.getElementById("email-label");
        const reserveBtn = document.getElementById("btn-reserve");
        if (!labelInput || !reserveBtn) return respond({ ok: false, error: "Reserve form not found" });

        const suffix = Math.random().toString(36).slice(2, 6).toUpperCase();
        labelInput.value = `Kling-${suffix}`;
        labelInput.dispatchEvent(new Event("input", { bubbles: true }));
        await sleep(300);
        reserveBtn.click();

        // Wait for inbox step to appear
        for (let i = 0; i < 50; i++) {
          await sleep(500);
          const inboxStep = document.getElementById("step-inbox");
          if (inboxStep && !inboxStep.classList.contains("hidden")) {
            return respond({ ok: true, suffix });
          }
        }
        respond({ ok: false, error: "Reserve timeout" });
      } catch (e) {
        respond({ ok: false, error: e.message });
      }
    };

    // Get server options count
    HANDLERS["WIZARD_GET_SERVERS"] = async (msg, respond) => {
      try {
        const picker = document.getElementById("account-picker");
        if (!picker) return respond({ ok: true, count: 0, servers: [] });
        const options = picker.querySelectorAll("option");
        const servers = Array.from(options).map((o, i) => ({
          index: i,
          value: o.value,
          text: o.textContent.trim(),
        }));
        respond({ ok: true, count: servers.length, servers });
      } catch (e) {
        respond({ ok: false, error: e.message });
      }
    };

    // Open saved emails list and click specific email card
    HANDLERS["WIZARD_OPEN_INBOX"] = async (msg, respond) => {
      try {
        const targetEmail = msg.email;

        // Click "Lihat Email Tersimpan"
        const savedBtn = document.getElementById("btn-show-saved");
        if (savedBtn) {
          savedBtn.click();
          await sleep(2000);
        }

        // Find and click the card
        const copyBtns = document.querySelectorAll(".btn-copy-saved");
        for (const btn of copyBtns) {
          if (btn.dataset.email === targetEmail) {
            const card = btn.closest(".bg-white") || btn.parentElement;
            if (card) {
              card.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
              await sleep(2000);
              return respond({ ok: true });
            }
          }
        }

        // Fallback: try spans
        const spans = document.querySelectorAll("span.font-mono, span.text-blue-600");
        for (const span of spans) {
          if (span.textContent.trim() === targetEmail) {
            const card = span.closest(".bg-white") || span.parentElement;
            if (card) {
              card.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
              await sleep(2000);
              return respond({ ok: true });
            }
          }
        }

        respond({ ok: false, error: "Email card not found" });
      } catch (e) {
        respond({ ok: false, error: e.message });
      }
    };

    // Refresh inbox and check for Figma email
    HANDLERS["WIZARD_CHECK_INBOX"] = async (msg, respond) => {
      try {
        const refreshBtn = document.getElementById("btn-refresh-inbox");
        if (refreshBtn) refreshBtn.click();
        await sleep(5000);

        const inboxEl = document.getElementById("inbox-messages");
        if (!inboxEl) return respond({ ok: false, hasFigma: false, error: "Inbox element not found" });

        const text = inboxEl.textContent || "";
        const hasFigma = text.toLowerCase().includes("figma");
        respond({ ok: true, hasFigma, preview: text.trim().substring(0, 100) });
      } catch (e) {
        respond({ ok: false, error: e.message });
      }
    };

    // Click Figma message and extract verification link from iframe
    HANDLERS["WIZARD_GET_VERIFY_LINK"] = async (msg, respond) => {
      try {
        // Click the Figma message
        const inboxEl = document.getElementById("inbox-messages");
        if (!inboxEl) return respond({ ok: false, error: "Inbox not found" });

        // Try clicking by text
        let clicked = false;
        const figmaEl = inboxEl.querySelector("div.flex-1 > div.flex");
        if (figmaEl) {
          figmaEl.click();
          clicked = true;
        }

        if (!clicked) {
          // Try XPath
          const xpath = document.evaluate(
            '//*[@id="inbox-messages"]/div/div[1]/div[2]/div[1]',
            document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null
          );
          if (xpath.singleNodeValue) {
            xpath.singleNodeValue.click();
            clicked = true;
          }
        }

        if (!clicked) {
          // Try text=Figma
          const allDivs = inboxEl.querySelectorAll("div");
          for (const div of allDivs) {
            if (div.textContent.includes("Figma") && div.children.length === 0) {
              div.click();
              clicked = true;
              break;
            }
          }
        }

        if (!clicked) return respond({ ok: false, error: "Could not click Figma message" });

        // Wait for iframe to load
        await sleep(6000);

        let verifyUrl = null;

        // Method 1: Check all iframes
        const iframes = document.querySelectorAll("iframe");
        for (const iframe of iframes) {
          try {
            const doc = iframe.contentDocument || iframe.contentWindow?.document;
            if (!doc) continue;
            const links = doc.querySelectorAll("a[href]");
            for (const link of links) {
              if (link.href.includes("figma.com")) {
                verifyUrl = link.href;
                break;
              }
            }
            if (verifyUrl) break;

            // Try tr:nth-of-type(3) a
            const trLink = doc.querySelector("tr:nth-of-type(3) a");
            if (trLink && trLink.href) {
              verifyUrl = trLink.href;
              break;
            }
          } catch (e) {
            // cross-origin, ignore
          }
        }

        // Method 2: Check page HTML
        if (!verifyUrl) {
          const html = document.documentElement.innerHTML;
          const m =
            html.match(/href="(https?:\/\/[^"]*figma\.com\/email\/[^"]+)"/) ||
            html.match(/href="(https?:\/\/[^"]*figma\.com[^"]*(?:verify|confirm)[^"]*)"/) ||
            html.match(/(https?:\/\/www\.figma\.com\/[^\s"<>]*(?:verify|confirm)[^\s"<>]*)/);
          if (m) verifyUrl = m[1];
        }

        respond({ ok: !!verifyUrl, url: verifyUrl || null });
      } catch (e) {
        respond({ ok: false, error: e.message });
      }
    };
  }

  // ═══════════════════════════════════════════════════════════════════════════
  // Figma Signup handlers
  // ═══════════════════════════════════════════════════════════════════════════

  if (hostname.includes("figma.com") && (pathname.includes("signup") || pathname.includes("login"))) {
    HANDLERS["WIZARD_FILL_SIGNUP"] = async (msg, respond) => {
      try {
        const { email, password } = msg;
        await sleep(1500);

        // Fill email
        const emailInput = document.querySelector("input[type='email'], input[name='email']");
        if (emailInput) {
          emailInput.focus();
          emailInput.value = email;
          emailInput.dispatchEvent(new Event("input", { bubbles: true }));
          emailInput.dispatchEvent(new Event("change", { bubbles: true }));
          await sleep(500);
        }

        // Click Continue
        const continueSelectors = [
          "button[type='submit']",
          "button:not([disabled])",
        ];
        for (const sel of continueSelectors) {
          const btns = document.querySelectorAll(sel);
          for (const btn of btns) {
            const text = btn.textContent.toLowerCase();
            if (text.includes("google")) continue;
            if (text.includes("continue") || text.includes("create") || text.includes("sign up")) {
              btn.click();
              await sleep(2500);
              break;
            }
          }
        }

        // Fill password if visible
        await sleep(1000);
        const passInput = document.querySelector("input[type='password']");
        if (passInput) {
          passInput.focus();
          passInput.value = password;
          passInput.dispatchEvent(new Event("input", { bubbles: true }));
          passInput.dispatchEvent(new Event("change", { bubbles: true }));
          await sleep(500);

          // Click submit
          const submitBtns = document.querySelectorAll("button[type='submit'], button");
          for (const btn of submitBtns) {
            const text = btn.textContent.toLowerCase();
            if (text.includes("google")) continue;
            if (text.includes("create") || text.includes("sign up") || text.includes("continue") || text.includes("log in")) {
              btn.click();
              break;
            }
          }
        }

        respond({ ok: true });
      } catch (e) {
        respond({ ok: false, error: e.message });
      }
    };

    // Check page status (did signup succeed? is there a CAPTCHA?)
    HANDLERS["WIZARD_CHECK_SIGNUP"] = async (msg, respond) => {
      try {
        const url = window.location.href;
        let isSuccess = url.includes("verify") || url.includes("files") ||
                          url.includes("team") || url.includes("recents");

        // If it's a dashboard URL, ensure figma onboarding is complete first
        if (isSuccess && (url.includes("files") || url.includes("team") || url.includes("recents"))) {
          const hasNameInput = !!document.querySelector("input[placeholder*='name'], input[type='text']");
          const hasContinueBtn = Array.from(document.querySelectorAll("button")).some(
            (b) => b.textContent.trim().toLowerCase() === "continue"
          );
          const hasSkipBtn = Array.from(document.querySelectorAll("button, a, div")).some(
            (el) => {
              const text = el.textContent.trim().toLowerCase();
              return text === "skip" || text === "skip this step" || text === "do this later";
            }
          );
          const hasFreePlanBtn = Array.from(document.querySelectorAll("button, span")).some(
            (el) => {
              const text = el.textContent.trim().toLowerCase();
              return text.includes("start for free") || text.includes("choose starter");
            }
          );
          if (hasNameInput || hasContinueBtn || hasSkipBtn || hasFreePlanBtn) {
            isSuccess = false; // still stuck in onboarding steps
          }
        }

        // Check for CAPTCHA
        const hasCaptcha = !!document.querySelector("[class*='captcha'], iframe[src*='captcha'], iframe[src*='recaptcha'], [id*='captcha']");

        // Check for error
        const errorEl = document.querySelector("[class*='error'], [role='alert']");
        const errorText = errorEl ? errorEl.textContent.trim() : "";

        respond({
          ok: true,
          url,
          isSuccess,
          hasCaptcha,
          errorText: errorText.substring(0, 200),
        });
      } catch (e) {
        respond({ ok: false, error: e.message });
      }
    };
  }

  // ═══════════════════════════════════════════════════════════════════════════
  // Weave/Weavy handlers  
  // ═══════════════════════════════════════════════════════════════════════════

  if (hostname.includes("weave.figma.com") || hostname.includes("app.weavy.ai")) {
    HANDLERS["WIZARD_WEAVY_LOGIN"] = async (msg, respond) => {
      try {
        await sleep(2000);
        const url = window.location.href;

        // If already in dashboard, done
        if (url.includes("weave.figma.com") && !url.endsWith("/") &&
            !url.includes("login") && !url.includes("signin")) {
          return respond({ ok: true, url, msg: "Already in dashboard" });
        }

        // Click "Try Now"
        const tryNow = document.querySelector("#try_now_top > div.nav-button-spacer") ||
                       document.querySelector("#try_now_top .nav-button-spacer") ||
                       document.querySelector("[id*='try'] .nav-button-spacer");
        if (tryNow) {
          tryNow.click();
          await sleep(3000);
        } else {
          // Try link-based
          const links = document.querySelectorAll("a");
          for (const link of links) {
            if (link.textContent.toLowerCase().includes("try now") || link.textContent.toLowerCase().includes("get started")) {
              link.click();
              await sleep(3000);
              break;
            }
          }
        }

        // Click "Log in with Figma"
        await sleep(2000);
        const btns = document.querySelectorAll("button");
        for (const btn of btns) {
          if (btn.textContent.toLowerCase().includes("log in with figma") ||
              btn.textContent.toLowerCase().includes("login with figma")) {
            btn.click();
            await sleep(5000);
            break;
          }
        }

        respond({ ok: true, url: window.location.href });
      } catch (e) {
        respond({ ok: false, error: e.message });
      }
    };

    HANDLERS["WIZARD_CHECK_TOKEN"] = async (msg, respond) => {
      respond({ ok: true, url: window.location.href });
    };
  }

  // Auto-bypass Figma onboarding steps once redirected to files/team pages
  if (hostname.includes("figma.com") && (pathname.includes("/files") || pathname.includes("/team") || pathname.includes("/recents"))) {
    setInterval(async () => {
      try {
        // 1. "What's your name?" page (Continue onboarding)
        const nameInput = document.querySelector("input[placeholder*='name'], input[type='text']");
        const continueBtn = Array.from(document.querySelectorAll("button")).find(
          (b) => b.textContent.trim().toLowerCase() === "continue"
        );
        if (continueBtn && nameInput) {
          if (!nameInput.value.trim()) {
            nameInput.value = "Kling User";
            nameInput.dispatchEvent(new Event("input", { bubbles: true }));
          }
          continueBtn.click();
          await sleep(1000);
        }

        // 2. Questions like "What kind of work do you do?" -> Click "Skip"
        const skipBtn = Array.from(document.querySelectorAll("button, a, div")).find(
          (el) => {
            const text = el.textContent.trim().toLowerCase();
            return text === "skip" || text === "skip this step" || text === "do this later";
          }
        );
        if (skipBtn && typeof skipBtn.click === "function") {
          skipBtn.click();
          await sleep(1000);
        }

        // 3. Choose plan: "Start for free"
        const freePlanBtn = Array.from(document.querySelectorAll("button, span")).find(
          (el) => {
            const text = el.textContent.trim().toLowerCase();
            return text.includes("start for free") || text.includes("choose starter");
          }
        );
        if (freePlanBtn && typeof freePlanBtn.click === "function") {
          freePlanBtn.click();
          await sleep(1000);
        }
      } catch (e) {
        // Ignore loop errors
      }
    }, 1500);
  }
})();
