<template>
<span v-if="disableLink" v-user-preview="disablePreview ? undefined : user.id" class="eiwwqkts _noSelect handleHash" :class="{ cat: user.isCat, square: defaultStore.state.squareAvatars }" :style="{ color, background: handleHash }" :title="acct(user)" @click="onClick">
	<img class="inner" :src="url" decoding="async"/>
	<MkUserOnlineIndicator v-if="showIndicator" class="indicator" :user="user"/>
</span>
<MkA v-else v-user-preview="disablePreview ? undefined : user.id" class="eiwwqkts _noSelect handleHash" :class="{ cat: user.isCat, square: defaultStore.state.squareAvatars }" :style="{ color, background: handleHash }" :to="userPage(user)" :title="acct(user)" :target="target">
	<img class="inner" :src="url" decoding="async"/>
	<MkUserOnlineIndicator v-if="showIndicator" class="indicator" :user="user"/>
</MkA>
</template>

<script lang="ts" setup>
import { watch } from 'vue';
import * as foundkey from 'foundkey-js';
import { getStaticImageUrl } from '@/scripts/get-static-image-url';
import { extractAvgColorFromBlurhash } from '@/scripts/extract-avg-color-from-blurhash';
import { acct, userPage } from '@/filters/user';
import MkUserOnlineIndicator from '@/components/user-online-indicator.vue';
import { defaultStore } from '@/store';

const props = withDefaults(defineProps<{
	user: foundkey.entities.User;
	target?: string | null;
	disableLink?: boolean;
	disablePreview?: boolean;
	showIndicator?: boolean;
}>(), {
	target: null,
	disableLink: false,
	disablePreview: false,
	showIndicator: false,
});

const emit = defineEmits<{
	(ev: 'click', v: MouseEvent): void;
}>();

const url = $computed(() => defaultStore.state.disableShowingAnimatedImages
	? getStaticImageUrl(props.user.avatarUrl)
	: props.user.avatarUrl);

// colors from Nature Methods column by Bang Wong
// https://www.nature.com/articles/nmeth.1618
const hashlette = ['rgb(0, 0, 0)', 'rgb(230, 159, 0)', 'rgb(86, 180, 233)', 'rgb(0, 158, 115)', 'rgb(240, 228, 66)', 'rgb(0, 114, 178)', 'rgb(213, 94, 0)', 'rgb(204, 121, 167)'] as const;

/**
 * FNV-1a Hash implementation (32, 64, 128, 256, 512, and 1024 bit)
 *
 * stolen under the terms of MIT license which i actually had to make up myself cause all i had was the readme
 *
 * Copyright © 2017 Travis Webb and desudesutalk
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 * @author Travis Webb <me@traviswebb.com>
 * @see http://tools.ietf.org/html/draft-eastlake-fnv-06
 */
function fnv1a32(str: string): number {
	let i: number, l = str.length - 3, t0 = 0, v0 = 0x9dc5, t1 = 0, v1 = 0x811c;

	for (i = 0; i < l;) {
		v0 ^= str.charCodeAt(i++);
		t0 = v0 * 403; t1 = v1 * 403;
		t1 += v0 << 8;
		v1 = (t1 + (t0 >>> 16)) & 65535; v0 = t0 & 65535;
		v0 ^= str.charCodeAt(i++);
		t0 = v0 * 403; t1 = v1 * 403;
		t1 += v0 << 8;
		v1 = (t1 + (t0 >>> 16)) & 65535; v0 = t0 & 65535;
		v0 ^= str.charCodeAt(i++);
		t0 = v0 * 403; t1 = v1 * 403;
		t1 += v0 << 8;
		v1 = (t1 + (t0 >>> 16)) & 65535; v0 = t0 & 65535;
		v0 ^= str.charCodeAt(i++);
		t0 = v0 * 403; t1 = v1 * 403;
		t1 += v0 << 8;
		v1 = (t1 + (t0 >>> 16)) & 65535; v0 = t0 & 65535;
	}

	while (i < l + 3) {
		v0 ^= str.charCodeAt(i++);
		t0 = v0 * 403; t1 = v1 * 403;
		t1 += v0 << 8;
		v1 = (t1 + (t0 >>> 16)) & 65535; v0 = t0 & 65535;
	}

	return ((v1 << 16) >>> 0) + v0;
}

const handleHash = $computed(() => {
	const stripColours = fnv1a32(acct(props.user)).toString(8).split('').map(digitStr => hashlette[parseInt(digitStr)]);
	const fraction = 1 / stripColours.length;
	const positions = stripColours.flatMap((colour, idx) =>
		[`${colour} ${fraction * idx}turn`, `${colour} ${fraction * (idx + 1)}turn`]
	);
	return `conic-gradient(${positions})`;
});

function onClick(ev: MouseEvent) {
	emit('click', ev);
}

let color = $ref();

watch(() => props.user.avatarBlurhash, () => {
	color = extractAvgColorFromBlurhash(props.user.avatarBlurhash);
}, {
	immediate: true,
});
</script>

<style lang="scss" scoped>
@keyframes earwiggleleft {
	from { transform: rotate(37.6deg) skew(30deg); }
	25% { transform: rotate(10deg) skew(30deg); }
	50% { transform: rotate(20deg) skew(30deg); }
	75% { transform: rotate(0deg) skew(30deg); }
	to { transform: rotate(37.6deg) skew(30deg); }
}

@keyframes earwiggleright {
	from { transform: rotate(-37.6deg) skew(-30deg); }
	30% { transform: rotate(-10deg) skew(-30deg); }
	55% { transform: rotate(-20deg) skew(-30deg); }
	75% { transform: rotate(0deg) skew(-30deg); }
	to { transform: rotate(-37.6deg) skew(-30deg); }
}

.eiwwqkts {
	position: relative;
	display: inline-block;
	vertical-align: bottom;
	flex-shrink: 0;
	border-radius: 100%;
	line-height: 16px;

	> .inner {
		position: absolute;
		bottom: 0;
		left: 0;
		right: 0;
		top: 0;
		border-radius: 100%;
		z-index: 1;
		overflow: hidden;
		object-fit: cover;
		width: 100%;
		height: 100%;
	}

	&.handleHash {
		> .inner {
			padding: 10%;
			width: 80%;
			height: 80%;
		}
	}

	> .indicator {
		position: absolute;
		z-index: 1;
		bottom: 0;
		left: 0;
		width: 20%;
		height: 20%;
	}

	&.square {
		border-radius: 20%;

		> .inner {
			border-radius: 20%;
		}
	}

	&.cat {
		&:before, &:after {
			background: #df548f;
			border: solid 4px currentColor;
			box-sizing: border-box;
			content: '';
			display: inline-block;
			height: 50%;
			width: 50%;
		}

		&:before {
			border-radius: 0 75% 75%;
			transform: rotate(37.5deg) skew(30deg);
		}

		&:after {
			border-radius: 75% 0 75% 75%;
			transform: rotate(-37.5deg) skew(-30deg);
		}

		&:hover {
			&:before {
				animation: earwiggleleft 1s infinite;
			}

			&:after {
				animation: earwiggleright 1s infinite;
			}
		}
	}
}
</style>
