const STORAGE_KEY = 'region-management-selection';

export interface RegionSelectionState {
  level1Id: number | null;
}

export function readRegionSelection(): RegionSelectionState {
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    if (!raw) {
      return { level1Id: null };
    }
    const parsed = JSON.parse(raw) as Partial<RegionSelectionState & { childId?: number }>;
    return {
      level1Id:
        parsed.level1Id != null && Number.isFinite(Number(parsed.level1Id))
          ? Number(parsed.level1Id)
          : null,
    };
  } catch {
    return { level1Id: null };
  }
}

export function writeRegionSelection(state: RegionSelectionState) {
  localStorage.setItem(
    STORAGE_KEY,
    JSON.stringify({
      level1Id: state.level1Id,
    }),
  );
}
