// ─── 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, EquipmentDef, BlueprintDef, LootInventory, EquipmentSpellState } from './equipment';

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

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';

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;         // Shield that absorbs damage before HP (0-1 as percentage of max HP)
  element: string;
}

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
}

// ─── 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' | '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 ─────────────────────────────────────────────────────────

export interface SummonedGolem {
  golemId: string;          // Reference to GOLEMS_DEF
  summonedFloor: number;    // Floor when golem was summoned
  attackProgress: number;   // Progress toward next attack (0-1)
}

export interface GolemancyState {
  enabledGolems: string[];      // Golem IDs the player wants active
  summonedGolems: SummonedGolem[]; // Currently summoned golems on this floor
  lastSummonFloor: number;      // Floor golems were last summoned on
}

// ─── 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>;

  // Skills
  skills: Record<string, number>;
  skillProgress: Record<string, number>;  // Saved study progress for skills
  skillUpgrades: Record<string, string[]>; // Selected upgrade IDs per skill
  skillTiers: Record<string, number>;      // Current tier for each base skill

  // Equipment System (new instance-based system)
  equippedInstances: Record<string, string | null>;  // slot -> instanceId
  equipmentInstances: Record<string, EquipmentInstance>;  // instanceId -> instance
  enchantmentDesigns: 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[];

  // Legacy Equipment (for backward compatibility)
  equipment: Record<string, EquipmentDef | null>;
  inventory: EquipmentDef[];

  // 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_SKILL'; skillId: 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' }
  | { type: 'SELECT_SKILL_UPGRADE'; skillId: string; upgradeId: string }
  | { type: 'TIER_UP_SKILL'; skillId: string };
