// Box Lovable v3.0 — Config (Supabase do usuario)
var CONFIG = {
  supabaseUrl: 'https://xqymhefnyxnmnwhzagxy.supabase.co',
  supabaseAnonKey: 'sb_publishable_Czfqflhzn9LNd2F85_k8Ug_8jioRCPR',
  webhookUrl: 'https://delicate-water-286cdarkluv-proxy.a-cruz6421.workers.dev/webhook/nm7k9x2q',
  optimizeWebhookUrl: 'https://webhook-processor-production-3727.up.railway.app/webhook/darkluv-optimize',
  licensePrefix: 'BL-'
};

var _serverTimeOffset = 0;

async function getServerTime() {
  try {
    var r = await fetch(CONFIG.supabaseUrl + '/rest/v1/licenses?select=created_at&limit=1', {
      headers: {
        'apikey': CONFIG.supabaseAnonKey,
        'Authorization': 'Bearer ' + CONFIG.supabaseAnonKey
      }
    });
    var dateHeader = r.headers.get('Date');
    if (dateHeader) {
      return new Date(dateHeader).getTime();
    }
  } catch(e) {}
  return Date.now();
}

async function supabaseRequest(endpoint, options) {
  options = options || {};
  var url = CONFIG.supabaseUrl + '/rest/v1/' + endpoint;
  var headers = {
    'apikey': CONFIG.supabaseAnonKey,
    'Authorization': 'Bearer ' + CONFIG.supabaseAnonKey,
    'Content-Type': 'application/json',
    'Prefer': options.prefer || 'return=representation'
  };
  if (options.headers) {
    for (var k in options.headers) headers[k] = options.headers[k];
  }

  var response = await fetch(url, {
    method: options.method || 'GET',
    headers: headers,
    body: options.body ? JSON.stringify(options.body) : undefined
  });

  // Capture server time from response header
  var dateHeader = response.headers.get('Date');
  if (dateHeader) {
    _serverTimeOffset = new Date(dateHeader).getTime() - Date.now();
  }

  if (!response.ok) {
    var text = await response.text();
    throw new Error('Supabase error (' + response.status + '): ' + text);
  }
  if (options.method === 'DELETE') return { ok: true };
  return response.json();
}

function serverNow() {
  return Date.now() + _serverTimeOffset;
}

function generateDeviceId() {
  var CHARS = 'abcdefghijklmnopqrstuvwxyz0123456789';
  var id = 'darkluv-';
  for (var i = 0; i < 24; i++) {
    id += CHARS.charAt(Math.floor(Math.random() * CHARS.length));
  }
  return id;
}

async function getDeviceId() {
  return new Promise(function(resolve) {
    chrome.storage.local.get('deviceId', function(result) {
      if (result.deviceId) {
        resolve(result.deviceId);
      } else {
        var deviceId = generateDeviceId();
        chrome.storage.local.set({ deviceId: deviceId }, function() {
          resolve(deviceId);
        });
      }
    });
  });
}

async function validateLicense(key) {
  // Get server time first
  await getServerTime();
  var now = serverNow();

  // Query only ACTIVE licenses
  var result = await supabaseRequest(
    'licenses?key=eq.' + encodeURIComponent(key) + '&active=eq.true&select=*'
  );

  if (!result || result.length === 0) {
    throw new Error('Chave de licenca invalida.');
  }

  var license = result[0];

  // Validate expiration using SERVER time (not local PC time)
  if (license.expires_at) {
    var expiresDate = new Date(license.expires_at).getTime();
    if (expiresDate < now) {
      throw new Error('Esta licenca expirou.');
    }
  }

  var deviceId = await getDeviceId();
  now = serverNow();
  var devices = await supabaseRequest(
    'license_devices?license_id=eq.' + license.id + '&select=*'
  );

  var existingDevice = null;
  for (var i = 0; i < devices.length; i++) {
    if (devices[i].device_id === deviceId) {
      existingDevice = devices[i];
      break;
    }
  }

  if (!existingDevice && devices.length >= (license.max_devices || 1)) {
    var staleThreshold = serverNow() - 25 * 60 * 60 * 1000;
    var staleDate = new Date(staleThreshold).toISOString();
    var cleaned = false;
    for (var d = 0; d < devices.length; d++) {
      var device = devices[d];
      if (device.last_seen && new Date(device.last_seen).getTime() < staleThreshold) {
        try {
          await supabaseRequest('license_devices?id=eq.' + device.id, { method: 'DELETE' });
          cleaned = true;
          break;
        } catch(e) {}
      }
    }
    if (!cleaned) {
      throw new Error('Limite de dispositivos atingido (' + (license.max_devices || 1) + ').');
    }
  }

  now = serverNow();
  var nowISO = new Date(now).toISOString();

  if (existingDevice) {
    await supabaseRequest('license_devices?id=eq.' + existingDevice.id, {
      method: 'PATCH',
      body: { last_seen: nowISO }
    });
  } else {
    try {
      await supabaseRequest('license_devices', {
        method: 'POST',
        headers: { 'Prefer': 'return=minimal' },
        body: {
          license_id: license.id,
          device_id: deviceId,
          last_seen: nowISO
        }
      });
    } catch(e) {
      try {
        await supabaseRequest(
          'license_devices?license_id=eq.' + license.id + '&device_id=eq.' + encodeURIComponent(deviceId),
          { method: 'PATCH', body: { last_seen: nowISO } }
        );
      } catch(e2) {}
    }
  }

  return {
    valid: true,
    license: {
      id: license.id,
      key: license.key,
      expiresAt: license.expires_at,
      maxDevices: license.max_devices
    }
  };
}

async function getStoredLicense() {
  return new Promise(function(resolve) {
    chrome.storage.local.get('license', function(result) {
      resolve(result.license || null);
    });
  });
}

async function saveLicense(license) {
  return new Promise(function(resolve) {
    chrome.storage.local.set({ license: license }, resolve);
  });
}

async function removeLicense() {
  return new Promise(function(resolve) {
    chrome.storage.local.remove('license', resolve);
  });
}

async function logout() {
  await removeLicense();
}

// Auto-revalidation watcher — kicks user immediately on block/expire
(function() {
  var REVALIDATE_MS = 5000;
  
  setInterval(function() {
    getStoredLicense().then(function(stored) {
      if (!stored || !stored.key) return;
      return validateLicense(stored.key);
    }).then(function() {
      // License still valid, do nothing
    }).catch(async function(e) {
      console.log('[BoxLov] License revoked:', e.message);
      await logout();
      await new Promise(function(r) { setTimeout(r, 200); });
      location.reload();
    });
  }, REVALIDATE_MS);
})();
