import type { PluginSimple } from 'markdown-it'
import { tab } from '@mdit/plugin-tab'
import { cleanMarkdownEnv } from '../utils/cleanMarkdownEnv.js'
import { stringifyProp } from '../utils/stringifyProp.js'

/**
 * Tabs plugin - Enable tabs container
 *
 * 标签页插件 - 启用标签页容器
 *
 * Syntax:
 * ```md
 * :::tabs
 * @tab Tab 1
 * Content 1
 * @tab Tab 2
 * Content 2
 * :::
 * ```
 *
 * @param md - Markdown-it instance / Markdown-it 实例
 */
export const tabs: PluginSimple = (md) => {
  tab(md, {
    name: 'tabs',

    openRender: ({ active, data }, tokens, index, _, env) => {
      const { meta } = tokens[index]
      const titles = data.map(({ title }) => md.renderInline(title, cleanMarkdownEnv(env)))
      const tabsData = data.map((item, dataIndex) => {
        const { id = titles[dataIndex] } = item

        return { id }
      })

      return `<Tabs id="${index}" :data='${stringifyProp(tabsData)}'${active === -1 ? '' : ` :active="${active}"`}${meta.id ? ` tab-id="${meta.id as string}"` : ''}>
${titles.map((title, titleIndex) =>
  `<template #title${titleIndex}="{ value, isActive }">${title}</template>`,
).join('')}`
    },

    closeRender: () => `</Tabs>`,

    tabOpenRender: ({ index }) =>
      `<template #tab${index}="{ value, isActive }">`,

    tabCloseRender: () => `</template>`,
  })
}
