import { useRouteMeta }                        from '@/router/hooks/useRouteMeta';
import { defaultDocument, tryOnBeforeUnmount } from '@vueuse/core';
import type { Ref }                            from 'vue';


let title: Ref<string>;


export function useTitle() {
  const defaultValue = import.meta.env.SIX_APP_TITLE;

  title ??= useRouteMeta('title', defaultValue);

  function format(t: string) {
    const template = t === defaultValue ? '%s' : `%s | ${ import.meta.env.SIX_APP_TITLE }`;
    return toValue(template).replace(/%s/g, t);
  }


  const handle = watch(
    title,
    (t, o) => {
      if ( t !== o && defaultDocument ) {
        defaultDocument.title = format(typeof t === 'string' ? t : '');
      }
    },
    { immediate: true },
  );

  tryOnBeforeUnmount(handle);

  return title;
}
