// Cuenta — pestaña de cuenta integrada de Cynamonurs (rediseño editorial).
// Datos fieles al modelo real de CynamonSup (ver src/Planes.jsx):
//   Free $0 · Basic $59 MXN/mes · PRO $109 MXN/mes · límites DIARIOS.
// Expone a window: CuentaSection, AccountBell, AccountMenu.
const { useState: kS, useEffect: kE } = React;

// ── Iconos ──────────────────────────────────────────────────
const CI = {
  bell: <svg viewBox="0 0 24 24" width="19" height="19" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round"><path d="M6 8a6 6 0 1 1 12 0c0 7 3 9 3 9H3s3-2 3-9"/><path d="M10 21a2 2 0 0 0 4 0"/></svg>,
  mail: <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="5" width="18" height="14" rx="2"/><path d="m3 7 9 6 9-6"/></svg>,
  user: <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="8" r="3.5"/><path d="M5 20c0-3.3 3.1-6 7-6s7 2.7 7 6"/></svg>,
  logout: <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4M16 17l5-5-5-5M21 12H9"/></svg>,
  card: <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3 10h18"/></svg>,
  globe: <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3a14 14 0 0 1 0 18M12 3a14 14 0 0 0 0 18"/></svg>,
  cloud: <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round"><path d="M7 18a4 4 0 0 1-.5-7.97A6 6 0 0 1 18 9a4 4 0 0 1 0 9z"/><path d="m9 13 2 2 4-4"/></svg>,
  check: <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6 9 17l-5-5"/></svg>,
  bcheck: <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round"><path d="M5 13l4 4L19 7"/></svg>,
  age: <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></svg>,
  building: <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round"><path d="M4 21V5a1 1 0 0 1 1-1h9a1 1 0 0 1 1 1v16M15 21V9h4a1 1 0 0 1 1 1v11M8 8h3M8 12h3M8 16h3"/></svg>,
  cam: <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round"><path d="M5 8h3l1.5-2h5L16 8h3a1 1 0 0 1 1 1v9a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V9a1 1 0 0 1 1-1z"/><circle cx="12" cy="13" r="3.2"/></svg>,
  refresh: <svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round"><path d="M3 12a9 9 0 0 1 15-6.7L21 8M21 3v5h-5M21 12a9 9 0 0 1-15 6.7L3 16M3 21v-5h5"/></svg>,
};

// ── Datos reales del plan (espejo de src/Planes.jsx) ─────────
const CYNA_PRICE = {
  free:  { amt: "$0",   per: "siempre gratis" },
  basic: { amt: "$59",  per: "MXN / mes" },
  pro:   { amt: "$109", per: "MXN / mes" },
};
// Límites DIARIOS por plan (idénticos a la tabla comparativa de Planes).
const CYNA_DAILY = {
  free:  { buscar: 3, caso: 1, exportar: 0,  calc: 3 },
  basic: { buscar: 8, caso: 5, exportar: 8,  calc: 30 },
  pro:   { buscar: Infinity, caso: Infinity, exportar: Infinity, calc: Infinity },
};
const CYNA_USED = { buscar: 3, caso: 2, exportar: 1, calc: 6 }; // uso simulado de hoy
const CYNA_LIMIT_ROWS = [
  ["buscar", "Buscar diagnósticos"],
  ["caso", "Crear caso de paciente"],
  ["exportar", "Exportar PDF / Word"],
  ["calc", "Calculadoras clínicas"],
];

const CYNA_NOTIFS = [
  { id: 1, unread: true,  title: "Tu suscripción se renueva en 5 días", desc: "Se cobrará automáticamente el 1 jul. Te lo recordamos por correo.", time: "Hace 2 h" },
  { id: 2, unread: true,  title: "Nuevas escalas en Herramientas", desc: "Añadimos Glasgow pediátrica y Silverman a tus calculadoras.", time: "Ayer" },
  { id: 3, unread: false, title: "Copia de seguridad completada", desc: "Tus casos y planes se respaldaron correctamente en la nube.", time: "Hace 2 días" },
];

