// admin-view.jsx — Vista de administración de miembros (Vanesa's view)

const { useState: useStateAV, useMemo: useMemoAV } = React;

// ── Mock members data ───────────────────────────────────────────────────────
const MEMBERS = [
  { id: "m01", name: "Lucía Fernández",     email: "lucia.fernandez@gmail.com",     plan: "Mentoría VIP",    status: "active",   joined: "2025-09-12", lastSeen: "hace 2 horas",  consultas: 89,  level: 5 },
  { id: "m02", name: "María Pérez",          email: "maria.perez@hotmail.com",       plan: "Plan Anual",      status: "active",   joined: "2025-11-03", lastSeen: "hace 18 min",   consultas: 142, level: 3 },
  { id: "m03", name: "Carolina Rodríguez",   email: "caro.rod@gmail.com",            plan: "Plan Mensual",    status: "active",   joined: "2026-01-22", lastSeen: "hoy",           consultas: 34,  level: 2 },
  { id: "m04", name: "Daniela Sánchez",      email: "dani.sanchez@outlook.com",      plan: "Plan Anual",      status: "active",   joined: "2025-08-04", lastSeen: "hace 3 días",   consultas: 211, level: 4 },
  { id: "m05", name: "Florencia Gómez",      email: "flor.gomez@gmail.com",          plan: "Plan Mensual",    status: "trial",    joined: "2026-04-29", lastSeen: "hace 1 día",    consultas: 7,   level: 1 },
  { id: "m06", name: "Camila Torres",        email: "camila.torres@yahoo.com",       plan: "Mentoría VIP",    status: "active",   joined: "2025-06-18", lastSeen: "hace 5 horas",  consultas: 178, level: 5 },
  { id: "m07", name: "Antonella Romero",     email: "antonella.r@gmail.com",         plan: "Plan Anual",      status: "active",   joined: "2025-10-11", lastSeen: "ayer",          consultas: 96,  level: 3 },
  { id: "m08", name: "Valentina Castro",     email: "val.castro@gmail.com",          plan: "Plan Mensual",    status: "paused",   joined: "2025-12-08", lastSeen: "hace 14 días",  consultas: 22,  level: 2 },
  { id: "m09", name: "Sofía Méndez",         email: "sofia.mendez@gmail.com",        plan: "Plan Mensual",    status: "active",   joined: "2026-02-15", lastSeen: "hoy",           consultas: 41,  level: 2 },
  { id: "m10", name: "Martina Vega",         email: "martina.vega@hotmail.com",      plan: "Plan Anual",      status: "active",   joined: "2025-07-21", lastSeen: "hace 6 horas",  consultas: 156, level: 4 },
  { id: "m11", name: "Paula Ortiz",          email: "paula.ortiz@gmail.com",         plan: "Plan Mensual",    status: "trial",    joined: "2026-05-15", lastSeen: "hace 30 min",   consultas: 3,   level: 1 },
  { id: "m12", name: "Renata Silva",         email: "renata.silva@outlook.com",      plan: "Mentoría VIP",    status: "active",   joined: "2025-05-09", lastSeen: "hoy",           consultas: 234, level: 5 },
  { id: "m13", name: "Agustina Herrera",     email: "agus.herrera@gmail.com",        plan: "Plan Anual",      status: "active",   joined: "2025-11-29", lastSeen: "hace 2 días",   consultas: 78,  level: 3 },
  { id: "m14", name: "Isabella Navarro",     email: "isa.navarro@gmail.com",         plan: "Plan Mensual",    status: "expired",  joined: "2025-10-02", lastSeen: "hace 45 días",  consultas: 19,  level: 1 },
  { id: "m15", name: "Constanza Ramos",      email: "consta.ramos@gmail.com",        plan: "Plan Anual",      status: "active",   joined: "2026-03-18", lastSeen: "hace 8 horas",  consultas: 52,  level: 2 },
];

const PLAN_STYLES = (p, t) => ({
  "Mentoría VIP":  { bg: t.accent + "1c", border: t.accent + "50", color: t.accent },
  "Plan Anual":    { bg: "rgba(46,125,107,0.14)", border: "rgba(46,125,107,0.4)", color: "#4FB59F" },
  "Plan Mensual":  { bg: p.bg2, border: p.border, color: p.text },
});

const STATUS_STYLES = (p) => ({
  active:  { dot: "#4FB59F", label: "Activo",     color: "#4FB59F" },
  trial:   { dot: "#D4AF7F", label: "En prueba",  color: "#D4AF7F" },
  paused:  { dot: "#8B7E73", label: "Pausado",    color: p.textMuted },
  expired: { dot: "#A85555", label: "Vencido",    color: "#A85555" },
});

// ── Opciones de edición ─────────────────────────────────────────────────────
const PLAN_OPTIONS = ["Plan Mensual", "Plan Anual", "Mentoría VIP"];
const STATUS_OPTIONS = [
  { id: "active",  label: "Activo" },
  { id: "trial",   label: "En prueba" },
  { id: "paused",  label: "Pausado" },
  { id: "expired", label: "Vencido" },
];

// Ciclo de facturación según el plan + monto por defecto.
const cycleOf = (plan) => plan === "Plan Anual" ? "anual" : "mensual";
const DEFAULT_AMOUNT = (plan) => plan === "Mentoría VIP" ? 297 : plan === "Plan Anual" ? 970 : 47;

