// Zustand store for app-level shared state (persisted to sessionStorage).
// No provider needed — import useAppStore or useAppContext anywhere.

import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';

interface AppState {
  unitSystem: 'metric' | 'imperial';
  setUnitSystem: (value: 'metric' | 'imperial') => void;
  calculationHistory: Array<{ id: string; height: number; weight: number; heightUnit: string; weightUnit: string; bmiValue: number; bmiCategory: string; timestamp: string }>;
  setCalculationHistory: (value: Array<{ id: string; height: number; weight: number; heightUnit: string; weightUnit: string; bmiValue: number; bmiCategory: string; timestamp: string }>) => void;
  sessionId: string;
  clearSession: () => void;
}

export const useAppStore = create<AppState>()((
  persist(
    (set) => ({
    sessionId: crypto.randomUUID(),
    unitSystem: 'metric',
    calculationHistory: [],
    setUnitSystem: (value) => set({ unitSystem: value }),
    setCalculationHistory: (value) => set({ calculationHistory: value }),
    clearSession: () => set({ sessionId: crypto.randomUUID(), unitSystem: 'metric', calculationHistory: [] }),
    }),
    {
      name: 'bmi_calculator_session',
      storage: createJSONStorage(() => sessionStorage),
    },
  )
));

// Convenience alias — pages import useAppContext as before.
export const useAppContext = useAppStore;

// Backward-compat: AppProvider is a no-op — zustand needs no provider.
export function AppProvider({ children }: { children: React.ReactNode }) {
  return <>{children}</>;
}
