import { describe, expect, it } from "vitest";
import { fmt, getDictionary } from "@/lib/i18n";
import { isLocale, localePath, otherLocalePath, stripLocale } from "@/lib/i18n/config";

function keys(value: unknown, prefix = ""): string[] {
  if (Array.isArray(value)) return value.map((_, index) => `${prefix}[${index}]`);
  if (value && typeof value === "object") {
    return Object.entries(value).flatMap(([key, child]) => keys(child, prefix ? `${prefix}.${key}` : key));
  }
  return [prefix];
}

describe("locale helpers", () => {
  it("recognises supported locales only", () => {
    expect(isLocale("fr")).toBe(true);
    expect(isLocale("ar")).toBe(true);
    expect(isLocale("de")).toBe(false);
    expect(isLocale(undefined)).toBe(false);
  });

  it("builds, strips and switches locale paths", () => {
    expect(localePath("en", "/shop")).toBe("/en/shop");
    expect(localePath("ar")).toBe("/ar");
    expect(localePath("fr", "/en/shop")).toBe("/fr/shop");
    expect(stripLocale("/ar/shop/rug")).toBe("/shop/rug");
    expect(stripLocale("/shop/rug")).toBe("/shop/rug");
    expect(otherLocalePath("/fr/shop/rug", "en")).toBe("/en/shop/rug");
    expect(otherLocalePath("/fr", "ar")).toBe("/ar");
  });
});

describe("dictionaries", () => {
  it("share the same key structure across FR, EN and AR", () => {
    const fr = keys(getDictionary("fr")).sort();
    expect(keys(getDictionary("en")).sort()).toEqual(fr);
    expect(keys(getDictionary("ar")).sort()).toEqual(fr);
  });

  it("exposes localised copy", () => {
    expect(getDictionary("fr").nav.shop).toBe("Boutique");
    expect(getDictionary("en").nav.shop).toBe("Shop");
    expect(getDictionary("ar").nav.shop).toBe("المتجر");
  });

  it("interpolates known variables and keeps unknown placeholders", () => {
    expect(fmt("Bonjour {name}", { name: "Youssef" })).toBe("Bonjour Youssef");
    expect(fmt("{count} articles", { count: 3 })).toBe("3 articles");
    expect(fmt("Hello {missing}", {})).toBe("Hello {missing}");
  });
});
