// ─── Enums ───────────────────────────────────────────────────────────────────

export enum AnimalStage {
  CALF = 'calf',
  YEARLING = 'yearling',
  ADULT = 'adult',
  ELDER = 'elder',
}

export enum AnimalStatus {
  HEALTHY = 'healthy',
  PREGNANT = 'pregnant',
  RECOVERING = 'recovering',
  NEGLECTED = 'neglected',
  RETIRED = 'retired',
  DEAD = 'dead',
}

export enum AnimalSex {
  MALE = 'male',
  FEMALE = 'female',
}

export enum RarityTier {
  COMMON = 'common',
  UNCOMMON = 'uncommon',
  RARE = 'rare',
  LEGENDARY = 'legendary',
}

export enum ListingType {
  FIXED = 'fixed',
  AUCTION = 'auction',
}

export enum ListingStatus {
  ACTIVE = 'active',
  SOLD = 'sold',
  EXPIRED = 'expired',
  CANCELLED = 'cancelled',
}

export enum ShowTier {
  ROOKIE = 'rookie',
  PRO = 'pro',
  ELITE = 'elite',
}

export enum ShowStatus {
  OPEN = 'open',
  JUDGING = 'judging',
  COMPLETED = 'completed',
}

export enum ClubRole {
  OWNER = 'owner',
  OFFICER = 'officer',
  MEMBER = 'member',
}

export enum TransactionCategory {
  MARKET_SALE = 'market_sale',
  MARKET_BUY = 'market_buy',
  UPKEEP = 'upkeep',
  FEE = 'fee',
  REWARD = 'reward',
  ADMIN_GRANT = 'admin_grant',
  REFUND = 'refund',
  STARTER = 'starter',
}

export enum BuildingType {
  BARN_BASIC = 'barn_basic',
  BARN_LARGE = 'barn_large',
  FEED_STORAGE = 'feed_storage',
  VET_CLINIC = 'vet_clinic',
  SHOW_PREP_BARN = 'show_prep_barn',
  BREEDING_CENTER = 'breeding_center',
  STAFF_QUARTERS = 'staff_quarters',
}

export enum BuildingStatus {
  CONSTRUCTING = 'constructing',
  ACTIVE = 'active',
  SUSPENDED = 'suspended',
}

// ─── Core Domain Types ────────────────────────────────────────────────────────

export interface Phenotype {
  weightScore: number;          // 0-1
  milkYieldScore: number;
  growthRateScore: number;
  temperamentScore: number;
  coatQualityScore: number;
  fertilityScore: number;
  hardinessScore: number;
  showPotentialScore: number;
}

export interface Animal {
  id: string;
  ownerId: string;
  ranchId: string;
  name: string;
  breed: string;
  sex: AnimalSex;
  bornAt: string;
  diedAt: string | null;
  stage: AnimalStage;
  health: number;
  condition: number;
  status: AnimalStatus;
  pregnancyEndAt: string | null;
  recoveryEndAt: string | null;
  sireId: string | null;
  damId: string | null;
  inbreedingCoefficient: number;
  rarityTier: RarityTier;
  phenotype: Phenotype;
  genotypeTested: boolean;
  createdAt: string;
}

export interface AnimalWithGenotype extends Animal {
  genotype: Phenotype; // only populated when genotype_tested = true and owner requests it
}

export interface Ranch {
  id: string;
  ownerId: string;
  name: string;
  description: string;
  plotCount: number;
  maxPlotCount: number;
  herdCapacity: number;
  lastUpkeepAt: string;
  debtFlag: boolean;
  prestigeLevel: number;
  createdAt: string;
}

export interface Building {
  id: string;
  ranchId: string;
  buildingType: BuildingType;
  plotPosition: number;
  status: BuildingStatus;
  completeAt: string | null;
  builtAt: string | null;
}

export interface BuildingDefinition {
  type: BuildingType;
  name: string;
  description: string;
  cost: number;
  constructionHours: number;
  herdCapacityBonus: number;
  effects: Record<string, number>;
}

export interface User {
  id: string;
  email: string;
  username: string;
  createdAt: string;
  lastLoginAt: string;
  status: 'active' | 'suspended' | 'banned';
  goldBalance: number;
  premiumBalance: number;
  prestigePoints: number;
  marketRestrictedUntil: string | null;
  ranch?: Ranch;
}

export interface MarketListing {
  id: string;
  sellerId: string;
  sellerUsername: string;
  animalId: string | null;
  itemType: string | null;
  listingType: ListingType;
  price: number;
  buyoutPrice: number | null;
  currentBid: number | null;
  currentBidderId: string | null;
  expiresAt: string;
  status: ListingStatus;
  createdAt: string;
  animal?: Animal;
}

export interface Show {
  id: string;
  name: string;
  tier: ShowTier;
  entryFee: number;
  entryClosesAt: string;
  judgedAt: string | null;
  status: ShowStatus;
  seasonId: string | null;
  entryCount?: number;
}

export interface ShowEntry {
  id: string;
  showId: string;
  playerId: string;
  playerUsername: string;
  animalId: string;
  score: number | null;
  rank: number | null;
  rewardClaimed: boolean;
  animal?: Animal;
}

