<script lang="ts">
    import moves from "../moves";
    import showBuildingPanel from "../stores/showBuildingPanel";
    import { getBuilding, getBuildingUpgradeCost } from "../utils";
    import village from "../village";
    import BuildingRecruitment from "./BuildingRecruitment.svelte";
    import Cost from "./Cost.svelte";


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

    function upgrade() {
        if ($showBuildingPanel === null) {
            return;
        }

        if (moves.upgradeBuilding($showBuildingPanel)) {
            close();
        }
    }

    $: building = ($showBuildingPanel !== null) ? getBuilding($village, $showBuildingPanel) : null;
</script>

{ #if building !== null }
<section>
    <div class="building-panel">
        <header>
            <h1>{ building.name } ({ building.level })</h1>
            <span class="close">
                <button on:click={ close }>X</button>
            </span>
        </header>
        <div class="content">
            { #if building.level === 0 }
            <p>Building in construction…</p>
            { :else if building.behavior.units }
            <BuildingRecruitment { building } />
            { /if }
        </div>
        <div class="upgrade">
            { #if building.state.upgrade.isUpgrading }
            <p>
                Upgrading to level { building.level + 1 }
                ({ Math.ceil(building.state.upgrade.remainingTime / 1000) }’)
            </p>
            { :else if building.level === building.maxLevel }
            <p>Max level reached!</p>
            { :else }
            <div>
                <Cost cost={ getBuildingUpgradeCost($village, building) } />
                <button on:click={ () => upgrade() }>Upgrade</button>
            </div>
            { /if }
        </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-panel {
        background-color: hsl(0, 0%, 20%);
        border: 0.2em solid grey;
        border-radius: .4em;
        width: 80%;
        height: 60%;
    }

    .building-panel header {
        position: relative;
    }

    .building-panel header .close {
        position: absolute;
        right: 1em;
        top: 0;
    }
</style>