// ── Store de perfil (localStorage + evento para sincronizar nav) ──
const ProfileStore = {
  key: "cyna_profile",
  defaults: {
    nombre: "María García",
    role: "Enfermera · Cuidados intensivos",
    edad: "34",
    sexo: "Femenino",
    tipo: "Pública",
    institucion: "Hospital General Dr. Salvador",
    photo: null,
  },
  get() {
    try { return { ...this.defaults, ...JSON.parse(localStorage.getItem(this.key) || "{}") }; }
    catch (e) { return { ...this.defaults }; }
  },
  set(patch) {
    const next = { ...this.get(), ...patch };
    try { localStorage.setItem(this.key, JSON.stringify(next)); } catch (e) {}
    window.dispatchEvent(new CustomEvent("cyna-profile", { detail: next }));
    return next;
  },
};
function useProfile() {
  const [p, setP] = kS(ProfileStore.get());
  kE(() => {
    const fn = (e) => setP(e.detail || ProfileStore.get());
    window.addEventListener("cyna-profile", fn);
    return () => window.removeEventListener("cyna-profile", fn);
  }, []);
  return p;
}

// ── Store de plan ────────────────────────────────────────────
const PlanState = {
  key: "cyna_plan",
  get() { try { return localStorage.getItem(this.key) || "basic"; } catch (e) { return "basic"; } },
  set(id) {
    try { localStorage.setItem(this.key, id); } catch (e) {}
    window.dispatchEvent(new CustomEvent("cyna-plan", { detail: id }));
  },
};
function usePlan() {
  const [p, setP] = kS(PlanState.get());
  kE(() => {
    const fn = (e) => setP(e.detail || PlanState.get());
    window.addEventListener("cyna-plan", fn);
    return () => window.removeEventListener("cyna-plan", fn);
  }, []);
  return p;
}

const cynaInitials = (name) =>
  (name || "").trim().split(/\s+/).slice(0, 2).map(s => s[0] || "").join("").toUpperCase() || "MG";

// ── Avatar con subir foto (input creado al vuelo) ────────────
function AvatarUpload({ src, label, onPick, size = 84, showCam = true }) {
  const pick = () => {
    const inp = document.createElement("input");
    inp.type = "file"; inp.accept = "image/*";
    inp.onchange = (e) => {
      const f = e.target.files && e.target.files[0];
      if (!f) return;
      const r = new FileReader();
      r.onload = () => onPick(r.result);
      r.readAsDataURL(f);
    };
    inp.click();
  };
  return (
    <div className="cta-avatar-wrap" style={{ width: size, height: size }}>
      <div className={"cta-avatar-lg" + (src ? " has-img" : "")}
           style={src ? { width: size, height: size, backgroundImage: `url(${src})`, margin: 0 } : { width: size, height: size, margin: 0 }}>
        {src ? "" : label}
      </div>
      {showCam && <button className="cta-avatar-cam" onClick={pick} aria-label="Subir foto de perfil" title="Subir foto">{CI.cam}</button>}
    </div>
  );
}

// ── Fila con toggle / chevron ───────────────────────────────
function CRow({ icon, title, desc, on, onToggle, lock, chev, danger, onClick }) {
  return (
    <div className={"cta-row" + (chev ? " clickable" : "") + (danger ? " danger" : "")} onClick={onClick}>
      <div className="cta-row-icon">{icon}</div>
      <div className="cta-row-body">
        <div className="cta-row-title">{title}</div>
        {desc && <div className="cta-row-desc">{desc}</div>}
      </div>
      {onToggle && <button className={"cta-toggle" + (on ? " on" : "")} onClick={(e) => { e.stopPropagation(); onToggle(); }} aria-label={title}/>}
      {lock && <span className="cta-locktag">{lock}</span>}
      {chev && <span className="cta-chev">›</span>}
    </div>
  );
}

