/* avatar.jsx — Componente compartido de avatar de estudiante
   Muestra la foto de Google Photos si está asignada; si no (o si falla la carga),
   muestra las iniciales con color determinístico basado en el nombre.
   referrerPolicy="no-referrer" para evitar bloqueos de origen cruzado.
*/
const { useState: useStateAV, useEffect: useEffectAV, useContext: useContextAV } = React;

// Contexto global de versión de foto — cuando cualquier foto cambia,
// el Provider raíz incrementa este valor y TODOS los StudentAvatar se re-renderizan.
var PhotoVersionContext = React.createContext(0);
window.PhotoVersionContext = PhotoVersionContext;

function StudentAvatar({ userId, userName, size, style }) {
  size = size || 34;
  var _st = useStateAV(false);
  var imgError = _st[0]; var setImgError = _st[1];

  // Suscribirse al contexto global de versión de foto —
  // cuando cualquier foto cambia en la app, este componente se re-renderiza
  // y re-lee getStudentPhoto(userId) desde localStorage automáticamente.
  useContextAV(PhotoVersionContext);

  var photo    = getStudentPhoto(userId);
  var photoUrl = (photo && !imgError) ? normalizePhotoUrl(photo) : null;
  var pal      = getAvatarPalette(userName || '');
  var initials = getAvatarInitials(userName || '');

  var base = Object.assign({
    width: size, height: size,
    borderRadius: '50%',
    flexShrink: 0,
  }, style || {});

  if (photoUrl) {
    return (
      <img
        src={photoUrl}
        alt={userName || ''}
        referrerPolicy="no-referrer"
        style={Object.assign({}, base, { objectFit: 'cover' })}
        onError={function () { setImgError(true); }}
      />
    );
  }

  return (
    <div style={Object.assign({}, base, {
      background: pal.bg,
      color: pal.fg,
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      fontSize: Math.max(10, Math.round(size * 0.36)),
      fontWeight: 700,
      letterSpacing: '0.02em',
    })}>
      {initials}
    </div>
  );
}

window.StudentAvatar = StudentAvatar;
