<template>
  <div v-if="shouldRenderField" class="parsed-value">
    <template v-for="entry in renderFieldEntries" :key="entry.key">
      <div v-if="entry.type === 'text'" class="content-body-text">
        {{ entry.value }}
      </div>
      <div v-else-if="entry.type === 'image'" class="content-body-image-card">
        <img class="content-body-image" :src="entry.value.image_id" mode="widthFix"
          @click="handlePredivClick(entry.value.image_id)" />
        <div v-if="entry.value.caption" class="content-body-image-caption">
          {{ entry.value.caption }}
        </div>
      </div>
      <div v-else-if="entry.type === 'list'" class="content-body-list-card">
        <div v-for="(item, index) in entry.value" :key="index" class="content-body-list-item">
          <div class="content-body-list-text">
            {{ formatLeafValue(item) }}
          </div>
        </div>
      </div>
    </template>
  </div>
</template>

<script setup>
import { computed, defineProps } from "vue";

const props = defineProps({
  fieldKey: {
    type: String,
    default: "",
  },
  value: {
    type: [Object, Array, String, Number, Boolean],
    default: null,
  },
});

const IGNORED_FIELD_KEYS = ["container_type", "content", "content_summary", "components"];

const isArrayValue = (value) => Array.isArray(value);

const isObjectValue = (value) => {
  return value !== null && typeof value === "object" && !Array.isArray(value);
};

const parseJsonStringValue = (value) => {
  if (typeof value !== "string") return value;

  const text = value.trim();
  if (!/^[\[{]/.test(text)) return value;

  try {
    return JSON.parse(text);
  } catch (e) {
    return value;
  }
};

const sanitizeValue = (value) => {
  const parsedValue = parseJsonStringValue(value);

  if (isArrayValue(parsedValue)) {
    return parsedValue.map((item) => sanitizeValue(item));
  }
  if (isObjectValue(parsedValue)) {
    return Object.keys(parsedValue).reduce((result, key) => {
      if (IGNORED_FIELD_KEYS.includes(key)) return result;
      result[key] = sanitizeValue(parsedValue[key]);
      return result;
    }, {});
  }
  return parsedValue;
};

const hasDisplayValue = (value) => {
  if (value === undefined || value === null) return false;
  if (typeof value === "string") return !!value.trim();
  if (isArrayValue(value)) return value.some((item) => hasDisplayValue(item));
  if (isObjectValue(value)) {
    const valueObj = sanitizeValue(value);
    return Object.keys(valueObj).some((key) => hasDisplayValue(valueObj[key]));
  }
  return true;
};

const formatLeafValue = (value) => {
  if (value === undefined || value === null) return "";
  if (typeof value === "boolean") return value ? "是" : "否";
  if (typeof value === "object") {
    try {
      return JSON.stringify(sanitizeValue(value));
    } catch (e) {
      return String(value);
    }
  }
  return String(value);
};

const isImageValue = (value) => {
  return isObjectValue(value) && hasDisplayValue(value.image_id);
};

const createImageEntry = (key, value) => ({
  key,
  type: "image",
  value: {
    image_id: formatLeafValue(value.image_id).trim(),
    caption: hasDisplayValue(value.caption) ? formatLeafValue(value.caption) : "",
  },
});

const renderFieldEntries = computed(() => {
  if (isIgnoredField.value || !hasDisplayValue(props.value)) return [];

  const value = sanitizeValue(props.value);
  if (isImageValue(value)) {
    return [createImageEntry(props.fieldKey, value)];
  }

  if (isArrayValue(value)) {
    return [{
      key: props.fieldKey,
      type: "list",
      value: value.filter((item) => hasDisplayValue(item)),
    }];
  }

  if (isObjectValue(value)) {
    return Object.keys(value)
      .filter((key) => hasDisplayValue(value[key]))
      .map((key) => {
        const entryValue = value[key];
        if (isImageValue(entryValue)) {
          return createImageEntry(key, entryValue);
        }
        if (isArrayValue(entryValue)) {
          return {
            key,
            type: "list",
            value: entryValue.filter((item) => hasDisplayValue(item)),
          };
        }
        return {
          key,
          type: "text",
          value: formatLeafValue(entryValue),
        };
      });
  }

  return [{
    key: props.fieldKey,
    type: "text",
    value: formatLeafValue(value),
  }];
});

const isIgnoredField = computed(() => IGNORED_FIELD_KEYS.includes(props.fieldKey));
const shouldRenderField = computed(() => renderFieldEntries.value.length > 0);

const handlePredivClick = (imageUrl) => {
  uni.predivImage({
    current: imageUrl,
    urls: [imageUrl],
  });
};

</script>

<style scoped lang="scss">
.parsed-value {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.content-body-text {
  color: #111827;
  font-size: 15px;
  font-weight: 400;
  line-height: 20px;
}

.content-body-image-card {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.content-body-image {
  width: 100%;
  display: block;
  border-radius: 8px;
  background: #f3f4f6;
}

.content-body-image-caption {
  color: #6b7280;
  font-size: 12px;
  font-weight: 400;
  line-height: 18px;
}

.content-body-list-card {
  display: flex;
  flex-direction: column;
  gap: 4px;
  padding: 12px;
  border-left: 4px solid #0CCD58;
  border-radius: 12px;
  background: rgba(#0CCD58, 0.08);
}

.content-body-list-item {
  display: flex;
  align-items: flex-start;
}

.content-body-list-text {
  flex: 1;
  color: $theme-color-800;
  font-size: 15px;
  font-weight: 400;
  line-height: 20px;
}
</style>
