/* Pagos → window. Pantalla INLINE dentro de AppFrame.
   Sólo visible para superadmin (gating en Perfil).
   Permite solicitar retiros vía Toke (toke.do/toke). El super coloca
   su número de teléfono + nombre completo, monto mínimo RD$100.
   Por ahora sólo se registra la solicitud; el procesamiento real
   queda para la fase admin. ESC = onClose. */
(function () {
  const { useState, useEffect } = React;
  const { useAuth, BackIcon } = window;

  const BRAND = "#2563EB";
  const VERDE = "#16A34A";

  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 estadoLabel(e) {
    if (e === "pendiente")  return "En revisión";
    if (e === "pagada")     return "Pagada";
    if (e === "cancelada")  return "Cancelada";
    if (e === "rechazada")  return "Rechazada";
    return e || "—";
  }

  function estadoColor(e) {
    if (e === "pendiente")  return { bg: "#FEF3C7", fg: "#92400E", bgDark: "#3F2D0A", fgDark: "#FBBF24" };
    if (e === "pagada")     return { bg: "#DCFCE7", fg: "#166534", bgDark: "#0F2A18", fgDark: "#4ADE80" };
    if (e === "cancelada")  return { bg: "#F3F4F6", fg: "#4B5563", bgDark: "#222226", fgDark: "#9CA3AF" };
    if (e === "rechazada")  return { bg: "#FEE2E2", fg: "#991B1B", bgDark: "#3A1414", fgDark: "#F87171" };
    return { bg: "#F3F4F6", fg: "#4B5563", bgDark: "#222226", fgDark: "#9CA3AF" };
  }

  function Pagos({ onClose }) {
    const { user } = useAuth();

    const [balance, setBalance] = useState(0);
    const [solicitudes, setSolicitudes] = useState([]);

    const [pagoTelefono, setPagoTelefono] = useState("");
    const [pagoNombre, setPagoNombre] = useState("");
    const [pagoMonto, setPagoMonto] = useState("");
    const [enviandoPago, setEnviandoPago] = useState(false);
    const [pagoError, setPagoError] = useState("");
    const [pagoExito, setPagoExito] = useState("");
    const [cancelando, setCancelando] = useState(null);

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

    const MIN_PAGO = (typeof window.MONTO_MIN_PAGO === "number") ? window.MONTO_MIN_PAGO : 100;

    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) return;
      if (typeof window.suscribirSolicitudesPago !== "function") return;
      const unsub = window.suscribirSolicitudesPago(user.uid, function (arr) {
        setSolicitudes(Array.isArray(arr) ? arr : []);
      });
      return function () { if (typeof unsub === "function") unsub(); };
    }, [user && user.uid]);

    // Prefill del nombre desde Auth.
    useEffect(function () {
      if (!user) return;
      if (pagoNombre) return;
      if (user.displayName) setPagoNombre(user.displayName);
    }, [user && user.uid]);

    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";

    const sumaPendientesPago = solicitudes.reduce(function (acc, s) {
      return acc + (s.estado === "pendiente" && typeof s.monto === "number" ? s.monto : 0);
    }, 0);
    const disponiblePago = Math.max(0, balance - sumaPendientesPago);

    async function enviarSolicitudPago(e) {
      if (e && e.preventDefault) e.preventDefault();
      if (!user || !user.uid) return;
      if (typeof window.solicitarPagoToke !== "function") return;
      setPagoError("");
      setPagoExito("");
      const monto = Number(pagoMonto);
      if (!isFinite(monto) || monto < MIN_PAGO) {
        setPagoError("El monto mínimo es " + fmtRD(MIN_PAGO) + ".");
        return;
      }
      if (monto > disponiblePago) {
        setPagoError("El monto excede el disponible (" + fmtRD(disponiblePago) + ").");
        return;
      }
      const tel = String(pagoTelefono || "").trim();
      if (tel.replace(/[^\d]/g, "").length < 10) {
        setPagoError("Ingrese un número de teléfono válido (mín. 10 dígitos).");
        return;
      }
      const nombre = String(pagoNombre || "").trim();
      if (nombre.length < 3) {
        setPagoError("Ingrese su nombre completo.");
        return;
      }
      try {
        setEnviandoPago(true);
        await window.solicitarPagoToke(user.uid, {
          telefono: tel,
          nombre_completo: nombre,
          monto: monto,
        });
        setPagoExito("Solicitud registrada. Se le pagará por Toke al " + tel + ".");
        setPagoMonto("");
      } catch (err) {
        const code = err && err.message;
        if (code === "monto_invalido")        setPagoError("El monto mínimo es " + fmtRD(MIN_PAGO) + ".");
        else if (code === "telefono_invalido") setPagoError("El número de teléfono no es válido.");
        else if (code === "nombre_invalido")   setPagoError("Ingrese su nombre completo.");
        else if (code === "balance_insuficiente") setPagoError("Saldo insuficiente para esta solicitud.");
        else setPagoError("No se pudo registrar la solicitud. Intente de nuevo.");
        console.warn("[Pagos] solicitar pago falló:", err);
      } finally {
        setEnviandoPago(false);
      }
    }

    async function ejecutarCancelar() {
      if (!cancelando || !user || !user.uid) return;
      if (typeof window.cancelarSolicitudPago !== "function") {
        setCancelando(null);
        return;
      }
      try {
        await window.cancelarSolicitudPago(user.uid, cancelando.id);
      } catch (_) { /* ignore */ }
      setCancelando(null);
    }

    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 }}>
            Pagos
          </h2>
        </div>

        {/* Disponible */}
        <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" }}>
              Disponible para retirar
            </div>
            <div style={{ marginTop: 8, fontSize: 36, fontWeight: 900, lineHeight: 1.1 }}>
              {fmtRD(disponiblePago)}
            </div>
            <div style={{ marginTop: 6, fontSize: 12, fontWeight: 600, opacity: 0.9 }}>
              Saldo {fmtRD(balance)} · {fmtRD(sumaPendientesPago)} en solicitudes pendientes.
            </div>
          </div>
        </div>

        {/* Tarjeta de solicitud */}
        <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: 8,
            }}>
              Método de pago
            </div>

            <div style={{ display: "flex", gap: 8, marginBottom: 14 }}>
              <div
                style={{
                  flex: 1,
                  borderRadius: 12,
                  border: "2px solid " + BRAND,
                  background: dark ? "#0F1830" : "#EFF6FF",
                  padding: "10px 12px",
                  display: "flex", alignItems: "center", gap: 10,
                }}
              >
                <div style={{
                  width: 36, height: 36, borderRadius: 10,
                  background: BRAND, color: "#FFFFFF",
                  display: "flex", alignItems: "center", justifyContent: "center",
                  fontWeight: 900, fontSize: 14, letterSpacing: 0.5,
                }}>
                  TK
                </div>
                <div style={{ minWidth: 0, flex: 1 }}>
                  <div style={{ fontSize: 13, fontWeight: 900, color: colorTexto }}>
                    Toke
                  </div>
                  <div style={{ fontSize: 11, fontWeight: 700, color: colorSecundario, lineHeight: 1.3 }}>
                    Pago por número de teléfono · toke.do/toke
                  </div>
                </div>
                <div style={{
                  fontSize: 10, fontWeight: 900, color: BRAND,
                  textTransform: "uppercase", letterSpacing: 0.4,
                }}>
                  Principal
                </div>
              </div>
            </div>

            <form onSubmit={enviarSolicitudPago}>
              <div style={{ display: "grid", gap: 10 }}>
                <label style={{ display: "block" }}>
                  <div style={{ fontSize: 11, fontWeight: 800, color: colorSecundario, marginBottom: 4 }}>
                    Su número de Toke
                  </div>
                  <input
                    type="tel"
                    inputMode="tel"
                    autoComplete="tel"
                    placeholder="809 555 1234"
                    value={pagoTelefono}
                    onChange={(e) => setPagoTelefono(e.target.value)}
                    style={{
                      width: "100%",
                      borderRadius: 10,
                      border: "1px solid " + colorBorde,
                      background: bgSoft,
                      color: colorTexto,
                      padding: "10px 12px",
                      fontSize: 14,
                      fontWeight: 700,
                      outline: "none",
                      boxSizing: "border-box",
                    }}
                  />
                </label>

                <label style={{ display: "block" }}>
                  <div style={{ fontSize: 11, fontWeight: 800, color: colorSecundario, marginBottom: 4 }}>
                    Nombre completo (titular de la cuenta Toke)
                  </div>
                  <input
                    type="text"
                    autoComplete="name"
                    placeholder="Su nombre y apellido"
                    value={pagoNombre}
                    onChange={(e) => setPagoNombre(e.target.value)}
                    style={{
                      width: "100%",
                      borderRadius: 10,
                      border: "1px solid " + colorBorde,
                      background: bgSoft,
                      color: colorTexto,
                      padding: "10px 12px",
                      fontSize: 14,
                      fontWeight: 700,
                      outline: "none",
                      boxSizing: "border-box",
                    }}
                  />
                </label>

                <label style={{ display: "block" }}>
                  <div style={{
                    display: "flex", justifyContent: "space-between", alignItems: "center",
                    fontSize: 11, fontWeight: 800, color: colorSecundario, marginBottom: 4,
                  }}>
                    <span>Monto a solicitar (mínimo {fmtRD(MIN_PAGO)})</span>
                    {disponiblePago >= MIN_PAGO && (
                      <button
                        type="button"
                        onClick={() => setPagoMonto(String(disponiblePago))}
                        style={{
                          border: "none", background: "transparent",
                          color: BRAND, fontSize: 11, fontWeight: 900,
                          cursor: "pointer", padding: 0,
                        }}
                      >
                        Usar todo
                      </button>
                    )}
                  </div>
                  <div style={{ position: "relative" }}>
                    <span style={{
                      position: "absolute", left: 12, top: "50%", transform: "translateY(-50%)",
                      fontSize: 14, fontWeight: 800, color: colorSecundario, pointerEvents: "none",
                    }}>
                      RD$
                    </span>
                    <input
                      type="number"
                      inputMode="decimal"
                      min={MIN_PAGO}
                      step="1"
                      placeholder={String(MIN_PAGO)}
                      value={pagoMonto}
                      onChange={(e) => setPagoMonto(e.target.value)}
                      style={{
                        width: "100%",
                        borderRadius: 10,
                        border: "1px solid " + colorBorde,
                        background: bgSoft,
                        color: colorTexto,
                        padding: "10px 12px 10px 50px",
                        fontSize: 14,
                        fontWeight: 800,
                        outline: "none",
                        boxSizing: "border-box",
                      }}
                    />
                  </div>
                </label>

                {pagoError && (
                  <div style={{
                    fontSize: 12, fontWeight: 700,
                    color: dark ? "#F87171" : "#991B1B",
                    background: dark ? "#3A1414" : "#FEE2E2",
                    padding: "8px 10px", borderRadius: 8,
                  }}>
                    {pagoError}
                  </div>
                )}
                {pagoExito && (
                  <div style={{
                    fontSize: 12, fontWeight: 700,
                    color: dark ? "#4ADE80" : "#166534",
                    background: dark ? "#0F2A18" : "#DCFCE7",
                    padding: "8px 10px", borderRadius: 8,
                  }}>
                    {pagoExito}
                  </div>
                )}

                <button
                  type="submit"
                  disabled={enviandoPago || disponiblePago < MIN_PAGO}
                  style={{
                    border: "none",
                    borderRadius: 12,
                    padding: "12px 14px",
                    background: (enviandoPago || disponiblePago < MIN_PAGO) ? "#9CA3AF" : BRAND,
                    color: "#FFFFFF",
                    fontSize: 14,
                    fontWeight: 900,
                    cursor: (enviandoPago || disponiblePago < MIN_PAGO) ? "default" : "pointer",
                    opacity: (enviandoPago || disponiblePago < MIN_PAGO) ? 0.85 : 1,
                  }}
                >
                  {enviandoPago ? "Enviando…" : "Solicitar pago"}
                </button>

                <div style={{ fontSize: 11, fontWeight: 600, color: colorSecundario, lineHeight: 1.5 }}>
                  Le enviaremos el pago por Toke al número que indique. Asegúrese de que su cuenta de Toke esté
                  registrada con ese mismo número y nombre.
                </div>
              </div>
            </form>
          </div>
        </div>

        {/* Mis solicitudes */}
        <div style={{ padding: "16px 16px 32px" }}>
          <div style={{
            fontSize: 12, fontWeight: 900, color: colorSecundario,
            textTransform: "uppercase", letterSpacing: 0.6, marginBottom: 8, paddingLeft: 2,
          }}>
            Mis solicitudes
          </div>

          {solicitudes.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 ha solicitado ningún pago. Cuando solicite uno aparecerá aquí con su estado actual.
            </div>
          )}

          {solicitudes.length > 0 && (
            <div style={{ display: "grid", gap: 8 }}>
              {solicitudes.map(function (s) {
                var col = estadoColor(s.estado);
                var pillBg = dark ? col.bgDark : col.bg;
                var pillFg = dark ? col.fgDark : col.fg;
                return (
                  <div
                    key={s.id}
                    style={{
                      borderRadius: 12,
                      border: "1px solid " + colorBorde,
                      background: bgCard,
                      padding: "12px 14px",
                      display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10,
                    }}
                  >
                    <div style={{ minWidth: 0, flex: 1 }}>
                      <div style={{ display: "flex", alignItems: "center", gap: 6, flexWrap: "wrap" }}>
                        <span style={{ fontSize: 14, fontWeight: 900, color: colorTexto }}>
                          {fmtRD(s.monto || 0)}
                        </span>
                        <span style={{
                          fontSize: 10, fontWeight: 900,
                          color: pillFg, background: pillBg,
                          padding: "2px 7px", borderRadius: 999,
                          textTransform: "uppercase", letterSpacing: 0.4,
                        }}>
                          {estadoLabel(s.estado)}
                        </span>
                      </div>
                      <div style={{
                        fontSize: 11, fontWeight: 700, color: colorSecundario,
                        marginTop: 2, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap",
                      }}>
                        Toke · {s.telefono || "—"} · {fmtFecha(s.creado_en)}
                      </div>
                    </div>
                    {s.estado === "pendiente" && (
                      <button
                        type="button"
                        onClick={() => setCancelando(s)}
                        style={{
                          border: "1px solid " + colorBorde,
                          background: bgSoft,
                          color: dark ? "#F87171" : "#991B1B",
                          fontSize: 11, fontWeight: 800,
                          padding: "6px 10px", borderRadius: 8,
                          cursor: "pointer", whiteSpace: "nowrap",
                        }}
                      >
                        Cancelar
                      </button>
                    )}
                  </div>
                );
              })}
            </div>
          )}
        </div>

        {cancelando && window.ConfirmModal && React.createElement(window.ConfirmModal, {
          abierto: !!cancelando,
          titulo: "Cancelar solicitud",
          mensaje: cancelando
            ? "¿Cancelar la solicitud de " + fmtRD(cancelando.monto || 0) + " por Toke al " + (cancelando.telefono || "—") + "?"
            : "",
          textoConfirmar: "Cancelar solicitud",
          textoCancelar: "Volver",
          tono: "peligro",
          onConfirmar: ejecutarCancelar,
          onCancelar: function () { setCancelando(null); },
        })}
      </div>
    );
  }

  window.Pagos = Pagos;
})();
