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

type Theme = 'light' | 'dark' | 'system';

interface SettingsState {
  theme: Theme;
  showTerrain: boolean;
  terrainOpacity: number;
  showGrid: boolean;
  measurementMode: boolean;
  showElevationInfo: boolean;
  showElevationOverlay: boolean;
  setTheme: (theme: Theme) => void;
  setShowTerrain: (show: boolean) => void;
  setTerrainOpacity: (opacity: number) => void;
  setShowGrid: (show: boolean) => void;
  setMeasurementMode: (mode: boolean) => void;
  setShowElevationInfo: (show: boolean) => void;
  setShowElevationOverlay: (show: boolean) => void;
}

function applyTheme(theme: Theme) {
  const root = window.document.documentElement;

  if (theme === 'system') {
    const systemDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
    root.classList.toggle('dark', systemDark);
  } else {
    root.classList.toggle('dark', theme === 'dark');
  }
}

export const useSettingsStore = create<SettingsState>()(
  persist(
    (set) => ({
      theme: 'system' as Theme,
      showTerrain: false,
      terrainOpacity: 0.5,
      showGrid: false,
      measurementMode: false,
      showElevationInfo: false,
      showElevationOverlay: false,
      setTheme: (theme: Theme) => {
        set({ theme });
        applyTheme(theme);
      },
      setShowTerrain: (show: boolean) => set({ showTerrain: show }),
      setTerrainOpacity: (opacity: number) => set({ terrainOpacity: opacity }),
      setShowGrid: (show: boolean) => set({ showGrid: show }),
      setMeasurementMode: (mode: boolean) => set({ measurementMode: mode }),
      setShowElevationInfo: (show: boolean) => set({ showElevationInfo: show }),
      setShowElevationOverlay: (show: boolean) => set({ showElevationOverlay: show }),
    }),
    {
      name: 'rfcp-settings',
    }
  )
);

// Apply theme on initial page load
if (typeof window !== 'undefined') {
  try {
    const raw = localStorage.getItem('rfcp-settings');
    if (raw) {
      const parsed = JSON.parse(raw);
      const theme = parsed?.state?.theme ?? 'system';
      applyTheme(theme);
    } else {
      applyTheme('system');
    }
  } catch {
    applyTheme('system');
  }

  // Listen for system theme changes
  window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
    const current = useSettingsStore.getState().theme;
    if (current === 'system') {
      applyTheme('system');
    }
  });
}
