import { create } from 'zustand'
import type { MediaProfile } from '@shared/ipc'
import { isPreview as PREVIEW } from '../isPreview'
import { logError } from '../reportError'
import { createReconciler } from '../lib/reconcile'

// Sample profiles so the manager + source picker have content during UI design.
const seed: MediaProfile[] = PREVIEW
  ? [
      { id: 'p1', name: 'Archive (1080p, subs)', kind: 'video', quality: '1080p' },
      { id: 'p2', name: 'Music (audio only)', kind: 'audio', quality: 'Best' }
    ]
  : []

interface ProfilesState {
  profiles: MediaProfile[]
  /** add a new profile or update an existing one (matched by id) */
  save: (profile: MediaProfile) => void
  remove: (id: string) => void
  /** re-fetch persisted profiles from main */
  reload: () => void
}

// Mutations apply main's authoritative return (sanitized/capped) via a
// latest-wins reconciler so the optimistic list matches disk (L142).
const reconcile = createReconciler()

export const useProfiles = create<ProfilesState>((set) => ({
  profiles: seed,

  save: (profile) => {
    set((s) => ({ profiles: [profile, ...s.profiles.filter((p) => p.id !== profile.id)] }))
    if (!PREVIEW)
      reconcile(
        'profiles',
        window.api.saveProfile(profile),
        (profiles) => set({ profiles }),
        logError('saveProfile')
      )
  },

  remove: (id) => {
    set((s) => ({ profiles: s.profiles.filter((p) => p.id !== id) }))
    if (!PREVIEW)
      reconcile(
        'profiles',
        window.api.removeProfile(id),
        (profiles) => set({ profiles }),
        logError('removeProfile')
      )
  },

  reload: () => {
    if (PREVIEW) return
    window.api
      .listProfiles()
      .then((profiles) => set({ profiles }))
      .catch(logError('listProfiles'))
  }
}))

// Load persisted profiles on startup.
if (!PREVIEW) useProfiles.getState().reload()
