<template>
  <div class="tree-container" ref="treeContainer">
    <tree-node
        v-if="parsedData"
        :data="parsedData"
        :key-name="'root'"
        :level="0"
        :expanded="allExpanded"
        @toggle="onNodeToggle"
        @resize="onTreeResize"
    />
  </div>
</template>

<script>
import TreeNode from './TreeNode.vue'

export default {
  name: 'JsonTreeViewer',
  components: {
    TreeNode
  },
  props: {
    data: {
      type: [Object, Array, String],
      default: null
    },
    allExpanded: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    parsedData() {
      if (!this.data) return null

      try {
        if (typeof this.data === 'string') {
          return JSON.parse(this.data)
        }
        return this.data
      } catch (error) {
        console.error('Invalid JSON data:', error)
        return null
      }
    }
  },
  methods: {
    toggleAll() {
      this.allExpanded = !this.allExpanded
    },
    onNodeToggle(expanded) {
      // Could be used for tracking expanded states if needed
    },
    onTreeResize() {
      // Force the parent container to recalculate its size
      this.$nextTick(() => {
        if (this.$refs.treeContainer) {
          this.$refs.treeContainer.style.height = 'auto'
        }
      })
    }
  }
}
</script>

<style scoped>
.tree-container {

  backdrop-filter: blur(10px);

  overflow-y: auto;
  /* Remove any fixed height constraints */
  min-height: fit-content;
  height: auto;
}

.tree-container::-webkit-scrollbar {
  width: 8px;
}

.tree-container::-webkit-scrollbar-track {
  background: rgba(0, 0, 0, 0.1);
  border-radius: 4px;
}

.tree-container::-webkit-scrollbar-thumb {
  background: rgba(0, 0, 0, 0.3);
  border-radius: 4px;
}

.tree-container::-webkit-scrollbar-thumb:hover {
  background: rgba(0, 0, 0, 0.4);
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: #666;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
  opacity: 0.5;
}

.empty-state p {
  font-size: 16px;
  margin: 0;
}
</style>