/**
 * TabataFit Pre-Workout Detail Screen
 * Clean scrollable layout — native header, no hero
 */

import React, { useEffect, useRef, useState } from 'react'
import {
  View,
  Text as RNText,
  StyleSheet,
  ScrollView,
  Pressable,
  Animated,
} from 'react-native'
import { Stack } from 'expo-router'
import { useRouter, useLocalSearchParams } from 'expo-router'
import { useSafeAreaInsets } from 'react-native-safe-area-context'
import { Icon } from '@/src/shared/components/Icon'
import { VideoPlayer } from '@/src/shared/components/VideoPlayer'
import { Image } from 'expo-image'
import { useTranslation } from 'react-i18next'

import { useHaptics } from '@/src/shared/hooks'
import { usePurchases } from '@/src/shared/hooks/usePurchases'
import { useUserStore } from '@/src/shared/stores'
import { track } from '@/src/shared/services/analytics'
import { canAccessWorkout, canAccessSession } from '@/src/shared/services/access'
import { getTabataSessionById, isTabataSession } from '@/src/shared/data/tabata'
import { isWorkoutProgramId, parseWorkoutProgramId, fetchProgramById, workoutProgramToTabataSession } from '@/src/shared/data/workoutPrograms'
import { BODY_ZONE_META } from '@/src/shared/types/workoutProgram'
import type { TabataSession } from '@/src/shared/types/program'
import { getWorkoutById, getTrainerById, getWorkoutAccentColor } from '@/src/shared/data'
import { useTranslatedWorkout, useMusicVibeLabel } from '@/src/shared/data/useTranslatedData'

import { useThemeColors } from '@/src/shared/theme'
import type { ThemeColors } from '@/src/shared/theme/types'
import { TYPOGRAPHY } from '@/src/shared/constants/typography'
import { SPACING, LAYOUT } from '@/src/shared/constants/spacing'
import { RADIUS } from '@/src/shared/constants/borderRadius'
import { SPRING } from '@/src/shared/constants/animations'
import { TEXT, NAVY, BRAND, GREEN, AMBER, RED, DARK, BORDER_COLORS } from '@/src/shared/constants/colors'
import { NativeButton } from '@/src/shared/components/native'

// ─── Save Button (headerRight) ───────────────────────────────────────────────

function SaveButton({
  isSaved,
  onPress,
  colors,
}: {
  isSaved: boolean
  onPress: () => void
  colors: ThemeColors
}) {
  return (
    <Pressable
      onPress={onPress}
      hitSlop={8}
      style={({ pressed }) => [
        { width: 32, height: 32, alignItems: 'center', justifyContent: 'center' },
        pressed && { opacity: 0.6 },
      ]}
    >
      <Icon
        name={isSaved ? 'heart.fill' : 'heart'}
        size={22}
        color={isSaved ? BRAND.DANGER : colors.text.primary}
      />
    </Pressable>
  )
}

// ─── Main Screen ─────────────────────────────────────────────────────────────

export default function WorkoutDetailScreen() {
  const insets = useSafeAreaInsets()
  const router = useRouter()
  const haptics = useHaptics()
  const { t } = useTranslation()
  const { id } = useLocalSearchParams<{ id: string }>()

  // ─── Dispatch: Workout Program → Tabata session → Legacy workout ─
  if (isWorkoutProgramId(id ?? '')) {
    return <WorkoutProgramDetailScreen compositeId={id ?? ''} />
  }

  if (isTabataSession(id ?? '')) {
    return <TabataSessionDetailScreen sessionId={id ?? ''} />
  }

  return <LegacyWorkoutDetailScreen id={id ?? '1'} />
}

/**
 * Workout Program Detail — loads a program tabata and delegates to TabataSessionDetailScreen
 */
