<template>
	<div class="header">
		<img class="background" :src="imageUrl" />
		<div class="content">
			<div>
				<NcAvatar
					:display-name="author || title"
					:is-no-user="true"
					:size="128"
					:url="imageUrl" />
				<a class="feed" :href="url" @click.prevent="copyFeed">
					<RssIcon :size="20" />
					<i>{{ t('repod', 'Copy feed') }}</i>
				</a>
			</div>
			<div class="inner">
				<div class="infos">
					<h2>{{ title }}</h2>
					<a :href="link" target="_blank">
						<i>{{ author }}</i>
					</a>
					<br /><br />
					<SafeHtml :source="description" />
				</div>
				<NcAppNavigationNew
					v-if="!getSubscriptions.includes(url)"
					:text="t('repod', 'Subscribe')"
					@click="addSubscription">
					<template #icon>
						<PlusIcon :size="20" />
					</template>
				</NcAppNavigationNew>
			</div>
		</div>
	</div>
</template>

<script>
import { NcAppNavigationNew, NcAvatar } from '@nextcloud/vue'
import { mapActions, mapState } from 'pinia'
import { showError, showSuccess } from '../../utils/toast.ts'
import PlusIcon from 'vue-material-design-icons/Plus.vue'
import RssIcon from 'vue-material-design-icons/Rss.vue'
import SafeHtml from '../Atoms/SafeHtml.vue'
import axios from '@nextcloud/axios'
import { decodeUrl } from '../../utils/url.ts'
import { generateUrl } from '@nextcloud/router'
import { useSubscriptions } from '../../store/subscriptions.ts'

export default {
	name: 'Banner',
	components: {
		NcAvatar,
		NcAppNavigationNew,
		PlusIcon,
		RssIcon,
		SafeHtml,
	},
	props: {
		author: {
			type: String,
			required: true,
		},
		description: {
			type: String,
			required: true,
		},
		imageUrl: {
			type: String,
			required: true,
		},
		link: {
			type: String,
			required: true,
		},
		title: {
			type: String,
			required: true,
		},
	},
	computed: {
		...mapState(useSubscriptions, ['getSubscriptions']),
		url() {
			return decodeUrl(this.$route.params.url)
		},
	},
	methods: {
		...mapActions(useSubscriptions, ['fetch']),
		async addSubscription() {
			try {
				await axios.post(
					generateUrl('/apps/gpoddersync/subscription_change/create'),
					{
						add: [this.url],
						remove: [],
					},
				)
			} catch (e) {
				console.error(e)
				showError(t('repod', 'Error while adding the feed'))
			}

			this.fetch()
		},
		copyFeed() {
			window.navigator.clipboard.writeText(this.url)
			showSuccess(t('repod', 'Link copied to the clipboard'))
		},
	},
}
</script>

<style scoped>
.background {
	filter: blur(1rem) brightness(50%);
	height: auto;
	left: 0;
	opacity: 0.4;
	position: absolute;
	top: 0;
	width: 100%;
	z-index: -1;
}

.content {
	display: flex;
	gap: 1rem;
	height: 10rem;
	position: relative;
}

.feed {
	display: flex;
	gap: 0.2rem;
	margin: 0.5rem;
}

.header {
	height: 14rem;
	overflow: hidden;
	padding: 2rem;
	position: relative;
}

.infos {
	overflow: auto;
}

.inner {
	display: flex;
}

@media only screen and (max-width: 768px) {
	.inner {
		flex-direction: column;
	}
}
</style>