<header class="fixed fill">
	<nav>
		<h5 class="max center-align">Campaigns</h5>
		<button class="circle small" on:click={newCampaign}>
			<i>add</i>
		</button>
	</nav>
</header>

<article>
	{#if !$campaigns || $campaigns.length === 0}
		<div class="fill medium-height middle-align center-align">
			<div class="center-align">
				<h5>No campaign created yet</h5>
			</div>
		</div>
	{/if}
	{#each $campaigns as campaign (campaign._id)}
		<div class="row">
			<i class="light-green-text">south_america</i>
			<div class="max">
				<h6>
					<a href={`#/campaign/${campaign._id}`}>
						{campaign.name}
					</a>
				</h6>
				<p>
					{#if campaign.battles}
						<a href={`#/campaign/${campaign._id}`}>
							chapter {currentChapter(campaign)}, battle of {currentCity(
								campaign,
							)}.
						</a>
					{/if}
				</p>
			</div>
			<button on:click={deleteCampaign(campaign)} class="none"
				>Delete</button
			>
		</div>
	{/each}
	<footer class="bottom absolute center">
		fan-made campaign manager for <a
			href="https://czechgames.com/en/under-falling-skies/"
			>Under Falling Skies</a
		><br /> written by
		<a href="mailto:yanick@sky.babyl.ca">Yanick Champoux</a>
	</footer>
</article>

{#if showNewCampaign}
	<div class="modal active">
		<form>
			<h5>New campaign</h5>
			<div>
				<div class="field border">
					<input
						autofocus
						type="text"
						bind:value={newCampaignName}
						placeholder="Campaign name"
					/>
				</div>
			</div>
			<nav class="right-align">
				<button
					class="border"
					on:click={() => (showNewCampaign = false)}>Cancel</button
				>
				<button on:click={saveNewCampaign}>Create</button>
			</nav>
		</form>
	</div>
{/if}

<script>
	import * as R from 'remeda';
	import { getContext } from 'svelte';
	//	import { goto } from '$app/navigation';
	const goto = () => {};

	export let api = getContext('api');
	export let campaigns = api?.campaigns;

	let showNewCampaign = false;
	let newCampaignName = '';

	const currentChapter = ({ battles }) =>
		R.clamp(1 + parseInt(battles?.length / 2), { max: 4 });
	const currentCity = ({ battles }) => {
		const c = R.last(battles)?.city;
		return typeof c === 'string' ? c : c?.selection;
	};

	async function deleteCampaign({ name, _id }) {
		if (!window.confirm(`delete campaign ${name}?`)) return;
		api.event.deleteCampaign(_id);
	}

	const newCampaign = () => {
		showNewCampaign = true;
	};

	const saveNewCampaign = () => {
		console.log('sent');
		api.event.addCampaign(newCampaignName);
		newCampaignName = '';
		showNewCampaign = false;
	};
</script>

<style>
	nav {
		width: 100%;
	}
	header {
		display: flex;
	}
	h5 {
		flex: 1;
	}
	article {
		height: 90vh;
	}
	footer {
		width: 90%;
		text-align: center;
	}
	footer a {
		text-decoration: underline;
	}
</style>
