// ─── Core Game State Types ───────────────────────────────────────────────

import type { AttunementState } from './attunements';
import type { ElementState } from './elements';
import type { SpellState } from './spells';
import type { EquipmentInstance, EnchantmentDesign, DesignProgress, PreparationProgress, ApplicationProgress, EquipmentCraftingProgress, BlueprintDef, LootInventory, EquipmentSpellState } from './equipment';

// ─── Activity Log Types ─────────────────────────────────────────────────
export type ActivityEventType = 
  | 'combat'
  | 'damage_dealt'
  | 'enemy_defeated'
  | 'floor_cleared'
  | 'floor_transition'
  | 'special_effect'
  | 'dodge'
  | 'armor_proc'
  | 'spell_cast'
  | 'golem_attack'
  | 'puzzle_solved'
  | 'debuff';

export interface ActivityLogEntry {
  id: string;                    // Unique ID for React key
  timestamp: number;             // Game time (day + hour) when event occurred
  eventType: ActivityEventType;  // Type of combat event
  message: string;               // Human-readable message
  details?: {
    damage?: number;
    enemyName?: string;
    floor?: number;
    spellName?: string;
    effectName?: string;
  };
}

// ─── Room and Enemy Types ─────────────────────────────────────────────────────

export type RoomType = 'combat' | 'puzzle' | 'swarm' | 'speed' | 'guardian' | 'recovery' | 'library' | 'treasure';

export type EffectType =
  | 'burn'
  | 'poison'
  | 'bleed'
  | 'freeze'
  | 'slow'
  | 'curse'
  | 'armor_corrode'
  | 'blind';

export interface ActiveEffect {
  type: EffectType;
  remainingDuration: number;  // in ticks
  magnitude: number;
  source: 'spell' | 'golem';
  bypassArmor?: boolean;
  bypassBarrier?: boolean;
}

export interface EnemyState {
  id: string;
  name: string;             // Display name for the enemy
  hp: number;
  maxHP: number;
  armor: number;            // Damage reduction (0-1)
  dodgeChance: number;      // For speed rooms (0-1)
  barrier?: number;         // Percentage damage reduction (0-1), e.g. from mage modifier
  shieldPool?: number;      // Flat HP one-time shield pool (spec §5.1), e.g. from shield modifier
  element: string;
  activeEffects: ActiveEffect[];  // DoT/debuff effects currently on this enemy
  effectiveArmor: number;         // Armor after corrode effects (0-1)
}

export interface FloorState {
  roomType: RoomType;
  enemies: EnemyState[];      // For swarm rooms, multiple enemies
  puzzleProgress?: number;    // For puzzle rooms (0-1)
  puzzleRequired?: number;    // Total progress needed
  puzzleId?: string;          // Which puzzle type
  puzzleAttunements?: string[]; // Which attunements speed up this puzzle
  cleared?: boolean;            // Whether this floor has been cleared
  // Recovery room fields
  recoveryProgress?: number;
  recoveryRequired?: number;
  recoveryStayed?: boolean;
  // Library room fields
  libraryProgress?: number;
  libraryRequired?: number;
  libraryStayed?: boolean;
  // Treasure room fields
  treasureProgress?: number;
  treasureRequired?: number;
  treasureLoot?: LootDrop[];
  treasureLootClaimed?: number[];

  // Room enchantment state — null when no footwear room enchants are equipped
  roomEnchantment?: {
    coverage: number;   // 0-100
  } | null;
}

// ─── Achievement Types ─────────────────────────────────────────────────────

export interface AchievementDef {
  id: string;
  name: string;
  desc: string;
  category: string;
  requirement: {
    type: string;
    value: number;
    subType?: string;
  };
  reward: {
    insight?: number;
    manaBonus?: number;
    damageBonus?: number;
    regenBonus?: number;
    title?: string;
    unlockEffect?: string;
  };
  hidden?: boolean;
}

