<script lang="ts" setup>
import { computed, inject } from 'vue'
import { Messages,Settings } from '~injections'

const { offers, properties } = defineProps<{
    offers: any,
    properties: Array<{name: string, value: string}> | undefined
}>()

const messages = inject(Messages)
const settings = inject(Settings)

const displayProperties = computed(() => {
    if (!properties || !offers?.current?.values || !offers?.properties) return properties || []

    return properties.map(property => {
        const findMatchingProperty = () => {
            let match = offers.properties.find((prop: any) => prop.name === property.name)
            if (match) return match

            const propNameLower = property.name.trim().toLowerCase()
            return offers.properties.find((prop: any) => {
                const foundNameLower = prop.name.trim().toLowerCase()
                return propNameLower.includes(foundNameLower) || foundNameLower.includes(propNameLower)
            })
        }

        const matchedProperty = findMatchingProperty()
        if (matchedProperty) {
            const valueId = offers.current.values[matchedProperty.code]
            const selectedValue = matchedProperty.values?.find((val: any) => val.id === valueId)

            if (selectedValue && !selectedValue.stub) {
                return {
                    name: property.name,
                    value: String(selectedValue.name)
                }
            }
        }

        return {
            name: property.name,
            value: String(property.value)
        }
    })
})

</script>

<template>
  <div v-if="displayProperties.length" class="product-properties">
    <div class="product-properties-header" v-html="messages?.displayProperties?.header"></div>
    <div class="product-properties-values">
      <div
          class="product-properties-property"
          v-for="property in displayProperties"
          :key="property.name"
      >
        <span v-html="property.name"></span>
        <span>&mdash;</span>
        <span v-html="property.value"></span>
      </div>
    </div>
    <a class="product-properties-anchor" href="#properties" v-html="messages?.displayProperties?.anchor"></a>
  </div>
</template>