// 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 {
  measurementSystem: 'metric' | 'imperial';
  setMeasurementSystem: (value: 'metric' | 'imperial') => void;
  calculationHistory: Array<{ id: string; height: number; weight: number; heightUnit: string; weightUnit: string; bmiValue: number; category: string; timestamp: string }>;
  setCalculationHistory: (value: Array<{ id: string; height: number; weight: number; heightUnit: string; weightUnit: string; bmiValue: number; category: string; timestamp: string }>) => void;
  sessionId: string;
  clearSession: () => void;
}

export const useAppStore = create<AppState>()((
  persist(
    (set) => ({
    sessionId: crypto.randomUUID(),
    measurementSystem: 'metric',
    calculationHistory: [],
    setMeasurementSystem: (value) => set({ measurementSystem: value }),
    setCalculationHistory: (value) => set({ calculationHistory: value }),
    clearSession: () => set({ sessionId: crypto.randomUUID(), measurementSystem: '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}</>;
}
