import { useState, useCallback, useEffect } from 'react';
import type { PersistedState } from '@wordle/shared';
import { defaultPersistedState } from '@wordle/shared';
import { detectLang } from '../messages/index.js';

function storageKey(): string {
  return `wordle-state-${detectLang()}`;
}

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

function saveState(state: PersistedState): void {
  localStorage.setItem(storageKey(), 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 };
}
