<template>
	<component :is="avatarTag" :to="profile.profileUrl">
		<div class="avatar" :style="borderStyle">
			<div class="avatar__space" :style="borderStyle">
				<img
					v-if="imgSrc"
					:src="imgSrc"
					:style="imgStyle"
					class="avatar__img"
				>
				<div
					v-else
					:style="imgStyle"
					class="avatar__placeholder"
				>
					{{ nameAbbr }}
				</div>
			</div>
		</div>
	</component>
</template>

<script lang="ts">
import Vue, { PropType } from 'vue';
import { Profile } from '../typings/models';
import { Optional } from '../typings/helpers';
import { cleanInt, expectProp } from '../src/helpers';

export default Vue.extend({
	name: 'Avatar',
	props: {
		profile: {
			required: true,
			type: Object as PropType<Profile>,
			validator: expectProp(['fullName', 'avatar', 'profileUrl'])
		},
		size: {
			type: [String, Number],
			default: 34
		},
		openProfile: {
			type: Boolean,
			default: true
		}
	},

	computed: {
		avatarTag(): string {
			return this.openProfile ? `router-link` : 'div';
		},
		borderStyle(): any {
			return {
				padding: Math.max(2, Math.ceil(cleanInt(this.size) / 24)) + 'px'
			};
		},
		nameAbbr(): string {
			return this.profile.fullName
				.split(' ')
				.map((s: string) => s[0])
				.join('');
		},
		imgSrc(): Optional<string> {
			return this.profile.avatar;
		},
		imgStyle(): any {
			const size = cleanInt(this.size);

			return {
				width: size + 'px',
				minWidth: size + 'px',
				height: size + 'px',
				maxHeight: size + 'px',
				fontSize: (size / 50) + 'em'
			};
		}
	}
});
</script>

<style lang="scss">
.avatar {
	@include rounded(full);

	user-select: none;
	vertical-align: top;
	display: inline-flex;
	background: linear-gradient(
		to bottom,
		rgb(245, 158, 11) 0%,
		rgb(219, 39, 119) 100%
	);

	&__space {
		@include rounded(full);

		background-color: var(--color-shade-0);
	}
	
	&__img {
		@include rounded(full);

		image-rendering: crisp-edges;
		object-fit: cover;
		display: block;
	}

	&__placeholder {
		@include rounded(full);
		@include font-weight(semibold);

		display: flex;
		align-items: center;
		justify-content: center;
		background-color: var(--color-shade-3);
		color: var(--color-negative-0);
	}
}
</style>