/**
 * FLOWhatsapp v2.0 - Cloud Backup (Premium Add-on)
 * Syncs tabs, kanban columns and quick replies to the server cloud.
 */

(() => {
  'use strict';

  /* ── Storage keys ───────────────────────────────────────── */
  const KEYS = {
    TABS    : 'flowhatsapp_tabs',
    KANBAN  : 'flowhatsapp_kanban',
    REPLIES : 'flowhatsapp_quick_replies'
  };

  const INTERVAL_MS  = 15 * 60 * 1000; // 15 minutes
  const STATUS_EL_ID = 'backup-status';

  let syncEnabled    = true;
  let intervalHandle = null;

  /* ── Helpers ────────────────────────────────────────────── */
  // The real license state lives behind FLOWHATSAPP_LICENSE_GET_STATE (managed by
  // flowhatsapp-license-service.js), not in flat chrome.storage.local keys — those were never
  // written by anything, which is why cloud backup silently never ran before this fix.
  function getConfig () {
    return new Promise((resolve) => {
      const serverUrl = String((self.FLOWHATSAPP_LICENSE_CONFIG && self.FLOWHATSAPP_LICENSE_CONFIG.appUrl) || '').replace(/\/$/, '');
      chrome.runtime.sendMessage({ type: 'FLOWHATSAPP_LICENSE_GET_STATE' }, (response) => {
        resolve({
          serverUrl,
          licenseKey: response?.result?.licenseKey || ''
        });
      });
    });
  }

  async function getAccessToken () {
    const response = await chrome.runtime.sendMessage({ type: 'FLOWHATSAPP_LICENSE_ACCESS_TOKEN' });
    return response?.result?.success === true ? response.result.accessToken : '';
  }

  function getLocalData () {
    return new Promise((resolve) => {
      chrome.storage.local.get([KEYS.TABS, KEYS.KANBAN, KEYS.REPLIES], (data) => {
        resolve({
          tabs         : data[KEYS.TABS]    || [],
          kanbanColumns: data[KEYS.KANBAN]  || [],
          quickReplies : data[KEYS.REPLIES] || []
        });
      });
    });
  }

  function setLocalData (payload) {
    return new Promise((resolve) => {
      chrome.storage.local.set({
        [KEYS.TABS]   : payload.tabs          || [],
        [KEYS.KANBAN] : payload.kanbanColumns || [],
        [KEYS.REPLIES]: payload.quickReplies  || []
      }, resolve);
    });
  }

  function isLocalDataEmpty (data) {
    return (
      (!data.tabs          || data.tabs.length === 0) &&
      (!data.kanbanColumns || data.kanbanColumns.length === 0) &&
      (!data.quickReplies  || data.quickReplies.length === 0)
    );
  }

  /* ── Status indicator ───────────────────────────────────── */
  function updateStatusElement (message) {
    // Works if called from popup context
    const el = document.getElementById(STATUS_EL_ID);
    if (el) el.textContent = message;

    // Also persist last status for popup to read on open
    chrome.storage.local.set({ flowhatsapp_backup_status: message });
  }

  function formatTime (ts) {
    if (!ts) return '--:--';
    const d = new Date(ts * 1000);
    return d.toLocaleTimeString('pt-BR', { hour: '2-digit', minute: '2-digit' });
  }

  /* ── Save to Cloud ──────────────────────────────────────── */
  async function saveToCloud () {
    if (!syncEnabled) return;

    try {
      const { serverUrl, licenseKey } = await getConfig();
      if (!serverUrl || !licenseKey) return;
      const accessToken = await getAccessToken();
      if (!accessToken) { updateStatusElement('Licença precisa ser validada'); return; }

      const localData = await getLocalData();

      const resp = await fetch(`${serverUrl}/api/cloud-backup.php`, {
        method : 'POST',
        headers: { 'Content-Type': 'application/json', 'X-FLOWhatsapp-Access': accessToken },
        body   : JSON.stringify({
          licenseKey,
          action       : 'save',
          tabs         : localData.tabs,
          kanbanColumns: localData.kanbanColumns,
          quickReplies : localData.quickReplies
        })
      });

      const data = await resp.json();

      if (data.upgrade === true) {
        // Feature not enabled for this license — disable silently
        syncEnabled = false;
        clearInterval(intervalHandle);
        console.log('[FLOWhatsapp Backup] Cloud backup não disponível nesta licença.');
        return;
      }

      if (data.success) {
        const timeStr = formatTime(data.savedAt);
        updateStatusElement(`☁️ Sincronizado às ${timeStr}`);
        console.log(`[FLOWhatsapp Backup] Salvo com sucesso às ${timeStr}`);
      } else {
        console.warn('[FLOWhatsapp Backup] Falha ao salvar:', data.error);
        updateStatusElement('⚠️ Falha ao sincronizar');
      }
    } catch (err) {
      console.warn('[FLOWhatsapp Backup] Erro de rede:', err.message);
      updateStatusElement('⚠️ Sem conexão');
    }
  }

  /* ── Restore from Cloud ─────────────────────────────────── */
  async function restoreFromCloud () {
    if (!syncEnabled) return;

    try {
      const { serverUrl, licenseKey } = await getConfig();
      if (!serverUrl || !licenseKey) return;
      const accessToken = await getAccessToken();
      if (!accessToken) return;

      // Only restore if local data is empty
      const localData = await getLocalData();
      if (!isLocalDataEmpty(localData)) {
        console.log('[FLOWhatsapp Backup] Dados locais existentes. Restauração ignorada.');
        return;
      }

      const resp = await fetch(`${serverUrl}/api/cloud-backup.php`, {
        method : 'POST',
        headers: { 'Content-Type': 'application/json', 'X-FLOWhatsapp-Access': accessToken },
        body   : JSON.stringify({ licenseKey, action: 'restore' })
      });

      const data = await resp.json();

      if (data.upgrade === true) {
        syncEnabled = false;
        clearInterval(intervalHandle);
        console.log('[FLOWhatsapp Backup] Cloud backup não disponível nesta licença.');
        return;
      }

      if (data.error) {
        console.warn('[FLOWhatsapp Backup] Erro ao restaurar:', data.error);
        return;
      }

      if (data.empty) {
        console.log('[FLOWhatsapp Backup] Nenhum backup encontrado na nuvem.');
        return;
      }

      if (data.success) {
        await setLocalData({
          tabs         : data.tabs          || [],
          kanbanColumns: data.kanbanColumns || [],
          quickReplies : data.quickReplies  || []
        });
        const timeStr = formatTime(data.savedAt);
        updateStatusElement(`☁️ Restaurado de ${timeStr}`);
        console.log(`[FLOWhatsapp Backup] Dados restaurados do backup de ${timeStr}`);
      }
    } catch (err) {
      console.warn('[FLOWhatsapp Backup] Erro de rede ao restaurar:', err.message);
    }
  }

  /* ── Init ───────────────────────────────────────────────── */
  async function init () {
    // Try to restore on startup if local is empty
    await restoreFromCloud();

    // Start periodic auto-save
    intervalHandle = setInterval(saveToCloud, INTERVAL_MS);

    // Restore last known status text in popup if open
    chrome.storage.local.get('flowhatsapp_backup_status', (data) => {
      if (data.flowhatsapp_backup_status) {
        updateStatusElement(data.flowhatsapp_backup_status);
      }
    });
  }

  init();

  /* ── Expose for manual trigger from popup ───────────────── */
  window.flowCloudBackup = { saveToCloud, restoreFromCloud, getLocalData, setLocalData };

})();
