<script lang="ts">
	import tl from '$lib/assets/images/tl.png'
	import { onMount } from 'svelte';
	import { openUrl } from '@tauri-apps/plugin-opener';
	import { getCurrentWindow } from '@tauri-apps/api/window';
	import { invoke } from '@tauri-apps/api/core';
	import { GAME_CONFIG } from '$lib/config';


	const win = getCurrentWindow();


	const closeWindow = async () => {
		if (openGameDir) {
			try {
				const result = await invoke('open_game_dir', {
					installPath: installPath
				});
				console.log(result);
			} catch (error) {
				console.error('启动游戏失败:', error);
			}
		}
	 	await create_shortcut()
		await win.close()

	};

	let data:[{attributes:{title:string, slug:string, id:string}}];
	let loading = true;
	let error;
	//是否创建快捷方式变量
	let createShortcut = true;
	//是否退出后启动变量
	let openGameDir = true;

	let installPath = localStorage.getItem('installPath');

	const url = "https://nopj.cn/api/discussions?include=tags.parent&filter[tag]=resources&sort=-createdAt&page[offset]=0&page[limit]=5"

	onMount(async () => {
		try {
			const res = await fetch(url,{
				method: 'GET',
				headers: {
					'Content-Type': 'application/json'
				}
			});

			if (!res.ok){
				throw new Error(res.statusText);
			}
			let jsonStr = await res.json();
			console.log(jsonStr.data);
			data = jsonStr.data
		}catch (e: any){
			error = e.message;
		} finally {

		}
	})



	async function handleExternalLink(event: MouseEvent, targetUrl: string) {

		event.preventDefault();

		try {
			await openUrl(targetUrl);
		} catch (e) {
			console.error("无法打开外部链接:", e);
		}
	}

	const create_shortcut = async () => {
		if (createShortcut){

			try{
				const result = await invoke('create_shortcut', {
					installPath: localStorage.getItem('installPath'),
					shortcutName: GAME_CONFIG.shortcut_name,
					exeName: GAME_CONFIG.launch,
				})
				console.log(result);
			}catch (e){
				console.error("创建快捷方式失败:", e);
				alert(e)
			}

		}
	}

</script>

<div class="h-screen w-screen flex z-10 pt-8 select-none relative">
	<div class="flex-1 flex items-center justify-center">
		<div class="w-2xl p-8 backdrop-blur-xl shadow-xl shadow-base/30">
			<div class=" text-center">
				<svg xmlns="http://www.w3.org/2000/svg" width="120" height="120" viewBox="0 0 32 32" class="m-auto">
					<g fill="none">
						<path fill="url(#SVGFnVq5bNm)" d="M30 16c0 7.732-6.268 14-14 14S2 23.732 2 16S8.268 2 16 2s14 6.268 14 14" />
						<path fill="url(#SVGcpquMdXZ)" d="M22.707 12.707a1 1 0 0 0-1.414-1.414L14.5 18.086l-3.293-3.293a1 1 0 0 0-1.414 1.414l4 4a1 1 0 0 0 1.414 0z" />
						<defs>
							<linearGradient id="SVGFnVq5bNm" x1="3" x2="22.323" y1="7.25" y2="27.326" gradientUnits="userSpaceOnUse">
								<stop stop-color="#52d17c" />
								<stop offset="1" stop-color="#22918b" />
							</linearGradient>
							<linearGradient id="SVGcpquMdXZ" x1="12.031" x2="14.162" y1="11.969" y2="22.66" gradientUnits="userSpaceOnUse">
								<stop stop-color="#fff" />
								<stop offset="1" stop-color="#e3ffd9" />
							</linearGradient>
						</defs>
					</g>
				</svg>

				<div class="font-bold text-3xl pt-2 pb-4">
					安装完成
				</div>
			</div>
			<fieldset class="fieldset bg-base-100/30 border-base-300/10 rounded-box w-full border p-4">
				<legend class="fieldset-legend">启动设置</legend>
				<label class="label">
					<input type="checkbox" checked={createShortcut} class="checkbox" />
					设置桌面快捷方式
				</label>
				<label class="label pt-4">
					<input type="checkbox" checked={openGameDir} class="checkbox" />
					打开游戏目录
				</label>
			</fieldset>
			<div class="w-full text-center pt-12">
				<button class="btn btn-primary btn-wide "
								on:click={closeWindow}
				>退出</button>
			</div>
		</div>
	</div>
	<div class=" w-96 bg-base-200  bg-cover bg-center text-base-300 overflow-hidden relative" style="background-image: url({tl})">
		<div class="h-full w-full absolute top-0  z-0">

		</div>
		<div class="z-10 relative p-4 w-full ">
			<h1 class="font-bold text-4xl text-right">NoPJ</h1>
			<p class="pt-2 ">
				<span class="text-rotate font-bold text-right ">
				<span>
					<span>最新资源</span>
					<span>Latest Resources</span>
					<span>Последний ресурс</span>
				</span>
			</span>
			</p>
			<div class="pt-4">
				<ul class="list">
					{#each data as item}
						<li class=" list-row backdrop-blur-xs hover:backdrop-blur-xl hover:font-bold transition-all mt-4  font-misans">
							<a href="https://nopj.cn/d/{item.attributes.slug}" class="  "
								 on:click={(e) => handleExternalLink(e, `https://nopj.cn/d/${item.attributes.slug}`)}
							>
							<span class="">
								{item.attributes.title}
							</span>
							</a>
						</li>
					{/each}
				</ul>
			</div>
		</div>
		<div class="absolute bottom-3 text-center z-10 left-0 w-full">
			<p class="font-bold">Designed by Chaos & <a href="https://nopj.cn"
																									on:click={(e)=>handleExternalLink(e, 'https://nopj.cn')}
			>Nopj</a></p>
		</div>
	</div>

</div>