<script lang="ts">
import { createEventDispatcher, onMount } from 'svelte'
import ArrowLeft from 'virtual:icons/lucide/chevron-left'
import ArrowRight from 'virtual:icons/lucide/chevron-right'

import { testIds } from '@/constants'
import { Carousel } from '@/modules/carousel'

import IconButton from '../core/IconButton.svelte'

export let perPage = 1
export let easing = 'ease-out'
export let startIndex = 0
export let draggable = true
export let multipleDrag = true
export let controls = true
export let threshold = 20
export let rtl = false
export let maxHeight = 'max-h-86'
export let controlsTop = '9rem'

let sel: HTMLElement
let controller: Carousel
let disableRightControl = false
let disableLeftControl = true

const dispatch = createEventDispatcher<{ change: { currentSlide: number; slideCount: number } }>()

$: pips = controller ? controller.innerElements : []
$: disableRightControl
$: disableLeftControl

onMount(() => {
	controller = new Carousel({
		selector: sel,
		perPage: typeof perPage === 'object' ? perPage : Number(perPage),
		easing,
		startIndex,
		draggable,
		multipleDrag,
		threshold,
		rtl,
		onChange: handleChange,
	})

	return () => {
		controller.destroy()
	}
})

const left = () => {
	controller.prev()
}

const right = () => {
	controller.next()
}

const handleChange = () => {
	dispatch('change', {
		currentSlide: controller.currentSlide,
		slideCount: controller.innerElements.length,
	})
	disableRightControl = controller ? controller.currentSlide === pips.length - perPage : false
	disableLeftControl = pips && controller ? controller.currentSlide === 0 : false
}
</script>

<div class="carousel">
	<div class={`slides ${maxHeight} `} bind:this={sel}>
		<slot />
	</div>
	{#if controls && pips.length > perPage}
		{#if !disableRightControl}
			<div class="button right" style={`top: ${controlsTop}`} data-testId={testIds.productCardArrowRight}>
				<IconButton icon={ArrowRight} iconDescription="right" variant={'primary'} on:click={right} size={'md'} />
			</div>
		{/if}
		{#if !disableLeftControl}
			<div class="button left" style={`top: ${controlsTop}`} data-testId={testIds.productCardArrowLeft}>
				<IconButton icon={ArrowLeft} iconDescription="left" variant={'primary'} on:click={left} size={'md'} />
			</div>
		{/if}
	{/if}
</div>

<style lang="postcss">
.carousel {
	width: 100%;
	justify-content: start;
	align-items: start;
}
.carousel:hover > .button {
	opacity: 1;
}

.button {
	position: absolute;
	opacity: 0;
	z-index: 50;
	border: none;
	background-color: transparent;
	transition: opacity 400ms;
}

.left {
	left: -1em;
}

.right {
	right: -1em;
}
</style>