// ── Modal Editar perfil ─────────────────────────────────────
function EditProfileModal({ onClose }) {
  const cur = ProfileStore.get();
  const [f, setF] = kS(cur);
  const up = (k) => (e) => setF(s => ({ ...s, [k]: e.target.value }));
  const save = () => { ProfileStore.set(f); onClose(); };
  return (
    <div className="cta-modal-scrim" onClick={onClose}>
      <div className="cta-modal" onClick={e => e.stopPropagation()}>
        <div className="cta-modal-head">
          <h3>Editar perfil</h3>
          <button className="cta-modal-close" onClick={onClose}>×</button>
        </div>
        <div className="cta-modal-body">
          <div className="cta-field">
            <label>Foto de perfil <span className="opt">· opcional</span></label>
            <div className="cta-photo-field">
              <AvatarUpload src={f.photo} label={cynaInitials(f.nombre)} size={64} onPick={(d) => setF(s => ({ ...s, photo: d }))}/>
              <div className="cta-photo-actions">
                <span style={{ fontSize: 12.5, color: "var(--fg-muted)" }}>JPG o PNG · máx. 5 MB</span>
                {f.photo && <button className="lnk muted" onClick={() => setF(s => ({ ...s, photo: null }))}>Quitar foto</button>}
              </div>
            </div>
          </div>
          <div className="cta-field">
            <label>Nombre completo</label>
            <input className="cta-input" value={f.nombre} onChange={up("nombre")}/>
          </div>
          <div className="cta-field">
            <label>Especialidad / rol</label>
            <input className="cta-input" value={f.role} onChange={up("role")}/>
          </div>
          <div className="cta-field-row">
            <div className="cta-field">
              <label>Edad</label>
              <input className="cta-input" type="number" value={f.edad} onChange={up("edad")}/>
            </div>
            <div className="cta-field">
              <label>Sexo</label>
              <select className="cta-select" value={f.sexo} onChange={up("sexo")}>
                <option>Femenino</option><option>Masculino</option><option>Otro</option><option>Prefiero no decir</option>
              </select>
            </div>
          </div>
          <div className="cta-field">
            <label>Tipo de institución</label>
            <div className="cta-seg">
              {["Pública", "Privada"].map(t => (
                <button key={t} className={f.tipo === t ? "on" : ""} onClick={() => setF(s => ({ ...s, tipo: t }))}>{t}</button>
              ))}
            </div>
          </div>
          <div className="cta-field">
            <label>Nombre de la institución <span className="opt">· opcional</span></label>
            <input className="cta-input" value={f.institucion} onChange={up("institucion")} placeholder="Opcional"/>
          </div>
        </div>
        <div className="cta-modal-foot">
          <button className="btn-secondary" onClick={onClose}>Cancelar</button>
          <button className="btn-primary" onClick={save}>Guardar cambios</button>
        </div>
      </div>
    </div>
  );
}

// ── Modal Cambiar de plan (usa los planes reales) ───────────
function ChangePlanModal({ current, onClose, onChoose }) {
  const planes = window.PLANES || [];
  return (
    <div className="cta-modal-scrim" onClick={onClose}>
      <div className="cta-modal wide" onClick={e => e.stopPropagation()}>
        <div className="cta-modal-head">
          <h3>Cambiar de plan</h3>
          <button className="cta-modal-close" onClick={onClose}>×</button>
        </div>
        <div className="cta-modal-body">
          <div className="cta-plan-grid">
            {planes.map(pl => {
              const isCur = pl.id === current;
              return (
                <div key={pl.id} className={"cta-plan-opt" + (isCur ? " current" : (pl.destacado ? " featured" : ""))}>
                  {isCur ? <span className="cta-plan-tag cur">Plan actual</span> : (pl.destacado ? <span className="cta-plan-tag">Recomendado</span> : null)}
                  <div className="cta-plan-opt-name">{pl.nombre}</div>
                  <div className="cta-plan-opt-price"><span className="amt">{pl.precio}</span><span className="per">{pl.periodo}</span></div>
                  <p className="cta-plan-opt-lema">{pl.lema}</p>
                  <ul className="cta-plan-opt-bullets">
                    {pl.bullets.map((b, i) => <li key={i}>{CI.bcheck}<span>{b}</span></li>)}
                  </ul>
                  {isCur
                    ? <button className="cta-plan-opt-cta" disabled>Tu plan actual</button>
                    : <button className={"cta-plan-opt-cta" + (pl.destacado ? "" : " ghost")} onClick={() => onChoose(pl)}>Cambiar a {pl.nombre}</button>}
                </div>
              );
            })}
          </div>
        </div>
        <div className="cta-plan-stripe-note">
          <span className="cta-stripe-badge">Stripe</span>
          <span>Al cambiar de plan te llevaremos a Stripe para confirmar el pago de forma segura. Puedes cambiar o cancelar cuando quieras; el ajuste se aplica en tu próximo ciclo.</span>
        </div>
        <div className="cta-modal-foot">
          <button className="btn-secondary" onClick={onClose}>Cerrar</button>
        </div>
      </div>
    </div>
  );
}

