import {
  WORKPULSE_LOCALE_MESSAGES,
  WORKPULSE_LOCALE_STORAGE_KEY,
  formatLocaleMessage,
  localizedFeatureDefs,
  type WorkpulseLocale,
  type WorkpulseLocaleMessages
} from "~/utils/workpulse-locale-messages";
import type { WorkpulseFeatureKey } from "~/utils/workpulse-permissions";

const DEFAULT_LOCALE: WorkpulseLocale = "id";

function normalizeLocale(raw: string | null | undefined): WorkpulseLocale {
  return raw === "en" ? "en" : "id";
}

export const useWorkpulseLocale = () => {
  const locale = useState<WorkpulseLocale>("workpulse-locale", () => DEFAULT_LOCALE);

  const messages = computed(
    () =>
      WORKPULSE_LOCALE_MESSAGES[normalizeLocale(locale.value)] ??
      WORKPULSE_LOCALE_MESSAGES[DEFAULT_LOCALE]
  );

  const applyLocale = (next: WorkpulseLocale) => {
    locale.value = normalizeLocale(next);
    if (typeof document !== "undefined") {
      document.documentElement.lang = next === "en" ? "en" : "id";
    }
    if (typeof localStorage !== "undefined") {
      localStorage.setItem(WORKPULSE_LOCALE_STORAGE_KEY, next);
    }
  };

  const initLocale = () => {
    if (typeof window === "undefined") return;
    const saved = localStorage.getItem(WORKPULSE_LOCALE_STORAGE_KEY);
    if (saved === "id" || saved === "en") {
      applyLocale(saved);
      return;
    }
    applyLocale("id");
  };

  const toggleLocale = () => {
    applyLocale(locale.value === "id" ? "en" : "id");
  };

  const t = <K extends keyof WorkpulseLocaleMessages>(
    section: K,
    key: keyof WorkpulseLocaleMessages[K] & string
  ): string => {
    const block = messages.value[section] as Record<string, string>;
    return block[key] ?? String(key);
  };

  const formatDate = (date: Date = new Date(), options?: Intl.DateTimeFormatOptions) => {
    const loc = locale.value === "en" ? "en-US" : "id-ID";
    return new Intl.DateTimeFormat(loc, options ?? { month: "long", day: "numeric", year: "numeric" }).format(date);
  };

  const fmt = (template: string, vars: Record<string, string | number>) =>
    formatLocaleMessage(template, vars);

  const featureDefs = computed(() => localizedFeatureDefs(normalizeLocale(locale.value)));

  const weekDayLabels = computed(() => [...messages.value.analyticsExtra.daysShort]);

  return {
    locale,
    messages,
    featureDefs,
    weekDayLabels,
    applyLocale,
    initLocale,
    toggleLocale,
    t,
    formatDate,
    fmt
  };
};
