const storage = chrome.storage.local;

const state = {
  apiBase: "https://meta.eggert.tools",
  token: "",
  user: null,
  access: null,
  metaConnection: null,
  snapshot: null,
  dashboard: null,
  weeklyReport: null
};

const qs = (selector) => document.querySelector(selector);

function setStatus(text) {
  qs("#sessionLabel").textContent = text;
}

function show(id, visible) {
  qs(id).classList.toggle("hidden", !visible);
}

function authHeaders() {
  return {
    "content-type": "application/json",
    ...(state.token ? { authorization: `Bearer ${state.token}` } : {})
  };
}

async function api(path, options = {}) {
  const response = await fetch(`${state.apiBase}${path}`, {
    ...options,
    headers: {
      ...authHeaders(),
      ...(options.headers || {})
    }
  });
  const data = await response.json().catch(() => ({}));
  if (!response.ok) throw new Error(data.message || data.error || "Erro na API");
  return data;
}

async function saveState() {
  await storage.set({
    egt_api_base: state.apiBase,
    egt_token: state.token,
    egt_compliance_form: getCheckForm()
  });
}

async function loadState() {
  const saved = await storage.get(["egt_api_base", "egt_token", "egt_compliance_form"]);
  state.apiBase = saved.egt_api_base || state.apiBase;
  state.token = saved.egt_token || "";
  qs("#apiBaseInput").value = state.apiBase;
  if (saved.egt_compliance_form) {
    for (const [key, value] of Object.entries(saved.egt_compliance_form)) {
      const input = qs(`#${key}`);
      if (input) input.value = value;
    }
  }
}

function getCheckForm() {
  return {
    clientName: qs("#clientName")?.value.trim() || "",
    adAccountName: qs("#adAccountName")?.value.trim() || "",
    balanceText: qs("#balanceText")?.value.trim() || "",
    balanceStatus: qs("#balanceStatus")?.value || "unknown",
    campaignName: qs("#campaignName")?.value.trim() || "",
    campaignStatus: qs("#campaignStatus")?.value || "unknown",
    campaignEndsAt: qs("#campaignEndsAt")?.value || "",
    deliveryStatus: qs("#deliveryStatus")?.value || "unknown",
    spendLast7Days: qs("#spendLast7Days")?.value.trim() || "",
    resultsLast7Days: qs("#resultsLast7Days")?.value.trim() || "",
    notes: qs("#notes")?.value.trim() || ""
  };
}

function clearCheckForm() {
  for (const key of Object.keys(getCheckForm())) {
    const input = qs(`#${key}`);
    if (!input) continue;
    input.value = input.tagName === "SELECT" ? "unknown" : "";
  }
}

function renderAccess() {
  const loggedIn = Boolean(state.user);
  const active = Boolean(state.access?.active);
  show("#authBox", !loggedIn);
  show("#accessBox", loggedIn && !active);
  show("#dashboardBox", loggedIn && active);
  show("#metaConnectionBox", loggedIn && active);
  show("#checkBox", loggedIn && active);
  show("#accountsBox", loggedIn && active);
  show("#reportBox", loggedIn && active);

  if (!loggedIn) {
    setStatus("Desconectado");
    return;
  }
  setStatus(state.user.email);
  qs("#accessStatus").textContent = active
    ? "Produto ativo."
    : "Sua conta ainda nao tem o Meta Ads Compliance ativo.";
  renderMetaConnection();
}

function severityLabel(severity) {
  return {
    critical: "Critica",
    warning: "Atencao",
    ok: "OK"
  }[severity] || "Nao conferido";
}

function renderDashboard() {
  const summary = state.dashboard?.summary || {};
  qs("#totalAccounts").textContent = String(summary.totalAccounts || 0);
  qs("#criticalAccounts").textContent = String(summary.criticalAccounts || 0);
  qs("#warningAccounts").textContent = String(summary.warningAccounts || 0);
  qs("#okAccounts").textContent = String(summary.okAccounts || 0);

  const list = qs("#accountsList");
  list.innerHTML = "";
  const accounts = state.dashboard?.accounts || [];
  if (!accounts.length) {
    const empty = document.createElement("p");
    empty.className = "muted";
    empty.textContent = "Nenhuma conta verificada ainda.";
    list.appendChild(empty);
    return;
  }

  for (const account of accounts) {
    const item = document.createElement("article");
    item.className = `account-card severity-${account.severity}`;
    item.innerHTML = `
      <div class="account-card-head">
        <strong>${account.clientName}</strong>
        <span>${severityLabel(account.severity)}</span>
      </div>
      <p>${account.adAccountName}</p>
      <dl>
        <div><dt>Saldo</dt><dd>${account.balanceText || account.balanceStatus || "-"}</dd></div>
        <div><dt>Campanha</dt><dd>${account.campaignStatus || "-"}</dd></div>
        <div><dt>Roda ate</dt><dd>${account.campaignEndsAt || "-"}</dd></div>
        <div><dt>7 dias</dt><dd>${account.spendLast7Days || "-"}</dd></div>
      </dl>
      <small>${account.recommendedAction || ""}</small>
    `;
    list.appendChild(item);
  }
}

