<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from "vue";
import { Ckeditor } from "@ckeditor/ckeditor5-vue";
import { ClassicEditor } from "ckeditor5";
import classicEditorConfig from "ChillMainAssets/module/ckeditor5/editor_config";
import {
  trans,
  EDITOR_SWITCH_TO_SIMPLE,
  EDITOR_SWITCH_TO_COMPLEX,
} from "translator";

const EDITOR_MODE_KEY = "editorMode";
const kind = ref<"simple" | "rich">("simple");
const value = defineModel({ required: true });

const isSimple = computed(() => kind.value === "simple");

const toggleButtonClass = computed(() => {
  return {
    ["toggle-button"]: true,
    onEditor: !isSimple.value,
    onSimple: isSimple.value,
  };
});

const toggleEditor = () => {
  let newValue;

  newValue = kind.value === "simple" ? "rich" : "simple";
  kind.value = "rich";
  window.localStorage.setItem(EDITOR_MODE_KEY, newValue);

  window.dispatchEvent(new Event("toggleEditorKind"));
};

const onKindChange = function (/* event: StorageEvent | Event */) {
  const newValue = window.localStorage.getItem(EDITOR_MODE_KEY);

  if (null === newValue || !(newValue === "rich" || newValue === "simple")) {
    throw "invalid new value: " + newValue;
  }

  if (kind.value !== newValue) {
    kind.value = newValue;
  }
};

onMounted(function () {
  const storage = window.localStorage;
  const savedKind = storage.getItem(EDITOR_MODE_KEY);

  if (null !== kind.value && (savedKind === "simple" || savedKind === "rich")) {
    kind.value = savedKind;
  }

  window.addEventListener("storage", onKindChange);
  window.addEventListener("toggleEditorKind", onKindChange);
});

onUnmounted(function () {
  window.removeEventListener("storage", onKindChange);
  window.removeEventListener("toggleEditorKind", onKindChange);
});
</script>

<template>
  <div>
    <div v-if="'rich' === kind">
      <Ckeditor
        :editor="ClassicEditor"
        :config="classicEditorConfig"
        v-model="value"
      />
    </div>
    <div v-else>
      <textarea v-model="value" class="form-control simple-editor"></textarea>
    </div>

    <button :class="toggleButtonClass" type="button" @click="toggleEditor">
      {{
        isSimple
          ? trans(EDITOR_SWITCH_TO_COMPLEX)
          : trans(EDITOR_SWITCH_TO_SIMPLE)
      }}
    </button>
  </div>
</template>

<style scoped lang="scss">
@import "ChillMainAssets/module/bootstrap/bootstrap";

.toggle-button {
  background: white;
  border: none;
  padding: 0.15rem;
  color: #069;
  cursor: pointer;

  @include media-breakpoint-up(md) {
    &.onEditor {
      position: relative;
      left: 1rem;
      top: -1.5rem;
    }
    &.onSimple {
      position: relative;
      top: -0.75rem;
      left: 1rem;
    }
  }
}

.simple-editor {
  min-height: 190px;
}
</style>