function WorkoutProgramDetailScreen({ compositeId }: { compositeId: string }) {
  const [session, setSession] = React.useState<TabataSession | null | undefined>(undefined)
  const [accent, setAccent] = React.useState<string>(GREEN[500])
  const [isFree, setIsFree] = React.useState<boolean>(false)

  React.useEffect(() => {
    let cancelled = false
    async function load() {
      const parsed = parseWorkoutProgramId(compositeId)
      if (!parsed) { if (!cancelled) setSession(null); return }
      const program = await fetchProgramById(parsed.programId)
      if (cancelled) return
      if (!program) { setSession(null); return }
      const tabataSession = workoutProgramToTabataSession(program)
      setSession(tabataSession)
      setIsFree(program.isFree === true)
      const zoneMeta = BODY_ZONE_META[program.bodyZone]
      setAccent(program.accentColor ?? zoneMeta.color)
    }
    load()
    return () => { cancelled = true }
  }, [compositeId])

  if (session === undefined) {
    return (
      <View style={{ flex: 1, backgroundColor: NAVY[900], justifyContent: 'center', alignItems: 'center' }}>
        <Stack.Screen options={{ headerShown: true, headerTitle: '', headerStyle: { backgroundColor: NAVY[900] }, headerTintColor: TEXT.PRIMARY }} />
        <RNText style={{ color: TEXT.SECONDARY }}>Chargement...</RNText>
      </View>
    )
  }

  if (session === null) {
    return (
      <View style={{ flex: 1, backgroundColor: NAVY[900], justifyContent: 'center', alignItems: 'center' }}>
        <Stack.Screen options={{ headerShown: true, headerTitle: '', headerStyle: { backgroundColor: NAVY[900] }, headerTintColor: TEXT.PRIMARY }} />
        <RNText style={{ color: TEXT.SECONDARY }}>Programme non trouvé</RNText>
      </View>
    )
  }

  return <TabataSessionDetailScreen sessionId={session.id} sessionOverride={session} accentOverride={accent} isFreeOverride={isFree} />
}

/**
 * Tabata Session Detail — shows warmup, blocks, cooldown, tabata tips
 */