// ── Tarjeta de suscripción (según plan actual) ──────────────
function SubCard({ plan, onChangePlan }) {
  const [autopay, setAutopay] = kS(true);
  const [preavisar, setPreavisar] = kS(true);
  const planObj = (window.PLANES || []).find(p => p.id === plan) || { nombre: "Basic" };
  const price = CYNA_PRICE[plan] || CYNA_PRICE.basic;
  const isFree = plan === "free";
  return (
    <div className="cta-subB">
      <div className="cta-subB-top">
        <div>
          <div className="cta-subB-eyebrow">CynamonSup · {isFree ? "Con anuncios" : "Sin anuncios"}</div>
          <div className="cta-subB-name">Plan {planObj.nombre}</div>
        </div>
        <span className="cta-subB-pill"><i style={isFree ? { background: "#e7d4a6" } : null}/> {isFree ? "Gratis" : "Activo"}</span>
      </div>
      <div className="cta-subB-meta">
        <div className="cta-subB-cell"><div className="k">Precio</div><div className="v">{price.amt} <small>{price.per}</small></div></div>
        <div className="cta-subB-cell"><div className="k">Siguiente cobro</div><div className="v">{isFree ? "Sin cobros" : "1 jul 2026"}</div></div>
        <div className="cta-subB-cell"><div className="k">Renueva</div><div className="v">{isFree ? "—" : "Cada mes"}</div></div>
      </div>
      {!isFree && (
        <div className="cta-subB-toggles">
          <CRow icon={CI.card} title="Renovación automática" desc="El cobro mensual lo procesa Stripe de forma segura." on={autopay} onToggle={() => setAutopay(v => !v)}/>
          <CRow icon={CI.mail} title="Avisarme por correo antes del cobro" desc="Te escribimos unos días antes de la renovación." on={preavisar} onToggle={() => setPreavisar(v => !v)}/>
        </div>
      )}
      <div className="cta-subB-actions">
        <button className="cta-subB-btn solid" onClick={onChangePlan}>Cambiar de plan</button>
        {!isFree && <button className="cta-subB-btn">Administrar pago en Stripe</button>}
      </div>
      <div className="cta-subB-stripe"><span className="cta-stripe-badge">Stripe</span><span>{isFree ? "Sube a Basic o PRO para guardar en la nube y quitar anuncios." : "Tus pagos se procesan de forma segura. Puedes cancelar cuando quieras."}</span></div>
    </div>
  );
}

// ── Sección de límites diarios (según plan) ─────────────────
function LimitsCard({ plan }) {
  const daily = CYNA_DAILY[plan] || CYNA_DAILY.basic;
  return (
    <React.Fragment>
      <div className="cta-limit-list">
        {CYNA_LIMIT_ROWS.map(([k, name]) => {
          const max = daily[k];
          if (max === 0) {
            return (
              <div key={k} className="cta-limit-row">
                <span className="cta-limit-name">{name}</span>
                <span className="cta-limit-count">No incluido en Free</span>
                <div className="cta-limit-bar"><i style={{ width: "0%" }}/></div>
              </div>
            );
          }
          if (!isFinite(max)) {
            return (
              <div key={k} className="cta-limit-row">
                <span className="cta-limit-name">{name}</span>
                <span className="cta-limit-count"><b>Ilimitado</b> ∞</span>
                <div className="cta-limit-bar"><i style={{ width: "100%", background: "var(--sage-500)" }}/></div>
              </div>
            );
          }
          const used = Math.min(CYNA_USED[k], max);
          const pct = Math.round((used / max) * 100);
          return (
            <div key={k} className="cta-limit-row">
              <span className="cta-limit-name">{name}</span>
              <span className="cta-limit-count"><b>{used}</b> / {max} usados</span>
              <div className="cta-limit-bar"><i className={pct >= 80 ? "warn" : ""} style={{ width: pct + "%" }}/></div>
            </div>
          );
        })}
      </div>
      <div className="cta-limit-note">{CI.refresh}<span>Los límites son diarios y se reinician cada día. {plan !== "pro" ? "¿Necesitas más? Sube a PRO para uso ilimitado." : "Tienes uso ilimitado."}</span></div>
    </React.Fragment>
  );
}

