/**
 * TabataFit User Store
 * Profile, settings, subscription — persisted via AsyncStorage
 * Added: Sync status for anonymous auth opt-in
 */

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,
  SyncStatus,
} from '../types'

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

interface UserState {
  profile: UserProfile
  settings: UserSettings
  savedWorkouts: string[]
  // Actions
  updateProfile: (updates: Partial<UserProfile>) => void
  updateSettings: (updates: Partial<UserSettings>) => void
  setSubscription: (plan: SubscriptionPlan) => void
  completeOnboarding: (data: OnboardingData) => void
  toggleSavedWorkout: (workoutId: string) => void
  // NEW: Sync-related actions
  setSyncStatus: (status: SyncStatus, userId?: string | null) => void
  setPromptPending: () => 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: [],
        savedWorkouts: [],
        // NEW: Sync fields
        syncStatus: 'never-synced',
        supabaseUserId: null,
      },
      settings: {
        haptics: true,
        soundEffects: true,
        voiceCoaching: true,
        musicEnabled: true,
        musicVolume: 0.5,
        reminders: false,
        reminderTime: '09:00',
      },

      savedWorkouts: [],

      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,
          },
        })),

      toggleSavedWorkout: (workoutId) =>
        set((state) => ({
          savedWorkouts: state.savedWorkouts.includes(workoutId)
            ? state.savedWorkouts.filter((id) => id !== workoutId)
            : [...state.savedWorkouts, workoutId],
        })),

      // NEW: Sync status management
      setSyncStatus: (status, userId = null) =>
        set((state) => ({
          profile: {
            ...state.profile,
            syncStatus: status,
            supabaseUserId: userId,
          },
        })),

      // NEW: Mark that we should show sync prompt after first workout
      setPromptPending: () =>
        set((state) => ({
          profile: {
            ...state.profile,
            syncStatus: 'prompt-pending',
          },
        })),
    }),
    {
      name: 'tabatafit-user',
      storage: createJSONStorage(() => AsyncStorage),
    }
  )
)
