"use client";

import { createContext, useCallback, useContext, useState, type ReactNode } from "react";
import { useRouter } from "next/navigation";
import { Icon } from "@/components/Icon";
import { api } from "@/lib/client";
import { dicts, type Dict } from "@/lib/i18n-dicts";

export type Locale = "ar" | "en";
const LOCALE_COOKIE = "bousla_locale";

type T = Dict;

const LocaleContext = createContext<{ locale: Locale; t: T; setLocale: (l: Locale) => void }>({
  locale: "ar",
  t: dicts.ar,
  setLocale: () => {},
});

export function LocaleProvider({ locale, children }: { locale: Locale; children: ReactNode }) {
  const [current, setCurrent] = useState(locale);
  const router = useRouter();
  const setLocale = useCallback(
    (l: Locale) => {
      document.cookie = `${LOCALE_COOKIE}=${l}; path=/; max-age=31536000; samesite=strict`;
      setCurrent(l);
      // best-effort server persistence across devices
      void api("/api/auth/preferences", "PUT", { locale: l }).catch(() => undefined);
      router.refresh();
    },
    [router],
  );
  return <LocaleContext.Provider value={{ locale: current, t: dicts[current], setLocale }}>{children}</LocaleContext.Provider>;
}

export function useT(): { locale: Locale; t: T; setLocale: (l: Locale) => void } {
  return useContext(LocaleContext);
}

/** Dark-mode toggle: persists to localStorage, flips the .dark class instantly. */
export function ThemeToggle({ className = "" }: { className?: string }) {
  const { t } = useT();
  const toggle = () => {
    const dark = document.documentElement.classList.toggle("dark");
    const theme = dark ? "dark" : "light";
    localStorage.setItem("bousla_theme", theme);
    document.cookie = `bousla_theme=${theme}; path=/; max-age=31536000; samesite=strict`;
    // best-effort server persistence (ignored on the login page where there is no session)
    void api("/api/auth/preferences", "PUT", { theme }).catch(() => undefined);
  };
  return (
    <button
      onClick={toggle}
      title={t.common.theme}
      aria-label={t.common.theme}
      className={`grid h-9 w-9 place-items-center rounded-lg transition hover:bg-white/5 ${className}`}
    >
      <Icon name="sparkles" className="h-5 w-5" />
    </button>
  );
}

/** Language toggle: ar ↔ en via the locale cookie + server refresh (dir flips too). */
export function LanguageToggle({ className = "" }: { className?: string }) {
  const { t, setLocale, locale } = useT();
  return (
    <button
      onClick={() => setLocale(locale === "ar" ? "en" : "ar")}
      title={t.common.language}
      aria-label={t.common.language}
      className={`grid h-9 min-w-9 place-items-center rounded-lg px-1.5 text-xs font-bold transition hover:bg-white/5 ${className}`}
    >
      {t.common.language}
    </button>
  );
}