// "Última conexión" en texto relativo, a partir de la fecha de la base.
function tiempoRelativo(fecha) {
  if (!fecha) return "sin ingresar aún";
  const d = new Date(fecha);
  if (isNaN(d)) return "—";
  const seg = Math.floor((Date.now() - d.getTime()) / 1000);
  if (seg < 60) return "recién";
  const min = Math.floor(seg / 60);
  if (min < 60) return `hace ${min} min`;
  const h = Math.floor(min / 60);
  if (h < 24) return `hace ${h} h`;
  const dias = Math.floor(h / 24);
  if (dias === 1) return "ayer";
  if (dias < 30) return `hace ${dias} días`;
  const meses = Math.floor(dias / 30);
  if (meses < 12) return `hace ${meses} mes${meses > 1 ? "es" : ""}`;
  return d.toISOString().slice(0, 10);
}

function initialsAV(name) {
  return (name || "").trim().split(/\s+/).map(w => w[0]).filter(Boolean).slice(0,2).join("").toUpperCase() || "?";
}

// ── Drawer para editar / crear miembro ───────────────────────────────────────
function EditMemberDrawer({ member, t, p, onClose, onSave, onDelete }) {
  const isNew = !!member.__new;
  const [form, setForm] = useStateAV({
    name: member.name || "",
    email: member.email || "",
    plan: member.plan || "Plan Mensual",
    status: member.status || "trial",
    level: member.level || 1,
    consultas: member.consultas ?? 0,
    amount: member.amount ?? DEFAULT_AMOUNT(member.plan || "Plan Mensual"),
    joined: member.joined || new Date().toISOString().slice(0,10),
    notes: member.notes || "",
  });
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const canSave = form.name.trim() && form.email.trim();

  const inputStyle = {
    width: "100%", boxSizing: "border-box",
    background: p.bg2, border: `1px solid ${p.border}`, borderRadius: 8,
    color: p.text, fontFamily: "'Geist', sans-serif", fontSize: 14,
    padding: "10px 12px", outline: "none",
  };
  const labelStyle = {
    fontFamily: "'Geist', sans-serif", fontSize: 10.5, color: p.textMuted,
    letterSpacing: "0.16em", textTransform: "uppercase", fontWeight: 500,
    marginBottom: 7, display: "block",
  };

  const handleSave = () => {
    if (!canSave) return;
    onSave({
      ...member,
      name: form.name.trim(),
      email: form.email.trim(),
      plan: form.plan,
      status: form.status,
      level: Number(form.level),
      consultas: Number(form.consultas) || 0,
      amount: Number(form.amount) || 0,
      joined: form.joined,
      notes: form.notes.trim(),
    });
  };

  return (
    <div onClick={onClose} style={{
      position: "fixed", inset: 0, zIndex: 60,
      background: "rgba(0,0,0,0.55)", backdropFilter: "blur(2px)",
      display: "flex", justifyContent: "flex-end",
      animation: "mdpFade .18s ease",
    }}>
      <style>{`@keyframes mdpFade{from{opacity:0}to{opacity:1}}@keyframes mdpDrawer{from{transform:translateX(28px);opacity:0}to{transform:translateX(0);opacity:1}}`}</style>
      <div onClick={e => e.stopPropagation()} style={{
        width: 460, maxWidth: "94vw", height: "100%",
        background: p.bg, borderLeft: `1px solid ${p.border}`,
        display: "flex", flexDirection: "column",
        boxShadow: "-24px 0 70px rgba(0,0,0,0.45)",
        animation: "mdpDrawer .24s cubic-bezier(.2,.8,.2,1)",
      }}>
        {/* Header */}
        <div style={{
          padding: "22px 26px", borderBottom: `1px solid ${p.border}`,
          display: "flex", alignItems: "center", gap: 14,
        }}>
          <div style={{
            width: 44, height: 44, borderRadius: 999,
            background: `linear-gradient(135deg, ${t.accent}, ${t.accent}99)`,
            display: "flex", alignItems: "center", justifyContent: "center",
            color: "#0A0A0A", fontWeight: 600, fontSize: 14, flexShrink: 0,
          }}>{initialsAV(form.name)}</div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{
              fontFamily: "'Geist', sans-serif", fontSize: 10.5, color: t.accent,
              letterSpacing: "0.2em", textTransform: "uppercase", fontWeight: 500,
            }}>{isNew ? "Invitar miembro" : "Editar miembro"}</div>
            <div style={{
              fontFamily: "'Montserrat', sans-serif", fontWeight: 700, fontSize: 19,
              color: p.text, lineHeight: 1.2, marginTop: 2,
              whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis",
            }}>{form.name || "Nuevo miembro"}</div>
          </div>
          <button onClick={onClose} style={{
            width: 32, height: 32, borderRadius: 8,
            background: "transparent", border: `1px solid ${p.border}`,
            color: p.textMuted, cursor: "default", flexShrink: 0,
            display: "flex", alignItems: "center", justifyContent: "center",
          }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none"
                 stroke="currentColor" strokeWidth="1.8" strokeLinecap="round">
              <path d="m6 6 12 12"/><path d="m18 6-12 12"/>
            </svg>
          </button>
        </div>

        {/* Body */}
        <div style={{ flex: 1, overflowY: "auto", padding: "24px 26px" }}>
          <div style={{ marginBottom: 18 }}>
            <label style={labelStyle}>Nombre completo</label>
            <input style={inputStyle} value={form.name}
                   onChange={e => set("name", e.target.value)}
                   placeholder="Nombre y apellido" />
          </div>
          <div style={{ marginBottom: 18 }}>
            <label style={labelStyle}>Email</label>
            <input style={inputStyle} type="email" value={form.email}
                   onChange={e => set("email", e.target.value)}
                   placeholder="correo@ejemplo.com" />
          </div>
          <div style={{ marginBottom: 18 }}>
            <label style={labelStyle}>Plan</label>
            <select style={{ ...inputStyle, cursor: "default" }} value={form.plan}
                    onChange={e => set("plan", e.target.value)}>
              {PLAN_OPTIONS.map(o => <option key={o} value={o}>{o}</option>)}
            </select>
          </div>
          <div style={{ marginBottom: 18 }}>
            <label style={labelStyle}>Estado</label>
            <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
              {STATUS_OPTIONS.map(o => {
                const on = form.status === o.id;
                return (
                  <button key={o.id} onClick={() => set("status", o.id)} style={{
                    padding: "8px 14px", borderRadius: 8,
                    background: on ? t.accent + "1c" : p.bg2,
                    border: `1px solid ${on ? t.accent + "66" : p.border}`,
                    color: on ? t.accent : p.textMuted,
                    fontFamily: "'Geist', sans-serif", fontSize: 13,
                    fontWeight: on ? 600 : 400, cursor: "default",
                  }}>{o.label}</button>
                );
              })}
            </div>
          </div>
          <div style={{ display: "flex", gap: 14, marginBottom: 18 }}>
            <div style={{ flex: 1 }}>
              <label style={labelStyle}>Nivel de acceso</label>
              <select style={{ ...inputStyle, cursor: "default" }} value={form.level}
                      onChange={e => set("level", e.target.value)}>
                {[1,2,3,4,5].map(n => <option key={n} value={n}>Nivel {n}</option>)}
              </select>
              <div style={{
                fontFamily: "'Geist', sans-serif", fontSize: 11, color: p.textDim, marginTop: 6,
              }}>Incluye todos los niveles anteriores.</div>
            </div>
            <div style={{ flex: 1 }}>
              <label style={labelStyle}>Consultas</label>
              <input style={inputStyle} type="number" min="0" value={form.consultas}
                     onChange={e => set("consultas", e.target.value)} />
            </div>
          </div>

          <div style={{ display: "flex", gap: 14, marginBottom: 18 }}>
            <div style={{ flex: 1 }}>
              <label style={labelStyle}>Monto que paga</label>
              <div style={{ position: "relative" }}>
                <span style={{
                  position: "absolute", left: 12, top: "50%", transform: "translateY(-50%)",
                  color: p.textMuted, fontFamily: "'Geist', sans-serif", fontSize: 14,
                }}>$</span>
                <input style={{ ...inputStyle, paddingLeft: 24, paddingRight: 56 }}
                       type="number" min="0" value={form.amount}
                       onChange={e => set("amount", e.target.value)} />
                <span style={{
                  position: "absolute", right: 12, top: "50%", transform: "translateY(-50%)",
                  color: p.textMuted, fontFamily: "'Geist', sans-serif", fontSize: 12.5,
                }}>/{cycleOf(form.plan) === "anual" ? "año" : "mes"}</span>
              </div>
              <div style={{
                fontFamily: "'Geist', sans-serif", fontSize: 11, color: p.textDim, marginTop: 6,
              }}>El ciclo se define por el plan ({cycleOf(form.plan) === "anual" ? "anual" : "mensual"}).</div>
            </div>
            <div style={{ flex: 1 }}>
              <label style={labelStyle}>Fecha de ingreso</label>
              <input style={{ ...inputStyle, cursor: "default" }} type="date" value={form.joined}
                     onChange={e => set("joined", e.target.value)} />
            </div>
          </div>

          <div style={{ marginBottom: 6 }}>
            <label style={labelStyle}>Notas internas</label>
            <textarea value={form.notes}
                      onChange={e => set("notes", e.target.value)}
                      placeholder="Notas privadas sobre este miembro (no las ve el usuario)…"
                      rows={4}
                      style={{ ...inputStyle, resize: "vertical", minHeight: 92, lineHeight: 1.5 }} />
          </div>
        </div>

        {/* Footer */}
        <div style={{
          padding: "16px 26px", borderTop: `1px solid ${p.border}`,
          display: "flex", alignItems: "center", gap: 10,
        }}>
          {!isNew && (
            <button onClick={() => onDelete(member.id)} style={{
              padding: "10px 14px", background: "transparent",
              border: `1px solid ${p.border}`, borderRadius: 9,
              color: "#C77", fontFamily: "'Geist', sans-serif", fontSize: 13,
              fontWeight: 500, cursor: "default", marginRight: "auto",
            }}>Eliminar</button>
          )}
          <button onClick={onClose} style={{
            padding: "10px 16px", background: "transparent",
            border: `1px solid ${p.border}`, borderRadius: 9, color: p.text,
            fontFamily: "'Geist', sans-serif", fontSize: 13, fontWeight: 500,
            cursor: "default", marginLeft: isNew ? "auto" : 0,
          }}>Cancelar</button>
          <button onClick={handleSave} disabled={!canSave} style={{
            padding: "10px 20px",
            background: canSave ? t.accent : p.bgCard, border: 0, borderRadius: 9,
            color: canSave ? "#0A0A0A" : p.textDim,
            fontFamily: "'Geist', sans-serif", fontSize: 13, fontWeight: 600,
            cursor: "default",
          }}>{isNew ? "Crear miembro" : "Guardar cambios"}</button>
        </div>
      </div>
    </div>
  );
}

