import React from 'react';
import { color, toRem } from 'folds';
import { Room } from 'matrix-js-sdk';
import { useMatrixClient } from '../../../hooks/useMatrixClient';

export type SpaceAvatarProps = {
  space: Room;
  size: number;
};

// Square-rounded space avatar with auto-generated initial fallback. Kept
// outside the folds `<Avatar>` recipe because every call-site needs an
// explicit pixel size (currently 40 — workspace footer + in-sheet
// SpaceRow); folds Avatar tokens don't expose that step cleanly. The
// border-radius scales with `size` (`Math.max(6, size / 3.5)`), so any
// future caller passing a different size still gets a proportional
// rounded-square shape.
export function SpaceAvatar({ space, size }: SpaceAvatarProps) {
  const mx = useMatrixClient();
  const mxcUrl = space.getMxcAvatarUrl();
  const httpUrl = mxcUrl
    ? mx.mxcUrlToHttp(mxcUrl, size * 2, size * 2, 'crop', undefined, false, true) ?? undefined
    : undefined;
  const initial = (space.name || space.roomId).trim().slice(0, 1).toUpperCase();
  return (
    <div
      style={{
        width: toRem(size),
        height: toRem(size),
        borderRadius: toRem(Math.max(6, Math.round(size / 3.5))),
        background: httpUrl
          ? `center/cover no-repeat url("${httpUrl}")`
          : color.Primary.Container,
        color: color.Primary.OnContainer,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        fontWeight: 600,
        fontSize: toRem(Math.round(size * 0.46)),
        flexShrink: 0,
      }}
      aria-hidden
    >
      {!httpUrl && initial}
    </div>
  );
}
