<script lang="ts">
    import { createBuilding } from "../create";
    import buildings from "../data/buildings";
    import moves from "../moves";
    import showBuildingCreator from "../stores/showBuildingCreator";
    import { canPayBuildingCost, getTownhall } from "../utils";
    import village from "../village";
    import Cost from "./Cost.svelte";

    function close() {
        showBuildingCreator.set(null);
    }


    function build(type: string) {
        if ($showBuildingCreator === null) {
            return;
        }

        if (moves.build(type, $showBuildingCreator)) {
            close();
        }
    }

    $: constructible = buildings
        .filter(b => !b.autoBuilt)
        .filter(b => !(b.unique && $village.buildings.some(b2 => b2.type === b.type)))
        .filter(b => !b.requiredTownhallLevel || getTownhall($village).level >= b.requiredTownhallLevel)
        .map(b =>{
            const building = createBuilding(b.type);
            building.level = 0;
            return building;
        })
        .sort((a, b) => a.requiredTownhallLevel - b.requiredTownhallLevel);
</script>

{ #if $showBuildingCreator !== null }
<section>
    <div class="building-creator">
        <header>
            <h1>Build</h1>
            <span class="close">
                <button on:click={ close }>X</button>
            </span>
        </header>
        <div class="buildings">
            { #each constructible as building }
            <div>
                <p>{ building.name }</p>
                <Cost cost={ building.cost(1) } />
                <button
                    on:click={ () => build(building.type) }
                    disabled={ !canPayBuildingCost($village, building) }
                >
                    Build
                </button>
            </div>
            { /each }
        </div>
    </div>
</section>
{ /if }

<style>
    section {
        background-color: hsl(0, 0%, 10%, 0.8);
        display: grid;
        place-items: center;
        height: 100vh;
        left: 0;
        position: absolute;
        top: 0;
        width: 100vw;
    }

    .building-creator {
        background-color: hsl(0, 0%, 20%);
        border: 0.2em solid grey;
        border-radius: .4em;
        width: 80%;
        height: 60%;
    }

    .building-creator header {
        position: relative;
    }

    .building-creator header .close {
        position: absolute;
        right: 1em;
        top: 0;
    }

    .building-creator .buildings {
        display: grid;
        gap: 1em;
        grid-template-columns: repeat(4, 1fr);
    }
</style>