function TabataSessionDetailScreen({
  sessionId,
  sessionOverride,
  accentOverride,
  isFreeOverride,
}: {
  sessionId: string
  sessionOverride?: TabataSession
  accentOverride?: string
  isFreeOverride?: boolean
}) {
  const router = useRouter()
  const insets = useSafeAreaInsets()
  const haptics = useHaptics()
  const session = sessionOverride ?? getTabataSessionById(sessionId)
  const { isPremium } = usePurchases()
  const canAccess = isFreeOverride !== undefined
    ? (isPremium || isFreeOverride)
    : canAccessSession(sessionId, isPremium)

  if (!session) {
    return (
      <View style={{ flex: 1, backgroundColor: NAVY[900], justifyContent: 'center', alignItems: 'center' }}>
        <Stack.Screen options={{ headerShown: true, headerTitle: '', headerStyle: { backgroundColor: NAVY[900] }, headerTintColor: TEXT.PRIMARY }} />
        <RNText style={{ color: TEXT.SECONDARY }}>Séance non trouvée</RNText>
      </View>
    )
  }

  const programId = sessionId.startsWith('deb-') ? 'debutant' : sessionId.startsWith('int-') ? 'intermediaire' : sessionId.startsWith('avc-') ? 'avance' : 'bureau'
  const accentMap: Record<string, string> = { debutant: GREEN[500], intermediaire: BRAND.INFO, avance: RED[500], bureau: AMBER[500] }
  const accent = accentOverride ?? accentMap[programId] ?? GREEN[500]

  const handleStart = () => {
    haptics.buttonTap()
    track('tabata_session_start_pressed', { session_id: sessionId })
    router.push(`/player/${sessionId}`)
  }

  return (
    <View style={styles.container}>
      <Stack.Screen options={{ headerShown: true, headerTitle: session.title, headerStyle: { backgroundColor: NAVY[900] }, headerTintColor: TEXT.PRIMARY }} />
      <ScrollView contentContainerStyle={{ paddingBottom: insets.bottom + 100 }}>
        {/* Session info */}
        <View style={[styles.heroSection, { backgroundColor: accent + '15' }]}>
          <RNText style={styles.sessionTitle}>{session.title}</RNText>
          <RNText style={styles.sessionDesc}>{session.description}</RNText>
          <View style={styles.metaRow}>
            <RNText style={styles.metaText}>{session.blocks.length} bloc{session.blocks.length > 1 ? 's' : ''}</RNText>
            <RNText style={styles.metaText}>·</RNText>
            <RNText style={styles.metaText}>{session.totalDuration} min</RNText>
            <RNText style={styles.metaText}>·</RNText>
            <RNText style={styles.metaText}>{session.calories} cal</RNText>
          </View>
          {/* Focus tags */}
          <View style={styles.focusRow}>
            {session.focus.map((f, i) => (
              <View key={i} style={[styles.focusTag, { borderColor: accent }]}>
                <RNText style={[styles.focusTagText, { color: accent }]}>{f}</RNText>
              </View>
            ))}
          </View>
        </View>

        {/* Warmup */}
        {session.warmup.movements.length > 0 && (
          <View style={styles.section}>
            <RNText style={styles.sectionTitle}>Échauffement · {Math.floor(session.warmup.totalDuration / 60)} min</RNText>
            {session.warmup.movements.map((m, i) => (
              <View key={i} style={styles.movementRow}>
                <RNText style={styles.movementDot}>●</RNText>
                <RNText style={styles.movementName}>{m.name}</RNText>
                <RNText style={styles.movementDuration}>{m.duration}s</RNText>
              </View>
            ))}
          </View>
        )}

        {/* Blocks */}
        {session.blocks.map((block, bi) => (
          <View key={block.id} style={styles.section}>
            <RNText style={styles.sectionTitle}>Bloc {bi + 1} · {block.rounds} rounds · {block.workTime}/{block.restTime}s</RNText>
            <View style={styles.exercisePair}>
              <View style={[styles.exerciseCard, { borderLeftColor: accent }]}>
                <RNText style={styles.exerciseLabel}>Rounds impairs</RNText>
                <RNText style={styles.exerciseName}>{block.oddExercise.name}</RNText>
                {block.oddExercise.conseil ? <RNText style={styles.exerciseTip}>📋 {block.oddExercise.conseil}</RNText> : null}
              </View>
              <View style={[styles.exerciseCard, { borderLeftColor: BRAND.INFO }]}>
                <RNText style={styles.exerciseLabel}>Rounds pairs</RNText>
                <RNText style={styles.exerciseName}>{block.evenExercise.name}</RNText>
                {block.evenExercise.conseil ? <RNText style={styles.exerciseTip}>📋 {block.evenExercise.conseil}</RNText> : null}
              </View>
            </View>
          </View>
        ))}

        {/* Cooldown */}
        {session.cooldown.movements.length > 0 && (
          <View style={styles.section}>
            <RNText style={styles.sectionTitle}>Retour au calme · {Math.floor(session.cooldown.totalDuration / 60)} min</RNText>
            {session.cooldown.movements.map((m, i) => (
              <View key={i} style={styles.movementRow}>
                <RNText style={styles.movementDot}>●</RNText>
                <RNText style={styles.movementName}>{m.name}</RNText>
                <RNText style={styles.movementDuration}>{m.duration}s</RNText>
              </View>
            ))}
          </View>
        )}

        {/* Equipment */}
        {session.equipment.length > 0 && (
          <View style={styles.section}>
            <RNText style={styles.sectionTitle}>Matériel</RNText>
            {session.equipment.map((eq, i) => (
              <RNText key={i} style={styles.equipText}>• {eq}</RNText>
            ))}
          </View>
        )}
      </ScrollView>

      {/* CTA */}
      <View style={[styles.ctaContainer, { paddingBottom: insets.bottom + SPACING[4] }]}>
        {canAccess ? (
          <Pressable style={[styles.ctaButton, { backgroundColor: accent }]} onPress={handleStart}>
            <RNText style={styles.ctaText}>Commencer la séance</RNText>
          </Pressable>
        ) : (
          <Pressable style={[styles.ctaButton, { backgroundColor: GREEN[500] }]} onPress={() => router.push('/paywall')}>
            <RNText style={styles.ctaText}>Débloquer avec Premium</RNText>
          </Pressable>
        )}
      </View>
    </View>
  )
}

/**
 * Legacy workout detail — original format
 */