function renderMetaConnection() {
  const status = qs("#metaConnectionStatus");
  if (!status) return;
  const connected = Boolean(state.metaConnection?.connected);
  const expires = state.metaConnection?.expiresAt
    ? new Date(state.metaConnection.expiresAt).toLocaleDateString("pt-BR")
    : "";
  status.textContent = connected
    ? `Conectado em modo leitura${expires ? `, token valido ate ${expires}` : ""}.`
    : "Nao conectado. Autorize a Meta para sincronizar contas, campanhas e insights sem editar nada.";
  qs("#syncMetaButton").disabled = !connected;
  qs("#disconnectMetaButton").disabled = !connected;
}

function renderWeeklyReport() {
  const container = qs("#weeklyReportPreview");
  container.innerHTML = "";
  if (!state.weeklyReport) {
    const empty = document.createElement("p");
    empty.className = "muted";
    empty.textContent = "Gere o resumo semanal depois de salvar as verificacoes.";
    container.appendChild(empty);
    return;
  }

  const header = document.createElement("div");
  header.className = "report-header";
  header.innerHTML = `
    <strong>Relatorio dos ultimos 7 dias</strong>
    <span>${new Date(state.weeklyReport.generatedAt).toLocaleString("pt-BR")}</span>
  `;
  container.appendChild(header);

  const feedback = document.createElement("article");
  feedback.className = "report-section";
  feedback.innerHTML = `<strong>Resumo para cliente</strong><p>${state.weeklyReport.clientFeedback.join("\n")}</p>`;
  container.appendChild(feedback);

  const risks = document.createElement("article");
  risks.className = "report-section";
  const riskText = state.weeklyReport.risks.length
    ? state.weeklyReport.risks
        .map((risk) => `${risk.clientName}: ${risk.reason}`)
        .join("\n")
    : "Nenhuma conta critica registrada no periodo.";
  risks.innerHTML = `<strong>Riscos e acoes</strong><p>${riskText}</p>`;
  container.appendChild(risks);

  const investment = document.createElement("article");
  investment.className = "report-section";
  const investmentText = state.weeklyReport.investment.length
    ? state.weeklyReport.investment
        .map((item) => `${item.clientName}: investiu ${item.spendLast7Days}; resultados: ${item.resultsLast7Days}`)
        .join("\n")
    : "Sem investimento registrado ainda.";
  investment.innerHTML = `<strong>Investimento e resultados</strong><p>${investmentText}</p>`;
  container.appendChild(investment);
}

async function refreshMe() {
  if (!state.token) {
    state.user = null;
    state.access = null;
    renderAccess();
    return;
  }
  try {
    const data = await api("/api/auth/me", { method: "GET" });
    state.user = data.user;
    state.access = data.access;
    state.metaConnection = data.user?.metaConnection || null;
  } catch {
    state.token = "";
    state.user = null;
    state.access = null;
    state.metaConnection = null;
    await saveState();
  }
  renderAccess();
  if (state.access?.active) await refreshDashboard();
}

async function login() {
  qs("#authStatus").textContent = "";
  try {
    const data = await api("/api/auth/login", {
      method: "POST",
      body: JSON.stringify({
        email: qs("#emailInput").value.trim(),
        password: qs("#passwordInput").value
      })
    });
    state.token = data.token;
    state.user = data.user;
    await saveState();
    await refreshMe();
  } catch (error) {
    qs("#authStatus").textContent = error.message;
  }
}

async function getCurrentTab() {
  const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  return tab;
}

function isMetaAdsUrl(url = "") {
  return url.startsWith("https://business.facebook.com/") || url.startsWith("https://adsmanager.facebook.com/");
}

