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

import { computed } from 'vue'

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

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)

const items = computed(() =>
  props.blockOrder
    .filter(id => props.blocks[id]?.type === 'intro_item')
    .map(id => ({
      id,
      block: props.blocks[id]!,
      renderedText: renderInlineContent(props.blocks[id]!.settings.text),
    })),
)

const { editableAttrs, blockEditableAttrs } = 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>
  <section>
    <p class="section-intro">
      <!-- eslint-disable-next-line vue/no-v-html -->
      <span v-if="s.bold_text" class="section-intro-bold" v-bind="editableAttrs('bold_text')" v-html="s.bold_text" />
      <!-- eslint-disable-next-line vue/no-v-html -->
      <span v-if="s.intro_text" v-bind="editableAttrs('intro_text')" v-html="s.intro_text" />
    </p>
    <ul v-if="items.length" class="section-intro-list">
      <li v-for="item in items" :key="item.id">
        <!-- eslint-disable-next-line vue/no-v-html -->
        <span v-bind="blockEditableAttrs(item.id, 'text')" v-html="item.renderedText" />
      </li>
    </ul>
    <!-- eslint-disable-next-line vue/no-v-html -->
    <p v-if="s.trailing_text" class="section-intro" v-bind="editableAttrs('trailing_text')" v-html="s.trailing_text" />
  </section>
</template>
