/**
 * content.js — Kling Token Bot Content Script
 * Runs on weave.figma.com — shows visual indicator when extension is active
 */

(function() {
  function isContextValid() {
    try {
      if (typeof chrome === "undefined" || !chrome.runtime || !chrome.runtime.id) {
        return false;
      }
      chrome.runtime.getManifest();
      return true;
    } catch (e) {
      return false;
    }
  }

  // Handle iCloud Setan auto-login
  if (window.location.hostname.includes("icloud-setan.texaproject.com")) {
    function handleICloudSetan() {
      if (!isContextValid()) return;
      try {
        chrome.storage.local.get("icloudSetanVoucher", (result) => {
          if (chrome.runtime?.lastError) return;
          const voucher = result.icloudSetanVoucher;
          if (!voucher) return;
          
          const checkExist = setInterval(() => {
            const input = document.getElementById("login-code");
            const submit = document.getElementById("login-submit");
            const overlay = document.getElementById("login-overlay");
            
            if (overlay && overlay.classList.contains("hidden")) {
              clearInterval(checkExist);
              return;
            }

            if (input && submit) {
              clearInterval(checkExist);
              input.value = voucher;
              input.dispatchEvent(new Event("input", { bubbles: true }));
              setTimeout(() => {
                submit.click();
              }, 500);
            }
          }, 500);
        });
      } catch (e) {
        // context invalidated, ignore
      }
    }

    if (document.body) {
      handleICloudSetan();
    } else {
      document.addEventListener("DOMContentLoaded", handleICloudSetan);
    }
    return;
  }

  // Only inject once for figma
  if (window.__klingBotInjected) return;
  window.__klingBotInjected = true;

  // Small floating indicator badge
  function createBadge() {
    const badge = document.createElement("div");
    badge.id = "__kling-bot-badge";
    badge.innerHTML = `
      <span style="font-size:14px">🤖</span>
      <span style="font-size:10px;font-weight:600;letter-spacing:0.3px">Kling Bot Aktif</span>
      <span id="__kling-bot-count" style="
        background:rgba(99,102,241,0.3);
        border:1px solid rgba(99,102,241,0.5);
        border-radius:10px;
        padding:1px 6px;
        font-size:9px;
        font-weight:700;
        color:#818cf8;
      ">0 token</span>
    `;
    Object.assign(badge.style, {
      position: "fixed",
      bottom: "16px",
      right: "16px",
      zIndex: "999999",
      background: "rgba(13,17,23,0.92)",
      border: "1px solid rgba(99,102,241,0.4)",
      borderRadius: "10px",
      padding: "6px 10px",
      display: "flex",
      alignItems: "center",
      gap: "6px",
      color: "#e6edf3",
      fontFamily: "-apple-system, BlinkMacSystemFont, 'Inter', sans-serif",
      fontSize: "11px",
      backdropFilter: "blur(8px)",
      boxShadow: "0 4px 20px rgba(0,0,0,0.5)",
      cursor: "pointer",
      transition: "all 0.2s",
      userSelect: "none",
    });

    badge.addEventListener("mouseenter", () => {
      badge.style.borderColor = "rgba(99,102,241,0.8)";
      badge.style.boxShadow = "0 4px 24px rgba(99,102,241,0.25)";
    });
    badge.addEventListener("mouseleave", () => {
      badge.style.borderColor = "rgba(99,102,241,0.4)";
      badge.style.boxShadow = "0 4px 20px rgba(0,0,0,0.5)";
    });
    badge.title = "Klik untuk membuka Kling Token Bot";

    document.body.appendChild(badge);
    return badge;
  }

  // Wait for body to be ready
  function init() {
    const badge = createBadge();

    // Update token count from storage
    function updateCount() {
      if (!isContextValid()) return;
      try {
        chrome.storage.local.get("kling_captured_tokens", (result) => {
          if (chrome.runtime?.lastError) return;
          const tokens = result.kling_captured_tokens || [];
          const active = tokens.filter(t => Date.now() / 1000 < t.exp).length;
          const countEl = document.getElementById("__kling-bot-count");
          if (countEl) {
            countEl.textContent = `${active} token`;
            countEl.style.background = active > 0
              ? "rgba(63,185,80,0.2)"
              : "rgba(99,102,241,0.2)";
            countEl.style.borderColor = active > 0
              ? "rgba(63,185,80,0.4)"
              : "rgba(99,102,241,0.4)";
            countEl.style.color = active > 0 ? "#3fb950" : "#818cf8";
          }
        });
      } catch (e) {
        // ignore
      }
    }

    updateCount();
    const intervalId = setInterval(() => {
      if (!isContextValid()) {
        clearInterval(intervalId);
        return;
      }
      updateCount();
    }, 10000);

    // Listen for storage changes to update count in real-time
    try {
      chrome.storage.onChanged.addListener((changes) => {
        if (!isContextValid()) return;
        if (changes.kling_captured_tokens) updateCount();
      });
    } catch (e) {
      // ignore
    }
  }

  if (document.body) {
    init();
  } else {
    document.addEventListener("DOMContentLoaded", init);
  }
})();
