<script lang="ts">
    import { flip } from "svelte/animate";
    import { fly } from "svelte/transition";

    import moves from "../moves";
    import type { Resource, ResourcesType } from "../types";
    import { getEmptyResources, getPrettyTime } from "../utils";
    import village from "../village";
    import Reward from "./Reward.svelte";


    $: availableHeroes = $village.heroes.filter(h => !$village.quests.some(q => q.hero === h.id));

    function startQuest(id: number, heroId: number) {
        moves.startQuest(id, heroId);
    }

    function getRewardAsResources(resource: Resource, reward: number): ResourcesType {
        const output = getEmptyResources();
        output[resource] = reward;
        return output;
    }
</script>

<section>
    { #each $village.quests as quest (quest.id) }
    <div
        class="quest"
        in:fly={{ duration: 200, delay: 100, x: -500 }}
        out:fly={{ duration: 200, x: 500 }}
        animate:flip={{ duration: 100 }}
    >
        <p class="reward">
            <span>
                <img src="./img/icons/time.png" alt="Duration">
                { #if quest.started }
                { getPrettyTime(quest.remainingTime || 0) }
                { :else }
                { quest.duration }
                { /if }
            </span>
            <Reward reward={ getRewardAsResources(quest.resource, quest.reward) } />
        </p>
        { #if !quest.started }
        <p>
            { #each availableHeroes as hero }
            <button
                on:click={ () => startQuest(quest.id, hero.id) }
            >
                Send { hero.name }
            </button>
            { :else }
            <span>No heroes available</span>
            { /each }
        </p>
        { /if }
    </div>
    { /each }
</section>

<style>
    .quest {
        border: 1px solid hsl(0, 0%, 20%);
        border-radius: 1em;
        margin-bottom: 0.5em;
        padding: 0 1em;
        text-align: left;
    }

    .quest .reward {
        display: flex;
        justify-content: space-between;
    }

    .quest .reward span {
        display: flex;
        align-items: center;
        gap: 0.5em;
    }
</style>
