/**
 * TabataFit Data Layer
 * New 3-Program System + Legacy Support
 */

import { PROGRAMS, ALL_PROGRAM_WORKOUTS, ASSESSMENT_WORKOUT } from './programs'
import { TRAINERS } from './trainers'
import { ACHIEVEMENTS } from './achievements'
import { WORKOUTS } from './workouts'
import { GREEN, PHASE, TEXT, BRAND } from '../constants/colors'
import type { ProgramId } from '../types'

// Re-export new program system
export {
  PROGRAMS,
  ALL_PROGRAM_WORKOUTS,
  ASSESSMENT_WORKOUT,
  TRAINERS,
  ACHIEVEMENTS,
}

// ═══════════════════════════════════════════════════════════════════════════
// PROGRAM LOOKUPS
// ═══════════════════════════════════════════════════════════════════════════

export function getProgramById(id: ProgramId) {
  return PROGRAMS[id]
}

export function getAllPrograms() {
  return Object.values(PROGRAMS)
}

export function getProgramWorkouts(programId: ProgramId) {
  const program = PROGRAMS[programId]
  if (!program) return []
  return program.weeks.flatMap((week) => week.workouts)
}

export function getWorkoutById(id: string) {
  return ALL_PROGRAM_WORKOUTS.find((w) => w.id === id)
}

export function getWorkoutsByCategory(category: string) {
  if (category === 'all') return ALL_PROGRAM_WORKOUTS
  return ALL_PROGRAM_WORKOUTS.filter((w) => {
    const programId = getWorkoutProgramId(w.id)
    return programId === category
  })
}

export function getWorkoutProgramId(workoutId: string): ProgramId | null {
  for (const [programId, program] of Object.entries(PROGRAMS)) {
    for (const week of program.weeks) {
      if (week.workouts.some((w) => w.id === workoutId)) {
        return programId as ProgramId
      }
    }
  }
  return null
}

// ═══════════════════════════════════════════════════════════════════════════
// TRAINER LOOKUPS
// ═══════════════════════════════════════════════════════════════════════════

export function getTrainerById(id: string) {
  return TRAINERS.find((t) => t.id === id)
}

export function getTrainerByName(name: string) {
  return TRAINERS.find((t) => t.name.toLowerCase() === name.toLowerCase())
}

// ═══════════════════════════════════════════════════════════════════════════
// ACCENT COLOR
// ═══════════════════════════════════════════════════════════════════════════

/** Per-program accent colors (matches home screen cards) */
const PROGRAM_ACCENT_COLORS: Record<ProgramId, string> = {
  'upper-body': PHASE.PREP,
  'lower-body': GREEN[500],
  'full-body': BRAND.INFO,
}

/**
 * Resolve accent color for a workout:
 * 1. Trainer color (if workout has trainerId)
 * 2. Program accent color (if workout belongs to a program)
 * 3. Fallback to orange
 */
export function getWorkoutAccentColor(workoutId: string): string {
  // Check if it's a legacy workout with a trainer
  const trainerWorkout = WORKOUTS.find((w) => w.id === workoutId)
  if (trainerWorkout) {
    const trainer = TRAINERS.find((t) => t.id === trainerWorkout.trainerId)
    if (trainer?.color) return trainer.color
  }

  // Check which program it belongs to
  const programId = getWorkoutProgramId(workoutId)
  if (programId) return PROGRAM_ACCENT_COLORS[programId]

  return GREEN[500] // fallback — brand primary
}

// ═══════════════════════════════════════════════════════════════════════════
// CATEGORY METADATA
// ═══════════════════════════════════════════════════════════════════════════

export const CATEGORIES: { id: ProgramId | 'all'; label: string }[] = [
  { id: 'all', label: 'All' },
  { id: 'upper-body', label: 'Upper Body' },
  { id: 'lower-body', label: 'Lower Body' },
  { id: 'full-body', label: 'Full Body' },
]

// ═══════════════════════════════════════════════════════════════════════════
// POPULAR / RECOMMENDED
// ═══════════════════════════════════════════════════════════════════════════

/** Return a shuffled sample of workouts across all programs (one per program per week). */
export function getPopularWorkouts(count: number = 4) {
  // Pick the first workout from each program week to get variety
  const picks = Object.values(PROGRAMS).flatMap((program) =>
    program.weeks.map((week) => week.workouts[0]).filter(Boolean)
  )
  // Simple deterministic shuffle based on id to avoid re-renders
  const sorted = [...picks].sort((a, b) => a.id.localeCompare(b.id))
  return sorted.slice(0, count)
}

// Legacy exports for backward compatibility (to be removed)
export { WORKOUTS } from './workouts'
export { FEATURED_COLLECTION_ID } from './collections'