function Stat({ label, value, sub, p, t, accent }) {
  return (
    <div style={{
      flex: 1, minWidth: 0,
      padding: "20px 22px",
      background: p.bgCard, border: `1px solid ${p.border}`,
      borderRadius: 12,
    }}>
      <div style={{
        fontFamily: "'Geist', sans-serif", fontSize: 10.5,
        color: p.textMuted, letterSpacing: "0.18em",
        textTransform: "uppercase", fontWeight: 500,
      }}>{label}</div>
      <div style={{
        fontFamily: "'Montserrat', sans-serif", fontWeight: 800,
        fontSize: 38, color: accent ? t.accent : p.text,
        lineHeight: 1.05, marginTop: 8, letterSpacing: "-0.01em",
        fontVariantNumeric: "tabular-nums",
      }}>{value}</div>
      {sub && (
        <div style={{
          fontFamily: "'Geist', sans-serif", fontSize: 12,
          color: p.textMuted, marginTop: 6,
        }}>{sub}</div>
      )}
    </div>
  );
}

function MemberRow({ m, t, p, planStyles, statusStyles, onEdit, onToggleStatus, onDelete, onResetPassword }) {
  const [hover, setHover] = useStateAV(false);
  const [menu, setMenu] = useStateAV(false);
  const [openUp, setOpenUp] = useStateAV(false);
  const moreRef = React.useRef(null);
  const isMobile = window.useIsMobile();
  const planSt = planStyles[m.plan] || planStyles["Plan Mensual"];
  const statSt = statusStyles[m.status];

  const toggleMenu = () => {
    if (!menu && moreRef.current) {
      const rect = moreRef.current.getBoundingClientRect();
      // Si hay poco espacio debajo del botón, abrimos el menú hacia arriba.
      setOpenUp(window.innerHeight - rect.bottom < 220);
    }
    setMenu(v => !v);
  };

  return (
    <div
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => { setHover(false); setMenu(false); }}
      style={{
        display: "grid",
        gridTemplateColumns: "minmax(220px, 1.6fr) minmax(140px, 1fr) minmax(110px, .8fr) minmax(110px, .8fr) minmax(120px, 1fr) 90px",
        alignItems: "center", gap: 16,
        padding: "16px 22px",
        minWidth: isMobile ? 760 : "auto",
        background: hover ? p.bg2 : "transparent",
        borderBottom: `1px solid ${p.borderSoft}`,
        transition: "background .12s",
      }}>
      {/* Member */}
      <div style={{ display: "flex", alignItems: "center", gap: 12, minWidth: 0 }}>
        <div style={{
          width: 36, height: 36, borderRadius: 999,
          background: `linear-gradient(135deg, ${t.accent}, ${t.accent}99)`,
          display: "flex", alignItems: "center", justifyContent: "center",
          color: "#0A0A0A", fontWeight: 600, fontSize: 12,
          flexShrink: 0,
        }}>
          {m.name.split(" ").map(w => w[0]).slice(0,2).join("")}
        </div>
        <div style={{ minWidth: 0 }}>
          <div style={{
            fontFamily: "'Geist', sans-serif", fontSize: 14, fontWeight: 500,
            color: p.text, lineHeight: 1.25,
            whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis",
          }}>{m.name}</div>
          <div style={{
            fontFamily: "'Geist', sans-serif", fontSize: 12,
            color: p.textMuted, lineHeight: 1.25, marginTop: 1,
            whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis",
          }}>{m.email}</div>
        </div>
      </div>

      {/* Plan */}
      <div>
        <span style={{
          display: "inline-flex", alignItems: "center",
          padding: "4px 10px", borderRadius: 6,
          background: planSt.bg, border: `1px solid ${planSt.border}`,
          fontFamily: "'Geist', sans-serif", fontSize: 11.5,
          color: planSt.color, fontWeight: 500,
          letterSpacing: "0.01em",
        }}>{m.plan}</span>
      </div>

      {/* Status */}
      <div style={{
        display: "flex", alignItems: "center", gap: 7,
        fontFamily: "'Geist', sans-serif", fontSize: 13,
        color: statSt.color,
      }}>
        <span style={{
          width: 6, height: 6, borderRadius: 999, background: statSt.dot,
          boxShadow: m.status === "active" ? `0 0 6px ${statSt.dot}80` : "none",
        }}/>
        {statSt.label}
      </div>

      {/* Nivel */}
      <div style={{
        fontFamily: "'Geist', sans-serif", fontSize: 13,
        color: p.text, fontVariantNumeric: "tabular-nums",
      }}>Nivel {m.level}</div>

      {/* Consultas + last seen */}
      <div>
        <div style={{
          fontFamily: "'Geist', sans-serif", fontSize: 13.5,
          color: p.text, fontVariantNumeric: "tabular-nums",
        }}>{m.consultas} consultas</div>
        <div style={{
          fontFamily: "'Geist', sans-serif", fontSize: 11.5,
          color: p.textMuted, marginTop: 1,
        }}>{tiempoRelativo(m.ultimo_login)}</div>
      </div>

      {/* Actions */}
      <div style={{
        display: "flex", justifyContent: "flex-end", gap: 6,
        opacity: hover || menu ? 1 : 0.55, transition: "opacity .15s",
        position: "relative",
      }}>
        <button title="Editar miembro" onClick={onEdit} style={{
          width: 30, height: 30, padding: 0,
          background: "transparent", border: `1px solid ${p.border}`,
          borderRadius: 7, color: p.textMuted, cursor: "default",
          display: "flex", alignItems: "center", justifyContent: "center",
        }}>
          <svg width="13" height="13" viewBox="0 0 24 24" fill="none"
               stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
            <path d="M3 21h4l11-11-4-4L3 17v4Z"/><path d="m14 6 4 4"/>
          </svg>
        </button>
        <button ref={moreRef} title="Más acciones" onClick={toggleMenu} style={{
          width: 30, height: 30, padding: 0,
          background: menu ? p.bg : "transparent", border: `1px solid ${menu ? t.accent + "55" : p.border}`,
          borderRadius: 7, color: menu ? t.accent : p.textMuted, cursor: "default",
          display: "flex", alignItems: "center", justifyContent: "center",
        }}>
          <svg width="13" height="13" viewBox="0 0 24 24" fill="currentColor">
            <circle cx="5" cy="12" r="1.5"/><circle cx="12" cy="12" r="1.5"/><circle cx="19" cy="12" r="1.5"/>
          </svg>
        </button>

        {menu && (
          <div style={{
            position: "absolute",
            ...(openUp ? { bottom: 36 } : { top: 36 }), right: 0, zIndex: 30,
            minWidth: 196, padding: 6,
            background: p.bgCard, border: `1px solid ${p.border}`, borderRadius: 10,
            boxShadow: "0 18px 50px rgba(0,0,0,0.45)",
            display: "flex", flexDirection: "column", gap: 2,
          }}>
            {[
              { label: "Editar perfil", icon: "M3 21h4l11-11-4-4L3 17v4Z", fn: () => { onEdit(); setMenu(false); } },
              { label: m.status === "paused" ? "Reactivar acceso" : "Suspender acceso",
                icon: m.status === "paused" ? "M5 3l14 9-14 9V3Z" : "M8 5h3v14H8zM13 5h3v14h-3z",
                fn: () => { onToggleStatus(m.id); setMenu(false); } },
              { label: "Restablecer clave", icon: "M7 11V7a5 5 0 0 1 10 0v4M5 11h14v10H5z", fn: () => { onResetPassword(m); setMenu(false); } },
              { label: "Eliminar miembro", icon: "M4 7h16M9 7V4h6v3M6 7l1 13h10l1-13", fn: () => { onDelete(m.id); setMenu(false); }, danger: true },
            ].map(item => (
              <button key={item.label} onClick={item.fn}
                onMouseEnter={e => e.currentTarget.style.background = p.bg2}
                onMouseLeave={e => e.currentTarget.style.background = "transparent"}
                style={{
                  display: "flex", alignItems: "center", gap: 10,
                  padding: "9px 11px", borderRadius: 7,
                  background: "transparent", border: 0, textAlign: "left",
                  color: item.danger ? "#D98A8A" : p.text,
                  fontFamily: "'Geist', sans-serif", fontSize: 13, cursor: "default",
                }}>
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none"
                     stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
                  <path d={item.icon}/>
                </svg>
                {item.label}
              </button>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

function AdminView({ t, p }) {
  const isMobile = window.useIsMobile();
  const [search, setSearch] = useStateAV("");
  const [filter, setFilter] = useStateAV("all"); // all | active | trial | paused | expired
  const [members, setMembers] = useStateAV([]);
  const [loading, setLoading] = useStateAV(true);
  const [loadError, setLoadError] = useStateAV("");
  const [editing, setEditing] = useStateAV(null); // member object | {__new:true} | null
  const [page, setPage] = useStateAV(1);
  const [notice, setNotice] = useStateAV(null);   // { tipo, titulo, clave?, texto? }

  const loadMembers = React.useCallback(async () => {
    setLoadError("");
    try {
      const list = await MDP_API.adminUsuarios();
      setMembers(list);
    } catch (err) {
      setLoadError(err.message || "No pudimos cargar los miembros.");
    } finally {
      setLoading(false);
    }
  }, []);

  React.useEffect(() => { loadMembers(); }, [loadMembers]);

  const saveMember = async (data) => {
    try {
      if (data.__new) {
        const { __new, ...rest } = data;
        const res = await MDP_API.adminCrearUsuario(rest);
        setEditing(null);
        await loadMembers();
        // Mostramos la clave temporal para que la admin se la pase al miembro.
        setNotice({
          tipo: "clave", titulo: "Miembro creado",
          texto: `${rest.name} ya puede entrar con su email y esta clave temporal. Deberá cambiarla al ingresar.`,
          clave: res.claveTemporal,
        });
      } else {
        await MDP_API.adminActualizarUsuario(data.id, data);
        setEditing(null);
        await loadMembers();
      }
    } catch (err) {
      setNotice({ tipo: "error", titulo: "No se pudo guardar", texto: err.message });
    }
  };
  const deleteMember = async (id) => {
    try {
      await MDP_API.adminEliminarUsuario(id);
      setEditing(null);
      await loadMembers();
    } catch (err) {
      setNotice({ tipo: "error", titulo: "No se pudo eliminar", texto: err.message });
    }
  };
  const toggleStatus = async (id) => {
    const m = members.find(x => String(x.id) === String(id));
    if (!m) return;
    const next = m.status === "paused" ? "active" : "paused";
    try {
      await MDP_API.adminActualizarUsuario(id, { status: next });
      await loadMembers();
    } catch (err) {
      setNotice({ tipo: "error", titulo: "No se pudo cambiar el estado", texto: err.message });
    }
  };
  const resetPassword = async (member) => {
    try {
      const res = await MDP_API.adminResetPassword(member.id);
      setNotice({
        tipo: "clave", titulo: "Clave restablecida",
        texto: `${member.name} deberá entrar con esta clave temporal y cambiarla al ingresar. No queda visible después.`,
        clave: res.claveTemporal,
      });
    } catch (err) {
      setNotice({ tipo: "error", titulo: "No se pudo restablecer", texto: err.message });
    }
  };

  const planStyles = useMemoAV(() => PLAN_STYLES(p, t), [p, t]);
  const statusStyles = useMemoAV(() => STATUS_STYLES(p), [p]);

  const filtered = members.filter(m => {
    if (filter !== "all" && m.status !== filter) return false;
    if (search) {
      const q = search.toLowerCase();
      if (!m.name.toLowerCase().includes(q) &&
          !m.email.toLowerCase().includes(q) &&
          !m.plan.toLowerCase().includes(q)) return false;
    }
    return true;
  });

  // Paginación real (cliente)
  const perPage = 10;
  const totalPages = Math.max(1, Math.ceil(filtered.length / perPage));
  const safePage = Math.min(page, totalPages);
  const paged = filtered.slice((safePage - 1) * perPage, safePage * perPage);
  const rangeStart = filtered.length === 0 ? 0 : (safePage - 1) * perPage + 1;
  const rangeEnd = Math.min(safePage * perPage, filtered.length);

  // Exportar CSV real de los miembros filtrados
  const exportCSV = () => {
    const headers = ["Nombre","Email","Plan","Estado","Nivel","Consultas","Monto","Ciclo","Ingreso","Notas"];
    const esc = (v) => `"${String(v == null ? "" : v).replace(/"/g, '""')}"`;
    const rows = filtered.map(m => [
      m.name, m.email, m.plan, m.status, m.level, m.consultas,
      m.amount ?? 0, cycleOf(m.plan), m.joined || "", (m.notes || "").replace(/\s+/g, " "),
    ]);
    const csv = [headers, ...rows].map(r => r.map(esc).join(",")).join("\r\n");
    const blob = new Blob(["\ufeff" + csv], { type: "text/csv;charset=utf-8;" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `miembros-mdp-${new Date().toISOString().slice(0,10)}.csv`;
    document.body.appendChild(a); a.click(); a.remove();
    URL.revokeObjectURL(url);
  };

  const stats = useMemoAV(() => {
    const total = members.length;
    const active = members.filter(m => m.status === "active").length;
    const trial = members.filter(m => m.status === "trial").length;
    const consultas = members.reduce((s, m) => s + m.consultas, 0);
    const billable = members.filter(m => m.status === "active" || m.status === "trial");
    const mensual = billable.filter(m => cycleOf(m.plan) === "mensual")
      .reduce((s, m) => s + (m.amount || 0), 0);
    const anual = billable.filter(m => cycleOf(m.plan) === "anual")
      .reduce((s, m) => s + (m.amount || 0) / 12, 0);
    return {
      total, active, trial, consultas,
      mrr: Math.round(mensual + anual),
      mrrMensual: Math.round(mensual),
      mrrAnual: Math.round(anual),
    };
  }, [members]);

  return (
    <div style={{
      flex: 1, overflowY: "auto",
      padding: isMobile ? "0 16px 64px" : "0 36px 80px",
    }}>
      <div style={{ maxWidth: 1280, margin: "0 auto" }}>
        {/* Header */}
        <section style={{ padding: isMobile ? "26px 0 20px" : "40px 0 28px" }}>
          <div style={{
            display: "flex", alignItems: "flex-end", justifyContent: "space-between",
            gap: 24, marginBottom: 6, flexWrap: "wrap",
          }}>
            <div style={{ minWidth: 0, flex: "1 1 auto" }}>
              <div style={{
                fontFamily: "'Geist', sans-serif", fontSize: 11,
                color: t.accent, letterSpacing: "0.22em", textTransform: "uppercase",
                marginBottom: 14, fontWeight: 500,
              }}>Panel de administración</div>
              <h1 style={{
                fontFamily: "'Montserrat', sans-serif", fontWeight: 800,
                fontSize: "clamp(36px, 4.5vw, 52px)", lineHeight: 1.02, letterSpacing: "-0.02em",
                margin: 0, color: p.text,
              }}>
                <em style={{ fontStyle: "italic", color: t.accent }}>Miembros</em> de la comunidad
              </h1>
            </div>
            <div style={{ display: "flex", gap: 10, flexShrink: 0 }}>
              <button onClick={exportCSV} style={{
                padding: "10px 16px",
                background: "transparent", border: `1px solid ${p.border}`,
                borderRadius: 9, color: p.text,
                fontFamily: "'Geist', sans-serif", fontSize: 13, fontWeight: 500,
                cursor: "default", display: "flex", alignItems: "center", gap: 8,
              }}>
                <svg width="13" height="13" viewBox="0 0 24 24" fill="none"
                     stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M12 3v12"/><path d="m7 10 5 5 5-5"/><path d="M5 21h14"/>
                </svg>
                Exportar CSV
              </button>
              <button onClick={() => setEditing({ __new: true })} style={{
                padding: "10px 18px",
                background: t.accent, border: 0, borderRadius: 9,
                color: "#0A0A0A",
                fontFamily: "'Geist', sans-serif", fontSize: 13, fontWeight: 600,
                cursor: "default", display: "flex", alignItems: "center", gap: 8,
              }}>
                <svg width="13" height="13" viewBox="0 0 24 24" fill="none"
                     stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M12 5v14"/><path d="M5 12h14"/>
                </svg>
                Invitar miembro
              </button>
            </div>
          </div>
        </section>

        {/* Stats */}
        <div style={{
          display: "grid", gap: 14,
          gridTemplateColumns: isMobile ? "repeat(2, 1fr)" : "repeat(4, 1fr)",
          marginBottom: 36,
        }}>
          <Stat p={p} t={t} label="Total miembros" value={stats.total}
                sub={`${stats.active} activos · ${stats.trial} en prueba`} />
          <Stat p={p} t={t} label="Activos" value={stats.active}
                sub={`${Math.round(stats.active/stats.total*100)}% del total`} />
          <Stat p={p} t={t} label="Consultas (mes)" value={stats.consultas}
                sub="Promedio 89 por miembro" />
          <Stat p={p} t={t} accent label="MRR estimado" value={`$${stats.mrr.toLocaleString()}`}
                sub={`Plan mes $${stats.mrrMensual.toLocaleString()} · Plan anual $${stats.mrrAnual.toLocaleString()}`} />
        </div>

        {/* Filters + table */}
        <div style={{
          background: p.bgCard, border: `1px solid ${p.border}`,
          borderRadius: 14, overflowX: isMobile ? "auto" : "hidden", overflowY: "hidden",
        }}>
          {/* Filter bar */}
          <div style={{
            padding: "16px 22px",
            display: "flex", alignItems: "center", gap: 14, flexWrap: "wrap",
            borderBottom: `1px solid ${p.border}`,
          }}>
            <div style={{
              display: "flex", alignItems: "center", gap: 9,
              flex: 1, maxWidth: 360,
              padding: "8px 12px",
              background: p.bg2, border: `1px solid ${p.border}`,
              borderRadius: 8,
            }}>
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke={p.textMuted}
                   strokeWidth="1.6" strokeLinecap="round">
                <circle cx="11" cy="11" r="7"/><path d="m20 20-4-4"/>
              </svg>
              <input
                value={search} onChange={(e) => { setSearch(e.target.value); setPage(1); }}
                placeholder="Buscar por nombre, email o plan…"
                style={{
                  flex: 1, background: "transparent", border: 0, outline: "none",
                  color: p.text, fontSize: 13,
                  fontFamily: "'Geist', sans-serif",
                }}
              />
            </div>

            {/* Status filter tabs */}
            <div style={{
              display: "flex", gap: 2, marginLeft: "auto",
              background: p.bg2, padding: 3,
              border: `1px solid ${p.border}`, borderRadius: 8,
            }}>
              {[
                { id: "all",     label: "Todos" },
                { id: "active",  label: "Activos" },
                { id: "trial",   label: "Prueba" },
                { id: "paused",  label: "Pausados" },
                { id: "expired", label: "Vencidos" },
              ].map(f => (
                <button key={f.id} onClick={() => { setFilter(f.id); setPage(1); }} style={{
                  padding: "6px 12px",
                  background: filter === f.id ? p.bg : "transparent",
                  border: 0, borderRadius: 6,
                  color: filter === f.id ? p.text : p.textMuted,
                  fontFamily: "'Geist', sans-serif", fontSize: 12.5,
                  fontWeight: filter === f.id ? 500 : 400,
                  cursor: "default",
                  boxShadow: filter === f.id ? "0 1px 0 rgba(255,255,255,0.04)" : "none",
                }}>{f.label}</button>
              ))}
            </div>
          </div>

          {/* Table header */}
          <div style={{
            display: "grid",
            gridTemplateColumns: "minmax(220px, 1.6fr) minmax(140px, 1fr) minmax(110px, .8fr) minmax(110px, .8fr) minmax(120px, 1fr) 90px",
            gap: 16,
            padding: "12px 22px",
            minWidth: isMobile ? 760 : "auto",
            background: p.bg2,
            borderBottom: `1px solid ${p.border}`,
            fontFamily: "'Geist', sans-serif", fontSize: 10.5,
            color: p.textMuted, letterSpacing: "0.18em",
            textTransform: "uppercase", fontWeight: 500,
          }}>
            <div>Miembro</div>
            <div>Plan</div>
            <div>Estado</div>
            <div>Acceso</div>
            <div>Actividad</div>
            <div style={{ textAlign: "right" }}>Acciones</div>
          </div>

          {/* Rows */}
          <div>
            {loading ? (
              <div style={{
                padding: 60, textAlign: "center",
                color: p.textMuted, fontFamily: "'Geist', sans-serif", fontSize: 13.5,
              }}>
                Cargando miembros…
              </div>
            ) : loadError ? (
              <div style={{
                padding: 48, textAlign: "center",
                color: "#D98A8A", fontFamily: "'Geist', sans-serif", fontSize: 13.5,
              }}>
                {loadError}
                <div style={{ marginTop: 14 }}>
                  <button onClick={loadMembers} style={{
                    padding: "8px 16px", background: "transparent",
                    border: `1px solid ${p.border}`, borderRadius: 8,
                    color: p.text, fontFamily: "'Geist', sans-serif", fontSize: 13, cursor: "default",
                  }}>Reintentar</button>
                </div>
              </div>
            ) : filtered.length === 0 ? (
              <div style={{
                padding: 60, textAlign: "center",
                color: p.textMuted, fontFamily: "'Geist', sans-serif", fontSize: 13.5,
              }}>
                {members.length === 0 ? "Todavía no hay miembros. Creá el primero con “Agregar miembro”." : "Sin resultados."}
              </div>
            ) : paged.map(m => (
              <MemberRow key={m.id} m={m} t={t} p={p}
                         planStyles={planStyles} statusStyles={statusStyles}
                         onEdit={() => setEditing(m)}
                         onToggleStatus={toggleStatus}
                         onResetPassword={resetPassword}
                         onDelete={deleteMember} />
            ))}
          </div>

          {/* Footer */}
          <div style={{
            padding: "14px 22px",
            display: "flex", alignItems: "center", justifyContent: "space-between",
            borderTop: `1px solid ${p.border}`,
            background: p.bg2,
            fontFamily: "'Geist', sans-serif", fontSize: 12,
            color: p.textMuted,
          }}>
            <span>Mostrando {rangeStart}–{rangeEnd} de {filtered.length} miembros{filtered.length !== members.length ? ` (${members.length} en total)` : ""}</span>
            <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
              <span style={{ color: p.textDim }}>Página {safePage} de {totalPages}</span>
              <div style={{ display: "flex", gap: 6 }}>
                <button onClick={() => setPage(Math.max(1, safePage - 1))} disabled={safePage <= 1} style={{
                  padding: "5px 10px",
                  background: "transparent", border: `1px solid ${p.border}`,
                  borderRadius: 6, color: safePage <= 1 ? p.textDim : p.text,
                  fontFamily: "inherit", fontSize: 12, cursor: "default",
                }}>← Anterior</button>
                <button onClick={() => setPage(Math.min(totalPages, safePage + 1))} disabled={safePage >= totalPages} style={{
                  padding: "5px 10px",
                  background: "transparent", border: `1px solid ${p.border}`,
                  borderRadius: 6, color: safePage >= totalPages ? p.textDim : p.text,
                  fontFamily: "inherit", fontSize: 12, cursor: "default",
                }}>Siguiente →</button>
              </div>
            </div>
          </div>
        </div>
      </div>

      {editing && (
        <EditMemberDrawer member={editing} t={t} p={p}
                          onClose={() => setEditing(null)}
                          onSave={saveMember}
                          onDelete={deleteMember} />
      )}

      {notice && (
        <NoticeModal notice={notice} t={t} p={p} onClose={() => setNotice(null)} />
      )}
    </div>
  );
}

// ── Modal de aviso (clave temporal / errores) ───────────────────────────────
function NoticeModal({ notice, t, p, onClose }) {
  const [copied, setCopied] = useStateAV(false);
  const esClave = notice.tipo === "clave";
  const copy = () => {
    try {
      navigator.clipboard.writeText(notice.clave);
      setCopied(true);
      setTimeout(() => setCopied(false), 1800);
    } catch {}
  };
  return (
    <div onClick={onClose} style={{
      position: "fixed", inset: 0, zIndex: 200,
      background: "rgba(0,0,0,0.6)",
      display: "flex", alignItems: "center", justifyContent: "center", padding: 20,
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        width: "100%", maxWidth: 420,
        background: p.bgCard, border: `1px solid ${p.border}`, borderRadius: 16,
        padding: 28, boxShadow: "0 30px 80px rgba(0,0,0,0.5)",
      }}>
        <div style={{
          fontFamily: "'Montserrat', sans-serif", fontWeight: 700,
          fontSize: 18, color: esClave ? p.text : "#D98A8A", marginBottom: 8,
        }}>{notice.titulo}</div>
        {notice.texto && (
          <div style={{
            fontFamily: "'Geist', sans-serif", fontSize: 13.5, lineHeight: 1.5,
            color: p.textMuted, marginBottom: esClave ? 18 : 22,
          }}>{notice.texto}</div>
        )}

        {esClave && (
          <div style={{
            display: "flex", alignItems: "center", gap: 10,
            padding: "14px 16px", marginBottom: 22,
            background: p.bg2, border: `1px solid ${t.accent}55`, borderRadius: 10,
          }}>
            <code style={{
              flex: 1, fontFamily: "ui-monospace, monospace", fontSize: 19,
              color: p.text, letterSpacing: "0.08em",
            }}>{notice.clave}</code>
            <button onClick={copy} style={{
              padding: "7px 13px", background: t.accent, border: 0, borderRadius: 8,
              color: "#0A0A0A", fontFamily: "'Geist', sans-serif", fontSize: 12.5,
              fontWeight: 600, cursor: "default", flexShrink: 0,
            }}>{copied ? "¡Copiada!" : "Copiar"}</button>
          </div>
        )}

        <div style={{ display: "flex", justifyContent: "flex-end" }}>
          <button onClick={onClose} style={{
            padding: "9px 20px", background: esClave ? t.accent : "transparent",
            border: `1px solid ${esClave ? t.accent : p.border}`, borderRadius: 8,
            color: esClave ? "#0A0A0A" : p.text, fontWeight: esClave ? 600 : 400,
            fontFamily: "'Geist', sans-serif", fontSize: 13.5, cursor: "default",
          }}>{esClave ? "Entendido" : "Cerrar"}</button>
        </div>
      </div>
    </div>
  );
}

window.AdminView = AdminView;
