// ─── Attunement Definitions ─────────────────────────────────────────────────────
// Attunements are class-like abilities tied to body locations
// Each provides unique capabilities, primary mana types, and skill access
//
// NEW MODEL: Attunements contribute base conversion rates for their primary mana type.
// Levels provide a multiplicative bonus (+50% per level) to conversions involving
// their primary element (as destination or component).

import type { AttunementDef, AttunementSlot } from '../types';

// Attunement slot display names
export const ATTUNEMENT_SLOT_NAMES: Record<AttunementSlot, string> = {
  rightHand: 'Right Hand',
  leftHand: 'Left Hand',
  head: 'Head',
  back: 'Back',
  chest: 'Chest',
  leftLeg: 'Left Leg',
  rightLeg: 'Right Leg',
};

// All attunement definitions
export const ATTUNEMENTS_DEF: Record<string, AttunementDef> = {
  // ─── Enchanter (Right Hand) ─────────────────────────────────────────────────
  enchanter: {
    id: 'enchanter',
    name: 'Enchanter',
    desc: 'Channel transference mana through your right hand to apply magical enchantments to equipment. The art of enchanting allows you to imbue items with spell effects, stat bonuses, and special properties.',
    slot: 'rightHand',
    icon: '✨',
    color: '#1ABC9C',
    primaryManaType: 'transference',
    rawManaRegen: 0.5,
    conversionRate: 0.2, // Base rate for transference conversion (per hour)
    unlocked: true,
    capabilities: ['enchanting'],
    skillCategories: ['enchant', 'effectResearch'],
  },

  // ─── Invoker (Chest/Heart) ───────────────────────────────────────────────────
  invoker: {
    id: 'invoker',
    name: 'Invoker',
    desc: 'Open your heart to the guardians of the spire. Form pacts with defeated guardians to gain their elemental affinity and access to their unique powers. Each pact grants access to a new mana type.',
    slot: 'chest',
    icon: '💜',
    color: '#9B59B6',
    primaryManaType: undefined,
    rawManaRegen: 0.3,
    conversionRate: 0, // No automatic conversion — mana comes from pacts
    unlocked: false,
    unlockCondition: 'Defeat your first guardian and choose the path of the Invoker',
    capabilities: ['pacts', 'guardianPowers', 'elementalMastery'],
    skillCategories: ['invocation', 'pact'],
  },

  // ─── Fabricator (Left Hand) ──────────────────────────────────────────────────
  fabricator: {
    id: 'fabricator',
    name: 'Fabricator',
    desc: 'Shape earth and metal through your left hand to craft golems and equipment. Start with earthen constructs, and unlock metalworking when you gain fire mana to create metal mana.',
    slot: 'leftHand',
    icon: '⚒️',
    color: '#F4A261',
    primaryManaType: 'earth',
    rawManaRegen: 0.4,
    conversionRate: 0.25, // Base rate for earth conversion (per hour)
    unlocked: false,
    unlockCondition: 'Prove your worth as a crafter',
    capabilities: ['golemCrafting', 'gearCrafting', 'earthShaping'],
    skillCategories: ['fabrication', 'golemancy'],
  },
};

// ─── Helpers ──────────────────────────────────────────────────────────────────

export function getAttunementBySlot(slot: AttunementSlot): AttunementDef | undefined {
  return Object.values(ATTUNEMENTS_DEF).find(a => a.slot === slot);
}

export function getUnlockedAttunements(attunements: Record<string, { active: boolean; level: number; experience: number }>): AttunementDef[] {
  return Object.entries(attunements)
    .filter(([, state]) => state.active)
    .map(([id]) => ATTUNEMENTS_DEF[id])
    .filter(Boolean);
}

/** Total raw mana regen from attunements (with level scaling) */
export function getTotalAttunementRegen(attunements: Record<string, { active: boolean; level: number; experience: number }>): number {
  return Object.entries(attunements)
    .filter(([, state]) => state.active)
    .reduce((total, [id, state]) => {
      const def = ATTUNEMENTS_DEF[id];
      if (!def) return total;
      const levelMult = Math.pow(1.5, (state.level || 1) - 1);
      return total + def.rawManaRegen * levelMult;
    }, 0);
}

/**
 * Get the attunement base conversion rate for a specific attunement.
 * Returns the flat base rate (no level scaling). Level scaling is applied
 * separately in computeConversionRates() via the attunementMult multiplier.
 * @param attunementId - The attunement ID (e.g. 'enchanter', 'fabricator')
 * @param level - The attunement level (unused; kept for API compatibility)
 */
export function getAttunementConversionRate(attunementId: string, _level: number): number {
  const def = ATTUNEMENTS_DEF[attunementId];
  if (!def || def.conversionRate <= 0) return 0;
  return def.conversionRate;
}

/**
 * Get the attunement level multiplier for conversions.
 * Exponential scaling: 1.5^(level-1) per spec §4.3.
 */
export function getAttunementLevelMultiplier(level: number): number {
  return Math.pow(1.5, (level || 1) - 1);
}

/** XP required for attunement level */
export function getAttunementXPForLevel(level: number): number {
  if (level <= 1) return 0;
  if (level === 2) return 1000;
  return Math.floor(1000 * Math.pow(2, level - 2) * (level >= 3 ? 1.25 : 1));
}

export function calculateEnchantingXP(capacityUsed: number): number {
  return Math.max(1, Math.floor(capacityUsed / 10));
}

export const MAX_ATTUNEMENT_LEVEL = 10;

export function getAttunementManaTypes(
  attunements: Record<string, { active: boolean; level: number; experience: number }>,
  signedPacts: number[]
): string[] {
  const manaTypes: string[] = [];
  Object.entries(attunements)
    .filter(([, state]) => state.active)
    .forEach(([id]) => {
      const def = ATTUNEMENTS_DEF[id];
      if (def?.primaryManaType) {
        manaTypes.push(def.primaryManaType);
      }
    });
  if (attunements.invoker?.active && signedPacts.length > 0) {
    manaTypes.push('pactElements');
  }
  return [...new Set(manaTypes)];
}

export function getAvailableSkillCategories(
  attunements: Record<string, { active: boolean; level: number; experience: number }>
): string[] {
  const categories = new Set<string>();
  categories.add('mana');
  categories.add('study');
  categories.add('research');
  Object.entries(attunements)
    .filter(([, state]) => state.active)
    .forEach(([id]) => {
      const def = ATTUNEMENTS_DEF[id];
      if (def?.skillCategories) {
        def.skillCategories.forEach(cat => categories.add(cat));
      }
    });
  return Array.from(categories);
}
