/* Facturacion → window. Pantalla INLINE dentro de AppFrame.
   Sólo visible para superadmin (gating se hace en Perfil).
   Muestra:
     - Total acumulado (monedero) arriba, grande.
     - Tabla histórica con cada transacción (fecha, descripción, monto).
   Suscribe a window.suscribirMonederoSuper / suscribirTransaccionesSuper.
   ESC = onClose. */
(function () {
  const { useState, useEffect } = React;
  const { useAuth, BackIcon } = window;

  const BRAND = "#2563EB";
  const VERDE = "#16A34A";
  const HOST_REF = "https://app.cultord.org";

  function fmtRD(n) {
    var v = typeof n === "number" ? n : 0;
    try {
      return "RD$" + v.toLocaleString("es-DO", {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      });
    } catch (_) { return "RD$" + v.toFixed(2); }
  }

  function fmtFecha(ms) {
    if (typeof ms !== "number") return "—";
    try {
      var d = new Date(ms);
      return d.toLocaleDateString("es-DO", {
        day: "2-digit", month: "short", year: "numeric",
      }) + " " + d.toLocaleTimeString("es-DO", {
        hour: "2-digit", minute: "2-digit",
      });
    } catch (_) { return "—"; }
  }

  function tipoLabel(t) {
    if (t === "credito_publicacion") return "Publicación";
    if (t === "credito_referido") return "Nuevo referido";
    if (t === "debito_retiro") return "Retiro";
    return t || "—";
  }

  function Facturacion({ onClose }) {
    const { user } = useAuth();
    const [balance, setBalance] = useState(0);
    const [tx, setTx] = useState([]);
    const [cargando, setCargando] = useState(true);
    const [codigoRef, setCodigoRef] = useState(null);
    const [generando, setGenerando] = useState(false);
    const [copiado, setCopiado] = useState(false);

    const dark =
      typeof document !== "undefined" &&
      document.querySelector(".app-frame")?.classList.contains("dark");

    useEffect(function () {
      const onKey = (e) => { if (e.key === "Escape") onClose && onClose(); };
      document.addEventListener("keydown", onKey);
      return () => document.removeEventListener("keydown", onKey);
    }, [onClose]);

    useEffect(function () {
      if (!user || !user.uid) return;
      if (typeof window.suscribirMonederoSuper !== "function") return;
      const unsub = window.suscribirMonederoSuper(user.uid, function (v) {
        setBalance(typeof v === "number" ? v : 0);
      });
      return function () { if (typeof unsub === "function") unsub(); };
    }, [user && user.uid]);

    useEffect(function () {
      if (!user || !user.uid) { setCargando(false); return; }
      if (typeof window.suscribirTransaccionesSuper !== "function") {
        setCargando(false);
        return;
      }
      setCargando(true);
      const unsub = window.suscribirTransaccionesSuper(user.uid, function (arr) {
        setTx(Array.isArray(arr) ? arr : []);
        setCargando(false);
      });
      return function () { if (typeof unsub === "function") unsub(); };
    }, [user && user.uid]);

    // Suscripción al código de referido del super.
    useEffect(function () {
      if (!user || !user.uid) return;
      if (typeof window.suscribirCodigoReferido !== "function") return;
      const unsub = window.suscribirCodigoReferido(user.uid, function (c) {
        setCodigoRef(typeof c === "string" ? c : null);
      });
      return function () { if (typeof unsub === "function") unsub(); };
    }, [user && user.uid]);

    // Al abrir Facturación, procesa pendientes — acredita RD$10 por cada
    // nuevo registro que llegó con su código de referido. Idempotente.
    useEffect(function () {
      if (!user || !user.uid) return;
      if (typeof window.procesarReferidosPendientes !== "function") return;
      window.procesarReferidosPendientes(user.uid).catch(function () { /* ignore */ });
    }, [user && user.uid]);

    async function generarCodigo() {
      if (!user || !user.uid) return;
      if (typeof window.obtenerOCrearCodigoReferido !== "function") return;
      try {
        setGenerando(true);
        const c = await window.obtenerOCrearCodigoReferido(user.uid);
        if (c) setCodigoRef(c);
      } catch (e) {
        console.warn("[Facturacion] generar código falló:", e);
      } finally {
        setGenerando(false);
      }
    }

    async function copiarEnlace() {
      if (!codigoRef) return;
      const url = HOST_REF + "/?ref=" + codigoRef;
      try {
        if (navigator.clipboard && navigator.clipboard.writeText) {
          await navigator.clipboard.writeText(url);
        } else {
          const t = document.createElement("textarea");
          t.value = url;
          document.body.appendChild(t);
          t.select();
          document.execCommand("copy");
          document.body.removeChild(t);
        }
        setCopiado(true);
        setTimeout(function () { setCopiado(false); }, 1800);
      } catch (e) {
        console.warn("[Facturacion] copiar falló:", e);
      }
    }

    const colorTexto = dark ? "#F0F0F0" : "#111827";
    const colorSecundario = dark ? "#9CA3AF" : "#6B7280";
    const colorBorde = dark ? "#2A2A2A" : "#E5E7EB";
    const bgCard = dark ? "#1A1A1A" : "#FFFFFF";
    const bgSoft = dark ? "#0F0F10" : "#F9FAFB";

    return (
      <div className="fade-in" style={{ paddingBottom: 96 }}>
        {/* Cabecera inline */}
        <div style={{ display: "flex", alignItems: "center", gap: 6, padding: "16px 16px 8px" }}>
          <button
            type="button"
            onClick={onClose}
            aria-label="Atrás"
            style={{
              width: 32, height: 32, borderRadius: 999, border: "none",
              background: "transparent", color: colorTexto, cursor: "pointer",
              display: "flex", alignItems: "center", justifyContent: "center",
              marginLeft: -6,
            }}
          >
            {BackIcon ? <BackIcon /> : <span style={{ fontSize: 20 }}>←</span>}
          </button>
          <h2 style={{ margin: 0, fontSize: 18, fontWeight: 900, color: colorTexto }}>
            Facturación
          </h2>
        </div>

        {/* Monedero */}
        <div style={{ padding: "8px 16px 4px" }}>
          <div
            style={{
              borderRadius: 18,
              border: "1px solid " + colorBorde,
              background: "linear-gradient(135deg, " + BRAND + " 0%, #1E40AF 100%)",
              color: "#FFFFFF",
              padding: "20px 18px",
              boxShadow: "0 6px 16px rgba(37,99,235,0.25)",
            }}
          >
            <div style={{ fontSize: 12, fontWeight: 800, opacity: 0.85, letterSpacing: 0.4, textTransform: "uppercase" }}>
              Monedero CultoRD
            </div>
            <div style={{ marginTop: 8, fontSize: 36, fontWeight: 900, lineHeight: 1.1 }}>
              {fmtRD(balance)}
            </div>
            <div style={{ marginTop: 6, fontSize: 12, fontWeight: 600, opacity: 0.9 }}>
              Acumulado total — RD$2 por publicación, RD$10 por referido.
            </div>
          </div>
        </div>

        {/* Mi enlace de referido */}
        <div style={{ padding: "16px 16px 4px" }}>
          <div
            style={{
              borderRadius: 16,
              border: "1px solid " + colorBorde,
              background: bgCard,
              padding: "16px 16px 18px",
            }}
          >
            <div style={{
              fontSize: 11, fontWeight: 900, color: colorSecundario,
              textTransform: "uppercase", letterSpacing: 0.6, marginBottom: 6,
            }}>
              Mi enlace de referido
            </div>
            <div style={{ fontSize: 13, fontWeight: 600, color: colorTexto, lineHeight: 1.5, marginBottom: 12 }}>
              Comparta este enlace. Por cada nuevo usuario que se registre con él, su monedero recibe
              <strong style={{ color: VERDE }}> {fmtRD(10)}</strong>.
            </div>

            {codigoRef ? (
              <React.Fragment>
                <div
                  style={{
                    borderRadius: 12,
                    border: "1px dashed " + colorBorde,
                    background: bgSoft,
                    padding: "10px 12px",
                    fontFamily: "ui-monospace, Menlo, Consolas, monospace",
                    fontSize: 13,
                    fontWeight: 700,
                    color: colorTexto,
                    wordBreak: "break-all",
                    lineHeight: 1.4,
                  }}
                >
                  {HOST_REF}/?ref={codigoRef}
                </div>
                <div style={{ marginTop: 6, fontSize: 11, fontWeight: 700, color: colorSecundario }}>
                  Código permanente: <strong style={{ color: colorTexto }}>{codigoRef}</strong>
                </div>
                <button
                  type="button"
                  onClick={copiarEnlace}
                  style={{
                    marginTop: 12,
                    width: "100%",
                    border: "none",
                    borderRadius: 12,
                    padding: "12px 14px",
                    background: copiado ? VERDE : BRAND,
                    color: "#FFFFFF",
                    fontSize: 14,
                    fontWeight: 900,
                    cursor: "pointer",
                  }}
                >
                  {copiado ? "Enlace copiado" : "Copiar enlace"}
                </button>
              </React.Fragment>
            ) : (
              <button
                type="button"
                disabled={generando}
                onClick={generarCodigo}
                style={{
                  width: "100%",
                  border: "none",
                  borderRadius: 12,
                  padding: "12px 14px",
                  background: generando ? "#9CA3AF" : BRAND,
                  color: "#FFFFFF",
                  fontSize: 14,
                  fontWeight: 900,
                  cursor: generando ? "default" : "pointer",
                  opacity: generando ? 0.85 : 1,
                }}
              >
                {generando ? "Generando…" : "Generar mi enlace"}
              </button>
            )}
          </div>
        </div>

        {/* Histórico */}
        <div style={{ padding: "16px 16px 32px" }}>
          <div style={{
            fontSize: 12, fontWeight: 900, color: colorSecundario,
            textTransform: "uppercase", letterSpacing: 0.6, marginBottom: 8, paddingLeft: 2,
          }}>
            Historial de transacciones
          </div>

          {cargando && (
            <div style={{ padding: "32px 0", textAlign: "center", color: colorSecundario, fontSize: 13, fontWeight: 700 }}>
              Cargando…
            </div>
          )}

          {!cargando && tx.length === 0 && (
            <div
              style={{
                borderRadius: 14,
                border: "1px dashed " + colorBorde,
                background: bgSoft,
                padding: "28px 18px",
                textAlign: "center",
                color: colorSecundario,
                fontSize: 13,
                fontWeight: 600,
                lineHeight: 1.5,
              }}
            >
              Aún no hay transacciones. Cada publicación a nombre de
              <strong style={{ color: colorTexto }}> CultoRD </strong>
              suma <strong style={{ color: VERDE }}>{fmtRD(2)}</strong> a su monedero.
            </div>
          )}

          {!cargando && tx.length > 0 && (
            <div
              style={{
                borderRadius: 14,
                border: "1px solid " + colorBorde,
                background: bgCard,
                overflow: "hidden",
              }}
            >
              {/* Header de tabla */}
              <div
                style={{
                  display: "grid",
                  gridTemplateColumns: "1fr auto",
                  gap: 8,
                  padding: "10px 14px",
                  background: bgSoft,
                  borderBottom: "1px solid " + colorBorde,
                  fontSize: 11,
                  fontWeight: 900,
                  color: colorSecundario,
                  textTransform: "uppercase",
                  letterSpacing: 0.4,
                }}
              >
                <div>Concepto</div>
                <div>Monto</div>
              </div>

              {tx.map(function (t) {
                var positivo = (t.monto || 0) >= 0;
                return (
                  <div
                    key={t.id}
                    style={{
                      display: "grid",
                      gridTemplateColumns: "1fr auto",
                      gap: 8,
                      padding: "12px 14px",
                      borderBottom: "1px solid " + colorBorde,
                      alignItems: "center",
                    }}
                  >
                    <div style={{ minWidth: 0 }}>
                      <div
                        style={{
                          fontSize: 13,
                          fontWeight: 800,
                          color: colorTexto,
                          overflow: "hidden",
                          textOverflow: "ellipsis",
                          whiteSpace: "nowrap",
                        }}
                      >
                        {t.descripcion || tipoLabel(t.tipo)}
                      </div>
                      <div style={{ fontSize: 11, fontWeight: 700, color: colorSecundario, marginTop: 2 }}>
                        {tipoLabel(t.tipo)} · {fmtFecha(t.creado_en)}
                      </div>
                    </div>
                    <div
                      style={{
                        fontSize: 14,
                        fontWeight: 900,
                        color: positivo ? VERDE : "#DC2626",
                        whiteSpace: "nowrap",
                      }}
                    >
                      {positivo ? "+" : ""}{fmtRD(t.monto || 0)}
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>
      </div>
    );
  }

  window.Facturacion = Facturacion;
})();