async function readScreen() {
  const tab = await getCurrentTab();
  if (!isMetaAdsUrl(tab?.url || "")) {
    qs("#checkStatus").textContent = "Abra o Meta Ads antes de ler a tela.";
    return null;
  }
  try {
    const response = await chrome.tabs.sendMessage(tab.id, { type: "GET_ADS_SNAPSHOT" });
    if (!response?.ok) throw new Error("Sem resposta da pagina");
    state.snapshot = response.snapshot;
    qs("#checkStatus").textContent = "Tela lida. Complete saldo, campanha e data final.";
    return response.snapshot;
  } catch {
    qs("#checkStatus").textContent = "Recarregue a aba do Meta Ads e tente novamente.";
    return null;
  }
}

async function refreshDashboard() {
  state.dashboard = await api("/api/compliance/dashboard", { method: "GET" });
  renderDashboard();
}

async function connectMeta() {
  if (!state.token) return;
  const url = `${state.apiBase}/api/meta/oauth/start?token=${encodeURIComponent(state.token)}`;
  await chrome.tabs.create({ url });
  qs("#metaSyncStatus").textContent = "Conclua a autorizacao na aba aberta e depois clique em Atualizar.";
}

async function disconnectMeta() {
  qs("#metaSyncStatus").textContent = "Desconectando...";
  try {
    const data = await api("/api/meta/connection", { method: "DELETE" });
    state.metaConnection = data.connection;
    qs("#metaSyncStatus").textContent = "Meta desconectada.";
    renderMetaConnection();
  } catch (error) {
    qs("#metaSyncStatus").textContent = error.message;
  }
}

async function syncMeta() {
  qs("#metaSyncStatus").textContent = "Sincronizando contas Meta...";
  try {
    const data = await api("/api/meta/sync", { method: "POST" });
    qs("#metaSyncStatus").textContent = `Sincronizacao concluida: ${data.importedCount} contas importadas${data.errorCount ? `, ${data.errorCount} com erro` : ""}.`;
    await refreshMe();
  } catch (error) {
    qs("#metaSyncStatus").textContent = error.message;
  }
}

async function saveComplianceCheck() {
  qs("#checkStatus").textContent = "Salvando verificacao...";
  try {
    await saveState();
    const payload = {
      ...getCheckForm(),
      pageSnapshot: state.snapshot
    };
    const data = await api("/api/compliance/check", {
      method: "POST",
      body: JSON.stringify(payload)
    });
    qs("#checkStatus").textContent = `Verificacao salva. Risco: ${severityLabel(data.check.severity)}.`;
    clearCheckForm();
    await saveState();
    await refreshDashboard();
  } catch (error) {
    qs("#checkStatus").textContent = error.message;
  }
}

async function generateWeeklyReport() {
  qs("#reportStatus").textContent = "Gerando relatorio...";
  try {
    state.weeklyReport = await api("/api/compliance/weekly-report", { method: "POST" });
    qs("#reportStatus").textContent = "Relatorio gerado.";
    renderWeeklyReport();
  } catch (error) {
    qs("#reportStatus").textContent = error.message;
  }
}

qs("#saveApiBaseButton").addEventListener("click", async () => {
  state.apiBase = qs("#apiBaseInput").value.trim().replace(/\/$/, "");
  await saveState();
  await refreshMe();
});

qs("#logoutButton").addEventListener("click", async () => {
  state.token = "";
  state.user = null;
  state.access = null;
  await saveState();
  renderAccess();
});

qs("#loginButton").addEventListener("click", login);
qs("#readScreenButton").addEventListener("click", readScreen);
qs("#saveCheckButton").addEventListener("click", saveComplianceCheck);
qs("#refreshDashboardButton").addEventListener("click", refreshDashboard);
qs("#weeklyReportButton").addEventListener("click", generateWeeklyReport);
qs("#connectMetaButton").addEventListener("click", connectMeta);
qs("#disconnectMetaButton").addEventListener("click", disconnectMeta);
qs("#syncMetaButton").addEventListener("click", syncMeta);

for (const key of Object.keys(getCheckForm())) {
  const input = qs(`#${key}`);
  input?.addEventListener("change", saveState);
  input?.addEventListener("blur", saveState);
}

await loadState();
await refreshMe();
renderDashboard();
renderWeeklyReport();
