<template>
    <div id="recipe-ingredients">
        <h2 class="fw-bolder">Ingredients</h2>
        <div class="ingredient row">
            <div v-for="ingredient in sortedIngredients" :key="ingredient.id" class="lh-lg ps-3 col-sm-6">
                <i :class="getIngredientIconClass(ingredient)"></i>
                <span class="ms-3">
                    <template v-if="ingredient.amount !== 0">
                        {{ ingredient.amount }} {{ ingredient.unit }} {{ ingredient.name }}<span v-if="ingredient.state">,{{
                            ingredient.state }}</span>
                    </template>
                    <template v-else>
                        {{ capitalizeFirstLetter(ingredient.name) }}<span v-if="ingredient.state">,{{ ingredient.state
                        }}</span>
                    </template>
                </span>
            </div>
        </div>
    </div>
</template>
  
<script>
export default {
    props: {
        ingredients: {
            type: Array,
            required: true,
        },
    },
    computed: {
        sortedIngredients() {
            return this.ingredients.sort((a, b) => {
                if (a.is_owned && !b.is_owned) {
                    return -1; // `a` comes before `b`
                } else if (!a.is_owned && b.is_owned) {
                    return 1; // `b` comes before `a`
                } else {
                    return 0; // maintain the original order
                }
            });
        },
    },
    methods: {
        getIngredientIconClass(ingredient) {
            return ingredient.is_owned ? 'fa-solid fa-circle-check text-success fa-lg' : 'fa-solid fa-circle-xmark text-danger fa-lg';
        },
        capitalizeFirstLetter(str) {
            return str.charAt(0).toUpperCase() + str.slice(1);
        },
    },
};
</script>
