<script setup lang="ts">
import type { BlockData } from '@vigilkids/section-core'

import { computed } from 'vue'

import { useInlineEdit } from '../../../composables/useInlineEdit'

const props = defineProps<{
  blockOrder: string[]
  blocks: Record<string, BlockData>
  editorMode?: boolean
  settings: Record<string, unknown>
}>()

const emit = defineEmits<{
  (e: 'update:setting', key: string, value: unknown): void
  (e: 'update:block-setting', blockId: string, key: string, value: unknown): void
  (e: 'inline-edit-start', key: string): void
  (e: 'inline-edit-end'): void
  (e: 'undo-redo', action: 'redo' | 'undo'): void
}>()

const s = computed(() => props.settings)

interface ColumnDef {
  label: string
  min_width?: number
}

function parseJsonOrArray<T>(value: unknown): T[] {
  if (Array.isArray(value))
    return value as T[]
  if (typeof value === 'string') {
    try {
      const parsed = JSON.parse(value)
      if (Array.isArray(parsed))
        return parsed as T[]
    }
    catch {
      /* JSON 解析失败，返回空数组 */
    }
  }
  return []
}

const isSticky = computed(() => String(s.value.variant) === 'sticky')

const columns = computed<ColumnDef[]>(() => parseJsonOrArray<ColumnDef>(s.value.columns))

const rows = computed(() =>
  props.blockOrder
    .filter(id => props.blocks[id]?.type === 'table-row')
    .map((id) => {
      const block = props.blocks[id]!
      return { id, cells: parseJsonOrArray<string>(block.settings.cells) }
    }),
)

// 保留完整 5-emit 契约，与其他 section 统一；columns/cells 为 JSON 聚合字段，内联编辑暂由配置面板承担
useInlineEdit({
  editorMode: () => !!props.editorMode,
  onSettingUpdate: (key, value) => emit('update:setting', key, value),
  onBlockSettingUpdate: (blockId, key, value) => emit('update:block-setting', blockId, key, value),
  onEditStart: key => emit('inline-edit-start', key),
  onEditEnd: () => emit('inline-edit-end'),
  onUndoRedo: action => emit('undo-redo', action),
})
</script>

<template>
  <div class="contrast-table" :class="[{ 'sticky-table': isSticky }]">
    <table cellspacing="0">
      <thead align="left">
        <tr>
          <!-- eslint-disable-next-line vue/no-v-html -->
          <th
            v-for="(col, idx) in columns"
            :key="idx"
            :style="col.min_width ? { minWidth: `${col.min_width}px` } : undefined"
            v-html="col.label"
          />
        </tr>
      </thead>
      <tbody align="left">
        <tr v-for="row in rows" :key="row.id">
          <!-- eslint-disable-next-line vue/no-v-html -->
          <td v-for="(cell, cellIdx) in row.cells" :key="cellIdx" v-html="cell" />
        </tr>
      </tbody>
    </table>
  </div>
</template>