// ── SECCIÓN CUENTA (pestaña dentro de la app) ───────────────
function CuentaSection() {
  const profile = useProfile();
  const plan = usePlan();
  const [edit, setEdit] = kS(false);
  const [changePlan, setChangePlan] = kS(false);
  const [toast, setToast] = kS(null);
  const [emailNotif, setEmailNotif] = kS(true);

  kE(() => {
    if (!toast) return;
    const t = setTimeout(() => setToast(null), 3200);
    return () => clearTimeout(t);
  }, [toast]);

  const choosePlan = (pl) => {
    PlanState.set(pl.id);
    setChangePlan(false);
    setToast(`Plan actualizado a ${pl.nombre}. El cobro lo procesa Stripe.`);
  };
  const logout = () => (window.__cynaLogout ? window.__cynaLogout() : null);

  return (
    <div className="fade-in cta-account" data-screen-label="App — Cuenta">
      {/* Banner de perfil con foto editable */}
      <div className="cta-bannerB">
        <AvatarUpload src={profile.photo} label={cynaInitials(profile.nombre)} size={84}
          onPick={(d) => ProfileStore.set({ photo: d })}/>
        <div className="cta-bannerB-info">
          <h2>{profile.nombre}</h2>
          <p className="role">{profile.role}</p>
          <div className="cta-chips">
            <span className="cta-chip">{CI.age} {profile.edad} años</span>
            <span className="cta-chip">{CI.user} {profile.sexo}</span>
            <span className="cta-chip">{CI.building} Institución {profile.tipo.toLowerCase()}</span>
            {profile.institucion && <span className="cta-chip">{profile.institucion}</span>}
          </div>
        </div>
        <button className="btn-secondary" onClick={() => setEdit(true)}>Editar perfil</button>
      </div>

      {/* Estadísticas acumuladas */}
      <div className="cta-sectionB">
        <div className="cta-sectionB-head"><div className="ey">Tu actividad</div><h3>Estadísticas</h3></div>
        <div className="cta-statsB" style={{ gridTemplateColumns: "repeat(3, 1fr)" }}>
          <div className="cta-statB"><div className="cta-statB-val">24</div><div className="cta-statB-lbl">Casos guardados</div></div>
          <div className="cta-statB"><div className="cta-statB-val">137</div><div className="cta-statB-lbl">Diagnósticos consultados</div></div>
          <div className="cta-statB"><div className="cta-statB-val">9<small> días</small></div><div className="cta-statB-lbl">Racha activa</div></div>
        </div>
      </div>

      {/* Usos disponibles hoy */}
      <div className="cta-sectionB">
        <div className="cta-sectionB-head"><div className="ey">Plan {(window.PLANES || []).find(p => p.id === plan)?.nombre || "Basic"}</div><h3>Usos disponibles hoy</h3></div>
        <LimitsCard plan={plan}/>
      </div>

      {/* Suscripción */}
      <div className="cta-sectionB">
        <div className="cta-sectionB-head"><div className="ey">CynamonSup</div><h3>Suscripción</h3></div>
        <SubCard plan={plan} onChangePlan={() => setChangePlan(true)}/>
      </div>

      {/* Configuración */}
      <div className="cta-sectionB">
        <div className="cta-sectionB-head"><div className="ey">Datos y preferencias</div><h3>Configuración</h3></div>
        <div className="cta-listB">
          <CRow icon={CI.cloud} title="Copia de seguridad en la nube" desc="Tus casos y planes se respaldan automáticamente · última copia hace 2 h." chev/>
          <CRow icon={CI.mail} title="Notificaciones por correo" desc="Recordatorios y avisos a tu correo electrónico." on={emailNotif} onToggle={() => setEmailNotif(v => !v)}/>
          <CRow icon={CI.globe} title="Idioma" desc="Español · único idioma disponible por ahora." lock="ES"/>
          <CRow icon={CI.logout} title="Cerrar sesión" desc="Te volveremos a esperar pronto." chev danger onClick={logout}/>
        </div>
      </div>

      {edit && <EditProfileModal onClose={() => setEdit(false)}/>}
      {changePlan && <ChangePlanModal current={plan} onClose={() => setChangePlan(false)} onChoose={choosePlan}/>}
      {toast && <div className="cta-toast">{CI.check}<span>{toast}</span></div>}
    </div>
  );
}

