type Alignment = "Lawful" | "Neutral" | "Chaotic";
type CharClass = "Fighter" | "Priest" | "Thief" | "Wizard";

// Title table from the Shadowdark Player Quickstart
// [level range min, level range max, lawful, chaotic, neutral]
const TITLES: Record<CharClass, [number, number, string, string, string][]> = {
  Fighter: [
    [1, 2, "Squire", "Knave", "Warrior"],
    [3, 4, "Cavalier", "Bandit", "Barbarian"],
    [5, 6, "Knight", "Slayer", "Battlerager"],
    [7, 8, "Thane", "Reaver", "Warchief"],
    [9, 10, "Lord", "Warlord", "Chieftain"],
  ],
  Priest: [
    [1, 2, "Acolyte", "Initiate", "Seeker"],
    [3, 4, "Crusader", "Zealot", "Invoker"],
    [5, 6, "Templar", "Cultist", "Haruspex"],
    [7, 8, "Champion", "Scourge", "Mystic"],
    [9, 10, "Paladin", "Chaos Knight", "Oracle"],
  ],
  Thief: [
    [1, 2, "Footpad", "Thug", "Robber"],
    [3, 4, "Burglar", "Cutthroat", "Outlaw"],
    [5, 6, "Rook", "Shadow", "Rogue"],
    [7, 8, "Underboss", "Assassin", "Renegade"],
    [9, 10, "Boss", "Wraith", "Bandit King"],
  ],
  Wizard: [
    [1, 2, "Apprentice", "Adept", "Shaman"],
    [3, 4, "Conjurer", "Channeler", "Seer"],
    [5, 6, "Arcanist", "Witch", "Warden"],
    [7, 8, "Mage", "Diabolist", "Sage"],
    [9, 10, "Archmage", "Sorcerer", "Druid"],
  ],
};

const ALIGNMENT_INDEX: Record<Alignment, 0 | 1 | 2> = {
  Lawful: 0,
  Chaotic: 1,
  Neutral: 2,
};

export function getShadowdarkTitle(
  charClass: string,
  alignment: string,
  level: number
): string | null {
  const classTable = TITLES[charClass as CharClass];
  if (!classTable) return null;

  const alignIndex = ALIGNMENT_INDEX[alignment as Alignment];
  if (alignIndex === undefined) return null;

  const clampedLevel = Math.min(Math.max(level, 1), 10);
  const row = classTable.find(([min, max]) => clampedLevel >= min && clampedLevel <= max);
  if (!row) return null;

  return row[2 + alignIndex] as string;
}
