(function () {
  'use strict';

  const cfg = window.SENIORCARE_CONFIG || {};
  const status = {
    configured: Boolean(cfg.SUPABASE_URL && cfg.SUPABASE_PUBLISHABLE_KEY),
    connected: false,
    schemaReady: false,
    error: null,
    lastCheckedAt: null
  };

  const nativeFetch = window.fetch.bind(window);
  const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
  const errorText = error => String(error?.message || error || '').trim();
  const isNetworkError = error => /load failed|failed to fetch|networkerror|network request failed|fetch failed|offline|internet connection|aborterror|timed out/i.test(errorText(error));
  const friendlyError = (error, fallback = 'No se pudo completar la operación.') => {
    const text = errorText(error);
    if (isNetworkError(error) || (typeof navigator !== 'undefined' && navigator.onLine === false)) {
      return 'No se pudo conectar con Supabase. Revise la conexión a internet y vuelva a intentar.';
    }
    return text || fallback;
  };

  async function resilientFetch(input, init = {}) {
    const request = input instanceof Request ? input : null;
    const method = String(init.method || request?.method || 'GET').toUpperCase();
    const url = String(request?.url || input || '');
    // Solo se reintentan lecturas y autenticación. No se reintentan escrituras clínicas
    // para evitar registros duplicados si el servidor recibió la solicitud.
    const retryable = method === 'GET' || method === 'HEAD' || /\/auth\/v1\/(token|user)/i.test(url);
    const attempts = retryable ? 2 : 1;
    let lastError;

    for (let attempt = 0; attempt < attempts; attempt++) {
      try {
        return await nativeFetch(input, init);
      } catch (error) {
        lastError = error;
        if (attempt + 1 < attempts) await sleep(650 * (attempt + 1));
      }
    }

    if (isNetworkError(lastError)) {
      const normalized = new Error('No se pudo conectar con Supabase. Revise la conexión a internet y vuelva a intentar.');
      normalized.name = 'SeniorCareNetworkError';
      normalized.cause = lastError;
      throw normalized;
    }
    throw lastError;
  }

  window.SENIORCARE_SUPABASE_STATUS = status;
  window.BHSC_IS_NETWORK_ERROR = isNetworkError;
  window.BHSC_FRIENDLY_ERROR = friendlyError;
  window.BHSC_WITH_RETRY = async function (task, attempts = 2, delay = 650) {
    let lastError;
    for (let attempt = 0; attempt < attempts; attempt++) {
      try {
        return await task();
      } catch (error) {
        lastError = error;
        if (!isNetworkError(error) || attempt + 1 >= attempts) break;
        await sleep(delay * (attempt + 1));
      }
    }
    if (isNetworkError(lastError)) throw new Error(friendlyError(lastError));
    throw lastError;
  };

  if (!status.configured) {
    status.error = 'Supabase no está configurado.';
    return;
  }

  if (!window.supabase || typeof window.supabase.createClient !== 'function') {
    status.error = 'No se pudo cargar la librería de Supabase.';
    return;
  }

  const client = window.supabase.createClient(
    cfg.SUPABASE_URL,
    cfg.SUPABASE_PUBLISHABLE_KEY,
    {
      global: { fetch: resilientFetch },
      auth: {
        persistSession: true,
        autoRefreshToken: true,
        detectSessionInUrl: true,
        storageKey: 'bernard-health-seniorcare-auth'
      }
    }
  );

  window.seniorcareSupabase = client;

  async function checkConnection() {
    status.lastCheckedAt = new Date().toISOString();
    try {
      const result = await window.BHSC_WITH_RETRY(
        () => client.from('organizations').select('id').limit(1),
        2,
        700
      );
      const { error } = result || {};
      if (error) {
        if (/relation .* does not exist|could not find the table/i.test(error.message || '')) {
          status.connected = true;
          status.schemaReady = false;
          status.error = 'Conexión correcta. Falta instalar el esquema SQL.';
          return status;
        }
        throw error;
      }
      status.connected = true;
      status.schemaReady = true;
      status.error = null;
      return status;
    } catch (error) {
      status.connected = false;
      status.error = friendlyError(error, 'No se pudo comprobar la conexión con Supabase.');
      return status;
    }
  }

  window.checkSeniorCareSupabase = checkConnection;
  checkConnection();
})();
