<template>
  <div v-html="parsedContent"></div>
</template>

<script>
import { createApp, h, ref, watch } from 'vue';
import WorshipRender from './WorshipRender.vue';
import ImageRender from './ImageRender.vue';

export default {
  name: 'RenderContentComponent',
  props: {
    content: {
      type: String,
      required: true,
    },
  },
  setup(props) {
    const parsedContent = ref('');

    const renderContent = (content) => {
      let result = renderWorship(content);
      result = renderImage(content);
      return result;
    };

    const renderWorship = (content) => {
      const worshipsPattern = /{{ worshipslist:(.*?) }}/g;
      let result = content;
      result = result.replace(worshipsPattern, (match, config) => {
        const props = parseConfig(config);
        const placeholderId = `worship-render-placeholder-${Math.random().toString(36).substr(2, 9)}`;
        setTimeout(() => {
          const placeholder = document.getElementById(placeholderId);
          if (placeholder) {
            const app = createApp({
              render() {
                return h(WorshipRender, props);
              },
            });
            app.mount(placeholder);
          }
        }, 0);
        return `<div id="${placeholderId}"></div>`;
      });
      return result;
    }

    const renderImage = (content) => {
      const imagePattern = /{{ image:(.*?) }}/g;
      let result = content;
      result = result.replace(imagePattern, (match, config) => {
        const placeholderId = `image-render-placeholder-${Math.random().toString(36).substr(2, 9)}`;
        setTimeout(() => {
          const placeholder = document.getElementById(placeholderId);
          if (placeholder) {
            const app = createApp({
              render() {
                console.log(config);
                return h(ImageRender, { 'id': config });
              },
            });
            app.mount(placeholder);
          }
        }, 0);
        return `<span id="${placeholderId}"></span>`;
      });
      return result;
    }

  const parseConfig = (configString) => {
    const config = {};
    const configArray = configString.split(',');
    configArray.forEach((item) => {
      const [key, value] = item.split('=');
      if (key && value !== undefined) {
        config[key.trim()] = isNaN(value) ? value.trim() : Number(value);
      }
    });
    return config;
  };

  watch(
      () => props.content,
  (newContent) => {
    parsedContent.value = renderContent(newContent);
  },
  { immediate: true }
    );

return {
  parsedContent,
};
  },
};
</script>

<style scoped>
/* Add styles if needed */
</style>
