<article>
	<header>
		<h5>Campaigns</h5>
		<button on:click={newCampaign}>new campaign</button>
	</header>

	{#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}
						chapter {currentChapter(campaign)}, battle of {currentCity(
							campaign,
						)}.
					{/if}
				</p>
			</div>
			<button on:click={deleteCampaign(campaign)} class="none"
				>Delete</button
			>
		</div>
	{/each}
</article>

<div class="modal" class:active={showNewCampaign}>
	<h5>New campaign</h5>
	<div>
		<div class="field border">
			<input
				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>
</div>

<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 }) => R.last(battles).city;

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

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

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

<style>
	header {
		display: flex;
	}
	h5 {
		flex: 1;
	}
	article {
		height: 90vh;
	}
</style>