function LegacyWorkoutDetailScreen({ id }: { id: string }) {
  const insets = useSafeAreaInsets()
  const router = useRouter()
  const haptics = useHaptics()
  const { t } = useTranslation()
  const savedWorkouts = useUserStore((s) => s.savedWorkouts)
  const toggleSavedWorkout = useUserStore((s) => s.toggleSavedWorkout)
  const { isPremium } = usePurchases()

  const colors = useThemeColors()
  const isDark = colors.colorScheme === 'dark'

  const rawWorkout = getWorkoutById(id ?? '1')
  const workout = useTranslatedWorkout(rawWorkout)
  const musicVibeLabel = useMusicVibeLabel(rawWorkout?.musicVibe ?? '')
  const trainer = rawWorkout ? getTrainerById(rawWorkout.trainerId) : undefined
  const accentColor = GREEN[500]

  // CTA entrance
  const ctaAnim = useRef(new Animated.Value(0)).current
  useEffect(() => {
    Animated.sequence([
      Animated.delay(300),
      Animated.spring(ctaAnim, {
        toValue: 1,
        ...SPRING.GENTLE,
        useNativeDriver: true,
      }),
    ]).start()
  }, [])

  useEffect(() => {
    if (workout) {
      track('workout_detail_viewed', {
        workout_id: workout.id,
        workout_title: workout.title,
        level: workout.level,
        duration: workout.duration,
      })
    }
  }, [workout?.id])

  const isSaved = savedWorkouts.includes(workout?.id?.toString() ?? '')
  const toggleSave = () => {
    if (!workout) return
    haptics.selection()
    toggleSavedWorkout(workout.id.toString())
  }

  if (!workout) {
    return (
      <>
        <Stack.Screen options={{ headerTitle: '' }} />
        <View style={[s.container, s.centered, { backgroundColor: colors.bg.base }]}>
          <RNText style={{ color: colors.text.primary, fontSize: 17 }}>
            {t('screens:workout.notFound')}
          </RNText>
        </View>
      </>
    )
  }

  const isLocked = !canAccessWorkout(workout.id, isPremium)
  const exerciseCount = workout.exercises?.length || 1
  const repeatCount = Math.max(1, Math.floor((workout.rounds || exerciseCount) / exerciseCount))

  const handleStartWorkout = () => {
    if (isLocked) {
      haptics.buttonTap()
      track('paywall_triggered', { source: 'workout_detail', workout_id: workout.id })
      router.push('/paywall')
      return
    }
    haptics.phaseChange()
    router.push(`/player/${workout.id}`)
  }

  const ctaBg = isDark ? TEXT.PRIMARY : NAVY[900]
  const ctaText = isDark ? NAVY[900] : TEXT.PRIMARY
  const ctaLockedBg = isDark ? 'rgba(255,255,255,0.12)' : 'rgba(0,0,0,0.08)'
  const ctaLockedText = colors.text.primary

  const equipmentText = workout.equipment.length > 0
    ? workout.equipment.join(' · ')
    : t('screens:workout.noEquipment', { defaultValue: 'No equipment needed' })

  return (
    <>
      <Stack.Screen
        options={{
          headerRight: () => (
            <SaveButton isSaved={isSaved} onPress={toggleSave} colors={colors} />
          ),
        }}
      />

      <View testID="workout-detail-screen" style={[s.container, { backgroundColor: colors.bg.base }]}>
        <ScrollView
          contentInsetAdjustmentBehavior="automatic"
          contentContainerStyle={[
            s.scrollContent,
            { paddingBottom: insets.bottom + 100 },
          ]}
          showsVerticalScrollIndicator={false}
        >
          {/* Thumbnail / Video Preview */}
          {rawWorkout?.thumbnailUrl ? (
            <View style={s.mediaContainer}>
              <Image
                source={rawWorkout.thumbnailUrl}
                style={s.thumbnail}
                contentFit="cover"
                transition={200}
              />
            </View>
          ) : rawWorkout?.videoUrl ? (
            <View style={s.mediaContainer}>
              <VideoPlayer
                videoUrl={rawWorkout.videoUrl}
                gradientColors={[NAVY[800], NAVY[700]]}
                mode="preview"
                isPlaying={false}
                style={s.thumbnail}
              />
            </View>
          ) : null}

          {/* Title */}
          <RNText selectable style={[s.title, { color: colors.text.primary }]}>
            {workout.title}
          </RNText>

          {/* Trainer */}
          {trainer && (
            <RNText style={[s.trainerName, { color: accentColor }]}>
              with {trainer.name}
            </RNText>
          )}

          {/* Inline metadata */}
          <View style={s.metaRow}>
            <View style={s.metaItem}>
              <Icon name="clock" size={15} tintColor={colors.text.tertiary} />
              <RNText style={[s.metaText, { color: colors.text.secondary }]}>
                {t('units.minUnit', { count: workout.duration })}
              </RNText>
            </View>
            <RNText style={[s.metaDot, { color: colors.text.hint }]}>·</RNText>
            <View style={s.metaItem}>
              <Icon name="flame" size={15} tintColor={colors.text.tertiary} />
              <RNText style={[s.metaText, { color: colors.text.secondary }]}>
                {t('units.calUnit', { count: workout.calories })}
              </RNText>
            </View>
            <RNText style={[s.metaDot, { color: colors.text.hint }]}>·</RNText>
            <RNText style={[s.metaText, { color: colors.text.secondary }]}>
              {t(`levels.${(workout.level ?? 'Beginner').toLowerCase()}`)}
            </RNText>
          </View>

          {/* Equipment */}
          <RNText style={[s.equipmentText, { color: colors.text.tertiary }]}>
            {equipmentText}
          </RNText>

          {/* Separator */}
          <View style={[s.separator, { backgroundColor: colors.border.dim }]} />

          {/* Timing Card */}
          <View style={[s.card, { backgroundColor: colors.bg.surface }]}>
            <View style={s.timingRow}>
              <View style={s.timingItem}>
                <RNText style={[s.timingValue, { color: accentColor }]}>
                  {workout.prepTime}s
                </RNText>
                <RNText style={[s.timingLabel, { color: colors.text.tertiary }]}>
                  {t('screens:workout.prep', { defaultValue: 'Prep' })}
                </RNText>
              </View>
              <View style={[s.timingDivider, { backgroundColor: colors.border.dim }]} />
              <View style={s.timingItem}>
                <RNText style={[s.timingValue, { color: accentColor }]}>
                  {workout.workTime}s
                </RNText>
                <RNText style={[s.timingLabel, { color: colors.text.tertiary }]}>
                  {t('screens:workout.work', { defaultValue: 'Work' })}
                </RNText>
              </View>
              <View style={[s.timingDivider, { backgroundColor: colors.border.dim }]} />
              <View style={s.timingItem}>
                <RNText style={[s.timingValue, { color: accentColor }]}>
                  {workout.restTime}s
                </RNText>
                <RNText style={[s.timingLabel, { color: colors.text.tertiary }]}>
                  {t('screens:workout.rest', { defaultValue: 'Rest' })}
                </RNText>
              </View>
              <View style={[s.timingDivider, { backgroundColor: colors.border.dim }]} />
              <View style={s.timingItem}>
                <RNText style={[s.timingValue, { color: accentColor }]}>
                  {workout.rounds}
                </RNText>
                <RNText style={[s.timingLabel, { color: colors.text.tertiary }]}>
                  {t('screens:workout.rounds', { defaultValue: 'Rounds' })}
                </RNText>
              </View>
            </View>
          </View>

          {/* Exercises Card */}
          <RNText style={[s.sectionTitle, { color: colors.text.primary }]}>
            {t('screens:workout.exercises', { count: workout.rounds })}
          </RNText>

          <View style={[s.card, { backgroundColor: colors.bg.surface }]}>
            {workout.exercises.map((exercise, index) => (
              <View key={index}>
                <View style={s.exerciseRow}>
                  <RNText style={[s.exerciseIndex, { color: accentColor }]}>
                    {index + 1}
                  </RNText>
                  <RNText selectable style={[s.exerciseName, { color: colors.text.primary }]}>
                    {exercise.name}
                  </RNText>
                  <RNText style={[s.exerciseDuration, { color: colors.text.tertiary }]}>
                    {exercise.duration}s
                  </RNText>
                </View>
                {index < workout.exercises.length - 1 && (
                  <View style={[s.exerciseSep, { backgroundColor: colors.border.dim }]} />
                )}
              </View>
            ))}
          </View>

          {repeatCount > 1 && (
            <View style={s.repeatRow}>
              <Icon name="repeat" size={13} color={colors.text.hint} />
              <RNText style={[s.repeatText, { color: colors.text.hint }]}>
                {t('screens:workout.repeatRounds', { count: repeatCount })}
              </RNText>
            </View>
          )}

          {/* Music */}
          <View style={s.musicRow}>
            <Icon name="music.note" size={14} tintColor={colors.text.hint} />
            <RNText style={[s.musicText, { color: colors.text.tertiary }]}>
              {t('screens:workout.musicMix', { vibe: musicVibeLabel })}
            </RNText>
          </View>
        </ScrollView>

        {/* CTA */}
        <Animated.View
          style={[
            s.bottomBar,
            {
              backgroundColor: colors.bg.base,
              paddingBottom: insets.bottom + SPACING[3],
              opacity: ctaAnim,
              transform: [
                {
                  translateY: ctaAnim.interpolate({
                    inputRange: [0, 1],
                    outputRange: [30, 0],
                  }),
                },
              ],
            },
          ]}
        >
          <NativeButton
            variant={isLocked ? 'secondary' : 'primary'}
            title={isLocked ? t('screens:workout.unlockWithPremium') : t('screens:workout.startWorkout')}
            systemImage={isLocked ? 'lock.fill' : 'play.fill'}
            onPress={handleStartWorkout}
            fullWidth
            controlSize="large"
            testID={isLocked ? 'workout-unlock-button' : 'workout-start-button'}
          />
        </Animated.View>
      </View>
    </>
  )
}

