/**
 * createProjectInPage.js
 * Este arquivo é injetado na pagina do Lovable para criar projetos.
 * NAO DEVE SER OFUSCADO pois roda no contexto MAIN da pagina.
 */
(async function createLovableProjectInPageInjected() {
  const API_BASE = "https://api.lovable.dev";
  const CASTLE_PK = "pk_TaKsqF94pjCsoyepV6mH3V24AXoM6A7M";

  // Recebe os argumentos via window
  const args = window.__createProjectArgs || {};
  const passedToken = args.token || "";
  const projectTitle = args.title || "Projeto " + new Date().toLocaleString("pt-BR");

  // Helper para parsear resposta
  const parseResponse = async (response) => {
    const text = await response.text();
    try {
      return JSON.parse(text);
    } catch (e) {
      return { raw: text };
    }
  };

  // Helper para obter Castle token
  const getCastleToken = async () => {
    try {
      if (!window.Castle || typeof window.Castle.configure !== "function") {
        return {};
      }
      window.__lovable3sCastleClient =
        window.__lovable3sCastleClient ||
        window.Castle.configure({ pk: CASTLE_PK });
      const token = await window.__lovable3sCastleClient.createRequestToken();
      return token ? { "X-Castle-Request-Token": token } : {};
    } catch (e) {
      return {};
    }
  };

  // Busca token do Supabase no localStorage
  const getSupabaseToken = () => {
    try {
      for (let i = 0; i < localStorage.length; i++) {
        const key = localStorage.key(i) || "";
        if (!/^sb-.*-auth-token$/.test(key)) continue;
        const raw = localStorage.getItem(key);
        if (!raw) continue;
        let parsed;
        try {
          parsed = JSON.parse(raw);
        } catch (e) {
          continue;
        }
        let accessToken = "";
        let refreshToken = "";
        let expiresAt = 0;
        if (Array.isArray(parsed)) {
          accessToken = parsed[0] || "";
          refreshToken = parsed[1] || "";
        } else if (parsed && typeof parsed === "object") {
          accessToken =
            parsed.access_token ||
            (parsed.currentSession && parsed.currentSession.access_token) ||
            "";
          refreshToken =
            parsed.refresh_token ||
            (parsed.currentSession && parsed.currentSession.refresh_token) ||
            "";
          expiresAt = Number(
            parsed.expires_at ||
              (parsed.currentSession && parsed.currentSession.expires_at) ||
              0
          );
        }
        if (accessToken) {
          return {
            accessToken: accessToken,
            refreshToken: refreshToken,
            expirationTime: expiresAt * 1000,
          };
        }
      }
    } catch (e) {}
    return null;
  };

  // Busca token do Firebase
  const getFirebaseToken = async () => {
    const extractToken = (obj) => {
      if (!obj || typeof obj !== "object") return null;
      const target = obj.value && typeof obj.value === "object" ? obj.value : obj;
      const manager = target.stsTokenManager || target.tokenManager || {};
      const accessToken = manager.accessToken || target.accessToken || "";
      const refreshToken = manager.refreshToken || target.refreshToken || "";
      const expirationTime = Number(manager.expirationTime || target.expirationTime || 0);
      return accessToken || refreshToken
        ? { accessToken, refreshToken, expirationTime }
        : null;
    };

    // Tenta localStorage
    try {
      for (let i = 0; i < localStorage.length; i++) {
        const key = localStorage.key(i) || "";
        if (!/firebase:authUser|authUser/i.test(key)) continue;
        const parsed = JSON.parse(localStorage.getItem(key) || "null");
        const result = extractToken(parsed);
        if (result) return result;
      }
    } catch (e) {}

    // Tenta IndexedDB
    try {
      return await new Promise((resolve) => {
        const request = indexedDB.open("firebaseLocalStorageDb");
        request.onerror = () => resolve(null);
        request.onsuccess = () => {
          const db = request.result;
          try {
            const tx = db.transaction("firebaseLocalStorage", "readonly");
            const store = tx.objectStore("firebaseLocalStorage");
            const getAll = store.getAll();
            getAll.onerror = () => resolve(null);
            getAll.onsuccess = () => {
              const results = getAll.result || [];
              for (const item of results) {
                const token = extractToken(item);
                if (token) return resolve(token);
              }
              resolve(null);
            };
          } catch (e) {
            resolve(null);
          }
        };
      });
    } catch (e) {
      return null;
    }
  };

  // Refresh token se necessario
  const refreshFirebaseToken = async (refreshToken) => {
    if (!refreshToken) return "";
    try {
      const params = new URLSearchParams({
        grant_type: "refresh_token",
        refresh_token: refreshToken,
      });
      const response = await fetch(
        "https://securetoken.googleapis.com/v1/token?key=AIzaSyBQNjlw9Vp4tP4VVeANzyPJnqbG2wLbYPw",
        {
          method: "POST",
          headers: { "Content-Type": "application/x-www-form-urlencoded" },
          body: params,
        }
      );
      const data = await parseResponse(response);
      return (response.ok && (data.id_token || data.access_token)) || "";
    } catch (e) {
      return "";
    }
  };

  // Obtem o melhor token disponivel
  const getBestToken = async () => {
    // Tenta Supabase primeiro
    const supabase = getSupabaseToken();
    if (supabase && supabase.accessToken) {
      return supabase.accessToken;
    }

    // Tenta Firebase
    const firebase = await getFirebaseToken();
    if (firebase) {
      // Refresh se perto de expirar
      if (
        firebase.expirationTime &&
        firebase.expirationTime - Date.now() < 300000 &&
        firebase.refreshToken
      ) {
        const refreshed = await refreshFirebaseToken(firebase.refreshToken);
        if (refreshed) return refreshed;
      }
      if (firebase.accessToken) return firebase.accessToken;
    }

    // Fallback para token passado
    return String(passedToken || "").replace(/^Bearer\s+/i, "").trim();
  };

  // Monta headers
  const getHeaders = async (withContentType = true) => {
    const token = await getBestToken();
    const castle = await getCastleToken();
    return {
      Accept: "application/json",
      ...(withContentType ? { "Content-Type": "application/json" } : {}),
      ...(token ? { Authorization: "Bearer " + token } : {}),
      ...castle,
    };
  };

  // Extrai workspaces da resposta
  const extractWorkspaces = (data) => {
    if (!data || typeof data !== "object") return [];
    if (Array.isArray(data.workspaces)) return data.workspaces;
    if (Array.isArray(data.data)) return data.data;
    if (data.workspace) return [data.workspace];
    return [];
  };

  // === EXECUCAO PRINCIPAL ===
  try {
    // 1. Busca workspaces
    const workspaceEndpoints = [
      API_BASE + "/user/workspaces",
      API_BASE + "/workspaces",
    ];

    let workspaces = [];
    let lastStatus = 0;
    let lastResponse = null;

    for (const endpoint of workspaceEndpoints) {
      try {
        const response = await fetch(endpoint, {
          method: "GET",
          headers: await getHeaders(false),
          credentials: "include",
        });
        lastStatus = response.status;
        const data = await parseResponse(response);
        lastResponse = data;
        if (response.ok) {
          workspaces = extractWorkspaces(data).filter((w) => w && w.id);
          if (workspaces.length) break;
        }
      } catch (e) {}
    }

    if (!workspaces.length) {
      window.__createProjectResult = {
        ok: false,
        error:
          (lastResponse && (lastResponse.message || lastResponse.error || lastResponse.type)) ||
          "Não consegui encontrar seu workspace Lovable.",
        status: lastStatus,
        details: lastResponse,
      };
      return;
    }

    // 2. Seleciona workspace
    // Tenta ler currentWorkspace.id do React state (UI atual do Lovable)
    let selectedWorkspace = null;

    // 2a. Ler React state (currentWorkspace.id)
    try {
      const rootEl = document.getElementById('app') || document.querySelector('main') || document.body;
      const reactFiberKey = Object.keys(rootEl).find(k => k.startsWith('__reactFiber'));
      if (reactFiberKey) {
        let fiber = rootEl[reactFiberKey];
        const maxDepth = 50; // Limite pra não ficar infinito
        let depth = 0;
        while (fiber && depth < maxDepth) {
          // Procura no memoizedState (hooks React)
          if (fiber.memoizedState) {
            let hook = fiber.memoizedState;
            while (hook) {
              if (hook.memoizedState && hook.memoizedState.currentWorkspace && hook.memoizedState.currentWorkspace.id) {
                selectedWorkspace = hook.memoizedState.currentWorkspace.id;
                console.log("[3S] Workspace do React:", selectedWorkspace);
                break;
              }
              hook = hook.next;
            }
          }
          if (selectedWorkspace) break;
          fiber = fiber.child || fiber.return;
          depth++;
        }
      }
    } catch (e) { console.log("[3S] Falha ao ler React state:", e.message); }

    // 2b. Fallback: localStorage com uid real do IndexedDB
    if (!selectedWorkspace) {
      try {
        const uid = await new Promise((res) => {
          const q = indexedDB.open('firebaseLocalStorageDb');
          q.onsuccess = (e) => {
            try {
              const st = e.target.result.transaction(['firebaseLocalStorage'], 'readonly').objectStore('firebaseLocalStorage').getAll();
              st.onsuccess = () => {
                for (const en of st.result) {
                  const u = en?.value?.uid;
                  if (u) return res(u);
                }
                res(null);
              };
              st.onerror = () => res(null);
            } catch { res(null); }
          };
          q.onerror = () => res(null);
        });
        if (uid) {
          const wsKey = 'lovable-current-workspace-id-' + uid;
          const stored = localStorage.getItem(wsKey);
          if (stored) {
            selectedWorkspace = stored;
            console.log("[3S] Workspace do localStorage:", selectedWorkspace);
          }
        }
      } catch (e) { console.log("[3S] Falha ao ler localStorage:", e.message); }
    }

    // 2c. Fallback final: primeiro workspace (nunca "primeiro pago")
    if (!selectedWorkspace) {
      selectedWorkspace = workspaces[0].id;
      console.log("[3S] Workspace padrão (primeiro):", selectedWorkspace);
    }

    // 3. Cria projeto
    const payloads = [
      {
        description: projectTitle,
        tech_stack: "modern",
        visibility: "private",
        metadata: { chat_mode_enabled: true, fullscreen_enabled: true },
      },
      {
        description: projectTitle,
        visibility: "private",
        metadata: { fullscreen_enabled: true },
      },
    ];

    const createEndpoint =
      API_BASE + "/workspaces/" + encodeURIComponent(selectedWorkspace) + "/projects";

    let lastAttempt = null;

    for (const payload of payloads) {
      try {
        const response = await fetch(createEndpoint, {
          method: "POST",
          headers: await getHeaders(true),
          credentials: "include",
          body: JSON.stringify(payload),
        });
        const data = await parseResponse(response);
        lastAttempt = { status: response.status, data: data, url: createEndpoint };

        if (response.ok) {
          const project = data.project || data.data || data;
          const projectId = project.id || project.project_id || data.id || data.projectId;
          window.__createProjectResult = {
            ok: true,
            success: true,
            link:
              project.editor_url ||
              project.url ||
              project.link ||
              data.editor_url ||
              data.url ||
              data.link ||
              (projectId ? "https://lovable.dev/projects/" + projectId : "https://lovable.dev/"),
            projectId: projectId || "",
            workspaceId: selectedWorkspace,
            data: data,
          };
          return;
        }

        // Se nao for erro de payload, para de tentar
        if (response.status !== 400 && response.status !== 404 && response.status !== 422) {
          break;
        }
      } catch (e) {
        lastAttempt = { status: 0, data: { error: e.message }, url: createEndpoint };
      }
    }

    // 4. Trata erros
    const errorMsg =
      (lastAttempt && lastAttempt.data && (lastAttempt.data.message || lastAttempt.data.error || lastAttempt.data.type)) ||
      "Falha ao criar projeto no Lovable.";

    if (lastAttempt && lastAttempt.status === 401) {
      window.__createProjectResult = {
        ok: false,
        status: 401,
        error: "Sua sessão do Lovable não autorizou a criação. Atualize a aba do Lovable.dev, confirme que está logado e tente novamente.",
        details: lastAttempt,
      };
    } else if (lastAttempt && lastAttempt.status === 402) {
      window.__createProjectResult = {
        ok: false,
        status: 402,
        error: "Sua conta Lovable precisa ter créditos/plano disponível para criar projeto.",
        details: lastAttempt,
      };
    } else if (/castle|denied|captcha/i.test(String(errorMsg))) {
      window.__createProjectResult = {
        ok: false,
        status: lastAttempt && lastAttempt.status,
        error: "O Lovable bloqueou a automação por segurança. Atualize a aba do Lovable.dev e tente novamente clicando pelo painel da extensão.",
        details: lastAttempt,
      };
    } else {
      window.__createProjectResult = {
        ok: false,
        status: lastAttempt && lastAttempt.status,
        error: errorMsg,
        details: lastAttempt,
      };
    }
  } catch (e) {
    window.__createProjectResult = {
      ok: false,
      error: e.message || "Erro desconhecido ao criar projeto.",
    };
  }
})();
