<template>
    <div class="basketItems">
        <h5>Items</h5>

        <section
            v-for="item in items"
            :key="item.id"
            class="basketItem"
        >
            <div
                class="basketItemInner"
                :data-id="item.id"
                :class="{ 'bagItemStockError': item.stock_error }"
            >
                <!-- Item Image -->
                <div class="basketItemImage">
                    <a
                        class="imageWrap"
                        :class="{ emptyImage: !item.item_image }"
                        :href="safeHref(item.item_url)"
                    >
                        <img
                            :src="item.item_image || placeholderImageUrl"
                            :alt="item.name"
                        >
                    </a>
                </div>

                <!-- Item Description -->
                <div class="basketItemDescription">
                    <!-- NHS Prescription Item -->
                    <div v-if="item.nhs_prescription_item" class="descRow">
                        <span class="itemTitle">
                            {{ item.nhs_prescription_item.name }}
                        </span>
                    </div>

                    <!-- Regular Item -->
                    <div v-else class="descRow">
                        <a
                            class="itemTitle"
                            v-if="!item.disable_url"
                            :href="safeHref(item.item_url)"
                            v-text="item.item_name"
                        ></a>
                        <span
                            class="itemTitle"
                            v-else
                            v-text="item.item_name"
                        ></span>
                    </div>

                    <!-- Additional Info -->
                    <div class="descRow" v-if="item.additional">
                        <!-- v-html: 'html' field emitted by plugins via BasketGetItemsEvent (trusted, generated server-side) -->
                        <div
                            v-for="(addition, addIndex) in item.additional"
                            :key="addIndex"
                            v-html="addition.html"
                            class="additionals"
                        ></div>
                    </div>

                    <!-- Item Size -->
                    <div class="descRow" v-if="showSizes">
                        <div
                            v-if="typeof item.size === 'string'"
                            v-text="item.size"
                            class="itemSize"
                        ></div>
                        <div v-else-if="item.size" class="itemSizes">
                            <ul>
                                <li
                                    v-for="(itemSizeString, sizeIndex) in item.size"
                                    :key="sizeIndex"
                                    v-text="itemSizeString"
                                />
                            </ul>
                        </div>
                    </div>

                    <!-- Group Buy Items -->
                    <div class="descRow" v-if="item.included_groupbuy_items">
                        <ul>
                            <li
                                v-for="(includedItem, gbIndex) in item.included_groupbuy_items"
                                :key="gbIndex"
                            >
                                <a
                                    :href="safeHref(includedItem.url)"
                                    v-text="includedItem.name"
                                    target="_blank"
                                    rel="noopener noreferrer"
                                ></a>
                            </li>
                        </ul>
                    </div>

                    <!-- Subscription Management -->
                    <div class="descRow" v-if="item.manage_subscription_button">
                        <span v-if="item.manage_subscription_button.url">
                            <a
                                :href="safeHref(item.manage_subscription_button.url)"
                                v-text="item.manage_subscription_button.label"
                            ></a>
                        </span>
                        <span v-else>
                            <p v-text="item.manage_subscription_button.label"></p>
                        </span>
                    </div>

                    <!-- NHS Quantity -->
                    <div v-if="item.nhs_prescription_item" class="descRow">
                        <span>{{ item.nhs_prescription_item.quantity }}</span>
                    </div>

                    <!-- Quantity Input -->
                    <div v-else class="descRow descQuantity">
                        <span class="descLabel">
                            Quantity:
                            <span v-if="!canEditItemQty(item)" v-text="item.quantity"></span>
                        </span>

                        <div class="row" v-if="canEditItemQty(item)">
                            <input
                                class="bagItemQuantity"
                                type="number"
                                min="0"
                                maxlength="3"
                                :value="item.quantity"
                                :name="'quantity_' + item.id"
                                :id="'item_' + item.id"
                                @input="onQuantityChange(item, $event)"
                                @blur="onQuantityBlur(item)"
                                autocomplete="off"
                            >
                        </div>
                    </div>
                </div>

                <!-- Item Totals -->
                <div class="basketItemTotals">
                    <div
                        class="basketItemActions"
                        v-if="!hideInputs && item.can_remove"
                    >
                        <button
                            type="button"
                            @click.prevent="onRemoveItem(item)"
                            class="itemDeleteButton"
                            aria-label="Remove item"
                        >
                            <font-awesome-icon :icon="['far', 'trash']" />
                        </button>
                    </div>

                    <!-- Price Display -->
                    <!-- v-html: formatPrice() returns the multi_currency filter's HTML markup (multiPriceBlock spans) -->
                    <div v-if="item.no_vat" class="itemPrice">
                        <del v-html="formatPrice(item.original_total)"></del>
                        <span v-html="formatPrice(item.line_total_exvat)"></span>
                    </div>
                    <div v-else class="itemPrice">
                        <span v-if="item.item_price != item.original_price">
                            <del v-html="formatPrice(item.original_total)"></del>
                        </span>
                        <span v-html="formatPrice(item.line_total)"></span>
                    </div>
                </div>
            </div>

            <!-- Item Alerts -->
            <basket-item-alerts :item="item" />
        </section>
    </div>
</template>

<script>
import BasketItemAlerts from './basket_item_alerts.vue';

export default {
    name: 'basket-items',

    // Injected from parent checkout component (multiCurrency method).
    // Falls back to GBP formatting if used outside the checkout context.
    inject: {
        formatPrice: {
            default: () => (value) => {
                const amount = parseFloat(value) || 0;
                return '\u00A3' + amount.toFixed(2);
            }
        }
    },

    components: {
        BasketItemAlerts
    },

    props: {
        items: {
            type: Array,
            default: () => []
        },
        hideInputs: {
            type: [Boolean, Number],
            default: false
        },
        placeholderImage: {
            type: [String, Boolean],
            default: false
        },
        showSizes: {
            type: Boolean,
            default: true
        },
        site: {
            type: String,
            default: 'default'
        }
    },

    computed: {
        placeholderImageUrl() {
            if (this.placeholderImage) {
                return this.placeholderImage;
            }
            return `/sites/${this.site}/images/placeholders/no-image-items-thumb.png`;
        }
    },

    methods: {
        // Normalise a payload-provided URL and allow only http(s) so a javascript:/data: scheme
        // can't slip into a checkout link.
        safeHref(rawUrl) {
            if (typeof rawUrl !== 'string' || !rawUrl.trim()) {
                return '#';
            }
            try {
                const parsed = new URL(rawUrl, window.location.origin);
                return ['http:', 'https:'].includes(parsed.protocol) ? parsed.href : '#';
            } catch (err) {
                return '#';
            }
        },

        canEditItemQty(item) {
            if (typeof item.quantity_lock === 'undefined') {
                return !this.hideInputs;
            }
            return !(this.hideInputs || item.quantity_lock);
        },

        onQuantityChange(item, event) {
            // type="number" ignores maxlength, so clamp to a sane 0-999 range before emitting.
            const parsed = Number.parseInt(event.target.value, 10);
            const newQuantity = Number.isNaN(parsed) ? 0 : Math.max(0, Math.min(parsed, 999));
            this.$emit('change-stock', { ...item, quantity: newQuantity });
        },

        onQuantityBlur(item) {
            this.$emit('update-stock', item);
        },

        onRemoveItem(item) {
            this.$emit('remove-item', item);
        }
    }
};
</script>
