import { create } from 'zustand'

export const DEFAULT_COLOURS = {
  light: {
    free: {
      cardBg:    '#dde5ef',
      badgeBg:   'rgba(255,255,255,0.92)',
      nameText:  '#3d5270',
      badgeText: '#3d5270',
    },
    mine: {
      cardBg:    '#e8610a',
      badgeBg:   'rgba(255,255,255,0.92)',
      nameText:  '#ffffff',
      badgeText: '#e8610a',
    },
    open: {
      cardBg:    '#FF8F60',
      badgeBg:   'rgba(255,255,255,0.92)',
      nameText:  '#ffffff',
      badgeText: '#FF8F60',
    },
    partially_paid: {
      cardBg:    '#FFDC67',
      badgeBg:   'rgba(255,255,255,0.92)',
      nameText:  '#ffffff',
      badgeText: '#d4a800',
    },
    paid: {
      cardBg:    '#81D264',
      badgeBg:   'rgba(255,255,255,0.92)',
      nameText:  '#ffffff',
      badgeText: '#81D264',
    },
  },
  dark: {
    free: {
      cardBg:    '#243044',
      badgeBg:   'rgba(255,255,255,0.92)',
      nameText:  '#94b8d4',
      badgeText: '#94b8d4',
    },
    mine: {
      cardBg:    '#e8610a',
      badgeBg:   'rgba(255,255,255,0.92)',
      nameText:  '#ffffff',
      badgeText: '#e8610a',
    },
    open: {
      cardBg:    '#FF8F60',
      badgeBg:   'rgba(255,255,255,0.92)',
      nameText:  '#ffffff',
      badgeText: '#FF8F60',
    },
    partially_paid: {
      cardBg:    '#FFDC67',
      badgeBg:   'rgba(255,255,255,0.92)',
      nameText:  '#ffffff',
      badgeText: '#d4a800',
    },
    paid: {
      cardBg:    '#81D264',
      badgeBg:   'rgba(255,255,255,0.92)',
      nameText:  '#ffffff',
      badgeText: '#81D264',
    },
  },
}

const useTableColourStore = create((set) => ({
  colours: DEFAULT_COLOURS,
  loadFromBackend: (raw) => {
    try {
      const parsed = JSON.parse(raw)
      if (parsed?.light && parsed?.dark) {
        // Deep-merge so any status keys added after the settings were saved
        // (e.g. 'paid') still fall back to their defaults.
        const merged = { light: {}, dark: {} }
        for (const mode of ['light', 'dark']) {
          for (const status of Object.keys(DEFAULT_COLOURS[mode])) {
            merged[mode][status] = { ...DEFAULT_COLOURS[mode][status], ...(parsed[mode][status] || {}) }
          }
        }
        set({ colours: merged })
      }
    } catch {}
  },
}))

export default useTableColourStore