// ─── Styles ──────────────────────────────────────────────────────────────────

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: NAVY[900] },
  heroSection: { padding: SPACING[5], alignItems: 'center' },
  sessionTitle: { ...TYPOGRAPHY.LARGE_TITLE, color: TEXT.PRIMARY, textAlign: 'center' },
  sessionDesc: { ...TYPOGRAPHY.BODY, color: TEXT.SECONDARY, textAlign: 'center', marginTop: SPACING[2], lineHeight: 22 },
  metaRow: { flexDirection: 'row', marginTop: SPACING[4], gap: SPACING[2], justifyContent: 'center' },
  metaText: { ...TYPOGRAPHY.SUBHEADLINE, color: TEXT.SECONDARY },
  focusRow: { flexDirection: 'row', flexWrap: 'wrap', gap: SPACING[2], marginTop: SPACING[3], justifyContent: 'center' },
  focusTag: { paddingHorizontal: 10, paddingVertical: 3, borderRadius: 12, borderWidth: 1 },
  focusTagText: { fontSize: 12, fontWeight: '600' },
  section: { paddingHorizontal: SPACING[5], marginTop: SPACING[6] },
  sectionTitle: { ...TYPOGRAPHY.HEADLINE, color: TEXT.PRIMARY, marginBottom: SPACING[3] },
  movementRow: { flexDirection: 'row', alignItems: 'center', gap: SPACING[2], marginBottom: SPACING[2] },
  movementDot: { fontSize: 8, color: TEXT.TERTIARY },
  movementName: { ...TYPOGRAPHY.BODY, color: TEXT.PRIMARY, flex: 1 },
  movementDuration: { ...TYPOGRAPHY.CAPTION_1, color: TEXT.TERTIARY },
  exercisePair: { gap: SPACING[3] },
  exerciseCard: { backgroundColor: NAVY[800], borderRadius: RADIUS.MD, padding: SPACING[3], borderLeftWidth: 3 },
  exerciseLabel: { ...TYPOGRAPHY.CAPTION_2, color: TEXT.TERTIARY, textTransform: 'uppercase', letterSpacing: 0.5, marginBottom: 4 },
  exerciseName: { ...TYPOGRAPHY.TITLE_3, color: TEXT.PRIMARY },
  exerciseTip: { ...TYPOGRAPHY.CAPTION_1, color: TEXT.SECONDARY, marginTop: SPACING[1], lineHeight: 18 },
  equipText: { ...TYPOGRAPHY.SUBHEADLINE, color: TEXT.SECONDARY, marginBottom: SPACING[1] },
  ctaContainer: { position: 'absolute', bottom: 0, left: 0, right: 0, paddingHorizontal: SPACING[5], paddingTop: SPACING[3], backgroundColor: DARK.SCRIM, borderTopWidth: 1, borderTopColor: BORDER_COLORS.DIM },
  ctaButton: { height: 52, borderRadius: RADIUS.MD, borderCurve: 'continuous', alignItems: 'center', justifyContent: 'center' },
  ctaText: { ...TYPOGRAPHY.BUTTON_MEDIUM, color: NAVY[900], letterSpacing: 0.5 },
})

