<script lang="ts">
    import moves from "../moves";
    import type { BuildingType } from "../types";
    import { canPayBuildingCost } from "../utils";
    import village from "../village";

    export let building: BuildingType;


    $: isUpgrading = building.state.upgrade.isUpgrading;
    $: canUpgrade = !isUpgrading && canPayBuildingCost($village, building);
    $: maxLevelReached = building.level === building.maxLevel;


    function upgradeBuilding() {
        moves.upgradeBuilding(building.id);
        return false;
    }
</script>

<div class="building">
    <div class="illustration">
        <img src="/img/buildings/{ building.type }.png" alt="">
    </div>
    <div class="content">
        <!-- <p>{ building.name }</p> -->
        <div class="level">
            <button
                class:can-upgrade={ canUpgrade }
                class:is-upgrading={ isUpgrading }
                class:max-level={ maxLevelReached }
                on:click|stopPropagation={ upgradeBuilding }
            >
                { building.level }
                { #if building.state.upgrade.isUpgrading }
                <span>
                    ({ Math.ceil(building.state.upgrade.remainingTime / 1000) }’)
                </span>
                { /if }
            </button>
        </div>
    </div>
</div>

<style>
    .building {
        position: relative;
        height: 100%;
    }

    .building .illustration,
    .building .illustration img {
        width: 100%;
    }

    .building .content {
        left: 0;
        height: 100%;
        position: absolute;
        top: 0;
        width: 100%;
    }

    .level {
        bottom: -0.4em;
        left: 50%;
        position: absolute;
        translate: -50%;
    }

    .level button {
        aspect-ratio: 1;
        background-color: hsl(208, 100%, 97%);
        border: 0.4em solid hsl(0, 0%, 45%);
        border-radius: 100%;
        box-sizing: border-box;
        box-shadow: 0 0 0.2em black;
        color: hsl(0, 0%, 10%);
        font-size: 1.2em;
        transition: all 100ms ease-in-out;
    }

    .level button span {
        font-size: 0.9em;
    }

    .level button.can-upgrade {
        border-color: hsl(90, 99%, 36%);
    }

    .level button.is-upgrading {
        border-color: hsl(56, 99%, 43%);
    }

    .level button.max-level {
        border-color: hsl(209, 70%, 52%);
    }

    .level button:hover {
        scale: 1.1;
    }
</style>
