import { create } from 'zustand';
import { persist, devtools } from 'zustand/middleware';
import { broadcastSync } from '@/utils/broadcastSync';
import type { UIState, Notification } from '@/types';

// FE-TYPE-011: Fully typed store interfaces
export interface UIActions {
  setTheme: (theme: 'light' | 'dark' | 'system') => void;
  setLanguage: (language: 'en' | 'fr') => void;
  setSidebarOpen: (open: boolean) => void;
  addNotification: (
    notification: Omit<Notification, 'id' | 'timestamp'>,
  ) => void;
  removeNotification: (id: string) => void;
  markNotificationAsRead: (id: string) => void;
  clearNotifications: () => void;
}

// FE-TYPE-011: Export store type for reuse
export type UIStore = UIState & UIActions;

export const useUIStore = create<UIStore>()(
  devtools(
    persist(
      broadcastSync(
        (set) => ({
          // État initial - Dark mode par défaut pour MVP Premium
          theme: 'dark',
          language: 'en',
          sidebarOpen: true,
          notifications: [],

          // Actions
          setTheme: (theme) => {
            set({ theme });
            // Appliquer le thème au DOM
            const root = document.documentElement;

            if (theme === 'system') {
              const prefersDark = window.matchMedia(
                '(prefers-color-scheme: dark)',
              ).matches;
              root.classList.remove('light', 'dark');
              root.classList.add(prefersDark ? 'dark' : 'light');
              root.setAttribute('data-theme', prefersDark ? 'dark' : 'light');
            } else {
              root.classList.remove('light', 'dark');
              root.classList.add(theme);
              root.setAttribute('data-theme', theme);
            }
          },

          setLanguage: (language) => {
            set({ language });
            // Synchroniser avec i18n
            if (typeof window !== 'undefined' && window.i18n) {
              window.i18n.changeLanguage(language);
            }
          },

          setSidebarOpen: (sidebarOpen) => set({ sidebarOpen }),

          addNotification: (notification) => {
            const newNotification: Notification = {
              ...notification,
              id: crypto.randomUUID(),
              timestamp: new Date().toISOString(),
            };
            set((state) => ({
              notifications: [...state.notifications, newNotification],
            }));
          },

          removeNotification: (id) => {
            set((state) => ({
              notifications: state.notifications.filter((n) => n.id !== id),
            }));
          },

          markNotificationAsRead: (id) => {
            set((state) => ({
              notifications: state.notifications.map((n) =>
                n.id === id ? { ...n, read: true } : n,
              ),
            }));
          },

          clearNotifications: () => set({ notifications: [] }),
        }),
        {
          channelName: 'ui-store',
          enabled: true,
          // FE-STATE-002: Sync UI preferences across tabs
          shouldSync: (state, prevState) => {
            // Only sync theme, language, and sidebar state (not notifications)
            return (
              state.theme !== prevState?.theme ||
              state.language !== prevState?.language ||
              state.sidebarOpen !== prevState?.sidebarOpen
            );
          },
        },
      ),
      {
        name: 'ui-storage',
        partialize: (state) => ({
          theme: state.theme,
          language: state.language,
          sidebarOpen: state.sidebarOpen,
        }),
      },
    ),
    {
      // FE-STATE-007: Enable Redux DevTools for debugging
      name: 'UIStore',
      enabled: import.meta.env.DEV,
    },
  ),
);
