import { create } from "zustand"
import { persist } from "zustand/middleware"

type PlateItem = {
  imgThumb: string
  plate: string
  confidence?: number | null
}

type PlateState = {
  activeStreamId: string | ""
  history: Record<string, PlateItem[]>

  setActiveStream: (id: string) => void
  addPlate: (streamId: string, newData: PlateItem) => void
  clearHistory: (streamId: string) => void
}

export const usePlateStore = create<PlateState>()(
  persist(
    (set, get) => ({
      // active stream
      activeStreamId: "",

      setActiveStream: (id: string) => set({ activeStreamId: id }),

      // history per stream
      history: {},

      addPlate: (streamId: string, newData: PlateItem) => {
        const state = get()
        const currentHistory = state.history[streamId] || []

        const index = currentHistory.findIndex(
          (item) => item.plate === newData.plate
        )

        let updatedHistory

        // kalau belum ada → tambah
        if (index === -1) {
          updatedHistory = [newData, ...currentHistory]
        } else {
          const existing = currentHistory[index]

          // kalau confidence lebih tinggi → replace
          if ((newData.confidence ?? 0) > (existing.confidence ?? 0)) {
            updatedHistory = [
              newData,
              ...currentHistory.filter((_, i) => i !== index),
            ]
          } else {
            updatedHistory = currentHistory
          }
        }

        updatedHistory = updatedHistory

        set({
          history: {
            ...state.history,
            [streamId]: updatedHistory,
          },
        })
      },

      // optional: clear history per stream
      clearHistory: (streamId) => {
        const state = get()
        const newHistory = { ...state.history }
        delete newHistory[streamId]

        set({ history: newHistory })
      },
    }),
    {
      name: "plate-storage", // key localStorage
    }
  )
)