const s = StyleSheet.create({
  container: {
    flex: 1,
  },
  centered: {
    alignItems: 'center',
    justifyContent: 'center',
  },
  scrollContent: {
    paddingHorizontal: LAYOUT.SCREEN_PADDING,
    paddingTop: SPACING[2],
  },

  // Media
  mediaContainer: {
    height: 200,
    borderRadius: RADIUS.LG,
    borderCurve: 'continuous',
    overflow: 'hidden',
    marginBottom: SPACING[4],
  },
  thumbnail: {
    width: '100%',
    height: '100%',
  },

  // Title
  title: {
    ...TYPOGRAPHY.TITLE_1,
    marginBottom: SPACING[2],
  },

  // Trainer
  trainerName: {
    ...TYPOGRAPHY.SUBHEADLINE,
    marginBottom: SPACING[3],
  },

  // Metadata
  metaRow: {
    flexDirection: 'row',
    alignItems: 'center',
    flexWrap: 'wrap',
    gap: SPACING[2],
    marginBottom: SPACING[2],
  },
  metaItem: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 4,
  },
  metaText: {
    ...TYPOGRAPHY.SUBHEADLINE,
  },
  metaDot: {
    ...TYPOGRAPHY.SUBHEADLINE,
  },

  // Equipment
  equipmentText: {
    ...TYPOGRAPHY.FOOTNOTE,
    marginBottom: SPACING[4],
  },

  // Separator
  separator: {
    height: StyleSheet.hairlineWidth,
    marginBottom: SPACING[4],
  },

  // Card
  card: {
    borderRadius: RADIUS.LG,
    borderCurve: 'continuous',
    overflow: 'hidden',
    marginBottom: SPACING[4],
  },

  // Timing
  timingRow: {
    flexDirection: 'row',
    paddingVertical: SPACING[4],
  },
  timingItem: {
    flex: 1,
    alignItems: 'center',
    gap: 2,
  },
  timingDivider: {
    width: StyleSheet.hairlineWidth,
    alignSelf: 'stretch',
  },
  timingValue: {
    ...TYPOGRAPHY.HEADLINE,
    fontVariant: ['tabular-nums'],
  },
  timingLabel: {
    ...TYPOGRAPHY.CAPTION_2,
    textTransform: 'uppercase' as const,
    letterSpacing: 0.5,
  },

  // Section
  sectionTitle: {
    ...TYPOGRAPHY.HEADLINE,
    marginBottom: SPACING[3],
  },

  // Exercise
  exerciseRow: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: SPACING[3],
    paddingHorizontal: SPACING[4],
  },
  exerciseIndex: {
    ...TYPOGRAPHY.FOOTNOTE,
    fontVariant: ['tabular-nums'],
    width: 24,
  },
  exerciseName: {
    ...TYPOGRAPHY.BODY,
    flex: 1,
  },
  exerciseDuration: {
    ...TYPOGRAPHY.SUBHEADLINE,
    fontVariant: ['tabular-nums'],
    marginLeft: SPACING[3],
  },
  exerciseSep: {
    height: StyleSheet.hairlineWidth,
    marginLeft: SPACING[4] + 24,
    marginRight: SPACING[4],
  },
  repeatRow: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: SPACING[2],
    marginTop: SPACING[2],
    paddingLeft: 24,
  },
  repeatText: {
    ...TYPOGRAPHY.FOOTNOTE,
  },

  // Music
  musicRow: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: SPACING[2],
    marginTop: SPACING[5],
  },
  musicText: {
    ...TYPOGRAPHY.FOOTNOTE,
  },

  // Bottom bar
  bottomBar: {
    position: 'absolute',
    bottom: 0,
    left: 0,
    right: 0,
    paddingHorizontal: LAYOUT.SCREEN_PADDING,
    paddingTop: SPACING[3],
  },
  ctaButton: {
    height: 54,
    borderRadius: RADIUS.MD,
    borderCurve: 'continuous',
    alignItems: 'center',
    justifyContent: 'center',
    flexDirection: 'row',
  },
  ctaText: {
    ...TYPOGRAPHY.BUTTON_LARGE,
  },
})
