import { defineStore } from 'pinia';
import { computed, ref, watch } from 'vue';
import { commentaryReplicant } from '../../../browser_shared/replicants';
import type { Schemas } from '../../../types';

type Commentary = Schemas.Commentary;

const defaultCommentary: Commentary = {
  leftCommentator: '',
  rightCommentator: '',
};

const normalizeCommentary = (input: unknown): Commentary => {
  const candidate = typeof input === 'object' && input !== null ? (input as Record<string, unknown>) : {};
  return {
    leftCommentator: typeof candidate.leftCommentator === 'string' ? candidate.leftCommentator : '',
    rightCommentator: typeof candidate.rightCommentator === 'string' ? candidate.rightCommentator : '',
  };
};

export const useCommentaryStore = defineStore('commentary', () => {
  const commentary = ref<Commentary>({ ...defaultCommentary });
  const replicant = commentaryReplicant;
  const isApplyingReplicant = ref(false);

  watch(
    () => replicant?.data,
    (value) => {
      if (!value) {
        return;
      }
      isApplyingReplicant.value = true;
      commentary.value = normalizeCommentary(value);
      isApplyingReplicant.value = false;
    },
    { deep: true, immediate: true },
  );

  watch(
    commentary,
    (value) => {
      if (isApplyingReplicant.value || !replicant) {
        return;
      }
      replicant.data = normalizeCommentary(value);
      replicant.save();
    },
    { deep: true, flush: 'sync' },
  );

  const leftCommentator = computed({
    get: () => commentary.value.leftCommentator,
    set: (value: string) => {
      commentary.value = {
        ...commentary.value,
        leftCommentator: value,
      };
    },
  });

  const rightCommentator = computed({
    get: () => commentary.value.rightCommentator,
    set: (value: string) => {
      commentary.value = {
        ...commentary.value,
        rightCommentator: value,
      };
    },
  });

  const swapCommentators = () => {
    commentary.value = {
      leftCommentator: commentary.value.rightCommentator,
      rightCommentator: commentary.value.leftCommentator,
    };
  };

  return {
    commentary,
    leftCommentator,
    rightCommentator,
    swapCommentators,
  };
});
