/**
 * RRYM / 002 — SULSYS
 * Route registry — the single source of truth for every URL on the site.
 *
 * Production Blueprint v1, section 03: fourteen pages per language, flat, product
 * first; Albanian, Macedonian, Turkish and English are parallel trees under
 * /sq, /mk, /tr and /en. Every page exists in all four or in none.
 *
 * Macedonian slugs are Latin transliterations (URL-safe, typeable); titles and
 * content are Cyrillic. Turkish slugs drop the diacritics for the same reason —
 * `uretim`, not `üretim` — so that every URL on the site can be typed from any
 * keyboard and pasted into any system without re-encoding.
 *
 * Brand names are never translated and never transliterated: `nexys` and
 * `sulsys` are the same segment in all four trees, because they are the same
 * word in all four languages.
 *
 * Because the registry holds every locale's segments for every page, the language
 * switch can always resolve the exact counterpart URL rather than falling back to
 * the other home page (Blueprint 03, "Language architecture").
 */

import { LOCALES, type Locale } from "./locales";

/* -------------------------------------------------------------------------- */
/* Page kinds                                                                 */
/* -------------------------------------------------------------------------- */

export const PAGE_KEYS = [
  "home",
  "nexys",
  "module",
  "sectors",
  "sector",
  "clients",
  "support",
  "company",
  "contact",
  "privacy",
  "notFound",
] as const;

export type PageKey = (typeof PAGE_KEYS)[number];

/* -------------------------------------------------------------------------- */
/* Top-level segments                                                         */
/* -------------------------------------------------------------------------- */

type SegmentMap = Record<Locale, string>;

/** Single-segment pages. `home` has no segment. */
const TOP_SEGMENTS = {
  nexys: { sq: "nexys", mk: "nexys", tr: "nexys", en: "nexys" },
  sectors: { sq: "sektoret", mk: "sektori", tr: "sektorler", en: "sectors" },
  clients: { sq: "klientet", mk: "klienti", tr: "referanslar", en: "clients" },
  support: { sq: "mbeshtetje", mk: "poddrshka", tr: "destek", en: "support" },
  company: { sq: "sulsys", mk: "sulsys", tr: "sulsys", en: "sulsys" },
  contact: { sq: "kontakt", mk: "kontakt", tr: "iletisim", en: "contact" },
  privacy: { sq: "privatesia", mk: "privatnost", tr: "gizlilik", en: "privacy" },
  notFound: { sq: "404", mk: "404", tr: "404", en: "404" },
} as const satisfies Record<string, SegmentMap>;

/* -------------------------------------------------------------------------- */
/* Modules — four, under /nexys                                               */
/* -------------------------------------------------------------------------- */

/**
 * Module identity. `id` is the stable content key and never appears in a URL;
 * `code` is the two-digit code shown in the UI in both languages (Blueprint 10).
 *
 * Brand names are Sulsys's own ~2024 marketing names (BLUEPRINT-DELTA D-01); the
 * descriptive name is the subtitle. Slugs stay descriptive, with the brand names
 * registered as redirect aliases.
 */
export const MODULES = [
  {
    id: "financa",
    code: "01",
    brandName: "Nexys Finance",
    alias: "nexys-finance",
    slug: { sq: "financa", mk: "finansii", tr: "finans", en: "finance" },
  },
  {
    id: "materiale",
    code: "02",
    brandName: "Nexys MAT",
    alias: "nexys-mat",
    slug: { sq: "materiale", mk: "materijalno", tr: "stok", en: "inventory" },
  },
  {
    id: "paga",
    code: "03",
    brandName: "Nexys Budget",
    alias: "nexys-budget",
    slug: { sq: "paga", mk: "plata", tr: "bordro", en: "payroll" },
  },
  {
    id: "bar-restorant",
    code: "04",
    brandName: "Nexys Caffe",
    alias: "nexys-caffe",
    slug: { sq: "bar-restorant", mk: "bar-restoran", tr: "bar-restoran", en: "bar-restaurant" },
  },
] as const;

export type ModuleId = (typeof MODULES)[number]["id"];

export const MODULE_IDS = MODULES.map((m) => m.id) as readonly ModuleId[];

export function moduleById(id: string) {
  return MODULES.find((m) => m.id === id);
}

/* -------------------------------------------------------------------------- */
/* Sectors — four clusters, under /sektoret                                   */
/* -------------------------------------------------------------------------- */

export const SECTORS = [
  { id: "tregti", slug: { sq: "tregti", mk: "trgovija", tr: "ticaret", en: "retail" } },
  {
    id: "hoteleri",
    slug: { sq: "hoteleri", mk: "hotelijerstvo", tr: "otelcilik", en: "hospitality" },
  },
  {
    id: "kontabilitet",
    slug: { sq: "kontabilitet", mk: "smetkovodstvo", tr: "muhasebe", en: "accounting" },
  },
  {
    id: "prodhim",
    slug: { sq: "prodhim", mk: "proizvodstvo", tr: "uretim", en: "manufacturing" },
  },
] as const;

export type SectorId = (typeof SECTORS)[number]["id"];