// ── Widget NAV: campana de notificaciones ───────────────────
function AccountBell() {
  const [open, setOpen] = kS(false);
  const unread = CYNA_NOTIFS.filter(n => n.unread).length;
  return (
    <div className="cta-popwrap">
      <button className={"cta-bell" + (open ? " on" : "")} onClick={() => setOpen(o => !o)} aria-label="Notificaciones">
        {CI.bell}
        {unread > 0 && <span className="cta-bell-count">{unread}</span>}
      </button>
      {open && (
        <React.Fragment>
          <div className="cta-pop-backdrop" onClick={() => setOpen(false)}/>
          <div className="cta-pop">
            <div className="cta-pop-head">
              <span className="cta-pop-title">Notificaciones</span>
              <button className="cta-pop-mark" onClick={() => setOpen(false)}>Cerrar</button>
            </div>
            {CYNA_NOTIFS.map(n => (
              <div key={n.id} className={"cta-notif " + (n.unread ? "unread" : "read")}>
                <span className="cta-notif-dot"/>
                <div className="cta-notif-body">
                  <div className="cta-notif-title">{n.title}</div>
                  <div className="cta-notif-desc">{n.desc}</div>
                  <div className="cta-notif-time">{n.time}</div>
                </div>
              </div>
            ))}
            <div className="cta-pop-foot">{CI.mail}<span>Estos avisos también llegan a tu correo electrónico.</span></div>
          </div>
        </React.Fragment>
      )}
    </div>
  );
}

// ── Widget NAV: avatar + menú de usuario ────────────────────
function AccountMenu({ onAccount }) {
  const profile = useProfile();
  const [open, setOpen] = kS(false);
  const go = (fn) => { setOpen(false); fn && fn(); };
  const logout = () => (window.__cynaLogout ? window.__cynaLogout() : null);
  return (
    <div className="cta-popwrap">
      <button className="cta-userbtn" onClick={() => setOpen(o => !o)}>
        <span className={"cta-avatar-sm" + (profile.photo ? " has-img" : "")}
          style={profile.photo ? { backgroundImage: `url(${profile.photo})`, backgroundSize: "cover", backgroundPosition: "center", color: "transparent" } : null}>
          {cynaInitials(profile.nombre)}
        </span>
        <span className="cta-userbtn-name">{profile.nombre.split(" ")[0]}</span>
        <span className="cta-chev-sm">▾</span>
      </button>
      {open && (
        <React.Fragment>
          <div className="cta-pop-backdrop" onClick={() => setOpen(false)}/>
          <div className="cta-pop menu">
            <button className="cta-menu-item" onClick={() => go(onAccount)}>{CI.user}Mi cuenta</button>
            <button className="cta-menu-item" onClick={() => go(onAccount)}>{CI.card}Suscripción</button>
            <div className="cta-menu-sep"/>
            <button className="cta-menu-item danger" onClick={() => go(logout)}>{CI.logout}Cerrar sesión</button>
          </div>
        </React.Fragment>
      )}
    </div>
  );
}

Object.assign(window, { CuentaSection, AccountBell, AccountMenu });