// Achievement state tracks unlocked achievements and progress
export interface AchievementState {
  unlocked: string[];              // IDs of unlocked achievements
  progress: Record<string, number>; // Progress toward achievement requirements
}

// ─── Game Actions and Scheduling ─────────────────────────────────────────

export type GameAction = 'meditate' | 'practicing' | 'climb' | 'study' | 'craft' | 'repair' | 'convert' | 'design' | 'prepare' | 'enchant';

export interface ScheduleBlock {
  id: string;
  action: GameAction;
  startHour: number;
  endHour: number;
  enabled: boolean;
  target?: string;          // spell id, blueprint id, skill id, element id
}

export interface StudyTarget {
  type: 'skill' | 'spell' | 'blueprint';
  id: string;
  progress: number;         // Hours studied
  required: number;         // Total hours needed
}

// ─── Golemancy Types ─────────────────────────────────────────────────────────

/**
 * Player-designed golem loadout entry.
 * Each entry is a complete golem design (Core + Frame + Mind Circuit + Enchantments).
 */
export interface GolemLoadoutEntry {
  designId: string;       // Reference to the GolemDesign
  /** Golem design (serialized component-based golem) */
  design: SerializedGolemDesign;
  enabled: boolean;       // Whether this golem is enabled for auto-summon
}

/**
 * Runtime active golem in combat (component-based system).
 * Tracks combat state per golem instance.
 */
export interface RuntimeActiveGolem {
  designId: string;          // Reference to the player's GolemDesign
  summonedFloor: number;     // Floor when golem was summoned
  attackProgress: number;    // Progress toward next attack (accumulated)
  roomsRemaining: number;    // Rooms before golem fades
  currentMana: number;       // Current mana in golem's own pool
  spellCastIndex: number;    // For alternating/cycling spell circuits
}

export interface SerializedGolemDesign {
  id: string;
  name: string;
  coreId: string;
  frameId: string;
  mindCircuitId: string;
  enchantmentIds: string[];
  selectedManaTypes: string[];
  selectedSpells: string[];
}

export interface GolemancyState {
  /** Player's saved golem designs indexed by design ID */
  golemDesigns: Record<string, SerializedGolemDesign>;
  /** Prioritized loadout of golem designs (persists across rooms, resets per run) */
  golemLoadout: GolemLoadoutEntry[];
  /** Runtime active golems in combat */
  activeGolems: RuntimeActiveGolem[];
  /** Floor golems were last summoned on */
  lastSummonFloor: number;
}


// ─── Main Game State ─────────────────────────────────────────────────────

export interface GameState {
  // Time
  day: number;
  hour: number;
  loopCount: number;
  gameOver: boolean;
  victory: boolean;
  paused: boolean;

  // Raw Mana
  rawMana: number;
  meditateTicks: number;
  totalManaGathered: number;
  flowSurgeEndTime: number;  // Hour timestamp for FLOW_SURGE effect (0 = inactive)

  // Attunements (class-like system)
  attunements: Record<string, AttunementState>;  // attunement id -> state

  // Elements
  elements: Record<string, ElementState>;

  // Spire
  currentFloor: number;
  floorHP: number;
  floorMaxHP: number;
  maxFloorReached: number;
  signedPacts: number[];
  activeSpell: string;
  currentAction: GameAction;
  castProgress: number;      // Progress towards next spell cast (0-1)
  
  // Room system for special floors
  currentRoom: FloorState;   // Current room state (swarm, puzzle, speed, etc.)

  // Spells
  spells: Record<string, SpellState>;

  // Equipment System (new instance-based system)
  equippedInstances: Record<string, string | null>;  // slot -> instanceId
  equipmentInstances: Record<string, EquipmentInstance>;  // instanceId -> instance
  completedEnchantmentDesigns: EnchantmentDesign[];  // Saved enchantment designs
  
