// NotifPrompt + notification helpers — opt-in del cliente y registro de suscriptores

const NOTIF_SUBS_KEY = "hlpraf_notif_subs";
const NOTIF_DISMISS_KEY = "hlpraf_notif_dismissed";

function loadNotifSubs() {
  try { return JSON.parse(localStorage.getItem(NOTIF_SUBS_KEY) || "[]"); } catch (e) { return []; }
}
function saveNotifSub(sub) {
  const subs = loadNotifSubs();
  // dedup por session_id (o email si existe)
  const key = sub.email || sub.session_id;
  const idx = subs.findIndex(s => (s.email || s.session_id) === key);
  if (idx >= 0) subs[idx] = { ...subs[idx], ...sub };
  else subs.push(sub);
  localStorage.setItem(NOTIF_SUBS_KEY, JSON.stringify(subs));
}

// Entrega campañas pendientes a este dispositivo (prototipo): muestra Notification real
// y registra notif_open / notif_action al interactuar.
function deliverPendingCampaigns(sessionId, branchId, logEvent) {
  if (!("Notification" in window) || Notification.permission !== "granted") return;
  let campaigns = [];
  try { campaigns = JSON.parse(localStorage.getItem("hlpraf_campaigns") || "[]"); } catch (e) { return; }
  const seenKey = "hlpraf_notif_seen_" + sessionId;
  let seen = [];
  try { seen = JSON.parse(localStorage.getItem(seenKey) || "[]"); } catch (e) {}

  const pending = campaigns.filter(c =>
    (c.branch_id === "all" || c.branch_id === branchId) && !seen.includes(c.id)
  );
  pending.forEach((c, i) => {
    setTimeout(() => {
      try {
        const n = new Notification(c.title, {
          body: c.body,
          icon: "assets/logo.png",
          tag: c.id,
          data: { campaignId: c.id },
        });
        logEvent("notif_open", c.id); // el navegador la mostró/recibió
        n.onclick = () => {
          logEvent("notif_action", c.id);
          window.focus();
          n.close();
        };
      } catch (e) {}
    }, 1200 + i * 800);
    seen.push(c.id);
  });
  localStorage.setItem(seenKey, JSON.stringify(seen));
}

function NotifPrompt({ accent, onGrant, onDismiss }) {
  return (
    <div style={{
      position: "fixed", left: 16, right: 16, bottom: 16,
      maxWidth: 488, marginLeft: "auto", marginRight: "auto",
      background: "#fff", borderRadius: 16, padding: "16px 18px",
      boxShadow: "0 12px 40px rgba(60,40,20,0.22)",
      border: "1px solid #ead9b8", zIndex: 350,
      animation: "slideUp 0.3s ease", fontFamily: "'DM Sans', sans-serif"
    }}>
      <div style={{ display: "flex", gap: 14, alignItems: "flex-start" }}>
        <div style={{
          background: `linear-gradient(135deg, ${accent}, #b91c1c)`,
          borderRadius: 12, width: 44, height: 44, flexShrink: 0,
          display: "flex", alignItems: "center", justifyContent: "center", fontSize: 22
        }}>🔔</div>
        <div style={{ flex: 1 }}>
          <div style={{ fontWeight: 800, fontSize: 15, color: "#1a1008" }}>Enterate de las ofertas primero</div>
          <div style={{ color: "#6b5d4e", fontSize: 13, lineHeight: 1.45, marginTop: 2 }}>
            Activá las notificaciones y te avisamos de promos y combos nuevos de tu sucursal.
          </div>
        </div>
      </div>
      <div style={{ display: "flex", gap: 8, marginTop: 14 }}>
        <button onClick={onDismiss} style={{
          flex: 1, background: "#f5ede1", border: "1px solid #e8dcc8",
          color: "#6b5d4e", borderRadius: 10, padding: "11px 0",
          fontWeight: 700, fontSize: 13, cursor: "pointer", fontFamily: "'DM Sans', sans-serif"
        }}>Ahora no</button>
        <button data-sui="btn-primary" onClick={onGrant} style={{
          flex: 2, background: accent, border: "none",
          color: "#fff", borderRadius: 10, padding: "11px 0",
          fontWeight: 800, fontSize: 13, cursor: "pointer", fontFamily: "'DM Sans', sans-serif"
        }}>Activar notificaciones</button>
      </div>
    </div>
  );
}

Object.assign(window, { NotifPrompt, loadNotifSubs, saveNotifSub, deliverPendingCampaigns, NOTIF_DISMISS_KEY });
