/**
 * TabataFit User Store
 * Profile, settings, subscription — persisted via AsyncStorage
 */

import { create } from 'zustand'
import { persist, createJSONStorage } from 'zustand/middleware'
import AsyncStorage from '@react-native-async-storage/async-storage'
import { getLocales } from 'expo-localization'
import type { UserProfile, UserSettings, SubscriptionPlan, FitnessLevel, FitnessGoal, WeeklyFrequency } from '../types'

interface OnboardingData {
  name: string
  fitnessLevel: FitnessLevel
  goal: FitnessGoal
  weeklyFrequency: WeeklyFrequency
  barriers: string[]
}

interface UserState {
  profile: UserProfile
  settings: UserSettings
  // Actions
  updateProfile: (updates: Partial<UserProfile>) => void
  updateSettings: (updates: Partial<UserSettings>) => void
  setSubscription: (plan: SubscriptionPlan) => void
  completeOnboarding: (data: OnboardingData) => void
}

export const useUserStore = create<UserState>()(
  persist(
    (set) => ({
      profile: {
        name: '',
        email: '',
        joinDate: new Date().toLocaleDateString(getLocales()[0]?.languageTag ?? 'en-US', { month: 'long', year: 'numeric' }),
        subscription: 'free',
        onboardingCompleted: false,
        fitnessLevel: 'beginner',
        goal: 'cardio',
        weeklyFrequency: 3,
        barriers: [],
      },
      settings: {
        haptics: true,
        soundEffects: true,
        voiceCoaching: true,
        musicEnabled: true,
        musicVolume: 0.5,
        reminders: false,
        reminderTime: '09:00',
      },

      updateProfile: (updates) =>
        set((state) => ({
          profile: { ...state.profile, ...updates },
        })),

      updateSettings: (updates) =>
        set((state) => ({
          settings: { ...state.settings, ...updates },
        })),

      setSubscription: (plan) =>
        set((state) => ({
          profile: { ...state.profile, subscription: plan },
        })),

      completeOnboarding: (data) =>
        set((state) => ({
          profile: {
            ...state.profile,
            name: data.name,
            fitnessLevel: data.fitnessLevel,
            goal: data.goal,
            weeklyFrequency: data.weeklyFrequency,
            barriers: data.barriers,
            onboardingCompleted: true,
          },
        })),
    }),
    {
      name: 'tabatafit-user',
      storage: createJSONStorage(() => AsyncStorage),
    }
  )
)