export const SECTOR_IDS = SECTORS.map((s) => s.id) as readonly SectorId[];

export function sectorById(id: string) {
  return SECTORS.find((s) => s.id === id);
}

/* -------------------------------------------------------------------------- */
/* Path building                                                              */
/* -------------------------------------------------------------------------- */

export type RouteTarget =
  | { key: "home" }
  | { key: "nexys" }
  | { key: "module"; module: ModuleId }
  | { key: "sectors" }
  | { key: "sector"; sector: SectorId }
  | { key: "clients" }
  | { key: "support" }
  | { key: "company" }
  | { key: "contact" }
  | { key: "privacy" }
  | { key: "notFound" };

/** Path segments after the locale, for one locale. */
export function segmentsFor(target: RouteTarget, locale: Locale): string[] {
  switch (target.key) {
    case "home":
      return [];
    case "module": {
      const m = moduleById(target.module);
      if (!m) throw new Error(`Unknown module: ${target.module}`);
      return [TOP_SEGMENTS.nexys[locale], m.slug[locale]];
    }
    case "sector": {
      const s = sectorById(target.sector);
      if (!s) throw new Error(`Unknown sector: ${target.sector}`);
      return [TOP_SEGMENTS.sectors[locale], s.slug[locale]];
    }
    default:
      return [TOP_SEGMENTS[target.key][locale]];
  }
}

/** Absolute in-site path, e.g. `/sq/nexys/materiale`. */
export function href(target: RouteTarget, locale: Locale): string {
  const segments = segmentsFor(target, locale);
  return `/${[locale, ...segments].join("/")}`;
}

/* -------------------------------------------------------------------------- */
/* Resolution — slug segments back to a page                                  */
/* -------------------------------------------------------------------------- */

/**
 * Resolve the catch-all segments of `/[locale]/[[...slug]]` to a page.
 * Returns `null` for anything not in the registry, which the page turns into a
 * localised 404.
 */
export function resolveRoute(locale: Locale, slug: string[] | undefined): RouteTarget | null {
  const parts = (slug ?? []).filter((s) => s.length > 0);

  if (parts.length === 0) return { key: "home" };

  if (parts.length === 1) {
    const [first] = parts;
    for (const key of Object.keys(TOP_SEGMENTS) as (keyof typeof TOP_SEGMENTS)[]) {
      if (TOP_SEGMENTS[key][locale] === first) {
        // `/nexys` and `/sektoret` are indexes with children; both are real pages.
        return { key } as RouteTarget;
      }
    }
    return null;
  }

  if (parts.length === 2) {
    const [first, second] = parts;

    if (first === TOP_SEGMENTS.nexys[locale]) {
      const m = MODULES.find((mod) => mod.slug[locale] === second);
      if (m) return { key: "module", module: m.id };
      return null;
    }

    if (first === TOP_SEGMENTS.sectors[locale]) {
      const s = SECTORS.find((sec) => sec.slug[locale] === second);
      if (s) return { key: "sector", sector: s.id };
      return null;
    }
  }

  return null;
}

/* -------------------------------------------------------------------------- */
/* Static generation                                                          */
/* -------------------------------------------------------------------------- */

/** Every page on the site, as a route target. The 404 page is registered too. */
export function allTargets(): RouteTarget[] {
  return [
    { key: "home" },
    { key: "nexys" },
    ...MODULE_IDS.map((module) => ({ key: "module", module }) as RouteTarget),
    { key: "sectors" },
    ...SECTOR_IDS.map((sector) => ({ key: "sector", sector }) as RouteTarget),
    { key: "clients" },
    { key: "support" },
    { key: "company" },
    { key: "contact" },
    { key: "privacy" },
    { key: "notFound" },
  ];
}

/** Pages that belong in the sitemap — everything except the 404. */
export function indexableTargets(): RouteTarget[] {
  return allTargets().filter((t) => t.key !== "notFound");
}

/** `generateStaticParams` output for `/[locale]/[[...slug]]`. */
export function staticParams(): { locale: Locale; slug?: string[] }[] {
  const out: { locale: Locale; slug?: string[] }[] = [];
  for (const locale of LOCALES) {
    for (const target of allTargets()) {
      const segments = segmentsFor(target, locale);
      out.push(segments.length === 0 ? { locale } : { locale, slug: segments });
    }
  }
  return out;
}

/* -------------------------------------------------------------------------- */
/* Redirect aliases (BLUEPRINT-DELTA D-01)                                    */
/* -------------------------------------------------------------------------- */

/**
 * `/sq/nexys/nexys-mat` → `/sq/nexys/materiale`, in every locale, so the names
 * Sulsys uses in its own campaigns resolve to the module pages whichever tree
 * a visitor happens to be in.
 */
export function moduleAliasRedirects(): { source: string; destination: string }[] {
  const out: { source: string; destination: string }[] = [];
  for (const locale of LOCALES) {
    for (const m of MODULES) {
      out.push({
        source: `/${locale}/nexys/${m.alias}`,
        destination: href({ key: "module", module: m.id }, locale),
      });
    }
  }
  return out;
}
