/* ============================================================
   Modal "Recordatorio de participación"
   ------------------------------------------------------------
   Empujón ocasional para que la gente siga pronosticando: aún
   queda mucho bote por repartir (sobre todo la eliminatoria).
   Clona el patrón de leagues-announce.jsx (window.QLeaguesAnnounce):
   eligible() + markShown() + persistencia por dispositivo en
   localStorage. La impresión se marca AL MOSTRAR (no al cerrar).

   Reglas de disparo:
     · Audiencia: usuario registrado (colaborador O invitado) con
       ≥2 partidos próximos sin pronosticar.
     · Cadencia:  a lo más 1 vez cada 24 h.
     · Tope:      máximo 4 impresiones.
     · Fin:       cuando arranca la fase eliminatoria, o cuando el
       usuario ya no tiene pendientes (eligible deja de cumplirse).
   ============================================================ */
(function () {
  "use strict";

  const MAX_SHOWS = 4;
  const COOLDOWN_MS = 24 * 3600 * 1000;            // 24 horas entre impresiones
  const PENDING_WINDOW_MS = 48 * 3600 * 1000;      // solo cuentan pendientes que cierran dentro de 48 h
  const KEY = (uid) => `quiniela_participation_nudge_v1_${uid || "anon"}`;

  function readState(uid) {
    try { return JSON.parse(localStorage.getItem(KEY(uid))) || { count: 0, last: 0 }; }
    catch (e) { return { count: 0, last: 0 }; }
  }
  function markShown(uid, now) {
    try {
      const s = readState(uid);
      localStorage.setItem(KEY(uid), JSON.stringify({ count: (s.count || 0) + 1, last: now }));
    } catch (e) {}
  }

  // inicio de la fase eliminatoria = primer kickoff de un partido KO. El modal se
  // autoapaga ahí (de ahí en adelante ya no se pronostica fase de grupos).
  function knockoutStart() {
    const Q = window.QStore;
    const ko = (Q.db.matches || []).filter((m) => Q.isKnockout(m));
    return ko.length ? Math.min.apply(null, ko.map((m) => m.kickoff)) : Infinity;
  }
  // partidos pronosticables y SIN pronóstico del usuario que CIERRAN PRONTO
  // (arrancan dentro de las próximas 48 h). Así el modal solo aparece cerca del
  // cierre: respeta a quien pronostica al último (se apaga al llenar lo inminente)
  // y no molesta por partidos lejanos.
  function pendingCount(uid, now) {
    const Q = window.QStore;
    return (Q.db.matches || []).filter((m) =>
      m.kickoff > now && m.kickoff < now + PENDING_WINDOW_MS &&
      Q.matchReady(m) && !Q.db.predictions[`${uid}_${m.id}`]
    ).length;
  }

  // Elegibilidad de FRECUENCIA/AUDIENCIA (las reglas de "no interrumpir" las
  // evalúa App en tryShowModals, igual que con el modal de Ligas).
  function eligible(now) {
    const Q = window.QStore;
    if (!Q) return false;
    const me = Q.current;
    if (!me) return false;                                 // registrado (colaborador o invitado)
    if (now >= knockoutStart()) return false;              // ya arrancó la eliminatoria
    if (pendingCount(me.userId, now) < 2) return false;    // ≥2 pendientes
    const s = readState(me.userId);
    if ((s.count || 0) >= MAX_SHOWS) return false;         // tope de impresiones
    if (now - (s.last || 0) < COOLDOWN_MS) return false;   // cooldown de 24 h
    return true;
  }

  // Métricas → Firebase Analytics (window.QAnalytics, no-op si no está disponible).
  function track(event) { if (window.QAnalytics) window.QAnalytics.log(event); }

  /* ---------- modal (presentacional) ---------- */
  function ParticipationNudgeModal({ onGoMatches, onDismiss }) {
    const { useEffect, useRef } = React;
    const primaryRef = useRef(null);
    const cardRef = useRef(null);
    const prevFocus = useRef(null);

    useEffect(() => {
      prevFocus.current = document.activeElement;
      if (primaryRef.current) primaryRef.current.focus();
      const onKey = (e) => {
        if (e.key === "Escape") { onDismiss(); return; }
        if (e.key !== "Tab") return;
        const f = cardRef.current ? cardRef.current.querySelectorAll(
          'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])') : [];
        if (!f.length) return;
        const first = f[0], last = f[f.length - 1];
        if (e.shiftKey && document.activeElement === first) { e.preventDefault(); last.focus(); }
        else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus(); }
      };
      document.addEventListener("keydown", onKey);
      return () => {
        document.removeEventListener("keydown", onKey);
        if (prevFocus.current && prevFocus.current.focus) { try { prevFocus.current.focus(); } catch (e) {} }
      };
    }, []);

    const onScrim = (e) => { if (e.target === e.currentTarget) onDismiss(); };
    const Q = window.QStore;
    const porJugar = Q && Q.pointsPool ? Q.pointsPool().pendientes : 0;

    return (
      <div className="la-scrim" onClick={onScrim}>
        <div className="la-modal" role="dialog" aria-modal="true" aria-labelledby="pn-title" aria-describedby="pn-desc" ref={cardRef}>
          <div className="la-handle" aria-hidden="true"></div>
          <button className="la-close" onClick={onDismiss} aria-label="Cerrar">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round"><path d="M6 6l12 12M18 6L6 18" /></svg>
          </button>

          <div className="la-hero">
            <span className="la-badge">👀 Ojo · La quiniela recién calienta</span>
            <div className="la-meter" aria-hidden="true">
              <div className="la-meter-phases">
                <span className="ph-grupos">Fase de grupos · 42%</span>
                <span className="ph-elim">Eliminatorias · 58%</span>
              </div>
              <div className="la-meter-track">
                <div className="la-seg la-seg-done" style={{ width: "14%" }}></div>
                <div className="la-seg la-seg-grupos" style={{ width: "28%" }}></div>
                <div className="la-seg la-seg-elim" style={{ width: "58%" }}>toda la eliminatoria</div>
              </div>
              <div className="la-meter-cap"><span>Jugado: 1 de 3 fechas</span><span>Te faltan {porJugar} puntos</span></div>
            </div>
          </div>

          <div className="la-body">
            <h1 id="pn-title">El que no pronostica, no remonta. Métele.</h1>
            <p className="la-lead" id="pn-desc">
              Apenas se jugó <strong>1 de 3 fechas</strong> de grupos y falta toda la eliminatoria,
              donde los puntos pesan más —hasta <strong>19 puntos solo en la final</strong>. El sueño
              está intacto: guarda la calculadora y métele pronóstico.
            </p>
            <div className="la-actions">
              <button className="la-btn-primary" ref={primaryRef} onClick={onGoMatches}>
                Voy a pronosticar
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14M13 6l6 6-6 6" /></svg>
              </button>
              <button className="la-btn-ghost" onClick={onDismiss}>Luego le meto</button>
            </div>
            <p className="la-note">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="9" /><path d="M12 7v5l3 2" /></svg>
              No te confíes ni te rindas
            </p>
          </div>
        </div>
      </div>
    );
  }

  window.QParticipationNudge = { eligible, markShown, track, ParticipationNudgeModal, MAX_SHOWS, COOLDOWN_MS };
  window.ParticipationNudgeModal = ParticipationNudgeModal;
})();
