<script lang="ts">
	import Icon from '@iconify/svelte';
	import type { Arxlet } from '../eve';
	import { onMount } from 'svelte';
	import LiquidGlass from './LiquidGlass.svelte';

	let {
		arxlet
	}: {
		arxlet: Arxlet;
	} = $props();

	let isInstalling = $state(false);
	let isInstalled = $state(false);
	let canUpdate = $state(false);

	let icon = $derived(arxlet.icon ?? 'mdi:package-variant');
	let iconColor = $derived(arxlet.iconColor ?? '#7f0707');
	let version = $derived(arxlet.version ?? deriveVersion(arxlet.versionDate));

	function deriveVersion(timestamp: number): string {
		const date = new Date(timestamp * 1000);
		const SCALE_FACTOR = 255 / 743;

		const components = {
			year: date.getFullYear() - 2025,
			month: date.getMonth(),
			day: date.getDate() - 1,
			hour: date.getHours(),
			minute: date.getMinutes(),
			second: date.getSeconds()
		};

		const dayHour = components.day * 24 + components.hour;
		const scaledDayHour = Math.floor(dayHour * SCALE_FACTOR);

		const major = (((components.year & 0xf) << 4) | (components.month & 0xf))
			.toString(16)
			.padStart(2, '0');

		const minor = scaledDayHour.toString(16).padStart(2, '0');

		const totalSeconds = dayHour * 3600 + components.minute * 60 + components.second;
		const baseSeconds = scaledDayHour * (3600 / SCALE_FACTOR);
		const patch = Math.floor(totalSeconds - baseSeconds)
			.toString(16)
			.padStart(4, '0');

		return `${major}.${minor}.${patch}`;
	}

	onMount(load);

	async function load() {
		const event = await window.eve.getSingleEventById(arxlet.eventId);

		if (event) return (isInstalled = true);

		const arxletInstalled = await window.eve.getArxlet(arxlet.id);
		if (arxletInstalled) {
			isInstalled = true;
			canUpdate = arxletInstalled.versionDate !== arxlet.versionDate;
		}
	}

	async function handleInstall() {
		if ((isInstalled && !canUpdate) || isInstalling) return;

		isInstalling = true;

		await window.eve.cloneRemoteEvent(arxlet.eventId);

		isInstalled = true;
		isInstalling = false;
		canUpdate = false;

		console.log(`Installing ${arxlet.name}...`);
	}
</script>

<LiquidGlass
	class="card shadow-lg hover:shadow-xl transition-all duration-300 border border-base-300 hover:border-primary/30"
>
	<div class="card-body p-6">
		<div class="flex items-start gap-4 mb-4">
			<div class="relative flex-shrink-0 group">
				<div
					class="w-16 h-16 rounded-2xl shadow-lg hover:shadow-xl
                    flex items-center justify-center relative overflow-hidden
                    transition-all duration-300 ease-out hover:scale-105
                    before:absolute before:inset-0 before:rounded-2xl
                    before:bg-gradient-to-br before:from-white/20 before:to-transparent before:opacity-80
                    after:absolute after:inset-0 after:rounded-2xl
                    after:shadow-inner after:shadow-black/10"
					style="background: linear-gradient(135deg, {iconColor}dd 0%, {iconColor} 50%, {iconColor}bb 100%)"
				>
					<Icon
						{icon}
						class="w-8 h-8 text-white drop-shadow-md relative z-10
                                          group-hover:drop-shadow-lg transition-all duration-300"
					/>
				</div>

				<div
					class="absolute inset-0 w-16 h-16 rounded-2xl
                    opacity-0 hover:opacity-20 transition-all duration-300
                    blur-sm scale-110"
					style="background: radial-gradient(circle, {iconColor}66 0%, transparent 70%)"
				/>
			</div>

			<div class="flex-1 min-w-0">
				<h3 class="card-title text-lg font-bold text-base-content truncate mb-1">
					{arxlet.name}
				</h3>
				<p class="text-base-content/80 text-sm leading-relaxed mb-1">
					Version: {version}
				</p>
			</div>
		</div>

		<p class="text-base-content/80 text-sm leading-relaxed mb-4 line-clamp-3">
			{arxlet.description}
		</p>

		<div class="card-actions justify-end">
			<button
				class="btn btn-sm {isInstalled && !canUpdate ? 'btn-success' : 'btn-primary'} {isInstalling
					? 'loading'
					: ''}"
				onclick={handleInstall}
				disabled={isInstalling || (isInstalled && !canUpdate)}
			>
				{#if isInstalling}
					<span class="loading loading-spinner loading-sm" />
					Installing...
				{:else if canUpdate}
					<Icon icon="mdi:update" class="w-4 h-4" />
					Update
				{:else if isInstalled}
					<Icon icon="mdi:check" class="w-4 h-4" />
					Installed
				{:else}
					<Icon icon="mdi:download" class="w-4 h-4" />
					Install
				{/if}
			</button>
		</div>
	</div>
</LiquidGlass>
