<script setup lang="ts">
import { toRefs } from 'vue';
import { storeToRefs } from 'pinia'
import DynamicComponents from '@/apps/settings/components/DynamicComponents.vue';
import ImporterTool from '@/apps/settings/components/ImporterTool.vue';
import {
  purifyHtml,
} from '@/helper';
import { useSettingsStore } from '@/stores/settings-store'

const props = defineProps({
  sectionData: {
    type: Object,
    required: true,
  },
  parentTab: {
    type: String,
    required: true,
  },
  childTab: {
    type: String,
    required: true,
  },
})
const { sectionData, parentTab, childTab } = toRefs(props)

// Check if this is the importer section
const isImporterSection = childTab.value === 'importer' && Object.keys(sectionData.value).includes('importer_settings')

const settingsStore = useSettingsStore()
const {
  inputValues,
} = storeToRefs(settingsStore)

const sections = sectionData;
const parent = parentTab;
const child = childTab;

const emit = defineEmits(['fieldData']);
const handleFieldData = (data: object) => {
  Object.entries(data).forEach(([key, value]) => {
    inputValues.value[key] = value;
  });
  emit('fieldData', inputValues.value);
}
</script>

<template>
  <section
    v-for="(section, sectionkey) in sections"
    :key="sectionkey"
    class="stw-section-handle stwlite-tw-bg-white stwlite-tw-rounded-lg stwlite-tw-shadow-sm stwlite-tw-border stwlite-tw-border-gray-200 stwlite-tw-p-6 stwlite-tw-space-y-6 stwlite-tw-border-solid"
  >
    <h3
      v-if="section.label"
      class="stwlite-tw-font-medium stwlite-tw-text-gray-900 stwlite-tw-m-0"
    >
      {{ section.label }}
    </h3>
    <div
      v-if="section.desc != ''"
      class="stwlite-tw-text-sm stwlite-tw-text-gray-600 stwlite-tw-mt-1"
      v-html="purifyHtml(section.desc?.length ? section.desc : '')"
    />

    <!-- Load ImporterTool for importer section -->
    <ImporterTool v-if="isImporterSection && sectionkey === 'importer_settings'" />

    <!-- Load controls for other sections -->
    <DynamicComponents
      v-else
      :section-parent="parent"
      :section-child="child"
      :section-key="sectionkey"
      @field-data="handleFieldData"
    />
  </section>
</template>

<style lang="scss" scoped>
  
</style>