  // Crafting Progress
  designProgress: DesignProgress | null;
  designProgress2: DesignProgress | null;  // For ENCHANT_MASTERY (2 concurrent designs)
  preparationProgress: PreparationProgress | null;
  applicationProgress: ApplicationProgress | null;
  equipmentCraftingProgress: EquipmentCraftingProgress | null;

  // Unlocked enchantment effects for designing
  unlockedEffects: string[];  // Effect IDs that have been researched

  // Equipment spell states for multi-casting
  equipmentSpellStates: EquipmentSpellState[];


  // Blueprints
  blueprints: Record<string, BlueprintDef>;

  // Loot Inventory
  lootInventory: LootInventory;

  // Schedule
  schedule: ScheduleBlock[];
  autoSchedule: boolean;
  studyQueue: string[];
  craftQueue: string[];

  // Current Study Target
  currentStudyTarget: StudyTarget | null;
  
  // Parallel Study Target (for Parallel Mind milestone upgrade)
  parallelStudyTarget: StudyTarget | null;
  
  // Study Momentum tracking (for STUDY_MOMENTUM special effect)
  consecutiveStudyHours: number;  // Tracks consecutive hours of studying

  // Golemancy (summoned golems)
  golemancy: GolemancyState;



  // Achievements
  achievements: AchievementState;

  // Stats tracking
  totalSpellsCast: number;
  totalDamageDealt: number;
  totalCraftsCompleted: number;

  // Combat special effect tracking
  comboHitCount: number;         // Hit counter for COMBO_MASTER (every 5th attack)
  floorHitCount: number;         // Hit counter for current floor (for FIRST_STRIKE)

  // Prestige
  insight: number;
  totalInsight: number;
  prestigeUpgrades: Record<string, number>;
  memorySlots: number;
  memories: string[];
  // Track selected mana types for unlockedManaTypeCapacity upgrade
  unlockedManaTypeUpgrades: Array<{ typeId: string; level: number }>;

  // Mana Well Effects (Phase 4)
  manaHeartBonus: number;      // Cumulative +10% max mana per loop from MANA_HEART

  // Incursion
  incursionStrength: number;
  containmentWards: number;

  // Conversion drains tracking (for UI display - Sub-Task 9)
  conversionDrains: Record<string, number>; // attunement id -> drain per hour

  // Log
  log: string[];

  // Activity Log (for Spire Mode UI)
  activityLog: ActivityLogEntry[];

  // Loop insight (earned at end of current loop)
  loopInsight: number;

  // Spire Mode - simplified UI for climbing
  spireMode: boolean;
  
  // Spire climbing state
  clearedFloors: Record<number, boolean>;  // Track cleared floors for respawning
  climbDirection: 'up' | 'down' | null;    // Current climb direction
  isDescending: boolean;                     // True when actively descending (prevents spam)
}

// ─── Action Types for Store ─────────────────────────────────────────────

export interface PrestigeDef {
  name: string;
  desc: string;
  max: number;
  cost: number;
}

export interface LootDrop {
  id: string;
  name: string;
  rarity: string;
  type: string;
  minFloor: number;
  dropChance: number;
  guardianOnly?: boolean;
  amount?: { min: number; max: number };
}

export type GameActionType =
  | { type: 'TICK' }
  | { type: 'GATHER_MANA' }
  | { type: 'SET_ACTION'; action: GameAction }
  | { type: 'SET_SPELL'; spellId: string }
  | { type: 'LEARN_SPELL'; spellId: string }
  | { type: 'START_STUDYING_SPELL'; spellId: string }
  | { type: 'CANCEL_STUDY' }
  | { type: 'CONVERT_MANA'; element: string; amount: number }
  | { type: 'UNLOCK_ELEMENT'; element: string }
  | { type: 'CRAFT_COMPOSITE'; target: string }
  | { type: 'DO_PRESTIGE'; id: string }
  | { type: 'START_NEW_LOOP' }
  | { type: 'TOGGLE_PAUSE' }
  | { type: 'RESET_GAME' };

