import { defineComponent } from 'vue';
import { SbMain, SbMode } from '@schlechtenburg/core';
import PageToolbar from '~~/components/PageToolbar';
import SbLayout from '@schlechtenburg/layout';
import SbHeading from '@schlechtenburg/heading';
import SbParagraph from '@schlechtenburg/paragraph';
import SbImage from '@schlechtenburg/image';

export default defineComponent({
  async setup() {
    const { me } = useMe();

    const loggedIn = computed(() => !!me.value?.id);

    const { currentPage } = useCurrentPage();
    const block = computed(() => currentPage.value?.attributes?.block);

    const {
      mode,
      draft,
      updateDraft,
    } = useEditor();

    watchEffect(() => {
      updateDraft(block.value!);
    });


    if (!block) {
      console.error('No block!');
      console.error('page', currentPage.value);
    }

    return () => (
      <div class="ex-page">
        {loggedIn.value ? <PageToolbar></PageToolbar> : null}
        {draft.value
        ? <SbMain
          class="ex-page"
          mode={mode.value}
          eventUpdate={(updatedBlock) => updateDraft(updatedBlock)}
          block={draft.value}
          availableBlocks={[
            SbLayout,
            SbHeading,
            SbParagraph,
            SbImage,
          ]}
        />
        : <div class="ex-page ex-page_corrupt">Corrupt page: {currentPage.value?.attributes?.slug} ({currentPage.value?.id})</div>}
      </div>
    );
  },
});
