import { useState, useCallback, useEffect } from 'react';
import type { PersistedState } from '@wordle/shared';
import { defaultPersistedState } from '@wordle/shared';

const STORAGE_KEY = 'wordle-state';

function loadState(): PersistedState {
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    if (raw) {
      return JSON.parse(raw) as PersistedState;
    }
  } catch {
    // corrupted data — reset
  }
  return defaultPersistedState();
}

function saveState(state: PersistedState): void {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(state));
}

export function usePersistence() {
  const [state, setState] = useState<PersistedState>(loadState);

  // Persist on every change
  useEffect(() => {
    saveState(state);
  }, [state]);

  const updateState = useCallback((patch: Partial<PersistedState>) => {
    setState((prev) => ({ ...prev, ...patch }));
  }, []);

  return { state, updateState };
}
