const SITE_BASE_CANDIDATES = [
  'https://claralex.studio',
  'https://project-sc204.vercel.app',
  'https://claralex-site.vercel.app',
  'https://claralex-site-temp.vercel.app',
  'https://claralex-site-temp-git-main.vercel.app',
  'http://localhost:3000',
  'http://127.0.0.1:3000',
];

async function getConfiguredBases() {
  const stored = await chrome.storage.local.get(['siteBaseUrl']);
  const bases = stored.siteBaseUrl ? [stored.siteBaseUrl, ...SITE_BASE_CANDIDATES] : SITE_BASE_CANDIDATES;
  return Array.from(new Set(bases.filter(Boolean)));
}

async function postToSite(path, payload) {
  const bases = await getConfiguredBases();
  let lastError = 'Nessun backend ClaraLex raggiungibile.';

  for (const baseUrl of bases) {
    try {
      const response = await fetch(`${baseUrl}${path}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
      });

      const rawText = await response.text();
      const data = rawText ? JSON.parse(rawText) : {};

      if (!response.ok) {
        lastError = data?.error || `${response.status} ${response.statusText}`;
        continue;
      }

      return data;
    } catch (error) {
      lastError = error.message;
    }
  }

  throw new Error(lastError);
}

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request?.action === 'claralex.analyze') {
    postToSite('/api/analizza', request.payload)
      .then((analysis) => sendResponse({ ok: true, data: analysis }))
      .catch((error) => sendResponse({ ok: false, error: error.message }));
    return true;
  }

  if (request?.action === 'claralex.updateBadge') {
    updateBadge(sender.tab?.id ?? request.tabId, request.analysis)
      .then(() => sendResponse({ ok: true }))
      .catch((error) => sendResponse({ ok: false, error: error.message }));
    return true;
  }

  if (request?.action === 'claralex.clearBadge') {
    clearBadge(sender.tab?.id ?? request.tabId)
      .then(() => sendResponse({ ok: true }))
      .catch((error) => sendResponse({ ok: false, error: error.message }));
    return true;
  }

  if (request?.action === 'claralex.generateAudioSummary') {
    postToSite('/api/audio-summary', request.payload)
      .then((summary) => sendResponse({ ok: true, data: summary }))
      .catch((error) => sendResponse({ ok: false, error: error.message }));
    return true;
  }

  return false;
});

async function updateBadge(tabId, analysis) {
  if (!tabId) return;

  const clauses = Array.isArray(analysis?.clauses) ? analysis.clauses : [];
  const riskyCount = clauses.filter((clause) => clause.type === 'danger' || clause.type === 'warning').length;
  let text = '';
  let color = '#1a73e8';

  if (!analysis?.isContractLike) {
    text = '';
  } else if (riskyCount === 0 && clauses.length > 0) {
    text = 'OK';
    color = '#1e8e3e';
  } else if (riskyCount > 0) {
    text = String(Math.min(riskyCount, 99));
    color = analysis?.riskLevel === 'danger' ? '#d93025' : '#f9ab00';
  }

  await chrome.action.setBadgeBackgroundColor({ color });
  await chrome.action.setBadgeText({ tabId, text });
}

async function clearBadge(tabId) {
  if (!tabId) return;
  await chrome.action.setBadgeText({ tabId, text: '' });
}


