/* LeadStore.jsx — Capa central de leads sobre Supabase (REST).
 * - addLead: inserta en Supabase; si falla, guarda en cola local y reintenta.
 * - getLeads: lee desde Supabase; si falla, usa el respaldo local.
 * - Marca de "registro unico" por persona en este navegador.
 * Exposed as window.LeadStore.
 */
const LeadStore = (() => {
  const cfg = window.SUPABASE_CONFIG || { enabled: false };
  const REST = cfg.enabled ? cfg.url + "/rest/v1/leads" : null;
  const QUEUE_KEY = "hondulegal_leads_queue";   // cola local si Supabase falla
  const CACHE_KEY = "hondulegal_leads_cache";   // ultimo listado leido
  const REG_KEY = "hondulegal_registered";      // marca de registro unico (persona)

  function headers() {
    return {
      "Content-Type": "application/json",
      "apikey": cfg.anonKey,
      "Authorization": "Bearer " + cfg.anonKey,
      "Prefer": "return=representation",
    };
  }

  function _readQueue() {
    try { return JSON.parse(localStorage.getItem(QUEUE_KEY)) || []; }
    catch { return []; }
  }
  function _writeQueue(q) {
    localStorage.setItem(QUEUE_KEY, JSON.stringify(q));
  }

  async function _flushQueue() {
    if (!REST) return;
    let q = _readQueue();
    if (q.length === 0) return;
    const remaining = [];
    for (const lead of q) {
      try {
        const res = await fetch(REST, { method: "POST", headers: headers(), body: JSON.stringify(lead) });
        if (!res.ok) remaining.push(lead);
      } catch { remaining.push(lead); }
    }
    _writeQueue(remaining);
  }

  return {
    isEnabled() { return !!REST; },

    // Marca de registro unico en este navegador.
    isRegistered() {
      try { return localStorage.getItem(REG_KEY) === "1"; }
      catch { return false; }
    },
    getRegisteredEmail() {
      try { return localStorage.getItem(REG_KEY + "_email") || ""; }
      catch { return ""; }
    },
    getRegisteredName() {
      try { return localStorage.getItem(REG_KEY + "_name") || ""; }
      catch { return ""; }
    },
    markRegistered(name, email) {
      try {
        localStorage.setItem(REG_KEY, "1");
        localStorage.setItem(REG_KEY + "_email", email || "");
        localStorage.setItem(REG_KEY + "_name", name || "");
      } catch { /* ignore */ }
    },

    // Inserta un lead. Devuelve true si quedo guardado (en Supabase o en cola).
    async addLead(lead) {
      const payload = {
        name: (lead.name || "").trim(),
        email: (lead.email || "").trim(),
        doc_id: lead.docId || "",
        doc_name: lead.docName || "",
      };
      if (!REST) {
        // Sin Supabase: guardar en cola local (respaldo).
        const q = _readQueue();
        q.push(payload);
        _writeQueue(q);
        return true;
      }
      try {
        const res = await fetch(REST, { method: "POST", headers: headers(), body: JSON.stringify(payload) });
        if (!res.ok) throw new Error("HTTP " + res.status);
        _flushQueue(); // aprovechar para reintentar pendientes
        return true;
      } catch (e) {
        // Si falla, no perder el lead: encolar y reintentar luego.
        const q = _readQueue();
        q.push(payload);
        _writeQueue(q);
        return true;
      }
    },

    // Lee todos los leads desde Supabase (o respaldo local en cache).
    async getLeads() {
      if (!REST) return _readQueue().map((l, i) => ({ ...l, id: "local-" + i, created_at: new Date().toISOString() }));
      try {
        await _flushQueue();
        const res = await fetch(REST + "?select=*&order=created_at.desc", { headers: headers() });
        if (!res.ok) throw new Error("HTTP " + res.status);
        const data = await res.json();
        localStorage.setItem(CACHE_KEY, JSON.stringify(data));
        return data;
      } catch (e) {
        try { return JSON.parse(localStorage.getItem(CACHE_KEY)) || []; }
        catch { return []; }
      }
    },

    // Cuenta de pendientes en cola (para avisar en el admin).
    pendingCount() { return _readQueue().length; },

    exportCSV(leads) {
      const header = ["Nombre", "Correo", "Documento", "Fecha"];
      const rows = (leads || []).map(l => [
        '"' + (l.name || "").replace(/"/g, '""') + '"',
        '"' + (l.email || "").replace(/"/g, '""') + '"',
        '"' + (l.doc_name || "").replace(/"/g, '""') + '"',
        '"' + new Date(l.created_at).toLocaleString("es-HN") + '"',
      ].join(","));
      return [header.join(","), ...rows].join("\n");
    },
  };
})();

Object.assign(window, { LeadStore });