export interface Club {
  id: string;
  name: string;
  ownerId: string;
  ownerUsername: string;
  description: string;
  goldVault: number;
  memberCount: number;
  createdAt: string;
  myRole?: ClubRole;
}

export interface ClubMember {
  clubId: string;
  userId: string;
  username: string;
  role: ClubRole;
  joinedAt: string;
}

export interface Transaction {
  id: string;
  userId: string;
  amount: number;
  currency: 'gold' | 'premium';
  category: TransactionCategory;
  refId: string | null;
  balanceAfter: number;
  createdAt: string;
}

// ─── API Request/Response Types ───────────────────────────────────────────────

export interface AuthResponse {
  token: string;
  refreshToken: string;
  user: User;
}

export interface PaginatedResponse<T> {
  data: T[];
  total: number;
  page: number;
  pageSize: number;
  hasMore: boolean;
}

export interface ApiError {
  error: string;
  message: string;
  statusCode: number;
  details?: Record<string, string>;
}

export interface BreedPreview {
  sireId: string;
  damId: string;
  traits: {
    [key in keyof Phenotype]: {
      min: number;
      max: number;
      mean: number;
    };
  };
  rarityDistribution: {
    common: number;
    uncommon: number;
    rare: number;
    legendary: number;
  };
  inbreedingCoefficient: number;
  inbreedingWarning: boolean;
}

export interface DashboardData {
  ranch: Ranch;
  herdSummary: {
    total: number;
    needingFeed: number;
    pregnant: number;
    inShows: number;
  };
  alerts: DashboardAlert[];
  recentResults: ShowEntry[];
}

export interface DashboardAlert {
  type: 'ready_to_breed' | 'show_closing' | 'upkeep_due' | 'birth_ready' | 'recovery_done' | 'animal_sick';
  message: string;
  animalId?: string;
  showId?: string;
  urgency: 'low' | 'medium' | 'high';
}

// ─── Constants ────────────────────────────────────────────────────────────────

export const BREEDS = [
  'Angus',
  'Hereford',
  'Longhorn',
  'Holstein',
  'Brahman',
] as const;

export type Breed = typeof BREEDS[number];

export const TRAIT_LABELS: Record<keyof Phenotype, string> = {
  weightScore: 'Weight',
  milkYieldScore: 'Milk Yield',
  growthRateScore: 'Growth Rate',
  temperamentScore: 'Temperament',
  coatQualityScore: 'Coat Quality',
  fertilityScore: 'Fertility',
  hardinessScore: 'Hardiness',
  showPotentialScore: 'Show Potential',
};

export const RARITY_COLORS: Record<RarityTier, string> = {
  [RarityTier.COMMON]: '#9ca3af',
  [RarityTier.UNCOMMON]: '#22c55e',
  [RarityTier.RARE]: '#3b82f6',
  [RarityTier.LEGENDARY]: '#f59e0b',
};

export const BUILDING_DEFINITIONS: Record<BuildingType, BuildingDefinition> = {
  [BuildingType.BARN_BASIC]: {
    type: BuildingType.BARN_BASIC,
    name: 'Basic Barn',
    description: 'A sturdy barn that increases your herd capacity.',
    cost: 500,
    constructionHours: 2,
    herdCapacityBonus: 10,
    effects: {},
  },
  [BuildingType.BARN_LARGE]: {
    type: BuildingType.BARN_LARGE,
    name: 'Large Barn',
    description: 'A spacious barn for a growing herd.',
    cost: 2000,
    constructionHours: 6,
    herdCapacityBonus: 25,
    effects: {},
  },
  [BuildingType.FEED_STORAGE]: {
    type: BuildingType.FEED_STORAGE,
    name: 'Feed Storage',
    description: 'Reduces feed consumption across your herd.',
    cost: 300,
    constructionHours: 1,
    herdCapacityBonus: 0,
    effects: { feedConsumptionReduction: 0.1 },
  },
  [BuildingType.VET_CLINIC]: {
    type: BuildingType.VET_CLINIC,
    name: 'Veterinary Clinic',
    description: 'Reduces medicine costs and healing time.',
    cost: 1500,
    constructionHours: 4,
    herdCapacityBonus: 0,
    effects: { medicineCostReduction: 0.2, healingTimeReduction: 0.25 },
  },
  [BuildingType.SHOW_PREP_BARN]: {
    type: BuildingType.SHOW_PREP_BARN,
    name: 'Show Prep Barn',
    description: 'Gives entered animals a small show score bonus.',
    cost: 2500,
    constructionHours: 8,
    herdCapacityBonus: 0,
    effects: { showScoreBonus: 0.03 },
  },
  [BuildingType.BREEDING_CENTER]: {
    type: BuildingType.BREEDING_CENTER,
    name: 'Breeding Center',
    description: 'Reduces pregnancy timers.',
    cost: 3000,
    constructionHours: 8,
    herdCapacityBonus: 0,
    effects: { breedingTimerReduction: 0.2 },
  },
  [BuildingType.STAFF_QUARTERS]: {
    type: BuildingType.STAFF_QUARTERS,
    name: 'Staff Quarters',
    description: 'Allows you to hire up to 2 staff members.',
    cost: 1000,
    constructionHours: 3,
    herdCapacityBonus: 0,
    effects: { maxStaff: 2 },
  },
};
